ModelFlowIb 1.46__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ModelFlowIb-1.46.dist-info/METADATA +151 -0
- ModelFlowIb-1.46.dist-info/RECORD +48 -0
- ModelFlowIb-1.46.dist-info/WHEEL +5 -0
- ModelFlowIb-1.46.dist-info/top_level.txt +44 -0
- data/ken_base.pcim +1 -0
- modelBLfunk.py +70 -0
- model_Excel.py +334 -0
- model_cvx.py +132 -0
- model_doable.py +40 -0
- model_dynare.py +164 -0
- model_financial_stability.py +88 -0
- model_ifrs9.py +88 -0
- model_latex.py +505 -0
- model_latex_class.py +478 -0
- model_latex_classpy.py +401 -0
- model_run_numba.py +15 -0
- modelclass.py +7057 -0
- modelclass2.py +463 -0
- modeldash.py +265 -0
- modeldashboot.py +202 -0
- modeldashsidebar.py +442 -0
- modeldekom.py +518 -0
- modeldiff.py +561 -0
- modelgrab.py +318 -0
- modelgrabwf2.py +554 -0
- modelhelp.py +253 -0
- modelinvert.py +211 -0
- modeljupyter.py +821 -0
- modeljupytermagic.py +267 -0
- modelmacrograb.py +98 -0
- modelmanipulation.py +1273 -0
- modelmf.py +265 -0
- modelnet.py +114 -0
- modelnewton.py +819 -0
- modelnormalize.py +348 -0
- modelpattern.py +253 -0
- modelpatternrev.py +72 -0
- modelsandbox.py +76 -0
- modelsandbox_Mixin.py +1565 -0
- modeltodo.py +31 -0
- modeluserfunk.py +97 -0
- modeluserfunk_old.py +90 -0
- modelvis.py +677 -0
- modelwidget.py +610 -0
- modelwidget_input.py +961 -0
- modelwidget_new.py +1005 -0
- modelwidget_new_new.py +1238 -0
- modelwidget_shinypy.py +935 -0
modelwidget_input.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Created on Mon Aug 9 14:46:11 2021
|
|
4
|
+
|
|
5
|
+
To define Jupyter widgets which accept user input and can update dataframes and show variables.
|
|
6
|
+
|
|
7
|
+
A user can define new widgets to suit the need for her use case. This requires some familliarity with the
|
|
8
|
+
ipywidget library https://ipywidgets.readthedocs.io/en/stable/
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
This module is a revision of the modelwidget module. Modelwidget is still around and is used for legacy and output widgets.
|
|
12
|
+
|
|
13
|
+
Ipywidgets are used
|
|
14
|
+
to define widgets which can be used in jupyter notebooks and in shiny.
|
|
15
|
+
|
|
16
|
+
:Tabwidget and basewidget: defines a **container of widgets**.
|
|
17
|
+
:updatawidget: defines a **widget to update** variables using the widgets defined in the classes mentioned abowe
|
|
18
|
+
:keep_plot_widget: Defines a **widget to display** the results from the model run made in the updatewidget
|
|
19
|
+
:sheetwidget slidewidget ect: defines a **basic widget** which can be dispayed and which might have the ability to
|
|
20
|
+
update a dataframe
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
Some methods and properties of widgets.
|
|
24
|
+
:datawidget: The ipywidget which can be dispayed and might accept input used for updating a dataframe
|
|
25
|
+
:datachildren: A list of widgets in a container widget
|
|
26
|
+
:update_df: a function which updates a dataframe
|
|
27
|
+
:reset: A function which resets the input values to the initial values.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@author: Ib
|
|
33
|
+
"""
|
|
34
|
+
# from shiny import App, event, html_dependencies, http_staticfiles, input_handler, module, reactive, render, render_image, render_plot, render_text, render_ui, req, run_app, session, types, ui
|
|
35
|
+
# from shinywidgets import output_widget, reactive_read, register_widget, render_widget
|
|
36
|
+
import ipywidgets as ipy
|
|
37
|
+
|
|
38
|
+
import pandas as pd
|
|
39
|
+
|
|
40
|
+
from ipywidgets import interact, Dropdown, Checkbox, IntRangeSlider, SelectMultiple, Layout
|
|
41
|
+
from ipywidgets import Select
|
|
42
|
+
from ipywidgets import interactive, ToggleButtons, SelectionRangeSlider, RadioButtons
|
|
43
|
+
from ipywidgets import interactive_output, HBox, VBox, link, Dropdown,Output
|
|
44
|
+
from copy import copy
|
|
45
|
+
|
|
46
|
+
import pandas as pd
|
|
47
|
+
import ipywidgets as widgets
|
|
48
|
+
|
|
49
|
+
from ipysheet import sheet, cell, current
|
|
50
|
+
from ipysheet.pandas_loader import from_dataframe, to_dataframe
|
|
51
|
+
|
|
52
|
+
from IPython.display import display, clear_output,Latex, Markdown
|
|
53
|
+
from dataclasses import dataclass,field
|
|
54
|
+
import matplotlib.pylab as plt
|
|
55
|
+
import yaml
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class singelwidget:
|
|
59
|
+
'''Parent class for widgets
|
|
60
|
+
|
|
61
|
+
Will do some common stuff'''
|
|
62
|
+
|
|
63
|
+
def __init__(self,widgetdef):
|
|
64
|
+
'''
|
|
65
|
+
Some common properties and methods are defines.
|
|
66
|
+
|
|
67
|
+
**Sets these properties:**
|
|
68
|
+
|
|
69
|
+
- self.widgetdef = widgetdef
|
|
70
|
+
- self.content = self.widgetdef['content'] the content of this widget
|
|
71
|
+
- self heading = self.widgetdef['heading'] the heading for this widget.
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
Parameters
|
|
76
|
+
----------
|
|
77
|
+
widgetdef : dict
|
|
78
|
+
A dict with the descrition of a widget
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
Returns
|
|
82
|
+
-------
|
|
83
|
+
None.
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
'''
|
|
88
|
+
# breakpoint()
|
|
89
|
+
self.widgetdef = widgetdef
|
|
90
|
+
self.content = widgetdef['content']
|
|
91
|
+
self.heading = widgetdef.get('heading','')
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def update_df(self,df,current_per):
|
|
95
|
+
''' will update container widgets'''
|
|
96
|
+
try:
|
|
97
|
+
for w in self.datachildren:
|
|
98
|
+
w.update_df(df,current_per)
|
|
99
|
+
except:
|
|
100
|
+
...
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def reset(self,g):
|
|
104
|
+
''' will reset container widgets '''
|
|
105
|
+
try:
|
|
106
|
+
for w in self.datachildren:
|
|
107
|
+
w.reset(g)
|
|
108
|
+
except:
|
|
109
|
+
...
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class basewidget(singelwidget):
|
|
114
|
+
''' basis for widget updating in jupyter'''
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def __init__(self,widgetdef ):
|
|
119
|
+
super().__init__(widgetdef)
|
|
120
|
+
|
|
121
|
+
# breakpoint()
|
|
122
|
+
self.datachildren = [globals()[widgettype+'widget'](widgetdict)
|
|
123
|
+
for widgettype,widgetdict in self.content ]
|
|
124
|
+
|
|
125
|
+
self.datawidget = VBox([child.datawidget for child in self.datachildren])
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def update_df(self,df,current_per):
|
|
129
|
+
''' will update container widgets'''
|
|
130
|
+
for w in self.datachildren:
|
|
131
|
+
w.update_df(df,current_per)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def reset(self,g):
|
|
136
|
+
''' will reset container widgets'''
|
|
137
|
+
for w in self.datachildren:
|
|
138
|
+
w.reset(g)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class tabwidget(singelwidget):
|
|
143
|
+
'''A widget to create tab or acordium contaners'''
|
|
144
|
+
|
|
145
|
+
# widgetdef : dict
|
|
146
|
+
# expname : str = "Carbon tax rate, US$ per tonn "
|
|
147
|
+
# tab: bool =True
|
|
148
|
+
|
|
149
|
+
def __init__(self,widgetdef):
|
|
150
|
+
# self.tabdefdict = self.widgetdef['content']
|
|
151
|
+
super().__init__(widgetdef)
|
|
152
|
+
self.selected_index = widgetdef.get('selected_index','0')
|
|
153
|
+
self.tab = widgetdef.get('tab',True)
|
|
154
|
+
self.tabdefheadings = [subtabdef[0] for subtabdef in self.content]
|
|
155
|
+
|
|
156
|
+
thiswidget = widgets.Tab if self.tab else widgets.Accordion
|
|
157
|
+
# breakpoint()
|
|
158
|
+
|
|
159
|
+
self.datachildren = [globals()[subwidgettype+'widget'](subwidgetdict)
|
|
160
|
+
for tabheading,(subwidgettype,subwidgetdict) in self.content ]
|
|
161
|
+
|
|
162
|
+
self.datawidget = thiswidget([child.datawidget for child in self.datachildren],
|
|
163
|
+
selected_index = self.selected_index,
|
|
164
|
+
layout={'height': 'max-content'})
|
|
165
|
+
|
|
166
|
+
for i,key in enumerate(self.tabdefheadings):
|
|
167
|
+
self.datawidget.set_title(i,key)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def update_df(self,df,current_per):
|
|
171
|
+
''' will update container widgets'''
|
|
172
|
+
for w in self.datachildren:
|
|
173
|
+
w.update_df(df,current_per)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def reset(self,g):
|
|
177
|
+
''' will reset container widgets'''
|
|
178
|
+
for w in self.datachildren:
|
|
179
|
+
w.reset(g)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class sheetwidget(singelwidget):
|
|
185
|
+
''' class defefining a widget with lines of slides '''
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def __init__(self,widgetdef ):
|
|
189
|
+
...
|
|
190
|
+
super().__init__(widgetdef)
|
|
191
|
+
# print(f'{self.content=}')
|
|
192
|
+
self.df_var =self.content # input dataframe to update
|
|
193
|
+
self.trans = widgetdef.get('trans',lambda x:x) # Translation of variable names
|
|
194
|
+
self.transpose = widgetdef.get('transpose',False)# if the dataframs should be transpossed
|
|
195
|
+
# print(f'{self.transpose=}')
|
|
196
|
+
self.wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
newnamedf = self.df_var.copy().rename(columns=self.trans)
|
|
200
|
+
self.org_df_var = newnamedf.T if self.transpose else newnamedf
|
|
201
|
+
|
|
202
|
+
self.wsheet = sheet(from_dataframe(self.org_df_var),column_resizing=True,row_headers=False)
|
|
203
|
+
|
|
204
|
+
self.org_values = [c.value for c in self.wsheet.cells]
|
|
205
|
+
# breakpoint()
|
|
206
|
+
self.datawidget=widgets.VBox([self.wexp,self.wsheet]) if len(self.heading) else self.wsheet
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def update_df(self,df,current_per=None):
|
|
210
|
+
# breakpoint()
|
|
211
|
+
self.df_new_var = to_dataframe(self.wsheet).T if self.transpose else to_dataframe(self.wsheet)
|
|
212
|
+
self.df_new_var.columns = self.df_var.columns
|
|
213
|
+
self.df_new_var.index = self.df_var.index
|
|
214
|
+
|
|
215
|
+
df.loc[self.df_new_var.index,self.df_new_var.columns] = df.loc[ self.df_new_var.index,self.df_new_var.columns] + self.df_new_var
|
|
216
|
+
pass
|
|
217
|
+
return df
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def reset(self,g):
|
|
221
|
+
for c,v in zip(self.wsheet.cells,self.org_values):
|
|
222
|
+
c.value = v
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class slidewidget(singelwidget):
|
|
226
|
+
''' class defefining a widget with lines of slides '''
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def __init__(self,widgetdef ):
|
|
231
|
+
...
|
|
232
|
+
super().__init__(widgetdef)
|
|
233
|
+
self.altname = self.widgetdef .get('altname','Alternative')
|
|
234
|
+
self.basename = self.widgetdef .get('basename','Baseiline')
|
|
235
|
+
# breakpoint()
|
|
236
|
+
|
|
237
|
+
wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
|
|
238
|
+
walt = widgets.Label(value = self.altname,layout={'width':'8%', 'border':"hide"})
|
|
239
|
+
wbas = widgets.Label(value = self.basename,layout={'width':'10%', 'border':"hide"})
|
|
240
|
+
whead = widgets.HBox([wexp,walt,wbas])
|
|
241
|
+
#
|
|
242
|
+
# breakpoint()
|
|
243
|
+
self.wset = [widgets.FloatSlider(description=des,
|
|
244
|
+
min=cont['min'],
|
|
245
|
+
max=cont['max'],
|
|
246
|
+
value=cont['value'],
|
|
247
|
+
step=cont.get('step',0.01),
|
|
248
|
+
layout={'width':'60%'},style={'description_width':'40%'},
|
|
249
|
+
readout_format = f":>,.{cont.get('dec',2)}f",
|
|
250
|
+
continuous_update=False
|
|
251
|
+
)
|
|
252
|
+
for des,cont in self.content.items()]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
for w in self.wset:
|
|
256
|
+
w.observe(self.set_slide_value,names='value',type='change')
|
|
257
|
+
|
|
258
|
+
waltval= [widgets.Label(
|
|
259
|
+
value=f"{cont['value']:>,.{cont.get('dec',2)}f}",
|
|
260
|
+
layout=widgets.Layout(display="flex", justify_content="center", width="10%", border="hide"))
|
|
261
|
+
for des,cont in self.content.items()
|
|
262
|
+
|
|
263
|
+
]
|
|
264
|
+
self.wslide = [widgets.HBox([s,v]) for s,v in zip(self.wset,waltval)]
|
|
265
|
+
self.slidewidget = widgets.VBox([whead] + self.wslide)
|
|
266
|
+
self.datawidget = widgets.VBox([whead] + self.wslide)
|
|
267
|
+
|
|
268
|
+
# define the result object
|
|
269
|
+
self.current_values = {des:
|
|
270
|
+
{key : v.split() if key=='var' else v for key,v in cont.items() if key in {'value','var','op'}}
|
|
271
|
+
for des,cont in self.widgetdef ['content'].items()}
|
|
272
|
+
|
|
273
|
+
# register_widget(self.widget_id, self.datawidget)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def reset(self,g):
|
|
277
|
+
for i,(des,cont) in enumerate(self.content .items()):
|
|
278
|
+
self.wset[i].value = cont['value']
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def update_df(self,df,current_per):
|
|
283
|
+
''' updates a dataframe with the values from the widget'''
|
|
284
|
+
for i,(des,cont) in enumerate(self.current_values.items()):
|
|
285
|
+
op = cont.get('op','=')
|
|
286
|
+
value = cont['value']
|
|
287
|
+
for var in cont['var']:
|
|
288
|
+
if op == '+':
|
|
289
|
+
df.loc[current_per,var] = df.loc[current_per,var] + value
|
|
290
|
+
elif op == '+impulse':
|
|
291
|
+
df.loc[current_per[0],var] = df.loc[current_per[0],var] + value
|
|
292
|
+
elif op == '=start-':
|
|
293
|
+
startindex = df.index.get_loc(current_per[0])
|
|
294
|
+
varloc = df.columns.get_loc(var)
|
|
295
|
+
df.iloc[:startindex,varloc] = value
|
|
296
|
+
elif op == '=':
|
|
297
|
+
df.loc[current_per,var] = value
|
|
298
|
+
elif op == '=impulse':
|
|
299
|
+
df.loc[current_per[0],var] = value
|
|
300
|
+
elif op == '%':
|
|
301
|
+
df.loc[current_per,var] = df.loc[current_per,var] * (1-value/100)
|
|
302
|
+
else:
|
|
303
|
+
print(f'Wrong operator in {cont}.\nNot updated')
|
|
304
|
+
assert 1==3,'wRONG OPERATOR'
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def set_slide_value(self,g):
|
|
308
|
+
''' updates the new values to the self.current_vlues
|
|
309
|
+
will be used in update_df
|
|
310
|
+
'''
|
|
311
|
+
line_des = g['owner'].description
|
|
312
|
+
if 0:
|
|
313
|
+
print()
|
|
314
|
+
for k,v in g.items():
|
|
315
|
+
print(f'{k}:{v}')
|
|
316
|
+
|
|
317
|
+
self.current_values[line_des]['value'] = g['new']
|
|
318
|
+
|
|
319
|
+
class sumslidewidget(singelwidget):
|
|
320
|
+
''' class defefining a widget with lines of slides the sum of the input variables can max be the parameter
|
|
321
|
+
maxsum (default=1.0) '''
|
|
322
|
+
def __init__(self,widgetdef ):
|
|
323
|
+
...
|
|
324
|
+
super().__init__(widgetdef)
|
|
325
|
+
self.altname = self.widgetdef .get('altname','Alternative')
|
|
326
|
+
self.basename = self.widgetdef .get('basename','Baseiline')
|
|
327
|
+
self.maxsum = self.widgetdef .get('maxsum',1.0)
|
|
328
|
+
# breakpoint()
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
self.first = list(self.content.keys())[:-1]
|
|
332
|
+
self.lastdes = list(self.content.keys())[-1]
|
|
333
|
+
|
|
334
|
+
wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
|
|
335
|
+
walt = widgets.Label(value = self.altname,layout={'width':'8%', 'border':"hide"})
|
|
336
|
+
wbas = widgets.Label(value = self.basename,layout={'width':'10%', 'border':"hide"})
|
|
337
|
+
whead = widgets.HBox([wexp,walt,wbas])
|
|
338
|
+
#
|
|
339
|
+
self.wset = [widgets.FloatSlider(description=des,
|
|
340
|
+
min=cont['min'],
|
|
341
|
+
max=cont['max'],
|
|
342
|
+
value=cont['value'],
|
|
343
|
+
step=cont.get('step',0.01),
|
|
344
|
+
layout={'width':'60%'},style={'description_width':'40%'},
|
|
345
|
+
readout_format = f":>,.{cont.get('dec',2)}f",
|
|
346
|
+
continuous_update=False,
|
|
347
|
+
disabled= False
|
|
348
|
+
)
|
|
349
|
+
for des,cont in self.content.items()]
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
for w in self.wset:
|
|
354
|
+
w.observe(self.set_slide_value,names='value',type='change')
|
|
355
|
+
|
|
356
|
+
waltval= [widgets.Label(
|
|
357
|
+
value=f"{cont['value']:>,.{cont.get('dec',2)}f}",
|
|
358
|
+
layout=widgets.Layout(display="flex", justify_content="center", width="10%", border="hide"))
|
|
359
|
+
for des,cont in self.content.items()
|
|
360
|
+
|
|
361
|
+
]
|
|
362
|
+
self.wslide = [widgets.HBox([s,v]) for s,v in zip(self.wset,waltval)]
|
|
363
|
+
self.slidewidget = widgets.VBox([whead] + self.wslide)
|
|
364
|
+
self.datawidget = widgets.VBox([whead] + self.wslide)
|
|
365
|
+
|
|
366
|
+
# define the result object
|
|
367
|
+
self.current_values = {des:
|
|
368
|
+
{key : v.split() if key=='var' else v for key,v in cont.items() if key in {'value','var','op','min','max'}}
|
|
369
|
+
for des,cont in self.content.items()}
|
|
370
|
+
|
|
371
|
+
def reset(self,g):
|
|
372
|
+
for i,(des,cont) in enumerate(self.content.items()):
|
|
373
|
+
self.wset[i].value = cont['value']
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def update_df(self,df,current_per):
|
|
378
|
+
''' updates a dataframe with the values from the widget'''
|
|
379
|
+
for i,(des,cont) in enumerate(self.current_values.items()):
|
|
380
|
+
op = cont.get('op','=')
|
|
381
|
+
value = cont['value']
|
|
382
|
+
for var in cont['var']:
|
|
383
|
+
if op == '+':
|
|
384
|
+
df.loc[current_per,var] = df.loc[current_per,var] + value
|
|
385
|
+
elif op == '+impulse':
|
|
386
|
+
df.loc[current_per[0],var] = df.loc[current_per[0],var] + value
|
|
387
|
+
elif op == '=start-':
|
|
388
|
+
startindex = df.index.get_loc(current_per[0])
|
|
389
|
+
varloc = df.columns.get_loc(var)
|
|
390
|
+
df.iloc[:startindex,varloc] = value
|
|
391
|
+
elif op == '=':
|
|
392
|
+
df.loc[current_per,var] = value
|
|
393
|
+
elif op == '=impulse':
|
|
394
|
+
df.loc[current_per[0],var] = value
|
|
395
|
+
else:
|
|
396
|
+
print(f'Wrong operator in {cont}.\nNot updated')
|
|
397
|
+
assert 1==3,'wRONG OPERATOR'
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def set_slide_value(self,g):
|
|
401
|
+
''' updates the new values to the self.current_vlues
|
|
402
|
+
will be used in update_df
|
|
403
|
+
'''
|
|
404
|
+
line_des = g['owner'].description
|
|
405
|
+
line_index = list(self.current_values.keys()).index(line_des)
|
|
406
|
+
if 0:
|
|
407
|
+
print()
|
|
408
|
+
for k,v in g.items():
|
|
409
|
+
print(f'{k}:{v}')
|
|
410
|
+
|
|
411
|
+
self.current_values[line_des]['value'] = g['new']
|
|
412
|
+
# print(f'{self.current_values=}')
|
|
413
|
+
if type(self.maxsum) == float:
|
|
414
|
+
allvalues = [v['value'] for v in self.current_values.values()]
|
|
415
|
+
thissum = sum(allvalues)
|
|
416
|
+
if thissum > self.maxsum:
|
|
417
|
+
# print(f'{allvalues=}')
|
|
418
|
+
# print(f"{self.current_values[self.lastdes]['min']=}")
|
|
419
|
+
newlast = self.maxsum-sum(allvalues[:-1])
|
|
420
|
+
newlast = max(newlast,self.current_values[self.lastdes]['min'])
|
|
421
|
+
# print(f'{newlast=}')
|
|
422
|
+
self.current_values[self.lastdes]['value']= newlast
|
|
423
|
+
|
|
424
|
+
newsum= sum([v['value'] for v in self.current_values.values()])
|
|
425
|
+
# print(f'{newsum=}')
|
|
426
|
+
# print(f'{line_index=}')
|
|
427
|
+
if newsum > self.maxsum:
|
|
428
|
+
self.current_values[line_des]['value']=self.wset[line_index].value-newsum +self.maxsum
|
|
429
|
+
self.wset[line_index].value = self.current_values[line_des]['value']
|
|
430
|
+
|
|
431
|
+
self.wset[-1].value = newlast
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
class radiowidget(singelwidget):
|
|
435
|
+
''' class defining a widget with a number of radiobutton groups
|
|
436
|
+
|
|
437
|
+
When df_update is executed the cheked variable will be set to 1 the other to 0
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
{'<heading 1> [['text1','variable1'],
|
|
442
|
+
['text2','variable2']
|
|
443
|
+
.....]
|
|
444
|
+
'heading 2' [['text1','variable1'],
|
|
445
|
+
['text2','variable2']
|
|
446
|
+
.....]
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
'''
|
|
454
|
+
|
|
455
|
+
def __init__(self,widgetdef):
|
|
456
|
+
...
|
|
457
|
+
super().__init__(widgetdef)
|
|
458
|
+
|
|
459
|
+
wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
|
|
460
|
+
whead = widgets.HBox([wexp])
|
|
461
|
+
#
|
|
462
|
+
self.wradiolist = [widgets.RadioButtons(options=[i for i,j in cont],description=des,layout={'width':'70%'},
|
|
463
|
+
style={'description_width':'37%'}) for des,cont in self.content.items()]
|
|
464
|
+
if len(self.wradiolist) <=2:
|
|
465
|
+
self.wradio = widgets.HBox(self.wradiolist)
|
|
466
|
+
else:
|
|
467
|
+
self.wradio = widgets.VBox(self.wradiolist)
|
|
468
|
+
|
|
469
|
+
self.datawidget = widgets.VBox([whead] + [self.wradio])
|
|
470
|
+
|
|
471
|
+
def reset(self,g):
|
|
472
|
+
for wradio in self.wradiolist:
|
|
473
|
+
wradio.index = 0
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def update_df(self,df,current_per):
|
|
477
|
+
''' updates a dataframe with the values from the widget'''
|
|
478
|
+
for wradio,(des,cont) in zip(self.wradiolist,self.content.items()):
|
|
479
|
+
# print(f'{des=} {wradio.value=},{wradio.index=},{cont[wradio.index]=}')
|
|
480
|
+
# print(f'{cont=}')
|
|
481
|
+
for varlabel,variable in cont:
|
|
482
|
+
df.loc[current_per,variable] = 0
|
|
483
|
+
selected_variable = cont[wradio.index][1]
|
|
484
|
+
df.loc[current_per,selected_variable] = 1
|
|
485
|
+
# print(df.loc[current_per,:])
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class checkwidget(singelwidget):
|
|
489
|
+
''' class defefining a widget with a number of radiobutton groups
|
|
490
|
+
|
|
491
|
+
When df_update is executed the cheked variable will be set to 1 the other to 0
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
{
|
|
496
|
+
'<heading 1>:['variable1 variable2 ---',value ],
|
|
497
|
+
'<heading 2>:['variable10 variable20 ---',value ]
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
'''
|
|
503
|
+
def __init__(self,widgetdef):
|
|
504
|
+
...
|
|
505
|
+
super().__init__(widgetdef)
|
|
506
|
+
|
|
507
|
+
wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
|
|
508
|
+
whead = widgets.HBox([wexp])
|
|
509
|
+
#
|
|
510
|
+
self.wchecklist = [widgets.Checkbox(description=des,value=val) for des,(var,val)
|
|
511
|
+
in self.content.items()]
|
|
512
|
+
self.wcheck = widgets.VBox(self.wchecklist)
|
|
513
|
+
|
|
514
|
+
self.datawidget = widgets.VBox([whead] + [self.wcheck])
|
|
515
|
+
|
|
516
|
+
def reset(self,g):
|
|
517
|
+
for wcheck,(des,(variable,val)) in zip(self.wchecklist,self.content.items()):
|
|
518
|
+
wcheck.value = val
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def update_df(self,df,current_per):
|
|
522
|
+
''' updates a dataframe with the values from the widget'''
|
|
523
|
+
for wcheck,(des,(variable,val)) in zip(self.wchecklist,self.content.items()):
|
|
524
|
+
for selected_variable in variable.split():
|
|
525
|
+
df.loc[current_per,selected_variable] = 1.0 if wcheck.value else 0.0
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
@dataclass
|
|
530
|
+
class updatewidget:
|
|
531
|
+
''' class to input and run a model
|
|
532
|
+
|
|
533
|
+
- display(wtotal) to activate the widget
|
|
534
|
+
|
|
535
|
+
'''
|
|
536
|
+
|
|
537
|
+
mmodel : any # a model
|
|
538
|
+
datawidget : any # a widget to update from
|
|
539
|
+
basename : str ='Business as usual'
|
|
540
|
+
keeppat : str = '*'
|
|
541
|
+
varpat : str ='*'
|
|
542
|
+
showvarpat : bool = True # Show varpaths to
|
|
543
|
+
exodif : any = pd.DataFrame() # definition
|
|
544
|
+
lwrun : bool = True
|
|
545
|
+
lwupdate : bool = False
|
|
546
|
+
lwreset : bool = True
|
|
547
|
+
lwsetbas : bool = True
|
|
548
|
+
outputwidget : str = 'jupviz'
|
|
549
|
+
display_first :any = None
|
|
550
|
+
# to the plot widget
|
|
551
|
+
|
|
552
|
+
prefix_dict : dict = field(default_factory=dict)
|
|
553
|
+
vline : list = field(default_factory=list)
|
|
554
|
+
relativ_start : int = 0
|
|
555
|
+
short :bool = False
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def __post_init__(self):
|
|
560
|
+
self.baseline = self.mmodel.basedf.copy()
|
|
561
|
+
self.wrun = widgets.Button(description="Run scenario")
|
|
562
|
+
self.wrun .on_click(self.run)
|
|
563
|
+
self.wrun .tooltip = 'Click to run'
|
|
564
|
+
self.wrun.style.button_color = 'Lime'
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
wupdate = widgets.Button(description="Update the dataset ")
|
|
568
|
+
wupdate.on_click(self.update)
|
|
569
|
+
|
|
570
|
+
wreset = widgets.Button(description="Reset to start")
|
|
571
|
+
wreset.on_click(self.reset)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
wsetbas = widgets.Button(description="Use as baseline")
|
|
575
|
+
wsetbas.on_click(self.setbasis)
|
|
576
|
+
self.experiment = 0
|
|
577
|
+
|
|
578
|
+
lbut = []
|
|
579
|
+
|
|
580
|
+
if self.lwrun: lbut.append(self.wrun )
|
|
581
|
+
if self.lwupdate: lbut.append(wupdate)
|
|
582
|
+
if self.lwreset: lbut.append(wreset)
|
|
583
|
+
if self.lwsetbas : lbut.append(wsetbas)
|
|
584
|
+
|
|
585
|
+
wbut = widgets.HBox(lbut)
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
self.wname = widgets.Text(value=self.basename,placeholder='Type something',description='Scenario name:',
|
|
589
|
+
layout={'width':'30%'},style={'description_width':'50%'})
|
|
590
|
+
self.wpat = widgets.Text(value= self.varpat,placeholder='Type something',description='Display variables:',
|
|
591
|
+
layout={'width':'65%'},style={'description_width':'30%'})
|
|
592
|
+
|
|
593
|
+
self.wpat.layout.visibility = 'visible' if self.showvarpat else 'hidden'
|
|
594
|
+
|
|
595
|
+
winputstring = widgets.HBox([self.wname,self.wpat])
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
self.mmodel.keep_solutions = {}
|
|
599
|
+
self.mmodel.keep_solutions = {self.wname.value : self.baseline}
|
|
600
|
+
self.mmodel.keep_exodif = {}
|
|
601
|
+
|
|
602
|
+
self.experiment += 1
|
|
603
|
+
self.wname.value = f'Experiment {self.experiment}'
|
|
604
|
+
|
|
605
|
+
self.wtotal = VBox([widgets.HTML(value="Hello <b>World</b>")])
|
|
606
|
+
|
|
607
|
+
def init_run(g):
|
|
608
|
+
# print(f'{g=}')
|
|
609
|
+
self.varpat = g['new']
|
|
610
|
+
self.keep_ui = keep_plot_widget(mmodel = self.mmodel,
|
|
611
|
+
selectfrom = self.varpat, prefix_dict=self.prefix_dict,
|
|
612
|
+
vline=self.vline,relativ_start=self.relativ_start,
|
|
613
|
+
short = self.short)
|
|
614
|
+
|
|
615
|
+
# self.wtotal = widgets.VBox([self.datawidget.datawidget,winputstring,wbut,
|
|
616
|
+
# self.keep_ui.datawidget])
|
|
617
|
+
self.wtotal.children = [self.datawidget.datawidget,winputstring,wbut,
|
|
618
|
+
self.keep_ui.datawidget]
|
|
619
|
+
|
|
620
|
+
self.start = copy(self.mmodel.current_per[0])
|
|
621
|
+
self.slut = copy(self.mmodel.current_per[-1])
|
|
622
|
+
|
|
623
|
+
self.wpat.observe(init_run,names='value',type='change')
|
|
624
|
+
|
|
625
|
+
init_run({'new':self.varpat})
|
|
626
|
+
|
|
627
|
+
def update(self,g):
|
|
628
|
+
self.thisexperiment = self.baseline.copy()
|
|
629
|
+
# print(f'update smpl {self.mmodel.current_per=}')
|
|
630
|
+
|
|
631
|
+
self.datawidget.update_df(self.thisexperiment,self.mmodel.current_per)
|
|
632
|
+
self.exodif = self.mmodel.exodif(self.baseline,self.thisexperiment)
|
|
633
|
+
# print(f'update 2 smpl {self.mmodel.current_per[0]=}')
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def run(self,g):
|
|
639
|
+
self.update(g)
|
|
640
|
+
# print(f'run smpl {self.mmodel.current_per[0]=}')
|
|
641
|
+
# self.start = self.mmodel.current_per[0]
|
|
642
|
+
# self.slut = self.mmodel.current_per[-1]
|
|
643
|
+
# print(f'{self.start=} {self.slut=}')
|
|
644
|
+
self.wrun .tooltip = 'Running'
|
|
645
|
+
self.wrun.style.button_color = 'Red'
|
|
646
|
+
|
|
647
|
+
self.mmodel(self.thisexperiment,start=self.start,slut=self.slut,progressbar=0,keep = self.wname.value,
|
|
648
|
+
keep_variables = self.keeppat)
|
|
649
|
+
self.wrun .tooltip = 'Click to run'
|
|
650
|
+
self.wrun.style.button_color = 'Lime'
|
|
651
|
+
# print(f'run efter smpl {self.mmodel.current_per[0]=}')
|
|
652
|
+
self.mmodel.keep_exodif[self.wname.value] = self.exodif
|
|
653
|
+
self.mmodel.inputwidget_alternativerun = True
|
|
654
|
+
self.current_experiment = self.wname.value
|
|
655
|
+
self.experiment += 1
|
|
656
|
+
self.wname.value = f'Experiment {self.experiment}'
|
|
657
|
+
self.keep_ui.trigger(None)
|
|
658
|
+
|
|
659
|
+
def setbasis(self,g):
|
|
660
|
+
self.mmodel.keep_solutions={self.current_experiment:self.mmodel.keep_solutions[self.current_experiment]}
|
|
661
|
+
|
|
662
|
+
self.mmodel.keep_exodif[self.current_experiment] = self.exodif
|
|
663
|
+
self.mmodel.inputwidget_alternativerun = True
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def reset(self,g):
|
|
669
|
+
self.datawidget.reset(g)
|
|
670
|
+
|
|
671
|
+
def fig_to_image(fig,format='svg'):
|
|
672
|
+
from io import StringIO
|
|
673
|
+
f = StringIO()
|
|
674
|
+
fig.savefig(f,format=format,bbox_inches="tight")
|
|
675
|
+
f.seek(0)
|
|
676
|
+
image= f.read()
|
|
677
|
+
return image
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
@dataclass
|
|
683
|
+
class keep_plot_widget:
|
|
684
|
+
mmodel : any # a model
|
|
685
|
+
pat : str ='*'
|
|
686
|
+
smpl=('', '')
|
|
687
|
+
relativ_start : int = 0
|
|
688
|
+
selectfrom : str ='*'
|
|
689
|
+
legend=0
|
|
690
|
+
dec=''
|
|
691
|
+
use_descriptions=True
|
|
692
|
+
select_width=''
|
|
693
|
+
select_height='200px'
|
|
694
|
+
vline : list = field(default_factory=list)
|
|
695
|
+
prefix_dict : dict = field(default_factory=dict)
|
|
696
|
+
add_var_name=False
|
|
697
|
+
short :any = 0
|
|
698
|
+
multi :any = False
|
|
699
|
+
|
|
700
|
+
"""
|
|
701
|
+
Plots the keept dataframes
|
|
702
|
+
|
|
703
|
+
Args:
|
|
704
|
+
mmodel : a modelflow model instance
|
|
705
|
+
pat (str, optional): a string of variables to select pr default. Defaults to '*'.
|
|
706
|
+
smpl (tuple with 2 elements, optional): the selected smpl, has to match the dataframe index used. Defaults to ('','').
|
|
707
|
+
selectfrom (list, optional): the variables to select from, Defaults to [] -> all keept variables .
|
|
708
|
+
legend (bool, optional)c: DESCRIPTION. legends or to the right of the curve. Defaults to 1.
|
|
709
|
+
dec (string, optional): decimals on the y-axis. Defaults to '0'.
|
|
710
|
+
use_descriptions : Use the variable descriptions from the model
|
|
711
|
+
|
|
712
|
+
Returns:
|
|
713
|
+
None.
|
|
714
|
+
|
|
715
|
+
self.keep_wiz_figs is set to a dictionary containing the figures. Can be used to produce publication
|
|
716
|
+
quality files.
|
|
717
|
+
|
|
718
|
+
"""
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def __post_init__(self):
|
|
722
|
+
from copy import copy
|
|
723
|
+
minper = self.mmodel.lastdf.index[0]
|
|
724
|
+
maxper = self.mmodel.lastdf.index[-1]
|
|
725
|
+
options = [(ind, nr) for nr, ind in enumerate(self.mmodel.lastdf.index)]
|
|
726
|
+
self.old_current_per = copy(self.mmodel.current_per)
|
|
727
|
+
# print(f'Før {self.mmodel.current_per=}')
|
|
728
|
+
with self.mmodel.set_smpl(*self.smpl):
|
|
729
|
+
# print(f'efter set smpl {self.mmodel.current_per=}')
|
|
730
|
+
with self.mmodel.set_smpl_relative(self.relativ_start,0):
|
|
731
|
+
# print(f'efter set smpl relativ {self.mmodel.current_per=}')
|
|
732
|
+
...
|
|
733
|
+
show_per = copy(list(self.mmodel.current_per)[:])
|
|
734
|
+
self.mmodel.current_per = copy(self.old_current_per)
|
|
735
|
+
# print(f'efter context set smpl {self.mmodel.current_per=}')
|
|
736
|
+
# breakpoint()
|
|
737
|
+
init_start = self.mmodel.lastdf.index.get_loc(show_per[0])
|
|
738
|
+
init_end = self.mmodel.lastdf.index.get_loc(show_per[-1])
|
|
739
|
+
keepvar = sorted (list(self.mmodel.keep_solutions.values())[0].columns)
|
|
740
|
+
defaultvar = ([v for v in self.mmodel.vlist(self.pat) if v in keepvar][0],)
|
|
741
|
+
# print('******* selectfrom')
|
|
742
|
+
_selectfrom = [s.upper() for s in self.mmodel.vlist(self.selectfrom)] if self.selectfrom else keepvar
|
|
743
|
+
# _selectfrom = keepvar
|
|
744
|
+
# print(f'{_selectfrom=}')
|
|
745
|
+
gross_selectfrom = [(f'{(v+" ") if self.add_var_name else ""}{self.mmodel.var_description[v] if self.use_descriptions else v}',v) for v in _selectfrom]
|
|
746
|
+
# print(f'{gross_selectfrom=}')
|
|
747
|
+
width = self.select_width if self.select_width else '50%' if self.use_descriptions else '50%'
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
description_width = 'initial'
|
|
751
|
+
description_width_long = 'initial'
|
|
752
|
+
keep_keys = list(self.mmodel.keep_solutions.keys())
|
|
753
|
+
keep_first = keep_keys[0]
|
|
754
|
+
select_prefix = [(c,iso) for iso,c in self.prefix_dict.items()]
|
|
755
|
+
i_smpl = SelectionRangeSlider(value=[init_start, init_end], continuous_update=False, options=options, min=minper,
|
|
756
|
+
max=maxper, layout=Layout(width='75%'), description='Show interval')
|
|
757
|
+
selected_vars = SelectMultiple( options=gross_selectfrom, layout=Layout(width=width, height=self.select_height, font="monospace"),
|
|
758
|
+
description='Select one or more', style={'description_width': description_width})
|
|
759
|
+
|
|
760
|
+
diff = RadioButtons(options=[('No', False), ('Yes', True), ('In percent', 'pct')], description=fr'Difference to: "{keep_first}"',
|
|
761
|
+
value=False, style={'description_width': 'auto'}, layout=Layout(width='auto'))
|
|
762
|
+
showtype = RadioButtons(options=[('Level', 'level'), ('Growth', 'growth')],
|
|
763
|
+
description='Data type', value='level', style={'description_width': description_width})
|
|
764
|
+
scale = RadioButtons(options=[('Linear', 'linear'), ('Log', 'log')], description='Y-scale',
|
|
765
|
+
value='linear', style={'description_width': description_width})
|
|
766
|
+
#
|
|
767
|
+
legend = RadioButtons(options=[('Yes', 1), ('No', 0)], description='Legends', value=self.legend, style={
|
|
768
|
+
'description_width': description_width})
|
|
769
|
+
|
|
770
|
+
self.widget_dict = {'i_smpl': i_smpl, 'selected_vars': selected_vars, 'diff': diff, 'showtype': showtype,
|
|
771
|
+
'scale': scale, 'legend': legend}
|
|
772
|
+
for wid in self.widget_dict.values():
|
|
773
|
+
wid.observe(self.trigger,names='value',type='change')
|
|
774
|
+
|
|
775
|
+
# breakpoint()
|
|
776
|
+
self.out_widget =VBox([widgets.HTML(value="Hello <b>World</b>",
|
|
777
|
+
placeholder='',
|
|
778
|
+
description='',)])
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def get_prefix(g):
|
|
783
|
+
''' this function is triggered when the prefix selection is changed. Used only when a prefix_dict has ben set.
|
|
784
|
+
|
|
785
|
+
g['new]'] contains the new prefix
|
|
786
|
+
|
|
787
|
+
It sets the variables the user can select from
|
|
788
|
+
|
|
789
|
+
'''
|
|
790
|
+
# print(f'{g=}')
|
|
791
|
+
try:
|
|
792
|
+
# fint the suffix for the variables in the current selection of variables
|
|
793
|
+
# to ensure we get the same variables for the next prefix
|
|
794
|
+
current_suffix = {v[len(g['old'][0]):] for v in selected_vars.value}
|
|
795
|
+
except:
|
|
796
|
+
# we are at the first call to getprefix
|
|
797
|
+
current_suffix = ''
|
|
798
|
+
|
|
799
|
+
new_prefix = g['new'] # returns the selected prefix as tuple as therre can be more
|
|
800
|
+
# print(new_prefix)
|
|
801
|
+
# find the variables which starts with the prefix
|
|
802
|
+
selected_prefix_var = tuple((des,variable) for des,variable in gross_selectfrom
|
|
803
|
+
if any([variable.startswith(n) for n in new_prefix]))
|
|
804
|
+
# An exception is trigered but has no consequences
|
|
805
|
+
try:
|
|
806
|
+
selected_vars.options = selected_prefix_var # Sets the variables to be selected from
|
|
807
|
+
except:
|
|
808
|
+
...
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
# print(f'{current_suffix=} \n{selected_prefix_var=}')
|
|
812
|
+
|
|
813
|
+
if current_suffix:
|
|
814
|
+
new_selection = [f'{n}{c}' for c in current_suffix for n in new_prefix
|
|
815
|
+
if f'{n}{c}' in {s for p,s in selected_prefix_var}]
|
|
816
|
+
selected_vars.value = new_selection
|
|
817
|
+
# print(f"{new_selection=}{current_suffix=}{g['old']=}")
|
|
818
|
+
else:
|
|
819
|
+
# we are where no prefix has been selected
|
|
820
|
+
selected_vars.value = [selected_prefix_var[0][1]]
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
if len(self.prefix_dict):
|
|
824
|
+
selected_prefix = SelectMultiple(value=[select_prefix[0][1]], options=select_prefix,
|
|
825
|
+
layout=Layout(width='25%', height=self.select_height, font="monospace"),
|
|
826
|
+
description='')
|
|
827
|
+
|
|
828
|
+
selected_prefix.observe(get_prefix,names='value',type='change')
|
|
829
|
+
select = HBox([selected_vars,selected_prefix])
|
|
830
|
+
# print(f'{select_prefix=}')
|
|
831
|
+
# we call get_prefix when the widget is set up.
|
|
832
|
+
get_prefix({'new':select_prefix[0]})
|
|
833
|
+
else:
|
|
834
|
+
# no prefix, so we only have to select variable names.
|
|
835
|
+
select = VBox([selected_vars])
|
|
836
|
+
selected_vars.value = [gross_selectfrom[0][1]]
|
|
837
|
+
|
|
838
|
+
options1 = HBox([diff]) if self.short >=2 else HBox([diff,legend])
|
|
839
|
+
options2 = HBox([scale, showtype])
|
|
840
|
+
if self.short:
|
|
841
|
+
vui = [select, options1, i_smpl]
|
|
842
|
+
else:
|
|
843
|
+
vui = [select, options1, options2, i_smpl]
|
|
844
|
+
vui = vui[:-1] if self.short >= 2 else vui
|
|
845
|
+
|
|
846
|
+
self.datawidget= VBox(vui+[self.out_widget])
|
|
847
|
+
# show = interactive_output(explain, {'i_smpl': i_smpl, 'selected_vars': selected_vars, 'diff': diff, 'showtype': showtype,
|
|
848
|
+
# 'scale': scale, 'legend': legend})
|
|
849
|
+
# print('klar til register')
|
|
850
|
+
|
|
851
|
+
def explain(self, i_smpl=None, selected_vars=None, diff=None, showtype=None, scale=None, legend= None):
|
|
852
|
+
# print(f'Start explain:\n {self.mmodel.current_per[0]=}\n{selected_vars=}\n')
|
|
853
|
+
variabler = ' '.join(v for v in selected_vars)
|
|
854
|
+
smpl = (self.mmodel.lastdf.index[i_smpl[0]], self.mmodel.lastdf.index[i_smpl[1]])
|
|
855
|
+
if type(diff) == str:
|
|
856
|
+
diffpct = True
|
|
857
|
+
ldiff = False
|
|
858
|
+
else:
|
|
859
|
+
ldiff = diff
|
|
860
|
+
diffpct = False
|
|
861
|
+
|
|
862
|
+
# clear_output()
|
|
863
|
+
with self.mmodel.set_smpl(*smpl):
|
|
864
|
+
|
|
865
|
+
if self.multi:
|
|
866
|
+
self.keep_wiz_fig = self.mmodel.keep_plot_multi(variabler, diff=ldiff, diffpct = diffpct, scale=scale, showtype=showtype,
|
|
867
|
+
legend=legend, dec=self.dec, vline=self.vline)
|
|
868
|
+
else:
|
|
869
|
+
self.keep_wiz_figs = self.mmodel.keep_plot(variabler, diff=ldiff, diffpct = diffpct,
|
|
870
|
+
scale=scale, showtype=showtype,
|
|
871
|
+
legend=legend, dec=self.dec, vline=self.vline)
|
|
872
|
+
self.keep_wiz_fig = self.keep_wiz_figs[selected_vars[0]]
|
|
873
|
+
plt.close('all')
|
|
874
|
+
return self.keep_wiz_figs
|
|
875
|
+
# print(f'Efter plot {self.mmodel.current_per=}')
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
def trigger(self,g):
|
|
879
|
+
self.mmodel.current_per = copy(self.old_current_per)
|
|
880
|
+
|
|
881
|
+
values = {widname : wid.value for widname,wid in self.widget_dict.items() }
|
|
882
|
+
# print(f'Triggerd:\n{values} \n Start trigger {self.mmodel.current_per=}\n')
|
|
883
|
+
figs = self.explain(**values)
|
|
884
|
+
if 0:
|
|
885
|
+
xxx = fig_to_image(self.keep_wiz_fig,format='svg')
|
|
886
|
+
self.out_widget.children = [widgets.HTML(xxx)]
|
|
887
|
+
else:
|
|
888
|
+
yyy = [widgets.HTML(fig_to_image(a_fig),width='100%',format = 'svg',layout=Layout(width='75%'))
|
|
889
|
+
for key,a_fig in figs.items() ]
|
|
890
|
+
self.out_widget.children = yyy
|
|
891
|
+
# print(f'end trigger {self.mmodel.current_per[0]=}')
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
@dataclass
|
|
895
|
+
class shinywidget:
|
|
896
|
+
'''A to translate a widget to shiny widget '''
|
|
897
|
+
|
|
898
|
+
a_widget : any # The datawidget to wrap
|
|
899
|
+
widget_id : str
|
|
900
|
+
|
|
901
|
+
def __post_init__(self):
|
|
902
|
+
from shinywidgets import register_widget
|
|
903
|
+
...
|
|
904
|
+
register_widget(self.widget_id, self.a_widget.datawidget)
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def update_df(self,df,current_per):
|
|
908
|
+
''' will update container widgets'''
|
|
909
|
+
self.a_widget.update_df(df,current_per)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def reset(self,g):
|
|
913
|
+
''' will reset container widgets'''
|
|
914
|
+
self.a_widget.reset(g)
|
|
915
|
+
|
|
916
|
+
def make_widget(widgetdef):
|
|
917
|
+
'''
|
|
918
|
+
'''
|
|
919
|
+
|
|
920
|
+
widgettype,widgetdict = widgetdef
|
|
921
|
+
reswidget = globals()[widgettype+'widget'](widgetdict)
|
|
922
|
+
return reswidget
|
|
923
|
+
|
|
924
|
+
|
|
925
|
+
if __name__ == '__main__':
|
|
926
|
+
|
|
927
|
+
slidedef = ['slide', {'heading':'Dette er en prøve',
|
|
928
|
+
'content' :{'Productivity' : {'var':'ALFA', 'value': 0.5 ,'min':0.0, 'max':1.0},
|
|
929
|
+
'DEPRECIATES_RATE' : {'var':'DEPRECIATES_RATE', 'value': 0.05,'min':0.0, 'max':1.0},
|
|
930
|
+
'LABOR_GROWTH' : {'var':'LABOR_GROWTH', 'value': 0.01,'min':0.0, 'max':1.0},
|
|
931
|
+
'SAVING_RATIO' : {'var': 'SAVING_RATIO', 'value': 0.05,'min':0.0, 'max':1.0}
|
|
932
|
+
}} ]
|
|
933
|
+
|
|
934
|
+
radiodef = ['radio', {'heading':'Dette er en anden prøve',
|
|
935
|
+
'content' : {'Ib': [['Arbejdskraft','LABOR_GROWTH'],
|
|
936
|
+
['Opsparing','SAVING_RATIO'] ],
|
|
937
|
+
'Søren': [['alfa','ALFA'],
|
|
938
|
+
['a','A'] ],
|
|
939
|
+
'Marie': [['Hest','HEST'],
|
|
940
|
+
['Ko','KO'] ],
|
|
941
|
+
|
|
942
|
+
}} ]
|
|
943
|
+
|
|
944
|
+
checkdef = ['check', {'heading':'Dette er en treidje prøve',
|
|
945
|
+
'content' :{'Arbejdskraft':['LABOR_GROWTH KO',1],
|
|
946
|
+
'Opsparing' :['SAVING_RATIO',0] }}]
|
|
947
|
+
|
|
948
|
+
alldef = [slidedef] + [radiodef] + [checkdef]
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
tabdef = ['tab',{'content':[['Den første',['base',{'content':alldef}]],
|
|
952
|
+
['Den anden' ,['base',{'content':alldef}]]]
|
|
953
|
+
,
|
|
954
|
+
'tab':False}]
|
|
955
|
+
|
|
956
|
+
basedef = ['base',{'content':[slidedef,radiodef]}]
|
|
957
|
+
|
|
958
|
+
xx = make_widget(tabdef)
|
|
959
|
+
|
|
960
|
+
# print(yaml.dump(tabdef,indent=4))
|
|
961
|
+
|