-
Notifications
You must be signed in to change notification settings - Fork 58
/
activity.py
590 lines (496 loc) · 25.6 KB
/
activity.py
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
# -*- coding: utf-8 -*-
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets
from .inventory import ActivitiesBiosphereTable
from .delegates import FloatDelegate, StringDelegate, ViewOnlyDelegate
from .table import ABTableWidget, ABTableItem
from .views import ABDataFrameEdit, dataframe_sync
from ..icons import icons, qicons
from ...signals import signals
from ...bwutils.commontasks import AB_names_to_bw_keys, bw_keys_to_AB_names
class BaseExchangeTable(ABDataFrameEdit):
COLUMNS = []
# Signal used to correctly control `DetailsGroupBox`
updated = QtCore.pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setDragEnabled(True)
self.setAcceptDrops(False)
self.setSizePolicy(QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Maximum)
)
self.delete_exchange_action = QtWidgets.QAction(
qicons.delete, "Delete exchange(s)", None
)
self.remove_formula_action = QtWidgets.QAction(
qicons.delete, "Unset formula(s)", None
)
self.downstream = False
self.key = None if not hasattr(parent, "key") else parent.key
self.exchanges = []
self._connect_signals()
def _connect_signals(self):
signals.database_changed.connect(lambda: self.sync())
self.delete_exchange_action.triggered.connect(self.delete_exchanges)
self.remove_formula_action.triggered.connect(self.remove_formula)
@dataframe_sync
def sync(self, exchanges=None):
""" Build the table using either new or stored exchanges iterable.
"""
if exchanges is not None:
self.exchanges = exchanges
self.dataframe = self.build_df()
def build_df(self) -> pd.DataFrame:
""" Use the Exchanges Iterable to construct a dataframe.
Make sure to store the Exchange object itself in the dataframe as well.
"""
df = pd.DataFrame([
self.create_row(exchange=exc)[0] for exc in self.exchanges
], columns=self.COLUMNS + ["exchange"])
return df
def create_row(self, exchange) -> (dict, object):
""" Take the given Exchange object and extract a number of attributes.
"""
adj_act = exchange.output if self.downstream else exchange.input
row = {
"Amount": exchange.get("amount"),
"Unit": adj_act.get("unit", "Unknown"),
"exchange": exchange,
}
return row, adj_act
def get_key(self, proxy: QtCore.QModelIndex) -> tuple:
""" Get the activity key from the exchange. """
index = self.get_source_index(proxy)
exchange = self.dataframe.iloc[index.row(), ]["exchange"]
return exchange.output if self.downstream else exchange.input
@QtCore.pyqtSlot()
def delete_exchanges(self) -> None:
""" Remove all of the selected exchanges from the activity.
"""
indexes = [self.get_source_index(p) for p in self.selectedIndexes()]
rows = [index.row() for index in indexes]
exchanges = self.dataframe.iloc[rows, ]["exchange"].to_list()
signals.exchanges_deleted.emit(exchanges)
def remove_formula(self) -> None:
""" Remove the formulas for all of the selected exchanges.
This will also check if the exchange has `original_amount` and
attempt to overwrite the `amount` with that value after removing the
`formula` field.
This can have the additional effect of removing the ActivityParameter
if it was set for the current activity and all formulas are gone.
"""
indexes = [self.get_source_index(p) for p in self.selectedIndexes()]
rows = [index.row() for index in indexes]
for exchange in self.dataframe.iloc[rows, ]["exchange"]:
signals.exchange_modified.emit(exchange, "formula", "")
def contextMenuEvent(self, a0) -> None:
menu = QtWidgets.QMenu()
menu.addAction(self.delete_exchange_action)
menu.addAction(self.remove_formula_action)
menu.exec(a0.globalPos())
def dataChanged(self, topLeft, bottomRight, roles=None) -> None:
""" Override the slot which handles data changes in the model.
Whenever data is changed, call an update to the relevant exchange
or activity.
Four possible editable fields:
Amount, Unit, Product and Formula
"""
# A single cell was edited.
if topLeft == bottomRight:
index = self.get_source_index(topLeft)
field = AB_names_to_bw_keys[self.dataframe.columns[index.column()]]
exchange = self.dataframe.iloc[index.row(), ]["exchange"]
if field in {"amount", "formula"}:
if field == "amount":
value = float(topLeft.data())
else:
value = str(topLeft.data()) if topLeft.data() is not None else ""
signals.exchange_modified.emit(exchange, field, value)
else:
value = str(topLeft.data())
act_key = exchange.output.key
signals.activity_modified.emit(act_key, field, value)
else:
super().dataChanged(topLeft, bottomRight, roles)
def dragMoveEvent(self, event) -> None:
""" For some reason, this method existing is required for allowing
dropEvent to occur _everywhere_ in the table.
"""
pass
def dropEvent(self, event):
source_table = event.source()
keys = [source_table.get_key(i) for i in source_table.selectedIndexes()]
event.accept()
signals.exchanges_add.emit(keys, self.key)
def mouseDoubleClickEvent(self, e: QtGui.QMouseEvent) -> None:
""" Be very strict in how double click events work.
"""
proxy = self.indexAt(e.pos())
delegate = self.itemDelegateForColumn(proxy.column())
# If the column we're clicking on is not view-only try and edit
if not isinstance(delegate, ViewOnlyDelegate):
self.doubleClicked.emit(proxy)
# But only edit if the editTriggers contain DoubleClicked
if self.editTriggers() & self.DoubleClicked:
self.edit(proxy)
return
# No opening anything from the 'product' or 'biosphere' tables
if self.table_name in {"product", "biosphere"}:
return
# Grab the activity key from the exchange and open a tab
index = self.get_source_index(proxy)
row = self.dataframe.iloc[index.row(), ]
key = row["exchange"]["output"] if self.downstream else row["exchange"]["input"]
signals.open_activity_tab.emit(key)
signals.add_activity_to_history.emit(key)
class ProductExchangeTable(BaseExchangeTable):
COLUMNS = ["Amount", "Unit", "Product"]
def __init__(self, parent=None):
super().__init__(parent)
self.setItemDelegateForColumn(0, FloatDelegate(self))
self.setItemDelegateForColumn(1, StringDelegate(self))
self.setItemDelegateForColumn(2, StringDelegate(self))
self.setDragDropMode(QtWidgets.QTableView.DragDrop)
self.table_name = "product"
def create_row(self, exchange) -> (dict, object):
row, adj_act = super().create_row(exchange)
row.update({
"Product": adj_act.get("reference product") or adj_act.get("name"),
})
return row, adj_act
def _resize(self) -> None:
""" Ensure the `exchange` column is hidden whenever the table is shown.
"""
self.setColumnHidden(3, True)
def dragEnterEvent(self, event):
""" Accept exchanges from a technosphere database table, and the
technosphere exchanges table.
"""
source = event.source()
if hasattr(source, "table_name") and source.table_name == "technosphere":
event.accept()
elif hasattr(source, "technosphere") and source.technosphere is True:
event.accept()
class TechnosphereExchangeTable(BaseExchangeTable):
COLUMNS = [
"Amount", "Unit", "Product", "Activity", "Location", "Database",
"Uncertainty", "Formula"
]
def __init__(self, parent=None):
super().__init__(parent)
self.setItemDelegateForColumn(0, FloatDelegate(self))
self.setItemDelegateForColumn(1, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(2, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(3, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(4, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(5, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(6, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(7, StringDelegate(self))
self.setDragDropMode(QtWidgets.QTableView.DragDrop)
self.table_name = "technosphere"
self.drag_model = True
def create_row(self, exchange) -> (dict, object):
row, adj_act = super().create_row(exchange)
row.update({
"Product": adj_act.get("reference product") or adj_act.get("name"),
"Activity": adj_act.get("name"),
"Location": adj_act.get("location", "Unknown"),
"Database": adj_act.get("database"),
"Uncertainty": adj_act.get("uncertainty type", 0),
"Formula": exchange.get("formula", ""),
})
return row, adj_act
def _resize(self) -> None:
""" Ensure the `exchange` column is hidden whenever the table is shown.
"""
self.setColumnHidden(8, True)
def dragEnterEvent(self, event):
""" Accept exchanges from a technosphere database table, and the
downstream exchanges table.
"""
source = event.source()
if isinstance(source, DownstreamExchangeTable):
event.accept()
elif hasattr(source, "technosphere") and source.technosphere is True:
event.accept()
class BiosphereExchangeTable(BaseExchangeTable):
COLUMNS = [
"Amount", "Unit", "Flow Name", "Compartments", "Database",
"Uncertainty", "Formula"
]
def __init__(self, parent=None):
super().__init__(parent)
self.setItemDelegateForColumn(0, FloatDelegate(self))
self.setItemDelegateForColumn(1, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(2, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(3, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(4, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(5, ViewOnlyDelegate(self))
self.setItemDelegateForColumn(6, StringDelegate(self))
self.table_name = "biosphere"
self.setDragDropMode(QtWidgets.QTableView.DropOnly)
def create_row(self, exchange) -> (dict, object):
row, adj_act = super().create_row(exchange)
row.update({
"Flow Name": adj_act.get("name"),
"Compartments": " - ".join(adj_act.get('categories', [])),
"Database": adj_act.get("database"),
"Uncertainty": adj_act.get("uncertainty type", 0),
"Formula": exchange.get("formula"),
})
return row, adj_act
def _resize(self) -> None:
self.setColumnHidden(7, True)
def dragEnterEvent(self, event):
""" Only accept exchanges from a technosphere database table
"""
source = event.source()
if hasattr(source, "technosphere") and source.technosphere is False:
event.accept()
class DownstreamExchangeTable(TechnosphereExchangeTable):
""" Inherit from the `TechnosphereExchangeTable` as the downstream class is
very similar.
"""
def __init__(self, parent=None):
super().__init__(parent)
# Override the amount column to be a view-only delegate
self.setItemDelegateForColumn(0, ViewOnlyDelegate(self))
self.downstream = True
self.table_name = "downstream"
self.drag_model = True
self.setDragDropMode(QtWidgets.QTableView.DragOnly)
def _resize(self) -> None:
""" Next to `exchange`, also hide the `formula` column.
"""
self.setColumnHidden(7, True)
self.setColumnHidden(8, True)
def contextMenuEvent(self, a0) -> None:
pass
class ExchangeTable(ABTableWidget):
""" All tables shown in the ActivityTab are instances of this class (inc. non-exchange types)
Differing Views and Behaviours of tables are handled based on their tableType
todo(?): possibly preferable to subclass for distinct table functionality, rather than conditionals in one class
The tables include functionalities: drag-drop, context menus, in-line value editing
The read-only/editable status of tables is handled in ActivityTab.set_exchange_tables_read_only()
Instantiated with headers but without row-data
Then set_queryset() called from ActivityTab with params
set_queryset calls Sync() to fill and format table data items
todo(?): the variables which are initiated as defaults then later populated in set_queryset() can be passed at init
Therefore this class could be simplified by removing self.qs,upstream,database defaults etc.
todo(?): column names determined by properties included in the activity and exchange?
this would mean less hard-coding of column titles and behaviour. But rather dynamic generation
and flexible editing based on assumptions about data types etc.
"""
COLUMN_LABELS = { # {exchangeTableName: headers}
"products": ["Amount", "Unit", "Product"], #, "Location", "Uncertainty"],
# technosphere inputs & Downstream product-consuming activities included as "technosphere"
# todo(?) should the table functionality for downstream activities really be identical to technosphere inputs?
"technosphere": ["Amount", "Unit", "Product", "Activity", "Location", "Database", "Uncertainty", "Formula"],
"biosphere": ["Amount", "Unit", "Flow Name", "Compartments", "Database", "Uncertainty"],
}
def __init__(self, parent=None, tableType=None):
super(ExchangeTable, self).__init__()
self.setDragEnabled(True)
self.setAcceptDrops(False)
self.setSortingEnabled(True)
self.tableType = tableType
self.column_labels = self.COLUMN_LABELS[self.tableType]
self.setColumnCount(len(self.column_labels))
# default values, updated later in set_queryset()
self.qs, self.downstream, self.database = None, False, None
# ignore_changes set to True whilst sync() executes to prevent conflicts(?)
self.ignore_changes = False
self.setup_context_menu()
self.connect_signals()
self.setSizePolicy(QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Maximum)
)
def setup_context_menu(self):
# todo: different table types require different context menu actions
self.delete_exchange_action = QtWidgets.QAction(
QtGui.QIcon(icons.delete), "Delete exchange(s)", None
)
self.addAction(self.delete_exchange_action)
self.delete_exchange_action.triggered.connect(self.delete_exchanges)
def connect_signals(self):
# todo: different table types require different signals connected
signals.database_changed.connect(self.update_when_database_has_changed)
self.cellChanged.connect(self.filter_change)
self.cellDoubleClicked.connect(self.handle_double_clicks)
def delete_exchanges(self, event):
signals.exchanges_deleted.emit(
[x.exchange for x in self.selectedItems()]
)
def dragEnterEvent(self, event):
acceptable = (
ExchangeTable,
ActivitiesBiosphereTable,
)
if isinstance(event.source(), acceptable):
event.accept()
def dropEvent(self, event):
source_table = event.source()
print('Dropevent from:', source_table)
keys = [source_table.get_key(i) for i in source_table.selectedIndexes()]
signals.exchanges_add.emit(keys, self.qs._key)
# items = event.source().selectedItems()
# if isinstance(items[0], ABTableItem):
# signals.exchanges_add.emit([x.key for x in items], self.qs._key)
# else:
# print(items)
# print(items.exchange)
# signals.exchanges_output_modified.emit(
# [x.exchange for x in items], self.qs._key
# )
event.accept()
def update_when_database_has_changed(self, database):
if self.database == database:
self.sync()
def filter_change(self, row, col):
try:
item = self.item(row, col)
if self.ignore_changes: # todo: check or remove
return
elif item.text() == item.previous:
return
else:
print("row:", row)
if col == 0: # expect number todo: improve substantially!
value = float(item.text())
item.previous = item.text()
exchange = item.exchange
signals.exchange_amount_modified.emit(exchange, value)
else: # exepct string
fields = {1: "unit", 2: "reference product"}
print("here 2")
act = item.exchange.output.key
value = str(item.text())
item.previous = item.text()
signals.activity_modified.emit(act, fields[col], value)
except ValueError:
print('You can only enter numbers here.')
item.setText(item.previous)
def handle_double_clicks(self, row, col):
""" handles double-click events rather than clicks... rename? """
item = self.item(row, col)
print("double-clicked on:", row, col, item.text())
# double clicks ignored for these table types and item flags (until an 'exchange edit' interface is written)
if self.tableType == "products" or self.tableType == "biosphere" or (item.flags() & QtCore.Qt.ItemIsEditable):
return
if hasattr(item, "exchange"):
# open the activity of the row which was double clicked in the table
if self.upstream:
key = item.exchange['output']
else:
key = item.exchange['input']
signals.open_activity_tab.emit(key)
signals.add_activity_to_history.emit(key)
def set_queryset(self, database, qs, limit=100, downstream=False):
# todo(?): rename function: it calls sync() - which appears to do more than just setting the queryset
# todo: use table paging rather than a hard arbitrary 'limit'. Could also increase load speed
# .upstream() exposes the exchanges which consume this activity.
self.database, self.qs, self.upstream = database, qs, downstream
self.sync(limit)
@ABTableWidget.decorated_sync
def sync(self, limit=100):
""" populates an exchange table view with data about the exchanges, bios flows, and adjacent activities """
self.ignore_changes = True
self.setRowCount(min(len(self.qs), limit))
self.setHorizontalHeaderLabels(self.column_labels)
if self.upstream:
# ideally these should not be set in the data syncing function
# todo: refactor so that on initialisation, the 'upstream' state is known so state can be set there
self.setDragEnabled(False)
self.setAcceptDrops(False)
# edit_flag is passed to table items which should be user-editable.
# Default flag for cells is uneditable - which still allows cell-selection/highlight
edit_flag = [QtCore.Qt.ItemIsEditable]
# todo: add a setting which allows user to choose their preferred number formatting, for use in tables
# e.g. a choice between all standard form: {0:.3e} and current choice: {:.3g}. Or more flexibility
amount_format_string = "{:.3g}"
for row, exc in enumerate(self.qs):
# adj_act is not the open activity, but rather one of the activities connected adjacently via an exchange
# When open activity is upstream of the two...
# The adjacent activity we want to view is the output of the exchange which connects them. And vice versa
adj_act = exc.output if self.upstream else exc.input
if row == limit:
break
if self.tableType == "products":
# headers: "Amount", "Unit", "Product", "Location", "Uncertainty"
self.setItem(row, 0, ABTableItem(
amount_format_string.format(exc.get('amount')), exchange=exc, set_flags=edit_flag, color="amount"))
self.setItem(row, 1, ABTableItem(
adj_act.get('unit', 'Unknown'), exchange=exc, set_flags=edit_flag, color="unit"))
self.setItem(row, 2, ABTableItem(
# correct reference product name is stored in the exchange itself and not the activity
# adj_act.get('reference product') or adj_act.get("name") if self.upstream else
adj_act.get('reference product') or adj_act.get("name"),
exchange=exc, set_flags=edit_flag, color="reference product"))
# self.setItem(row, 3, ABTableItem(
# # todo: remove? it makes no sense to show the (open) activity location...
# # showing exc locations (as now) makes sense. But they rarely have one...
# # I believe they usually implicitly inherit the location of the producing activity
# str(exc.get('location', '')), color="location"))
# # todo: can both outputs and inputs of a process both have uncertainty data?
# self.setItem(row, 3, ABTableItem(
# str(exc.get("uncertainty type", ""))))
elif self.tableType == "technosphere":
# headers: "Amount", "Unit", "Product", "Activity", "Location", "Database", "Uncertainty", "Formula"
self.setItem(row, 0, ABTableItem(
amount_format_string.format(exc.get('amount')), exchange=exc, set_flags=edit_flag, color="amount"))
self.setItem(row, 1, ABTableItem(
adj_act.get('unit', 'Unknown'), exchange=exc, color="unit"))
self.setItem(row, 2, ABTableItem( # product
# if statement used to show different activities for products and downstream consumers tables
# reference product shown, and if absent, just the name of the activity or exchange...
# would this produce inconsistent/unclear behaviour for users?
adj_act.get('reference product') or adj_act.get("name") if self.upstream else
exc.get('reference product') or exc.get("name"),
exchange=exc, color="reference product"))
self.setItem(row, 3, ABTableItem( # name of adjacent activity (up or downstream depending on table)
adj_act.get('name'), exchange=exc, color="name"))
self.setItem(row, 4, ABTableItem(
str(adj_act.get('location', '')), exchange=exc, color="location"))
self.setItem(row, 5, ABTableItem(
adj_act.get('database'), exchange=exc, color="database"))
self.setItem(row, 6, ABTableItem(
str(exc.get("uncertainty type", "")), exchange=exc,))
self.setItem(row, 7, ABTableItem(
exc.get('formula', ''), exchange=exc,))
elif self.tableType == "biosphere":
# headers: "Amount", "Unit", "Flow Name", "Compartments", "Database", "Uncertainty"
self.setItem(row, 0, ABTableItem(
amount_format_string.format(exc.get('amount')), exchange=exc, set_flags=edit_flag, color="amount"))
self.setItem(row, 1, ABTableItem(
adj_act.get('unit', 'Unknown'), exchange=exc, color="unit"))
self.setItem(row, 2, ABTableItem(
adj_act.get('name'), exchange=exc, color="product"))
self.setItem(row, 3, ABTableItem(
" - ".join(adj_act.get('categories', [])), exchange=exc, color="categories"))
self.setItem(row, 4, ABTableItem(
adj_act.get('database'), exchange=exc, color="database"))
self.setItem(row, 5, ABTableItem(
str(exc.get("uncertainty type", "")), exchange=exc))
# todo: investigate BW: can flows have both a Formula and an Amount? Or mutually exclusive?
# what if they have both, and they contradict? Is this handled in BW - so AB doesn't need to worry?
# is the amount calculated and persisted separately to the formula?
# if not - optimal behaviour of this table is: show Formula instead of amount in 1st col when present?
self.setItem(row, 6, ABTableItem(exc.get('formula', ''), exchange=exc, ))
self.ignore_changes = False
# start of a simplified way to handle these tables...
class ExchangesTablePrototype(ABTableWidget):
amount_format_string = "{:.3g}"
def __init__(self, parent=None):
super(ExchangesTablePrototype, self).__init__()
self.column_labels = [bw_keys_to_AB_names[val] for val in self.COLUMNS.values()]
self.setColumnCount(len(self.column_labels))
self.setSizePolicy(QtWidgets.QSizePolicy(
QtWidgets.QSizePolicy.Preferred,
QtWidgets.QSizePolicy.Maximum)
)
def set_queryset(self, database, qs, limit=100, upstream=False):
self.database, self.qs, self.upstream = database, qs, upstream
# print("Queryset:", self.database, self.qs, self.upstream)
self.sync(limit)