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_new_new.py ADDED
@@ -0,0 +1,1238 @@
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.
6
+
7
+ this version is made to make is easy to define input widgets as dictikonaries.
8
+
9
+ @author: Ib
10
+ """
11
+ # 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
12
+ # from shinywidgets import output_widget, reactive_read, register_widget, render_widget
13
+ import ipywidgets as ipy
14
+
15
+ import pandas as pd
16
+
17
+ from ipywidgets import interact, Dropdown, Checkbox, IntRangeSlider, SelectMultiple, Layout
18
+ from ipywidgets import Select
19
+ from ipywidgets import interactive, ToggleButtons, SelectionRangeSlider, RadioButtons
20
+ from ipywidgets import interactive_output, HBox, VBox, link, Dropdown,Output
21
+ from copy import copy
22
+
23
+ import pandas as pd
24
+ import ipywidgets as widgets
25
+
26
+ from ipysheet import sheet, cell, current
27
+ from ipysheet.pandas_loader import from_dataframe, to_dataframe
28
+
29
+ from IPython.display import display, clear_output,Latex, Markdown
30
+ from dataclasses import dataclass,field
31
+ import matplotlib.pylab as plt
32
+ import yaml
33
+
34
+
35
+ class singelwidget:
36
+ '''Parent class for widgets
37
+
38
+ Will do some common stuff'''
39
+
40
+ def __init__(self,widgetdef):
41
+ '''
42
+
43
+
44
+ Parameters
45
+ ----------
46
+ widgetdef : dict
47
+ A dict with the descrition of a widget
48
+
49
+ Sets properties
50
+ ----------------
51
+ self.widgetdef = widgetdef
52
+ self.content = self.widgetdef['content'] the content of this widget
53
+ self heading = self.widgetdef['heading'] the heading for this widget.
54
+
55
+ Returns
56
+ -------
57
+ None.
58
+
59
+ '''
60
+ # breakpoint()
61
+ self.widgetdef = widgetdef
62
+ self.content = widgetdef['content']
63
+ self.heading = widgetdef.get('heading','')
64
+
65
+
66
+ def update_df(self,df,current_per):
67
+ ''' will update container widgets'''
68
+ try:
69
+ for w in self.datachildren:
70
+ w.update_df(df,current_per)
71
+ except:
72
+ ...
73
+
74
+
75
+ def reset(self,g):
76
+ ''' will reset container widgets '''
77
+ try:
78
+ for w in self.datachildren:
79
+ w.reset(g)
80
+ except:
81
+ ...
82
+
83
+
84
+
85
+ class basewidget(singelwidget):
86
+ ''' basis for widget updating in jupyter'''
87
+
88
+
89
+
90
+ def __init__(self,widgetdef ):
91
+ super().__init__(widgetdef)
92
+
93
+ # breakpoint()
94
+ self.datachildren = [globals()[widgettype+'widget'](widgetdict)
95
+ for widgettype,widgetdict in self.content ]
96
+
97
+ self.datawidget = VBox([child.datawidget for child in self.datachildren])
98
+
99
+
100
+ def update_df(self,df,current_per):
101
+ ''' will update container widgets'''
102
+ for w in self.datachildren:
103
+ w.update_df(df,current_per)
104
+
105
+
106
+
107
+ def reset(self,g):
108
+ ''' will reset container widgets'''
109
+ for w in self.datachildren:
110
+ w.reset(g)
111
+
112
+
113
+
114
+ class tabwidget(singelwidget):
115
+ '''A widget to create tab or acordium contaners'''
116
+
117
+ # widgetdef : dict
118
+ # expname : str = "Carbon tax rate, US$ per tonn "
119
+ # tab: bool =True
120
+
121
+ def __init__(self,widgetdef):
122
+ # self.tabdefdict = self.widgetdef['content']
123
+ super().__init__(widgetdef)
124
+ self.selected_index = widgetdef.get('selected_index','0')
125
+ self.tab = widgetdef.get('tab',True)
126
+ self.tabdefheadings = [subtabdef[0] for subtabdef in self.content]
127
+
128
+ thiswidget = widgets.Tab if self.tab else widgets.Accordion
129
+ # breakpoint()
130
+
131
+ self.datachildren = [globals()[subwidgettype+'widget'](subwidgetdict)
132
+ for tabheading,(subwidgettype,subwidgetdict) in self.content ]
133
+
134
+ self.datawidget = thiswidget([child.datawidget for child in self.datachildren],
135
+ selected_index = self.selected_index,
136
+ layout={'height': 'max-content'})
137
+
138
+ for i,key in enumerate(self.tabdefheadings):
139
+ self.datawidget.set_title(i,key)
140
+
141
+
142
+ def update_df(self,df,current_per):
143
+ ''' will update container widgets'''
144
+ for w in self.datachildren:
145
+ w.update_df(df,current_per)
146
+
147
+
148
+ def reset(self,g):
149
+ ''' will reset container widgets'''
150
+ for w in self.datachildren:
151
+ w.reset(g)
152
+
153
+
154
+
155
+ # @dataclass
156
+ # class sheetwidget:
157
+ # ''' class defining a widget which updates from a sheet '''
158
+ # df_var : any = pd.DataFrame() # definition
159
+ # trans : any = lambda x : x # renaming of variables
160
+ # transpose : bool = False # orientation of dataframe
161
+ # expname : str = "Carbon tax rate, US$ per tonn "
162
+
163
+ class sheetwidget(singelwidget):
164
+ ''' class defefining a widget with lines of slides '''
165
+
166
+
167
+ def __init__(self,widgetdef ):
168
+ ...
169
+ super().__init__(widgetdef)
170
+ # print(f'{self.content=}')
171
+ self.df_var =self.content # input dataframe to update
172
+ self.trans = widgetdef.get('trans',lambda x:x) # Translation of variable names
173
+ self.transpose = widgetdef.get('transpose',False)# if the dataframs should be transpossed
174
+ # print(f'{self.transpose=}')
175
+ self.wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
176
+
177
+
178
+ newnamedf = self.df_var.copy().rename(columns=self.trans)
179
+ self.org_df_var = newnamedf.T if self.transpose else newnamedf
180
+
181
+ self.wsheet = sheet(from_dataframe(self.org_df_var),column_resizing=True,row_headers=False)
182
+
183
+ self.org_values = [c.value for c in self.wsheet.cells]
184
+ # breakpoint()
185
+ self.datawidget=widgets.VBox([self.wexp,self.wsheet]) if len(self.heading) else self.wsheet
186
+
187
+
188
+ def update_df(self,df,current_per=None):
189
+ # breakpoint()
190
+ self.df_new_var = to_dataframe(self.wsheet).T if self.transpose else to_dataframe(self.wsheet)
191
+ self.df_new_var.columns = self.df_var.columns
192
+ self.df_new_var.index = self.df_var.index
193
+
194
+ 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
195
+ pass
196
+ return df
197
+
198
+
199
+ def reset(self,g):
200
+ for c,v in zip(self.wsheet.cells,self.org_values):
201
+ c.value = v
202
+
203
+
204
+ class slidewidget(singelwidget):
205
+ ''' class defefining a widget with lines of slides '''
206
+
207
+
208
+ def __init__(self,widgetdef ):
209
+ ...
210
+ super().__init__(widgetdef)
211
+ self.altname = self.widgetdef .get('altname','Alternative')
212
+ self.basename = self.widgetdef .get('basename','Baseiline')
213
+ # breakpoint()
214
+
215
+ wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
216
+ walt = widgets.Label(value = self.altname,layout={'width':'8%', 'border':"hide"})
217
+ wbas = widgets.Label(value = self.basename,layout={'width':'10%', 'border':"hide"})
218
+ whead = widgets.HBox([wexp,walt,wbas])
219
+ #
220
+ # breakpoint()
221
+ self.wset = [widgets.FloatSlider(description=des,
222
+ min=cont['min'],
223
+ max=cont['max'],
224
+ value=cont['value'],
225
+ step=cont.get('step',0.01),
226
+ layout={'width':'60%'},style={'description_width':'40%'},
227
+ readout_format = f":>,.{cont.get('dec',2)}f",
228
+ continuous_update=False
229
+ )
230
+ for des,cont in self.content.items()]
231
+
232
+
233
+ for w in self.wset:
234
+ w.observe(self.set_slide_value,names='value',type='change')
235
+
236
+ waltval= [widgets.Label(
237
+ value=f"{cont['value']:>,.{cont.get('dec',2)}f}",
238
+ layout=widgets.Layout(display="flex", justify_content="center", width="10%", border="hide"))
239
+ for des,cont in self.content.items()
240
+
241
+ ]
242
+ self.wslide = [widgets.HBox([s,v]) for s,v in zip(self.wset,waltval)]
243
+ self.slidewidget = widgets.VBox([whead] + self.wslide)
244
+ self.datawidget = widgets.VBox([whead] + self.wslide)
245
+
246
+ # define the result object
247
+ self.current_values = {des:
248
+ {key : v.split() if key=='var' else v for key,v in cont.items() if key in {'value','var','op'}}
249
+ for des,cont in self.widgetdef ['content'].items()}
250
+
251
+ # register_widget(self.widget_id, self.datawidget)
252
+
253
+
254
+ def reset(self,g):
255
+ for i,(des,cont) in enumerate(self.content .items()):
256
+ self.wset[i].value = cont['value']
257
+
258
+
259
+
260
+ def update_df(self,df,current_per):
261
+ ''' updates a dataframe with the values from the widget'''
262
+ for i,(des,cont) in enumerate(self.current_values.items()):
263
+ op = cont.get('op','=')
264
+ value = cont['value']
265
+ for var in cont['var']:
266
+ if op == '+':
267
+ df.loc[current_per,var] = df.loc[current_per,var] + value
268
+ elif op == '+impulse':
269
+ df.loc[current_per[0],var] = df.loc[current_per[0],var] + value
270
+ elif op == '=start-':
271
+ startindex = df.index.get_loc(current_per[0])
272
+ varloc = df.columns.get_loc(var)
273
+ df.iloc[:startindex,varloc] = value
274
+ elif op == '=':
275
+ df.loc[current_per,var] = value
276
+ elif op == '=impulse':
277
+ df.loc[current_per[0],var] = value
278
+ elif op == '%':
279
+ df.loc[current_per,var] = df.loc[current_per,var] * (1-value/100)
280
+ else:
281
+ print(f'Wrong operator in {cont}.\nNot updated')
282
+ assert 1==3,'wRONG OPERATOR'
283
+
284
+
285
+ def set_slide_value(self,g):
286
+ ''' updates the new values to the self.current_vlues
287
+ will be used in update_df
288
+ '''
289
+ line_des = g['owner'].description
290
+ if 0:
291
+ print()
292
+ for k,v in g.items():
293
+ print(f'{k}:{v}')
294
+
295
+ self.current_values[line_des]['value'] = g['new']
296
+
297
+ class sumslidewidget(singelwidget):
298
+ ''' class defefining a widget with lines of slides '''
299
+ def __init__(self,widgetdef ):
300
+ ...
301
+ super().__init__(widgetdef)
302
+ self.altname = self.widgetdef .get('altname','Alternative')
303
+ self.basename = self.widgetdef .get('basename','Baseiline')
304
+ self.maxsum = self.widgetdef .get('maxsum',1.0)
305
+ # breakpoint()
306
+
307
+
308
+ self.first = list(self.content.keys())[:-1]
309
+ self.lastdes = list(self.content.keys())[-1]
310
+
311
+ wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
312
+ walt = widgets.Label(value = self.altname,layout={'width':'8%', 'border':"hide"})
313
+ wbas = widgets.Label(value = self.basename,layout={'width':'10%', 'border':"hide"})
314
+ whead = widgets.HBox([wexp,walt,wbas])
315
+ #
316
+ self.wset = [widgets.FloatSlider(description=des,
317
+ min=cont['min'],
318
+ max=cont['max'],
319
+ value=cont['value'],
320
+ step=cont.get('step',0.01),
321
+ layout={'width':'60%'},style={'description_width':'40%'},
322
+ readout_format = f":>,.{cont.get('dec',2)}f",
323
+ continuous_update=False,
324
+ disabled= False
325
+ )
326
+ for des,cont in self.content.items()]
327
+
328
+
329
+
330
+ for w in self.wset:
331
+ w.observe(self.set_slide_value,names='value',type='change')
332
+
333
+ waltval= [widgets.Label(
334
+ value=f"{cont['value']:>,.{cont.get('dec',2)}f}",
335
+ layout=widgets.Layout(display="flex", justify_content="center", width="10%", border="hide"))
336
+ for des,cont in self.content.items()
337
+
338
+ ]
339
+ self.wslide = [widgets.HBox([s,v]) for s,v in zip(self.wset,waltval)]
340
+ self.slidewidget = widgets.VBox([whead] + self.wslide)
341
+ self.datawidget = widgets.VBox([whead] + self.wslide)
342
+
343
+ # define the result object
344
+ self.current_values = {des:
345
+ {key : v.split() if key=='var' else v for key,v in cont.items() if key in {'value','var','op','min','max'}}
346
+ for des,cont in self.content.items()}
347
+
348
+ def reset(self,g):
349
+ for i,(des,cont) in enumerate(self.content.items()):
350
+ self.wset[i].value = cont['value']
351
+
352
+
353
+
354
+ def update_df(self,df,current_per):
355
+ ''' updates a dataframe with the values from the widget'''
356
+ for i,(des,cont) in enumerate(self.current_values.items()):
357
+ op = cont.get('op','=')
358
+ value = cont['value']
359
+ for var in cont['var']:
360
+ if op == '+':
361
+ df.loc[current_per,var] = df.loc[current_per,var] + value
362
+ elif op == '+impulse':
363
+ df.loc[current_per[0],var] = df.loc[current_per[0],var] + value
364
+ elif op == '=start-':
365
+ startindex = df.index.get_loc(current_per[0])
366
+ varloc = df.columns.get_loc(var)
367
+ df.iloc[:startindex,varloc] = value
368
+ elif op == '=':
369
+ df.loc[current_per,var] = value
370
+ elif op == '=impulse':
371
+ df.loc[current_per[0],var] = value
372
+ else:
373
+ print(f'Wrong operator in {cont}.\nNot updated')
374
+ assert 1==3,'wRONG OPERATOR'
375
+
376
+
377
+ def set_slide_value(self,g):
378
+ ''' updates the new values to the self.current_vlues
379
+ will be used in update_df
380
+ '''
381
+ line_des = g['owner'].description
382
+ line_index = list(self.current_values.keys()).index(line_des)
383
+ if 0:
384
+ print()
385
+ for k,v in g.items():
386
+ print(f'{k}:{v}')
387
+
388
+ self.current_values[line_des]['value'] = g['new']
389
+ # print(f'{self.current_values=}')
390
+ if type(self.maxsum) == float:
391
+ allvalues = [v['value'] for v in self.current_values.values()]
392
+ thissum = sum(allvalues)
393
+ if thissum > self.maxsum:
394
+ # print(f'{allvalues=}')
395
+ # print(f"{self.current_values[self.lastdes]['min']=}")
396
+ newlast = self.maxsum-sum(allvalues[:-1])
397
+ newlast = max(newlast,self.current_values[self.lastdes]['min'])
398
+ # print(f'{newlast=}')
399
+ self.current_values[self.lastdes]['value']= newlast
400
+
401
+ newsum= sum([v['value'] for v in self.current_values.values()])
402
+ # print(f'{newsum=}')
403
+ # print(f'{line_index=}')
404
+ if newsum > self.maxsum:
405
+ self.current_values[line_des]['value']=self.wset[line_index].value-newsum +self.maxsum
406
+ self.wset[line_index].value = self.current_values[line_des]['value']
407
+
408
+ self.wset[-1].value = newlast
409
+
410
+
411
+ class radiowidget(singelwidget):
412
+ ''' class defefining a widget with a number of radiobutton groups
413
+
414
+ When df_update is executed the cheked variable will be set to 1 the other to 0
415
+
416
+
417
+
418
+ {'<heading 1> [['text1','variable1'],
419
+ ['text2','variable2']
420
+ .....]
421
+ 'heading 2' [['text1','variable1'],
422
+ ['text2','variable2']
423
+ .....]
424
+
425
+ ....
426
+ ....
427
+ }
428
+
429
+
430
+
431
+ '''
432
+
433
+ def __init__(self,widgetdef):
434
+ ...
435
+ super().__init__(widgetdef)
436
+
437
+ wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
438
+ whead = widgets.HBox([wexp])
439
+ #
440
+ self.wradiolist = [widgets.RadioButtons(options=[i for i,j in cont],description=des,layout={'width':'70%'},
441
+ style={'description_width':'37%'}) for des,cont in self.content.items()]
442
+ if len(self.wradiolist) <=2:
443
+ self.wradio = widgets.HBox(self.wradiolist)
444
+ else:
445
+ self.wradio = widgets.VBox(self.wradiolist)
446
+
447
+ self.datawidget = widgets.VBox([whead] + [self.wradio])
448
+
449
+ def reset(self,g):
450
+ for wradio in self.wradiolist:
451
+ wradio.index = 0
452
+
453
+
454
+ def update_df(self,df,current_per):
455
+ ''' updates a dataframe with the values from the widget'''
456
+ for wradio,(des,cont) in zip(self.wradiolist,self.content.items()):
457
+ # print(f'{des=} {wradio.value=},{wradio.index=},{cont[wradio.index]=}')
458
+ # print(f'{cont=}')
459
+ for varlabel,variable in cont:
460
+ df.loc[current_per,variable] = 0
461
+ selected_variable = cont[wradio.index][1]
462
+ df.loc[current_per,selected_variable] = 1
463
+ # print(df.loc[current_per,:])
464
+
465
+
466
+ class checkwidget(singelwidget):
467
+ ''' class defefining a widget with a number of radiobutton groups
468
+
469
+ When df_update is executed the cheked variable will be set to 1 the other to 0
470
+
471
+
472
+
473
+ {
474
+ '<heading 1>:['variable1 variable2 ---',value ],
475
+ '<heading 2>:['variable10 variable20 ---',value ]
476
+ }
477
+
478
+
479
+
480
+ '''
481
+ def __init__(self,widgetdef):
482
+ ...
483
+ super().__init__(widgetdef)
484
+
485
+ wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
486
+ whead = widgets.HBox([wexp])
487
+ #
488
+ self.wchecklist = [widgets.Checkbox(description=des,value=val) for des,(var,val)
489
+ in self.content.items()]
490
+ self.wcheck = widgets.VBox(self.wchecklist)
491
+
492
+ self.datawidget = widgets.VBox([whead] + [self.wcheck])
493
+
494
+ def reset(self,g):
495
+ for wcheck,(des,(variable,val)) in zip(self.wchecklist,self.content.items()):
496
+ wcheck.value = val
497
+
498
+
499
+ def update_df(self,df,current_per):
500
+ ''' updates a dataframe with the values from the widget'''
501
+ for wcheck,(des,(variable,val)) in zip(self.wchecklist,self.content.items()):
502
+ for selected_variable in variable.split():
503
+ df.loc[current_per,selected_variable] = 1.0 if wcheck.value else 0.0
504
+
505
+
506
+
507
+ @dataclass
508
+ class updatewidget:
509
+ ''' class to input and run a model
510
+
511
+ - display(wtotal) to activate the widget
512
+
513
+ '''
514
+
515
+ mmodel : any # a model
516
+ datawidget : any # a widget to update from
517
+ basename : str ='Business as usual'
518
+ keeppat : str = '*'
519
+ varpat : str ='*'
520
+ showvarpat : bool = True # Show varpaths to
521
+ exodif : any = pd.DataFrame() # definition
522
+ lwrun : bool = True
523
+ lwupdate : bool = False
524
+ lwreset : bool = True
525
+ lwsetbas : bool = True
526
+ outputwidget : str = 'jupviz'
527
+ display_first :any = None
528
+ # to the plot widget
529
+ prefix_dict : dict = field(default_factory=dict)
530
+ vline : list = field(default_factory=list)
531
+ relativ_start : int = 0
532
+ short :bool = False
533
+
534
+
535
+
536
+ def __post_init__(self):
537
+ self.baseline = self.mmodel.basedf.copy()
538
+ self.wrun = widgets.Button(description="Run scenario")
539
+ self.wrun .on_click(self.run)
540
+ self.wrun .tooltip = 'Click to run'
541
+ self.wrun.style.button_color = 'Lime'
542
+
543
+
544
+ wupdate = widgets.Button(description="Update the dataset ")
545
+ wupdate.on_click(self.update)
546
+
547
+ wreset = widgets.Button(description="Reset to start")
548
+ wreset.on_click(self.reset)
549
+
550
+
551
+ wsetbas = widgets.Button(description="Use as baseline")
552
+ wsetbas.on_click(self.setbasis)
553
+ self.experiment = 0
554
+
555
+ lbut = []
556
+
557
+ if self.lwrun: lbut.append(self.wrun )
558
+ if self.lwupdate: lbut.append(wupdate)
559
+ if self.lwreset: lbut.append(wreset)
560
+ if self.lwsetbas : lbut.append(wsetbas)
561
+
562
+ wbut = widgets.HBox(lbut)
563
+
564
+
565
+ self.wname = widgets.Text(value=self.basename,placeholder='Type something',description='Scenario name:',
566
+ layout={'width':'30%'},style={'description_width':'50%'})
567
+ self.wpat = widgets.Text(value= self.varpat,placeholder='Type something',description='Display variables:',
568
+ layout={'width':'65%'},style={'description_width':'30%'})
569
+
570
+ self.wpat.layout.visibility = 'visible' if self.showvarpat else 'hidden'
571
+
572
+ winputstring = widgets.HBox([self.wname,self.wpat])
573
+
574
+
575
+ self.mmodel.keep_solutions = {}
576
+ self.mmodel.keep_solutions = {self.wname.value : self.baseline}
577
+ self.mmodel.keep_exodif = {}
578
+
579
+ self.experiment += 1
580
+ self.wname.value = f'Experiment {self.experiment}'
581
+
582
+ self.wtotal = VBox([widgets.HTML(value="Hello <b>World</b>")])
583
+
584
+ def init_run(g):
585
+ # print(f'{g=}')
586
+ self.varpat = g['new']
587
+ self.keep_ui = keep_plot_shiny(mmodel = self.mmodel,
588
+ selectfrom = self.varpat, prefix_dict=self.prefix_dict,
589
+ vline=self.vline,relativ_start=self.relativ_start,
590
+ short = self.short)
591
+
592
+ # self.wtotal = widgets.VBox([self.datawidget.datawidget,winputstring,wbut,
593
+ # self.keep_ui.datawidget])
594
+ self.wtotal.children = [self.datawidget.datawidget,winputstring,wbut,
595
+ self.keep_ui.datawidget]
596
+
597
+ self.start = copy(self.mmodel.current_per[0])
598
+ self.slut = copy(self.mmodel.current_per[-1])
599
+
600
+ self.wpat.observe(init_run,names='value',type='change')
601
+
602
+ init_run({'new':self.varpat})
603
+
604
+ def update(self,g):
605
+ self.thisexperiment = self.baseline.copy()
606
+ # print(f'update smpl {self.mmodel.current_per=}')
607
+
608
+ self.datawidget.update_df(self.thisexperiment,self.mmodel.current_per)
609
+ self.exodif = self.mmodel.exodif(self.baseline,self.thisexperiment)
610
+ # print(f'update 2 smpl {self.mmodel.current_per[0]=}')
611
+
612
+
613
+
614
+
615
+ def run(self,g):
616
+ self.update(g)
617
+ # print(f'run smpl {self.mmodel.current_per[0]=}')
618
+ # self.start = self.mmodel.current_per[0]
619
+ # self.slut = self.mmodel.current_per[-1]
620
+ # print(f'{self.start=} {self.slut=}')
621
+ self.wrun .tooltip = 'Running'
622
+ self.wrun.style.button_color = 'Red'
623
+
624
+ self.mmodel(self.thisexperiment,start=self.start,slut=self.slut,progressbar=0,keep = self.wname.value,
625
+ keep_variables = self.keeppat)
626
+ self.wrun .tooltip = 'Click to run'
627
+ self.wrun.style.button_color = 'Lime'
628
+ # print(f'run efter smpl {self.mmodel.current_per[0]=}')
629
+ self.mmodel.keep_exodif[self.wname.value] = self.exodif
630
+ self.mmodel.inputwidget_alternativerun = True
631
+ self.current_experiment = self.wname.value
632
+ self.experiment += 1
633
+ self.wname.value = f'Experiment {self.experiment}'
634
+ self.keep_ui.trigger(None)
635
+
636
+ def setbasis(self,g):
637
+ self.mmodel.keep_solutions={self.current_experiment:self.mmodel.keep_solutions[self.current_experiment]}
638
+
639
+ self.mmodel.keep_exodif[self.current_experiment] = self.exodif
640
+ self.mmodel.inputwidget_alternativerun = True
641
+
642
+
643
+
644
+
645
+ def reset(self,g):
646
+ self.datawidget.reset(g)
647
+
648
+ def fig_to_image(fig,format='svg'):
649
+ from io import StringIO
650
+ f = StringIO()
651
+ fig.savefig(f,format=format,bbox_inches="tight")
652
+ f.seek(0)
653
+ image= f.read()
654
+ return image
655
+
656
+ @dataclass
657
+ class htmlwidget_df:
658
+ ''' class displays a dataframe in a html widget '''
659
+
660
+ mmodel : any # a model
661
+ df_var : any = pd.DataFrame() # definition
662
+ trans : any = lambda x : x # renaming of variables
663
+ transpose : bool = False # orientation of dataframe
664
+ expname : str = "Test"
665
+ percent : bool = False
666
+
667
+
668
+ def __post_init__(self):
669
+ ...
670
+
671
+
672
+
673
+ newnamedf = self.df_var.copy().rename(columns=self.trans)
674
+ self.org_df_var = newnamedf.T if self.transpose else newnamedf
675
+ self.wexp = widgets.Label(value = f'{self.expname} {self.org_df_var.shape}',layout={'width':'54%'})
676
+ self.datawidget=self.wexp
677
+ # return
678
+ image = self.mmodel.ibsstyle(self.org_df_var,percent = self.percent).to_html()
679
+ # image = self.org_df_var.to_html()
680
+ self.whtml = widgets.HTML(image)
681
+ # self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.expname) else self.whtml
682
+ self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.expname) else self.whtml
683
+
684
+ @property
685
+ def show(self):
686
+ display(self.datawidget)
687
+
688
+ @dataclass
689
+ class html_dfwidget(singelwidget):
690
+ ''' class displays a dataframe in a html widget '''
691
+
692
+
693
+
694
+ def __init__(self,widgetdef):
695
+ ...
696
+ super().__init__(widgetdef)
697
+ self.df_var = self.content # definition
698
+
699
+ self.mmodel = widgetdef['mmodel']
700
+ self.trans = widgetdef.get('trans',lambda x : x ) # renaming of variables
701
+ self.transpose = widgetdef.get('transpose',False ) # orientation of dataframe
702
+ self.expname : str = "Test"
703
+ self.percent = widgetdef.get('percent',False )
704
+
705
+
706
+ newnamedf = self.df_var.copy().rename(columns=self.trans)
707
+ self.org_df_var = newnamedf.T if self.transpose else newnamedf
708
+ self.wexp = widgets.Label(value = f'{self.heading} {self.org_df_var.shape}',layout={'width':'54%'})
709
+ self.datawidget=self.wexp
710
+ # return
711
+ image = self.mmodel.ibsstyle(self.org_df_var,percent = self.percent).to_html()
712
+ # image = self.org_df_var.to_html()
713
+ self.whtml = widgets.HTML(image)
714
+ # self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.expname) else self.whtml
715
+ self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.heading ) else self.whtml
716
+
717
+ @property
718
+ def show(self):
719
+ display(self.datawidget)
720
+
721
+
722
+ @dataclass
723
+ class htmlwidget_fig:
724
+ ''' class displays a dataframe in a html widget '''
725
+
726
+ figs : any # a model
727
+ expname : str = ""
728
+ format : str = "svg"
729
+
730
+
731
+ def __post_init__(self):
732
+ ...
733
+
734
+ self.wexp = widgets.Label(value = self.expname,layout={'width':'54%'})
735
+
736
+
737
+ image = fig_to_image(self.figs,format=self.format)
738
+ print(image)
739
+ # self.whtml = widgets.HTML(image,layout={'width':'54%'})
740
+ self.whtml = widgets.Image(image,width=300,format = 'svg')
741
+ self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.expname) else self.whtml
742
+
743
+
744
+
745
+ class html_figwidget_fig(singelwidget):
746
+ ''' class displays a dataframe in a html widget '''
747
+
748
+
749
+ def __init__(self,widgetdef):
750
+ ...
751
+ super().__init__(widgetdef)
752
+ self.figs = self.content
753
+ self.wexp = widgets.Label(value = self.heading,layout={'width':'54%'})
754
+ self.format = widgetdefget('format','svg')
755
+
756
+ image = fig_to_image(self.figs,format=self.format)
757
+ print(image)
758
+ # self.whtml = widgets.HTML(image,layout={'width':'54%'})
759
+ self.whtml = widgets.Image(image,width=300,format = 'svg')
760
+ self.datawidget=widgets.VBox([self.wexp,self.whtml]) if len(self.expname) else self.whtml
761
+
762
+
763
+
764
+ @dataclass
765
+ class htmlwidget_label:
766
+ ''' class displays a dataframe in a html widget '''
767
+
768
+ expname : str = ""
769
+ format : str = "svg"
770
+
771
+
772
+ def __post_init__(self):
773
+ ...
774
+
775
+ self.wexp = widgets.Label(value = self.expname,layout={'width':'54%'})
776
+
777
+
778
+ self.datawidget=self.wexp
779
+
780
+ class visshowwidget(singelwidget):
781
+
782
+
783
+
784
+ def __init__(self,widgetdef):
785
+ ...
786
+ super().__init__(widgetdef)
787
+ ...
788
+ self.mmodel = self.content
789
+ self.varpat = singelwidget.get('varpat','*')
790
+ self.showvarpat = singelwidget.get('showvarpat',True)
791
+ self.show_on = singelwidget.get('show_on',True)
792
+
793
+ from IPython import get_ipython
794
+ try:
795
+ get_ipython().magic('matplotlib notebook')
796
+ except:
797
+ ...
798
+ # print(plt.get_backend())
799
+ this_vis = self.mmodel[self.varpat]
800
+ self.out_dict = {}
801
+ self.out_dict['Baseline'] ={'df':this_vis.base}
802
+ self.out_dict['Alternative'] ={'df':this_vis}
803
+ self.out_dict['Difference'] ={'df':this_vis.dif}
804
+ self.out_dict['Diff. pct. level'] ={'df':this_vis.difpctlevel.mul100,'percent':True}
805
+ self.out_dict['Base growth'] ={'df':this_vis.base.pct.mul100,'percent':True}
806
+ self.out_dict['Alt. growth'] ={'df':this_vis.pct.mul100,'percent':True}
807
+ self.out_dict['Diff. in growth'] ={'df':this_vis.difpct.mul100,'percent':True}
808
+
809
+ self.out_to_data = {
810
+ ['html_df',{
811
+ 'content':value['df'].df.T,
812
+ 'heading':key,
813
+ 'mmodel': self.mmodel,
814
+ 'percent': value.get('percent',False) } ]
815
+ for key,value in self.out_dict.items()}
816
+
817
+ out = widgets.Output()
818
+ with out: # to suppress the display of matplotlib creation
819
+ self.out_to_figs ={key:
820
+ ['html_fig',{'content':value['df'].rename().plot(top=0.9,title='')}]
821
+
822
+ for key,value in self.out_dict.items() }
823
+
824
+
825
+ tabnew = {key: tabwidget({'Charts':self.out_to_figs[key],'Data':self.out_to_data[key]},selected_index=0)
826
+ for key in self.out_to_figs.keys()}
827
+
828
+ exodif = self.mmodel.exodif()
829
+ exonames = exodif.columns
830
+ exoindex = exodif.index
831
+ if len(exonames):
832
+ exobase = self.mmodel.basedf.loc[exoindex,exonames]
833
+ exolast = self.mmodel.lastdf.loc[exoindex,exonames]
834
+
835
+ out_exodif = htmlwidget_df(self.mmodel,exodif.T)
836
+ out_exobase = htmlwidget_df(self.mmodel,exobase.T)
837
+ out_exolast = htmlwidget_df(self.mmodel,exolast.T)
838
+ else:
839
+ out_exodif = htmlwidget_label(expname = 'No difference in exogenous')
840
+ out_exobase = htmlwidget_label(expname = 'No difference in exogenous')
841
+ out_exolast = htmlwidget_label(expname = 'No difference in exogenous')
842
+
843
+
844
+ out_tab_info = tabwidget({'Delta exogenous':out_exodif,
845
+ 'Baseline exogenous':out_exobase,
846
+ 'Alt. exogenous':out_exolast},selected_index=0)
847
+
848
+ tabnew['Exo info'] = out_tab_info
849
+
850
+ this = tabwidget(tabnew,selected_index=0)
851
+
852
+
853
+
854
+ self.datawidget = this.datawidget
855
+ if self.show_on:
856
+ ...
857
+ display(self.datawidget)
858
+ try:
859
+ get_ipython().magic('matplotlib inline')
860
+ except:
861
+ ...
862
+
863
+ def __repr__(self):
864
+ return ''
865
+
866
+ def _html_repr_(self):
867
+ return self.datawidget
868
+
869
+ @property
870
+ def show(self):
871
+ display(self.datawidget)
872
+
873
+
874
+
875
+ @dataclass
876
+ class visshow:
877
+ mmodel : any # a model
878
+ varpat : str ='*'
879
+ showvarpat : bool = True
880
+ show_on : bool = True # Display when called
881
+
882
+ def __post_init__(self):
883
+ ...
884
+ from IPython import get_ipython
885
+ try:
886
+ get_ipython().magic('matplotlib notebook')
887
+ except:
888
+ ...
889
+ # print(plt.get_backend())
890
+ this_vis = self.mmodel[self.varpat]
891
+ self.out_dict = {}
892
+ self.out_dict['Baseline'] ={'df':this_vis.base}
893
+ self.out_dict['Alternative'] ={'df':this_vis}
894
+ self.out_dict['Difference'] ={'df':this_vis.dif}
895
+ self.out_dict['Diff. pct. level'] ={'df':this_vis.difpctlevel.mul100,'percent':True}
896
+ self.out_dict['Base growth'] ={'df':this_vis.base.pct.mul100,'percent':True}
897
+ self.out_dict['Alt. growth'] ={'df':this_vis.pct.mul100,'percent':True}
898
+ self.out_dict['Diff. in growth'] ={'df':this_vis.difpct.mul100,'percent':True}
899
+
900
+ out = widgets.Output()
901
+ self.out_to_data = {key:
902
+ htmlwidget_df(self.mmodel,value['df'].df.T,expname=key,
903
+
904
+ percent=value.get('percent',False))
905
+ for key,value in self.out_dict.items()}
906
+
907
+ with out: # to suppress the display of matplotlib creation
908
+ self.out_to_figs ={key:
909
+ htmlwidget_fig(value['df'].rename().plot(top=0.9,title=''),expname='')
910
+ for key,value in self.out_dict.items() }
911
+
912
+
913
+ 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()}
914
+
915
+ exodif = self.mmodel.exodif()
916
+ exonames = exodif.columns
917
+ exoindex = exodif.index
918
+ if len(exonames):
919
+ exobase = self.mmodel.basedf.loc[exoindex,exonames]
920
+ exolast = self.mmodel.lastdf.loc[exoindex,exonames]
921
+
922
+ out_exodif = htmlwidget_df(self.mmodel,exodif.T)
923
+ out_exobase = htmlwidget_df(self.mmodel,exobase.T)
924
+ out_exolast = htmlwidget_df(self.mmodel,exolast.T)
925
+ else:
926
+ out_exodif = htmlwidget_label(expname = 'No difference in exogenous')
927
+ out_exobase = htmlwidget_label(expname = 'No difference in exogenous')
928
+ out_exolast = htmlwidget_label(expname = 'No difference in exogenous')
929
+
930
+
931
+ out_tab_info = tabwidget({'Delta exogenous':out_exodif,
932
+ 'Baseline exogenous':out_exobase,
933
+ 'Alt. exogenous':out_exolast},selected_index=0)
934
+
935
+ tabnew['Exo info'] = out_tab_info
936
+
937
+ this = tabwidget(tabnew,selected_index=0)
938
+
939
+
940
+
941
+ self.datawidget = this.datawidget
942
+ if self.show_on:
943
+ ...
944
+ display(self.datawidget)
945
+ try:
946
+ get_ipython().magic('matplotlib inline')
947
+ except:
948
+ ...
949
+
950
+ def __repr__(self):
951
+ return ''
952
+
953
+ def _html_repr_(self):
954
+ return self.datawidget
955
+
956
+ @property
957
+ def show(self):
958
+ display(self.datawidget)
959
+
960
+
961
+ @dataclass
962
+ class shinywidget:
963
+ '''A to translate a widget to shiny widget '''
964
+
965
+ a_widget : any # The datawidget to wrap
966
+ widget_id : str
967
+
968
+ def __post_init__(self):
969
+ from shinywidgets import register_widget
970
+ ...
971
+ register_widget(self.widget_id, self.a_widget.datawidget)
972
+
973
+
974
+ def update_df(self,df,current_per):
975
+ ''' will update container widgets'''
976
+ self.a_widget.update_df(df,current_per)
977
+
978
+
979
+ def reset(self,g):
980
+ ''' will reset container widgets'''
981
+ self.a_widget.reset(g)
982
+
983
+ @dataclass
984
+ class keep_plot_shiny:
985
+ mmodel : any # a model
986
+ pat : str ='*'
987
+ smpl=('', '')
988
+ relativ_start : int = 0
989
+ selectfrom : str ='*'
990
+ legend=0
991
+ dec=''
992
+ use_descriptions=True
993
+ select_width=''
994
+ select_height='200px'
995
+ vline : list = field(default_factory=list)
996
+ prefix_dict : dict = field(default_factory=dict)
997
+ add_var_name=False
998
+ short :any = 0
999
+ multi :any = False
1000
+
1001
+ """
1002
+ Plots the keept dataframes
1003
+
1004
+ Args:
1005
+ mmodel : a modelflow model instance
1006
+ pat (str, optional): a string of variables to select pr default. Defaults to '*'.
1007
+ smpl (tuple with 2 elements, optional): the selected smpl, has to match the dataframe index used. Defaults to ('','').
1008
+ selectfrom (list, optional): the variables to select from, Defaults to [] -> all keept variables .
1009
+ legend (bool, optional)c: DESCRIPTION. legends or to the right of the curve. Defaults to 1.
1010
+ dec (string, optional): decimals on the y-axis. Defaults to '0'.
1011
+ use_descriptions : Use the variable descriptions from the model
1012
+
1013
+ Returns:
1014
+ None.
1015
+
1016
+ self.keep_wiz_figs is set to a dictionary containing the figures. Can be used to produce publication
1017
+ quality files.
1018
+
1019
+ """
1020
+
1021
+
1022
+ def __post_init__(self):
1023
+ from copy import copy
1024
+ minper = self.mmodel.lastdf.index[0]
1025
+ maxper = self.mmodel.lastdf.index[-1]
1026
+ options = [(ind, nr) for nr, ind in enumerate(self.mmodel.lastdf.index)]
1027
+ self.old_current_per = copy(self.mmodel.current_per)
1028
+ # print(f'Før {self.mmodel.current_per=}')
1029
+ with self.mmodel.set_smpl(*self.smpl):
1030
+ # print(f'efter set smpl {self.mmodel.current_per=}')
1031
+ with self.mmodel.set_smpl_relative(self.relativ_start,0):
1032
+ # print(f'efter set smpl relativ {self.mmodel.current_per=}')
1033
+ ...
1034
+ show_per = copy(list(self.mmodel.current_per)[:])
1035
+ self.mmodel.current_per = copy(self.old_current_per)
1036
+ # print(f'efter context set smpl {self.mmodel.current_per=}')
1037
+ # breakpoint()
1038
+ init_start = self.mmodel.lastdf.index.get_loc(show_per[0])
1039
+ init_end = self.mmodel.lastdf.index.get_loc(show_per[-1])
1040
+ keepvar = sorted (list(self.mmodel.keep_solutions.values())[0].columns)
1041
+ defaultvar = ([v for v in self.mmodel.vlist(self.pat) if v in keepvar][0],)
1042
+ # print('******* selectfrom')
1043
+ _selectfrom = [s.upper() for s in self.mmodel.vlist(self.selectfrom)] if self.selectfrom else keepvar
1044
+ # _selectfrom = keepvar
1045
+ # print(f'{_selectfrom=}')
1046
+ 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]
1047
+ # print(f'{gross_selectfrom=}')
1048
+ width = self.select_width if self.select_width else '50%' if self.use_descriptions else '50%'
1049
+
1050
+
1051
+ description_width = 'initial'
1052
+ description_width_long = 'initial'
1053
+ keep_keys = list(self.mmodel.keep_solutions.keys())
1054
+ keep_first = keep_keys[0]
1055
+ select_prefix = [(c,iso) for iso,c in self.prefix_dict.items()]
1056
+ i_smpl = SelectionRangeSlider(value=[init_start, init_end], continuous_update=False, options=options, min=minper,
1057
+ max=maxper, layout=Layout(width='75%'), description='Show interval')
1058
+ selected_vars = SelectMultiple( options=gross_selectfrom, layout=Layout(width=width, height=self.select_height, font="monospace"),
1059
+ description='Select one or more', style={'description_width': description_width})
1060
+
1061
+ diff = RadioButtons(options=[('No', False), ('Yes', True), ('In percent', 'pct')], description=fr'Difference to: "{keep_first}"',
1062
+ value=False, style={'description_width': 'auto'}, layout=Layout(width='auto'))
1063
+ showtype = RadioButtons(options=[('Level', 'level'), ('Growth', 'growth')],
1064
+ description='Data type', value='level', style={'description_width': description_width})
1065
+ scale = RadioButtons(options=[('Linear', 'linear'), ('Log', 'log')], description='Y-scale',
1066
+ value='linear', style={'description_width': description_width})
1067
+ #
1068
+ legend = RadioButtons(options=[('Yes', 1), ('No', 0)], description='Legends', value=self.legend, style={
1069
+ 'description_width': description_width})
1070
+
1071
+ self.widget_dict = {'i_smpl': i_smpl, 'selected_vars': selected_vars, 'diff': diff, 'showtype': showtype,
1072
+ 'scale': scale, 'legend': legend}
1073
+ for wid in self.widget_dict.values():
1074
+ wid.observe(self.trigger,names='value',type='change')
1075
+
1076
+ # breakpoint()
1077
+ self.out_widget =VBox([widgets.HTML(value="Hello <b>World</b>",
1078
+ placeholder='',
1079
+ description='',)])
1080
+
1081
+
1082
+
1083
+ def get_prefix(g):
1084
+ ''' this function is triggered when the prefix selection is changed. Used only when a prefix_dict has ben set.
1085
+
1086
+ g['new]'] contains the new prefix
1087
+
1088
+ It sets the variables the user can select from
1089
+
1090
+ '''
1091
+ # print(f'{g=}')
1092
+ try:
1093
+ # fint the suffix for the variables in the current selection of variables
1094
+ # to ensure we get the same variables for the next prefix
1095
+ current_suffix = {v[len(g['old'][0]):] for v in selected_vars.value}
1096
+ except:
1097
+ # we are at the first call to getprefix
1098
+ current_suffix = ''
1099
+
1100
+ new_prefix = g['new'] # returns the selected prefix as tuple as therre can be more
1101
+ # print(new_prefix)
1102
+ # find the variables which starts with the prefix
1103
+ selected_prefix_var = tuple((des,variable) for des,variable in gross_selectfrom
1104
+ if any([variable.startswith(n) for n in new_prefix]))
1105
+ # An exception is trigered but has no consequences
1106
+ try:
1107
+ selected_vars.options = selected_prefix_var # Sets the variables to be selected from
1108
+ except:
1109
+ ...
1110
+
1111
+
1112
+ # print(f'{current_suffix=} \n{selected_prefix_var=}')
1113
+
1114
+ if current_suffix:
1115
+ new_selection = [f'{n}{c}' for c in current_suffix for n in new_prefix
1116
+ if f'{n}{c}' in {s for p,s in selected_prefix_var}]
1117
+ selected_vars.value = new_selection
1118
+ # print(f"{new_selection=}{current_suffix=}{g['old']=}")
1119
+ else:
1120
+ # we are where no prefix has been selected
1121
+ selected_vars.value = [selected_prefix_var[0][1]]
1122
+
1123
+
1124
+ if len(self.prefix_dict):
1125
+ selected_prefix = SelectMultiple(value=[select_prefix[0][1]], options=select_prefix,
1126
+ layout=Layout(width='25%', height=self.select_height, font="monospace"),
1127
+ description='')
1128
+
1129
+ selected_prefix.observe(get_prefix,names='value',type='change')
1130
+ select = HBox([selected_vars,selected_prefix])
1131
+ # print(f'{select_prefix=}')
1132
+ # we call get_prefix when the widget is set up.
1133
+ get_prefix({'new':select_prefix[0]})
1134
+ else:
1135
+ # no prefix, so we only have to select variable names.
1136
+ select = VBox([selected_vars])
1137
+
1138
+ options1 = HBox([diff]) if self.short >=2 else HBox([diff,legend])
1139
+ options2 = HBox([scale, showtype])
1140
+ if self.short:
1141
+ vui = [select, options1, i_smpl]
1142
+ else:
1143
+ vui = [select, options1, options2, i_smpl]
1144
+ vui = vui[:-1] if self.short >= 2 else vui
1145
+
1146
+ self.datawidget= VBox(vui+[self.out_widget])
1147
+ # show = interactive_output(explain, {'i_smpl': i_smpl, 'selected_vars': selected_vars, 'diff': diff, 'showtype': showtype,
1148
+ # 'scale': scale, 'legend': legend})
1149
+ # print('klar til register')
1150
+
1151
+ def explain(self, i_smpl=None, selected_vars=None, diff=None, showtype=None, scale=None, legend= None):
1152
+ # print(f'Start explain:\n {self.mmodel.current_per[0]=}\n{selected_vars=}\n')
1153
+ variabler = ' '.join(v for v in selected_vars)
1154
+ smpl = (self.mmodel.lastdf.index[i_smpl[0]], self.mmodel.lastdf.index[i_smpl[1]])
1155
+ if type(diff) == str:
1156
+ diffpct = True
1157
+ ldiff = False
1158
+ else:
1159
+ ldiff = diff
1160
+ diffpct = False
1161
+
1162
+ # clear_output()
1163
+ with self.mmodel.set_smpl(*smpl):
1164
+
1165
+ if self.multi:
1166
+ self.keep_wiz_fig = self.mmodel.keep_plot_multi(variabler, diff=ldiff, diffpct = diffpct, scale=scale, showtype=showtype,
1167
+ legend=legend, dec=self.dec, vline=self.vline)
1168
+ else:
1169
+ self.keep_wiz_figs = self.mmodel.keep_plot(variabler, diff=ldiff, diffpct = diffpct,
1170
+ scale=scale, showtype=showtype,
1171
+ legend=legend, dec=self.dec, vline=self.vline)
1172
+ self.keep_wiz_fig = self.keep_wiz_figs[selected_vars[0]]
1173
+ plt.close('all')
1174
+ return self.keep_wiz_figs
1175
+ print(f'Efter plot {self.mmodel.current_per=}')
1176
+
1177
+
1178
+ def trigger(self,g):
1179
+ self.mmodel.current_per = copy(self.old_current_per)
1180
+
1181
+ values = {widname : wid.value for widname,wid in self.widget_dict.items() }
1182
+ # print(f'Triggerd:\n{values} \n Start trigger {self.mmodel.current_per=}\n')
1183
+ figs = self.explain(**values)
1184
+ if 0:
1185
+ xxx = fig_to_image(self.keep_wiz_fig,format='svg')
1186
+ self.out_widget.children = [widgets.HTML(xxx)]
1187
+ else:
1188
+ yyy = [widgets.HTML(fig_to_image(a_fig),width='100%',format = 'svg',layout=Layout(width='75%'))
1189
+ for key,a_fig in figs.items() ]
1190
+ self.out_widget.children = yyy
1191
+ # print(f'end trigger {self.mmodel.current_per[0]=}')
1192
+
1193
+
1194
+
1195
+
1196
+ def make_widget(widgetdef):
1197
+ '''
1198
+ '''
1199
+
1200
+ widgettype,widgetdict = widgetdef
1201
+ reswidget = globals()[widgettype+'widget'](widgetdict)
1202
+ return reswidget
1203
+
1204
+ slidedef = ['slide', {'heading':'Dette er en prøve',
1205
+ 'content' :{'Productivity' : {'var':'ALFA', 'value': 0.5 ,'min':0.0, 'max':1.0},
1206
+ 'DEPRECIATES_RATE' : {'var':'DEPRECIATES_RATE', 'value': 0.05,'min':0.0, 'max':1.0},
1207
+ 'LABOR_GROWTH' : {'var':'LABOR_GROWTH', 'value': 0.01,'min':0.0, 'max':1.0},
1208
+ 'SAVING_RATIO' : {'var': 'SAVING_RATIO', 'value': 0.05,'min':0.0, 'max':1.0}
1209
+ }} ]
1210
+
1211
+ radiodef = ['radio', {'heading':'Dette er en anden prøve',
1212
+ 'content' : {'Ib': [['Arbejdskraft','LABOR_GROWTH'],
1213
+ ['Opsparing','SAVING_RATIO'] ],
1214
+ 'Søren': [['alfa','ALFA'],
1215
+ ['a','A'] ],
1216
+ 'Marie': [['Hest','HEST'],
1217
+ ['Ko','KO'] ],
1218
+
1219
+ }} ]
1220
+
1221
+ checkdef = ['check', {'heading':'Dette er en treidje prøve',
1222
+ 'content' :{'Arbejdskraft':['LABOR_GROWTH KO',1],
1223
+ 'Opsparing' :['SAVING_RATIO',0] }}]
1224
+
1225
+ alldef = [slidedef] + [radiodef] + [checkdef]
1226
+
1227
+
1228
+ tabdef = ['tab',{'content':[['Den første',['base',{'content':alldef}]],
1229
+ ['Den anden' ,['base',{'content':alldef}]]]
1230
+ ,
1231
+ 'tab':False}]
1232
+
1233
+ basedef = ['base',{'content':[slidedef,radiodef]}]
1234
+
1235
+ xx = make_widget(tabdef)
1236
+
1237
+ # print(yaml.dump(tabdef,indent=4))
1238
+