forked from oie-mines-paristech/lca_algebraic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.html
2072 lines (1742 loc) · 86.7 KB
/
helpers.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.7.4" />
<title>lca_algebraic.helpers API documentation</title>
<meta name="description" content="" />
<link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/8.0.0/sanitize.min.css' rel='stylesheet'>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" rel="stylesheet">
<style>.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{font-weight:bold}#index h4 + ul{margin-bottom:.6em}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>lca_algebraic.helpers</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">import functools
import re
import types
from copy import deepcopy
from itertools import chain
import pandas as pd
from bw2data.backends.peewee.utils import dict_as_exchangedataset
from bw2data.meta import databases as dbmeta
from sympy import symbols
from .base_utils import *
from .base_utils import _getDb, _actDesc, _getAmountOrFormula, _actName, _isOutputExch
from .params import *
from .params import _param_registry, _completeParamValues
from typing import Tuple, Dict
BIOSPHERE3_DB_NAME="biosphere3"
_metaCache = defaultdict(lambda : {})
def _setMeta(dbname, key, value) :
"""Set meta param on DB"""
_metaCache[dbname][key] = value
data = dbmeta[dbname]
data[key] = value
dbmeta[dbname] = data
dbmeta.flush()
def _getMeta(db_name, key) :
if key in _metaCache[db_name] :
return _metaCache[db_name][key]
val = dbmeta[db_name].get(key)
_metaCache[db_name][key] = val
return val
FOREGROUND_KEY = "fg"
def _isForeground(db_name) :
""" Check is db is marked as foreground DB : which means activities may be parametrized / should be developped. """
return _getMeta(db_name, FOREGROUND_KEY)
def setForeground(db_name) :
""" Set a db as being a foreground database, meaning it is parametrized and lca_algebraic should develop its activities"""
return _setMeta(db_name, FOREGROUND_KEY, True)
def setBackground(db_name) :
""" Set a db as being a foreground database, meaning it should be considred as static"""
return _setMeta(db_name, FOREGROUND_KEY, False)
def SET_USER_DB(db_name) :
"""Deprecated, use #setForeground() / setBackground() instead"""
error("Deprecated, use #setForeground() / setBackground() instead")
setForeground(db_name)
def _listTechBackgroundDbs() :
"""List all background databases technosphere (non biosphere) batabases"""
return list(name for name in bw.databases if not _isForeground(name) and not name == BIOSPHERE3_DB_NAME)
old_amount = symbols("old_amount") # Can be used in expression of amount for updateExchanges, in order to reference the previous value
NumOrExpression = Union[float, Basic]
def list_databases() :
"""List of databases and their status"""
data = list(
dict(
name=name,
backend=_getMeta(name, "backend"),
type="foreground" if _isForeground(name) else "background") for name in bw.databases)
res = pd.DataFrame(data)
return res.set_index("name")
def with_db_context(func):
""" Internal decorator wrapping function into DbContext, using its first parameters (either Activity, Db or Db name)"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
act = args[0]
dbname = act.key[0]
with DbContext(dbname) :
return func(*args, **kwargs)
return wrapper
class ActivityExtended(Activity):
"""Improved API for activity : adding a few useful methods.
Those methods are backported to #Activity in order to be directly available on all existing instances
"""
@with_db_context
def listExchanges(self) :
""" Iterates on all exchanges (except "production") and return a list of (exch-name, target-act, amount) """
res = []
for exc in self.exchanges():
# Don't show production
if _isOutputExch(exc) :
continue
input = bw.get_activity(exc.input.key)
amount = _getAmountOrFormula(exc)
res.append((exc["name"], input, amount))
return res
@with_db_context
def getExchange(self, name=None, input=None, single=True):
"""Get exchange by name or input
Parameters
----------
name : name of the exchange. Name can be suffixed with '#LOCATION' to distinguish several exchanges with same name. \
It can also be suffised by '*' to match an exchange starting with this name. Location can be a negative match '!'
Exampple : "Wood*#!RoW" matches any exchange with name containing Wood, and location not "RoW"
single :True if a single match is expected. Otherwize, a list of result is returned
Returns
-------
Single exchange or list of exchanges (if _single is False or "name" contains a '*')
raise Exception if not matching exchange found
"""
def single_match(name, exch):
# Name can be "Elecricity#RER"
if "#" in name:
name, loc = name.split("#")
negative = False
if loc.startswith("!"):
negative = True
loc = loc[1:]
act = getActByCode(*exch['input'])
if not 'location' in act or (negative and act['location'] == loc) or (
not negative and act['location'] != loc):
return False
if '*' in name:
name = name.replace('*', '')
return name in exch['name']
else:
return name == exch['name']
def match(exch):
if name:
if isinstance(name, list):
return any(single_match(iname, exch) for iname in name)
else:
return single_match(name, exch)
if input:
return input == exch['input']
exchs = list(exch for exch in self.exchangesNp() if match(exch))
if len(exchs) == 0:
raise Exception("Found no exchange matching name : %s" % name)
if single and len(exchs) != 1:
raise Exception("Expected 1 exchange with name '%s' found %d" % (name, len(exchs)))
if single:
return exchs[0]
else:
return exchs
def setOutputAmount(self, amount):
'''Set the amount for the single output exchange (1 by default)'''
self.addExchanges({self: amount})
@with_db_context
def updateExchanges(self, updates: Dict[str, any] = dict()):
"""Update existing exchanges, by name.
Parameters
----------
updates : Dict of "<exchange name>" => <new value>
<exchange name> can be suffixed with '#LOCATION' to distinguish several exchanges with same name. \
It can also be suffixed by '*' to match an exchange starting with this name. Location can be a negative match '!'
Exampple : "Wood*#!RoW" matches any exchange with name containing Wood, and location not "RoW"
<New Value> : either single value (float or SympPy expression) for updating only amount, or activity for updating only input,
or dict of attributes, for updating both at once, or any other attribute.
The amount can reference the symbol 'old_amount' that will be replaced with the current amount of the exchange.
"""
parametrized = False
# Update exchanges
for name, attrs in updates.items():
exchs = self.getExchange(name, single=not '*' in name)
if not isinstance(exchs, list):
exchs = [exchs]
for exch in exchs:
if attrs is None:
exch.delete()
exch.save()
continue
# Single value ? => amount
if not isinstance(attrs, dict):
if isinstance(attrs, Activity):
attrs = dict(input=attrs)
else:
attrs = dict(amount=attrs)
if 'amount' in attrs:
attrs.update(_amountToFormula(attrs['amount'], exch['amount']))
exch.update(attrs)
exch.save()
# We have a formula now ? => register it to parametrized exchange
if 'formula' in attrs:
parametrized = True
def deleteExchanges(self, name, single=True):
''' Remove matching exchanges '''
exchs = self.getExchange(name, single=single)
if not isinstance(exchs, list):
exchs = [exchs]
if len(exchs) == 0:
raise Exception("No exchange found for '%s'" % name)
for ex in exchs:
ex.delete()
ex.save()
self.save()
@with_db_context
def substituteWithDefault(self, exchange_name: str, switch_act: Activity, paramSwitch: EnumParam, amount=None):
"""Substitutes one exchange with a switch on other activities, or fallback to the current one as default (parameter set to None)
For this purpose, we create a new exchange referencing the activity switch, and we multiply current activity by '<param_name>_default',
making it null as soon as one enum value is set.
This is useful for changing electricty mix, leaving the default one if needed
Parameters
----------
act : Activity to update
exchange_name : Name of the exchange to update
switch_act : Activity to substitue as input
amount : Amount of the input (uses previous amount by default)
"""
current_exch = self.getExchange(exchange_name)
prev_amount = amount if amount else _getAmountOrFormula(current_exch)
self.addExchanges({switch_act: prev_amount})
self.updateExchanges({exchange_name: paramSwitch.symbol(None) * prev_amount})
@with_db_context
def addExchanges(self, exchanges: Dict[Activity, Union[NumOrExpression, dict]] = dict()):
"""Add exchanges to an existing activity, with a compact syntax :
Parameters
----------
exchanges : Dict of activity => amount or activity => attributes_dict. \
Amount being either a fixed value or Sympy expression (arithmetic expression of Sympy symbols)
"""
with DbContext(self.key[0]) :
for sub_act, attrs in exchanges.items():
if isinstance(attrs, dict):
amount = attrs.pop('amount')
else:
amount = attrs
attrs = dict()
exch = self.new_exchange(
input=sub_act.key,
name=sub_act['name'],
unit=sub_act['unit'] if 'unit' in sub_act else None,
type='production' if self == sub_act else 'technosphere' if sub_act.get('type') == 'process' else 'biosphere')
exch.update(attrs)
exch.update(_amountToFormula(amount))
if 'formula' in exch:
parametrized = True
exch.save()
self.save()
@with_db_context
def getAmount(self, *args, sum=False, **kargs):
"""
Get the amount of one or several exchanges, selected by name or input. See #getExchange()
"""
exchs = self.getExchange(*args, single=not sum, **kargs)
if sum:
res = 0
if len(exchs) == 0:
raise Exception("No exchange found")
for exch in exchs:
res += _getAmountOrFormula(exch)
return res
else:
return _getAmountOrFormula(exchs)
def getOutputAmount(self):
""" Return the amount of the production : 1 if none is found """
res = 1
for exch in self.exchanges() :
if exch['input'] == exch['output']:
# Not 1 ?
if exch['amount'] != 1:
res = exch['amount']
break
return res
def exchangesNp(self):
""" List of exchange, except production (output) one."""
for exch in self.exchanges():
if exch['input'] != exch['output']:
yield exch
# Backport new methods to vanilla Activity class in order to benefit from it for all existing instances
for name, item in ActivityExtended.__dict__.items():
if isinstance(item, types.FunctionType):
setattr(Activity, name, item)
def _split_words(name):
clean = re.sub('[^0-9a-zA-Z]+', ' ', name)
clean = re.sub(' +', ' ', clean)
clean = clean.lower()
return clean.split(' ')
def _build_index(db):
res = defaultdict(set)
for act in db:
words = _split_words(act['name'])
for word in words:
res[word].add(act)
return res
# Index of activities per name, for fast search dict[db_name][activity_word] => list of activitites
db_index = dict()
def _get_indexed_db(db_name):
if not db_name in db_index:
db_index[db_name] = _build_index(_getDb(db_name))
return db_index[db_name]
def _find_candidates(db_name, name):
res = []
index = _get_indexed_db(db_name)
words = _split_words(name)
for word in words:
candidates = index[word]
if len(res) == 0 or (0 < len(candidates) < len(res)):
res = list(candidates)
return res
def getActByCode(db_name, code):
""" Get activity by code """
return _getDb(db_name).get(code)
def findActivity(name=None, loc=None, in_name=None, code=None, categories=None, category=None, db_name=None,
single=True, unit=None) -> ActivityExtended :
"""
Find single activity by name & location
Uses index for fast fetching
"""
if name and '*' in name:
in_name = name.replace("*", "")
name = None
def act_filter(act):
if name and not name == act['name']:
return False
if in_name and not in_name in act['name']:
return False
if loc and not loc == act['location']:
return False
if unit and not unit == act['unit']:
return False
if category and not category in act['categories']:
return False
if categories and not tuple(categories) == act['categories']:
return False
return True
if code:
acts = [getActByCode(db_name, code)]
else:
search = name if name is not None else in_name
search = search.lower()
search = search.replace(',', ' ')
# Find candidates via index
# candidates = _find_candidates(db_name, name_key)
candidates = _getDb(db_name).search(search, limit=200)
if len(candidates) == 0 :
# Try again removing strange caracters
search = re.sub(r'\w*[^a-zA-Z ]+\w*', ' ', search)
candidates = _getDb(db_name).search(search, limit=200)
# print(search, candidates)
# Exact match
acts = list(filter(act_filter, candidates))
if single and len(acts) == 0:
raise Exception("No activity found in '%s' with name '%s' and location '%s'" % (db_name, name, loc))
if single and len(acts) > 1:
raise Exception("Several activity found in '%s' with name '%s' and location '%s':\n%s" % (
db_name, name, loc, str(acts)))
if len(acts) == 1:
return acts[0]
else:
return acts
def findBioAct(name=None, loc=None, **kwargs):
"""Alias for findActivity(name, ... db_name=BIOSPHERE3_DB_NAME) """
return findActivity(name=name, loc=loc, db_name=BIOSPHERE3_DB_NAME, **kwargs)
def findTechAct(name=None, loc=None, single=True, **kwargs):
""" Search activities in any background db not being biospehere """
dbs = _listTechBackgroundDbs()
if len(dbs) > 1 :
raise Exception("There is more than one technosphere background DB (%s) please use findActivity(..., db_name=YOUR_DB)" % str(dbs))
return findActivity(name=name, loc=loc, db_name=dbs[0], single=single, **kwargs)
def _amountToFormula(amount: Union[float, str, Basic], currentAmount=None):
"""Transform amount in exchange to either simple amount or formula"""
res = dict()
if isinstance(amount, Basic):
if currentAmount != None:
amount = amount.subs(old_amount, currentAmount)
# Check the expression does not reference undefined params
all_symbols = list([key for param in _param_registry().values() for key, val in param.expandParams().items()])
for symbol in amount.free_symbols:
if not str(symbol) in all_symbols:
raise Exception("Symbol '%s' not found in params : %s" % (symbol, all_symbols))
res['formula'] = str(amount)
res['amount'] = 0
elif isinstance(amount, float) or isinstance(amount, int):
res['amount'] = amount
else:
raise Exception(
"Amount should be either a constant number or a Sympy expression (expression of ParamDef). Was : %s" % type(
amount))
return res
def _newAct(db_name, code):
if not _isForeground(db_name) :
error("WARNING: You are creating activity in background DB. You should only do it in your foreground / user DB : ", db_name)
db = _getDb(db_name)
# Already present : delete it ?
for act in db:
if act['code'] == code:
error("Activity '%s' was already in '%s'. Overwriting it" % (code, db_name))
act.delete()
return db.new_activity(code)
def newActivity(db_name, name, unit,
exchanges: Dict[Activity, Union[float, str]] = dict(),
code=None,
**argv):
"""Creates a new activity
Parameters
----------
name : Name ofthe new activity
db_name : Destination DB : ACV DB by default
exchanges : Dict of activity => amount. If amount is a string, is it considered as a formula with parameters
argv : extra params passed as properties of the new activity
"""
act = _newAct(db_name, code if code else name)
act['name'] = name
act['type'] = 'process'
act['unit'] = unit
act.update(argv)
# Add exchanges
act.addExchanges(exchanges)
return act
def copyActivity(db_name, activity: ActivityExtended, code=None, withExchanges=True, **kwargs) -> ActivityExtended:
"""Copy activity into a new DB"""
res = _newAct(db_name, code)
for key, value in activity.items():
if key not in ['database', 'code']:
res[key] = value
for k, v in kwargs.items():
res._data[k] = v
res._data[u'code'] = code
res['name'] = code
res['type'] = 'process'
res.save()
if withExchanges:
for exc in activity.exchanges():
data = deepcopy(exc._data)
data['output'] = res.key
# Change `input` for production exchanges
if exc['input'] == exc['output']:
data['input'] = res.key
ExchangeDataset.create(**dict_as_exchangedataset(data))
return res
ActivityOrActivityAmount = Union[Activity, Tuple[Activity, float]]
def newSwitchAct(dbname, name, paramDef: ParamDef, acts_dict: Dict[str, ActivityOrActivityAmount]):
"""Create a new parametrized, virtual activity, made of a map of other activities, controlled by an enum parameter.
This enables to implement a "Switch" with brightway parameters
Internally, this will create a linear sum of other activities controlled by <param_name>_<enum_value> : 0 or 1
By default, all activities have associated amount of 1.
You can provide other amounts by providing a tuple of (activity, amount).
Parameters
----------
dbname: name of the target DB
name: Name of the new activity
paramDef : parameter definition of type enum
acts_dict : dict of "enumValue" => activity or "enumValue" => (activity, amount)
Examples
--------
>>> newSwitchAct(MYDB, "switchAct", switchParam, {
>>> "val1" : act1 # Amount is 1
>>> "val2" : (act2, 0.4) # Different amount
>>> "val3" : (act3, b + 6) # Amount with formula
>>> }
"""
# Transform map of enum values to corresponding formulas <param_name>_<enum_value>
exch = defaultdict(lambda : 0)
# Forward last unit as unit of the switch
unit= None
for key, act in acts_dict.items() :
amount = 1
if type(act) == list or type(act) == tuple :
act, amount = act
exch[act] += amount * paramDef.symbol(key)
unit = act["unit"]
res = newActivity(
dbname,
name,
unit=unit,
exchanges=exch)
return res
def printAct(*args, impact=None, **params):
"""
Print activities and their exchanges.
If parameter values are provided, formulas will be evaluated accordingly.
If impact is provided it will be computed.
"""
tables = []
names = []
activities = args
for act in activities:
with DbContext(act.key[0]) :
inputs_by_ex_name = dict()
df = pd.DataFrame(index=['input', 'amount', 'unit'])
data = dict()
for (i, exc) in enumerate(act.exchanges()):
# Don't show production
if _isOutputExch(exc) :
continue
input = bw.get_activity(exc.input.key)
amount = _getAmountOrFormula(exc)
# Params provided ? Evaluate formulas
if len(params) > 0 and isinstance(amount, Basic):
new_params = [(name, value) for name, value in _completeParamValues(params).items()]
amount = amount.subs(new_params)
ex_name = exc['name']
#if 'location' in input and input['location'] != "GLO":
# name += "#%s" % input['location']
#if exc.input.key[0] not in [BIOSPHERE3_DB_NAME, ECOINVENT_DB_NAME()]:
# name += " {user-db}"
# Unique name : some exchanges may havve same names
_name = ex_name
i = 1
while ex_name in data:
ex_name = "%s#%d" % (_name, i)
i += 1
inputs_by_ex_name[ex_name] = input
input_name = _actName(input)
if _isForeground(input.key[0]):
input_name += "{FG}"
data[ex_name] = [input_name, amount, exc.unit]
# Provide impact calculation if impact provided
for key, values in data.items():
df[key] = values
tables.append(df.T)
names.append(_actDesc(act))
full = pd.concat(tables, axis=1, keys=names, sort=True)
# Highlight differences in case two activites are provided
if len(activities) == 2:
yellow = "background-color:yellow"
iamount1 = full.columns.get_loc((names[0], "amount"))
iamount2 = full.columns.get_loc((names[1], "amount"))
iact1 = full.columns.get_loc((names[0], "input"))
iact2 = full.columns.get_loc((names[1], "input"))
def same_amount(row):
res = [""] * len(row)
if row[iamount1] != row[iamount2]:
res[iamount1] = yellow
res[iamount2] = yellow
if row[iact1] != row[iact2]:
res[iact1] = yellow
res[iact2] = yellow
return res
full = full.style.apply(same_amount, axis=1)
display(full)
def newInterpolatedAct(dbname: str, name: str, act1: ActivityExtended, act2: ActivityExtended, x1, x2, x, alpha1=1,
alpha2=1, **kwargs):
"""Creates a new activity made of interpolation of two similar activities.
For each exchange :
amount = alpha1 * a1 + (x - X1) * (alpha2 * a2 - alpha1 * a1) / (x2 - x1)
Parameters
----------
name : Name of new activity
act1 : Activity 1
act2 : Activity 2
x1 : X for act1
x2 : X for act 2
x : Should be a parameter symbol
alpha1 : Ratio for act1 (Default value = 1)
alpha2 : Ratio for act2 (Default value = 1)
kwargs : Any other param will be added as attributes of new activity
"""
res = copyActivity(dbname, act1, name, withExchanges=False, **kwargs)
exch1_by_input = dict({exch['input']: exch for exch in act1.exchangesNp()})
exch2_by_input = dict({exch['input']: exch for exch in act2.exchangesNp()})
inputs = set(chain(exch1_by_input.keys(), exch2_by_input.keys()))
for input in inputs:
exch1 = exch1_by_input.get(input)
exch2 = exch2_by_input.get(input)
exch = exch1 if exch1 else exch2
amount1 = exch1['amount'] if exch1 else 0
amount2 = exch2['amount'] if exch2 else 0
if exch1 and exch2 and exch1['name'] != exch2['name']:
raise Exception("Input %s refer two different names : %s, %s" % (input, exch1['name'], exch2['name']))
amount = interpolate(x, x1, x2, amount1 * alpha1, amount2 * alpha2)
act = getActByCode(*input)
res.addExchanges({act: dict(amount=amount, name=exch['name'])})
return res
def findMethods(search=None, mainCat=None) :
"""
Find impact method. Search in all methods against a list of match strings.
Each parameter can be either an exact match match, or case insenstive search, if suffixed by '*'
Parameters
----------
search : String to search
mainCat : if specified, limits the research for method[0] == mainCat.
"""
res = []
search = search.lower()
for method in bw.methods:
text = str(method).lower()
match = search in text
if mainCat :
match = match and (mainCat == method[0])
if match :
res.append(method)
return res</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="lca_algebraic.helpers.SET_USER_DB"><code class="name flex">
<span>def <span class="ident">SET_USER_DB</span></span>(<span>db_name)</span>
</code></dt>
<dd>
<section class="desc"><p>Deprecated, use #setForeground() / setBackground() instead</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def SET_USER_DB(db_name) :
"""Deprecated, use #setForeground() / setBackground() instead"""
error("Deprecated, use #setForeground() / setBackground() instead")
setForeground(db_name)</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.copyActivity"><code class="name flex">
<span>def <span class="ident">copyActivity</span></span>(<span>db_name, activity, code=None, withExchanges=True, **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>Copy activity into a new DB</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def copyActivity(db_name, activity: ActivityExtended, code=None, withExchanges=True, **kwargs) -> ActivityExtended:
"""Copy activity into a new DB"""
res = _newAct(db_name, code)
for key, value in activity.items():
if key not in ['database', 'code']:
res[key] = value
for k, v in kwargs.items():
res._data[k] = v
res._data[u'code'] = code
res['name'] = code
res['type'] = 'process'
res.save()
if withExchanges:
for exc in activity.exchanges():
data = deepcopy(exc._data)
data['output'] = res.key
# Change `input` for production exchanges
if exc['input'] == exc['output']:
data['input'] = res.key
ExchangeDataset.create(**dict_as_exchangedataset(data))
return res</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.findActivity"><code class="name flex">
<span>def <span class="ident">findActivity</span></span>(<span>name=None, loc=None, in_name=None, code=None, categories=None, category=None, db_name=None, single=True, unit=None)</span>
</code></dt>
<dd>
<section class="desc"><p>Find single activity by name & location
Uses index for fast fetching</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def findActivity(name=None, loc=None, in_name=None, code=None, categories=None, category=None, db_name=None,
single=True, unit=None) -> ActivityExtended :
"""
Find single activity by name & location
Uses index for fast fetching
"""
if name and '*' in name:
in_name = name.replace("*", "")
name = None
def act_filter(act):
if name and not name == act['name']:
return False
if in_name and not in_name in act['name']:
return False
if loc and not loc == act['location']:
return False
if unit and not unit == act['unit']:
return False
if category and not category in act['categories']:
return False
if categories and not tuple(categories) == act['categories']:
return False
return True
if code:
acts = [getActByCode(db_name, code)]
else:
search = name if name is not None else in_name
search = search.lower()
search = search.replace(',', ' ')
# Find candidates via index
# candidates = _find_candidates(db_name, name_key)
candidates = _getDb(db_name).search(search, limit=200)
if len(candidates) == 0 :
# Try again removing strange caracters
search = re.sub(r'\w*[^a-zA-Z ]+\w*', ' ', search)
candidates = _getDb(db_name).search(search, limit=200)
# print(search, candidates)
# Exact match
acts = list(filter(act_filter, candidates))
if single and len(acts) == 0:
raise Exception("No activity found in '%s' with name '%s' and location '%s'" % (db_name, name, loc))
if single and len(acts) > 1:
raise Exception("Several activity found in '%s' with name '%s' and location '%s':\n%s" % (
db_name, name, loc, str(acts)))
if len(acts) == 1:
return acts[0]
else:
return acts</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.findBioAct"><code class="name flex">
<span>def <span class="ident">findBioAct</span></span>(<span>name=None, loc=None, **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>Alias for findActivity(name, … db_name=BIOSPHERE3_DB_NAME)</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def findBioAct(name=None, loc=None, **kwargs):
"""Alias for findActivity(name, ... db_name=BIOSPHERE3_DB_NAME) """
return findActivity(name=name, loc=loc, db_name=BIOSPHERE3_DB_NAME, **kwargs)</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.findMethods"><code class="name flex">
<span>def <span class="ident">findMethods</span></span>(<span>search=None, mainCat=None)</span>
</code></dt>
<dd>
<section class="desc"><p>Find impact method. Search in all methods against a list of match strings.
Each parameter can be either an exact match match, or case insenstive search, if suffixed by '*'</p>
<h2 id="parameters">Parameters</h2>
<dl>
<dt><strong><code>search</code></strong> : <code>String</code> <code>to</code> <code>search</code></dt>
<dd> </dd>
</dl>
<p>mainCat : if specified, limits the research for method[0] == mainCat.</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def findMethods(search=None, mainCat=None) :
"""
Find impact method. Search in all methods against a list of match strings.
Each parameter can be either an exact match match, or case insenstive search, if suffixed by '*'
Parameters
----------
search : String to search
mainCat : if specified, limits the research for method[0] == mainCat.
"""
res = []
search = search.lower()
for method in bw.methods:
text = str(method).lower()
match = search in text
if mainCat :
match = match and (mainCat == method[0])
if match :
res.append(method)
return res</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.findTechAct"><code class="name flex">
<span>def <span class="ident">findTechAct</span></span>(<span>name=None, loc=None, single=True, **kwargs)</span>
</code></dt>
<dd>
<section class="desc"><p>Search activities in any background db not being biospehere</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def findTechAct(name=None, loc=None, single=True, **kwargs):
""" Search activities in any background db not being biospehere """
dbs = _listTechBackgroundDbs()
if len(dbs) > 1 :
raise Exception("There is more than one technosphere background DB (%s) please use findActivity(..., db_name=YOUR_DB)" % str(dbs))
return findActivity(name=name, loc=loc, db_name=dbs[0], single=single, **kwargs)</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.getActByCode"><code class="name flex">
<span>def <span class="ident">getActByCode</span></span>(<span>db_name, code)</span>
</code></dt>
<dd>
<section class="desc"><p>Get activity by code</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def getActByCode(db_name, code):
""" Get activity by code """
return _getDb(db_name).get(code)</code></pre>
</details>
</dd>
<dt id="lca_algebraic.helpers.list_databases"><code class="name flex">
<span>def <span class="ident">list_databases</span></span>(<span>)</span>
</code></dt>
<dd>
<section class="desc"><p>List of databases and their status</p></section>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def list_databases() :
"""List of databases and their status"""
data = list(