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