modelflowib 2.73__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.
modeldash.py ADDED
@@ -0,0 +1,265 @@
1
+ try:
2
+ import dash_interactive_graphviz
3
+ from jupyter_dash import JupyterDash
4
+ import dash
5
+ #from dash.dependencies import Input, Output, State
6
+ #import dash_html_components as html
7
+ # import dash_core_components as dcc
8
+ from dash import Dash, callback, html, dcc, dash_table, Input, Output, State, MATCH, ALL
9
+ import dash_bootstrap_components as dbc
10
+ import plotly.graph_objs as go
11
+ except:
12
+ ...
13
+
14
+ import webbrowser
15
+ from threading import Timer
16
+
17
+ import json
18
+ import networkx as nx
19
+
20
+
21
+ from pathlib import Path
22
+ import pandas as pd
23
+
24
+ from modelclass import model
25
+ from modelhelp import cutout
26
+
27
+
28
+ #%%
29
+ if 0:
30
+ smallmodel = '''
31
+ frml <> a = c + b $
32
+ frml <> d1 = x + 3 * a(-1)+ c **2 +a $
33
+ frml <> d3 = x + 3 * a(-1)+c **3 $
34
+ Frml <> x = 0.5 * c +a$'''
35
+ des = {'A':'Bruttonationalprodukt i faste priser',
36
+ 'X': 'Eksport <æøåÆØÅ>;',
37
+ 'C': 'Forbrug'}
38
+ mmodel = model(smallmodel,var_description=des,svg=1,browser=1)
39
+ df = pd.DataFrame({'X' : [0.2,0.2] , 'C' :[0.,0.] , 'R':[1.,0.4] , 'P':[0.,0.4]})
40
+ df2 = pd.DataFrame({'X' : [0.2,0.2] , 'C' :[10.,10.] , 'R':[1.,0.4] , 'P':[0.,0.4]})
41
+
42
+ xx = mmodel(df)
43
+ yy = mmodel(df2)
44
+
45
+ class Dash_Mixin():
46
+
47
+
48
+ def modeldashexplain(self,pre_var='',selected_data_show ='baseline+last run',
49
+ debug=True,jupyter=False,show_trigger=False,port=5001):
50
+
51
+ def get_stack(df,v='Guess it',heading='Yes'):
52
+ pv = cutout(df,5. )
53
+ trace = [go.Bar(x=pv.columns, y=pv.loc[rowname,:], name=rowname,hovertemplate = '%{y:10.0f}%',) for rowname in pv.index]
54
+ out = { 'data': trace,
55
+ 'layout':
56
+ go.Layout(title=f'{heading}', barmode='relative',legend_itemclick='toggleothers',
57
+ yaxis = {'tickformat': ',.0','ticksuffix':'%'})
58
+ }
59
+ return out
60
+
61
+ def get_line(pv,v='Guess it',heading='Yes'):
62
+ trace = [go.Line(x=pv.columns, y=pv.loc[rowname,:], name=rowname) for rowname in pv.index]
63
+ out = { 'data': trace,
64
+ 'layout':
65
+ go.Layout(title=f'{heading}')
66
+ }
67
+ return out
68
+
69
+
70
+ def generate_table(dataframe, max_rows=10):
71
+ return html.Table([
72
+ html.Thead(
73
+ html.Tr([html.Th('var')]+[html.Th(col) for col in dataframe.columns])
74
+ ),
75
+ html.Tbody([
76
+ html.Tr([html.Td(dataframe.index[i])]+[html.Td(f'{dataframe.iloc[i][col]:25.2f}') for col in dataframe.columns])
77
+ for i in range(min(len(dataframe), max_rows))
78
+ ])
79
+ ])
80
+
81
+
82
+ if jupyter:
83
+ app = JupyterDash(__name__)
84
+ else:
85
+ app = dash.Dash(__name__)
86
+ selected_var = pre_var if pre_var else sorted(self.allvar.keys())[0]
87
+
88
+
89
+ app.layout = html.Div(
90
+
91
+ [
92
+ html.Div([
93
+
94
+ html.Div(dash_interactive_graphviz.DashInteractiveGraphviz(id="gv",engine='dot',
95
+ dot_source = self.explain(selected_var,up=0,select=False,showatt=True,lag=True,debug=0,dot=True,HR=True))
96
+ , style={'display': 'inline-block', 'vertical-align': 'bottom', 'margin-left': '3vw', 'margin-top': '3vw'} ),
97
+ html.Div(dcc.Graph(
98
+ id='graph',
99
+ figure=get_stack(nx.get_node_attributes(self.newgraph,'att')[selected_var],selected_var,heading=f'{selected_var}'))
100
+ , style={'display': 'inline-block', 'vertical-align': 'top', 'margin-left': '3vw','margin-right': '3vw', 'margin-top': '3vw'} ) ,
101
+
102
+ ]
103
+ , style=dict()),
104
+
105
+
106
+ html.Div(
107
+ [
108
+
109
+ html.H3("Variable"),
110
+ dcc.Markdown(
111
+ id='outvar-state',
112
+ children=f'{selected_var}'),
113
+
114
+ dcc.Dropdown(id='var',value=selected_var,options=[
115
+ dict(label=v, value=v)
116
+ for v in sorted(self.allvar.keys())],
117
+ )
118
+ ,
119
+ html.H3("Up, preceeding levels"),
120
+ dcc.Dropdown(id="up",value=1,options=[
121
+ dict(label=engine, value=engine)
122
+ for engine in list(range(10))],
123
+ ),
124
+ html.H3("Show"),
125
+ dcc.RadioItems(id='data_show',
126
+ options=[
127
+ {'label': 'Variables', 'value': False},
128
+ {'label': 'Attributions', 'value': True},
129
+ ],
130
+ value=False
131
+ ),
132
+
133
+ dcc.RadioItems(id='graph_show',
134
+ options=[
135
+ {'label': 'Values', 'value': 'values'},
136
+ {'label': 'Diff', 'value': 'diff'},
137
+ {'label': 'Attributions', 'value': 'att'},
138
+ ],
139
+ value='values',labelStyle={'display': 'block'}
140
+ ),
141
+
142
+ html.H3("Graph orientation"),
143
+ dcc.RadioItems(id='orient',
144
+ options=[
145
+ {'label': 'Vertical', 'value': False},
146
+ {'label': 'Horisontal', 'value': True},
147
+ ],
148
+ value=True
149
+ )
150
+
151
+ ],
152
+ style=dict(display="flex", flexDirection="column"),
153
+ ),
154
+
155
+
156
+
157
+ ],
158
+ style=dict(position="absolute", height="100%", width="100%", display="flex"),
159
+
160
+
161
+
162
+ )
163
+
164
+
165
+ @app.callback(
166
+ [Output("gv", "dot_source"),Output('outvar-state', "children"),Output('graph', "figure")],
167
+ [
168
+ Input('var', "value"),Input('gv', "selected_node"),Input('gv', "selected_edge"),Input('up', "value"),
169
+ Input('data_show', "value"),Input('graph_show', "value"),
170
+ Input('orient', "value")],
171
+ State('outvar-state','children')
172
+ )
173
+ def display_output( var,select_var,select_node,up,data_show,figtype,orient,outvar_state):
174
+ # value=self.drawmodel(svg=1,all=True,browser=0,pdf=0,des=True,dot=True)
175
+ ctx = dash.callback_context
176
+ if ctx.triggered:
177
+ trigger = ctx.triggered[0]['prop_id'].split('.')[0]
178
+
179
+ if trigger in ['var']:
180
+ try:
181
+ outvar=var[:]
182
+ except:
183
+ return [dash.no_update,dash.no_update,dash.no_update]
184
+
185
+
186
+
187
+ elif trigger == 'gv':
188
+ pass
189
+ try:
190
+ xvar= select_var.split('(')[0]
191
+ if xvar in self.endogene or xvar in self.exogene:
192
+ outvar = xvar[:]
193
+ except:
194
+ outvar= select_node.split('->')[0]
195
+ else:
196
+ outvar=outvar_state
197
+
198
+ value = self.explain(outvar,up=up,select=False,showatt=data_show,lag=True,debug=0,dot=True,HR=orient)
199
+
200
+
201
+
202
+ # else:
203
+ # value=self.draw(outvar,dot=True,up=int(up),down=int(down),all=False)
204
+ if show_trigger:
205
+ ctx_msg = json.dumps({
206
+ 'states': ctx.states,
207
+ 'triggered': ctx.triggered,
208
+ 'inputs': ctx.inputs
209
+ }, indent=2)
210
+ print(ctx_msg)
211
+ # print(f'{outvar=},{data_show=}')
212
+ # print(value)
213
+
214
+ if outvar in self.endogene:
215
+ if figtype == 'values':
216
+ out_graph = get_line(nx.get_node_attributes(self.newgraph,'values')[outvar].iloc[:2,:],outvar,outvar)
217
+ elif figtype == 'diff':
218
+ out_graph = get_line(nx.get_node_attributes(self.newgraph,'values')[outvar].iloc[[2],:],outvar,outvar)
219
+ elif figtype == 'att':
220
+ out_graph = get_stack(nx.get_node_attributes(self.newgraph,'att')[outvar],outvar,outvar)
221
+ else:
222
+ out_graph = get_line(nx.get_node_attributes(self.newgraph,'values')[outvar].iloc[[2],:],outvar,outvar)
223
+ else:
224
+ out_graph= dash.no_update
225
+
226
+
227
+
228
+
229
+
230
+ return [value,outvar,out_graph]
231
+
232
+ def open_browser(port=port):
233
+ webbrowser.open_new(f"http://localhost:{port}")
234
+
235
+
236
+ if jupyter:
237
+ Timer(1, open_browser).start()
238
+ app.run_server(debug=debug,port=port,mode='external')
239
+ else:
240
+ Timer(1, open_browser).start()
241
+ app.run_server(debug=debug,port=port)
242
+
243
+
244
+
245
+ if __name__ == "__main__":
246
+
247
+ from modelclass import model
248
+
249
+ class xmodel(model,Dash_Mixin):
250
+
251
+ ...
252
+
253
+ if not 'baseline' in locals():
254
+ mmodel,baseline = model.modelload('../Examples/ADAM/baseline.pcim',run=1,silent=0 )
255
+ scenarie = baseline.copy()
256
+ scenarie.TG = scenarie.TG + 0.05
257
+ _ = mmodel(scenarie)
258
+ setattr(model, "modeldashexplain", Dash_Mixin.modeldashexplain)
259
+ mmodel.modeldashexplain('FY',jupyter=False,show_trigger=True,debug=False)
260
+ #%%
261
+ pd.options.plotting.backend = "plotly"
262
+
263
+ df = pd.DataFrame(dict(a=[1,3,2], b=[3,2,1]))
264
+ fig = df.plot()
265
+ fig.show()
modeldashboot.py ADDED
@@ -0,0 +1,202 @@
1
+ try:
2
+ import dash_interactive_graphviz
3
+ from jupyter_dash import JupyterDash
4
+ import dash
5
+ from dash.dependencies import Input, Output, State
6
+ import dash_html_components as html
7
+ import dash_core_components as dcc
8
+ import dash_bootstrap_components as dbc
9
+ import plotly.graph_objs as go
10
+ except:
11
+ ...
12
+
13
+ import webbrowser
14
+ from threading import Timer
15
+
16
+ import json
17
+ import networkx as nx
18
+
19
+
20
+ from pathlib import Path
21
+ import pandas as pd
22
+
23
+ from modelclass import model
24
+ from modelhelp import cutout
25
+
26
+
27
+ #%%
28
+ if 0:
29
+ smallmodel = '''
30
+ frml <> a = c + b $
31
+ frml <> d1 = x + 3 * a(-1)+ c **2 +a $
32
+ frml <> d3 = x + 3 * a(-1)+c **3 $
33
+ Frml <> x = 0.5 * c +a$'''
34
+ des = {'A':'Bruttonationalprodukt i faste priser',
35
+ 'X': 'Eksport <æøåÆØÅ>;',
36
+ 'C': 'Forbrug'}
37
+ mmodel = model(smallmodel,var_description=des,svg=1,browser=1)
38
+ df = pd.DataFrame({'X' : [0.2,0.2] , 'C' :[0.,0.] , 'R':[1.,0.4] , 'P':[0.,0.4]})
39
+ df2 = pd.DataFrame({'X' : [0.2,0.2] , 'C' :[10.,10.] , 'R':[1.,0.4] , 'P':[0.,0.4]})
40
+
41
+ xx = mmodel(df)
42
+ yy = mmodel(df2)
43
+
44
+ class Dash_Mixin():
45
+
46
+ def modeldash(self,pre_var='',selected_data_show ='baseline+last run',debug=True,jupyter=False,show_trigger=False):
47
+ import dash_interactive_graphviz
48
+ from jupyter_dash import JupyterDash
49
+ import dash
50
+ from dash.dependencies import Input, Output, State
51
+ import dash_html_components as html
52
+ import dash_core_components as dcc
53
+
54
+ import webbrowser
55
+ from threading import Timer
56
+
57
+ import json
58
+
59
+ if jupyter:
60
+ app = JupyterDash(__name__)
61
+ else:
62
+ app = dash.Dash(__name__)
63
+
64
+ selected_var = pre_var if pre_var else sorted(self.allvar.keys())[0]
65
+
66
+
67
+ app.layout = html.Div(
68
+ [
69
+ html.Div([
70
+ dash_interactive_graphviz.DashInteractiveGraphviz(id="gv",engine='dot',
71
+ dot_source = self.draw(selected_var,dot=True,up=0,down=1,
72
+ last=0,all = 1 , HR=False)),],
73
+ style=dict(flexGrow=1, position="relative")
74
+ ,
75
+ ),
76
+
77
+
78
+ html.H3("Variable"),
79
+
80
+ html.Div(
81
+ [
82
+
83
+ html.H3("Variable"),
84
+ dcc.Markdown(
85
+ id='outvar-state',
86
+ children=f'{selected_var}'),
87
+
88
+ dcc.Dropdown(id='var',value=selected_var,options=[
89
+ dict(label=v, value=v)
90
+ for v in sorted(self.allvar.keys())],
91
+ )
92
+ ,
93
+ html.H3("Up, preceeding levels"),
94
+ dcc.Dropdown(id="up",value=0,options=[
95
+ dict(label=engine, value=engine)
96
+ for engine in list(range(10))],
97
+ ),
98
+ html.H3("Down, dependent levels"),
99
+ dcc.Dropdown(id="down",value=1,options=[
100
+ dict(label=engine, value=engine)
101
+ for engine in list(range(10))],
102
+ ),
103
+ html.H3("Data"),
104
+ dcc.Dropdown(id="data_show",value=selected_data_show,options=[
105
+ dict(label=engine, value=engine)
106
+ for engine in ['Variable names','baseline+last run','last run']],
107
+ ),
108
+ html.H3("Graph orientation"),
109
+ dcc.RadioItems(id='orient',
110
+ options=[
111
+ {'label': 'Vertical', 'value': False},
112
+ {'label': 'Horisontal', 'value': True},
113
+ ],
114
+ value=True
115
+ )
116
+
117
+ ],
118
+ style=dict(display="flex", flexDirection="column"),
119
+ ),
120
+ ],
121
+ style=dict(position="absolute", height="100%", width="100%", display="flex"),
122
+ )
123
+
124
+
125
+ @app.callback(
126
+ [Output("gv", "dot_source"),Output('outvar-state', "children")],
127
+ [
128
+ Input('var', "value"),Input('gv', "selected_node"),Input('up', "value"),
129
+ Input('down', "value"), Input('data_show', "value"),
130
+ Input('orient', "value")],
131
+ State('outvar-state','children')
132
+ )
133
+ def display_output( var,select_var,up,down,data_show,orient,outvar_state):
134
+ # value=self.drawmodel(svg=1,all=True,browser=0,pdf=0,des=True,dot=True)
135
+ ctx = dash.callback_context
136
+ if ctx.triggered:
137
+ if show_trigger:
138
+ ctx_msg = json.dumps({
139
+ 'states': ctx.states,
140
+ 'triggered': ctx.triggered,
141
+ 'inputs': ctx.inputs
142
+ }, indent=2)
143
+ print(ctx_msg)
144
+ # print(f'{outvar=},{data_show=}')
145
+ print(orient)
146
+ trigger = ctx.triggered[0]['prop_id'].split('.')[0]
147
+
148
+ if trigger in ['var']:
149
+ try:
150
+ outvar=var[:]
151
+ except:
152
+ return [dash.no_update,dash.no_update]
153
+
154
+
155
+
156
+ elif trigger == 'gv':
157
+ pass
158
+ try:
159
+ xvar= select_var.split('(')[0]
160
+ if xvar in self.endogene or xvar in self.exogene:
161
+ outvar = xvar[:]
162
+ except:
163
+ outvar= select_node.split('->')[0]
164
+ else:
165
+ outvar=outvar_state
166
+
167
+
168
+ value=self.draw(outvar,dot=True,up=up,down=down,
169
+ last=data_show=='last run',all =data_show=='baseline+last run' ,
170
+ HR=orient)
171
+
172
+ # else:
173
+ # value=self.draw(outvar,dot=True,up=int(up),down=int(down),all=False)
174
+
175
+
176
+
177
+ return [value,outvar]
178
+
179
+ def open_browser():
180
+ webbrowser.open_new(f"http://localhost:{5000}")
181
+
182
+ Timer(1, open_browser).start()
183
+ app.run_server(debug=debug,port=5000)
184
+
185
+
186
+ if __name__ == "__main__":
187
+
188
+ from modelclass import model
189
+
190
+ class xmodel(model,Dash_Mixin):
191
+
192
+ ...
193
+
194
+ if not 'baseline' in locals():
195
+ mmodel,baseline = model.modelload('../Examples/ADAM/baseline.pcim',run=1,silent=0 )
196
+ scenarie = baseline.copy()
197
+ scenarie.TG = scenarie.TG + 0.05
198
+ _ = mmodel(scenarie)
199
+ setattr(model, "modeldash", Dash_Mixin.modeldash)
200
+
201
+ mmodel.modeldash('FY',jupyter=False,show_trigger=True,debug=False)
202
+ #%%