ModelFlowIb 2.52__tar.gz → 2.54__tar.gz

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.
Files changed (51) hide show
  1. {modelflowib-2.52 → modelflowib-2.54}/ModelFlowIb.egg-info/PKG-INFO +2 -2
  2. {modelflowib-2.52 → modelflowib-2.54}/PKG-INFO +2 -2
  3. {modelflowib-2.52 → modelflowib-2.54}/modelclass.py +56 -22
  4. {modelflowib-2.52 → modelflowib-2.54}/modelgrabwf2.py +76 -27
  5. {modelflowib-2.52 → modelflowib-2.54}/modelnormalize.py +5 -0
  6. {modelflowib-2.52 → modelflowib-2.54}/modelwidget.py +34 -36
  7. {modelflowib-2.52 → modelflowib-2.54}/modelwidget_input.py +419 -279
  8. {modelflowib-2.52 → modelflowib-2.54}/pyproject.toml +1 -1
  9. {modelflowib-2.52 → modelflowib-2.54}/ModelFlowIb.egg-info/SOURCES.txt +0 -0
  10. {modelflowib-2.52 → modelflowib-2.54}/ModelFlowIb.egg-info/dependency_links.txt +0 -0
  11. {modelflowib-2.52 → modelflowib-2.54}/ModelFlowIb.egg-info/requires.txt +0 -0
  12. {modelflowib-2.52 → modelflowib-2.54}/ModelFlowIb.egg-info/top_level.txt +0 -0
  13. {modelflowib-2.52 → modelflowib-2.54}/modelBLfunk.py +0 -0
  14. {modelflowib-2.52 → modelflowib-2.54}/model_Excel.py +0 -0
  15. {modelflowib-2.52 → modelflowib-2.54}/model_cvx.py +0 -0
  16. {modelflowib-2.52 → modelflowib-2.54}/model_doable.py +0 -0
  17. {modelflowib-2.52 → modelflowib-2.54}/model_dynare.py +0 -0
  18. {modelflowib-2.52 → modelflowib-2.54}/model_financial_stability.py +0 -0
  19. {modelflowib-2.52 → modelflowib-2.54}/model_ifrs9.py +0 -0
  20. {modelflowib-2.52 → modelflowib-2.54}/model_latex.py +0 -0
  21. {modelflowib-2.52 → modelflowib-2.54}/model_latex_class.py +0 -0
  22. {modelflowib-2.52 → modelflowib-2.54}/model_run_numba.py +0 -0
  23. {modelflowib-2.52 → modelflowib-2.54}/modelclass2.py +0 -0
  24. {modelflowib-2.52 → modelflowib-2.54}/modeldash.py +0 -0
  25. {modelflowib-2.52 → modelflowib-2.54}/modeldashboot.py +0 -0
  26. {modelflowib-2.52 → modelflowib-2.54}/modeldashsidebar.py +0 -0
  27. {modelflowib-2.52 → modelflowib-2.54}/modeldekom.py +0 -0
  28. {modelflowib-2.52 → modelflowib-2.54}/modeldiff.py +0 -0
  29. {modelflowib-2.52 → modelflowib-2.54}/modeldisplay.py +0 -0
  30. {modelflowib-2.52 → modelflowib-2.54}/modelfeedback.py +0 -0
  31. {modelflowib-2.52 → modelflowib-2.54}/modelgrab.py +0 -0
  32. {modelflowib-2.52 → modelflowib-2.54}/modelhelp.py +0 -0
  33. {modelflowib-2.52 → modelflowib-2.54}/modelinvert.py +0 -0
  34. {modelflowib-2.52 → modelflowib-2.54}/modeljupyter.py +0 -0
  35. {modelflowib-2.52 → modelflowib-2.54}/modeljupytermagic.py +0 -0
  36. {modelflowib-2.52 → modelflowib-2.54}/modelmacrograb.py +0 -0
  37. {modelflowib-2.52 → modelflowib-2.54}/modelmanipulation.py +0 -0
  38. {modelflowib-2.52 → modelflowib-2.54}/modelmf.py +0 -0
  39. {modelflowib-2.52 → modelflowib-2.54}/modelnet.py +0 -0
  40. {modelflowib-2.52 → modelflowib-2.54}/modelnewton.py +0 -0
  41. {modelflowib-2.52 → modelflowib-2.54}/modelpattern.py +0 -0
  42. {modelflowib-2.52 → modelflowib-2.54}/modelpatternrev.py +0 -0
  43. {modelflowib-2.52 → modelflowib-2.54}/modelreport.py +0 -0
  44. {modelflowib-2.52 → modelflowib-2.54}/modelsandbox.py +0 -0
  45. {modelflowib-2.52 → modelflowib-2.54}/modelsandbox_Mixin.py +0 -0
  46. {modelflowib-2.52 → modelflowib-2.54}/modeltodo.py +0 -0
  47. {modelflowib-2.52 → modelflowib-2.54}/modeluserfunk.py +0 -0
  48. {modelflowib-2.52 → modelflowib-2.54}/modeluserfunk_old.py +0 -0
  49. {modelflowib-2.52 → modelflowib-2.54}/modelvis.py +0 -0
  50. {modelflowib-2.52 → modelflowib-2.54}/modelwidget_shinypy.py +0 -0
  51. {modelflowib-2.52 → modelflowib-2.54}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: ModelFlowIb
3
- Version: 2.52
3
+ Version: 2.54
4
4
  Summary: A tool to solve and manage dynamic economic models
5
5
  Author-email: Ib Hansen <your@email.com>
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: ModelFlowIb
3
- Version: 2.52
3
+ Version: 2.54
4
4
  Summary: A tool to solve and manage dynamic economic models
5
5
  Author-email: Ib Hansen <your@email.com>
6
6
  License: MIT
@@ -332,7 +332,7 @@ class BaseModel():
332
332
  self.endogene_true = self.endogene if self.normalized else {
333
333
  v for v in self.exogene if v+'___RES' in self.endogene}
334
334
 
335
-
335
+ self.check_endo_rhs()
336
336
  # dummy variables for variables for which to calculate adjustment variables
337
337
 
338
338
 
@@ -1070,8 +1070,19 @@ class BaseModel():
1070
1070
  len(self.endogene))
1071
1071
  return '<\n'+out+'>'
1072
1072
 
1073
-
1074
- #
1073
+ def check_endo_rhs(self):
1074
+ if self.normalized:
1075
+ for i,endovar in enumerate(sorted(self.endogene)):
1076
+ if i >= 2000000000000000 :break
1077
+ this_term = self.allvar[endovar]['terms']
1078
+ ap = self.allvar[endovar]['assigpos']
1079
+ lhs = {t.var for t in this_term[:ap] if t.var}
1080
+ rhs_nolag = {t.var for t in this_term[ap:] if t.var and not t.lag}
1081
+ both = lhs & rhs_nolag
1082
+ if both:
1083
+ print('\n\n*** PROBLEM **')
1084
+ print(self.allvar[endovar]['frml'])
1085
+ raise Exception (f'ERROR in frml for {endovar} this is on right hand side un-lagged {both}')
1075
1086
 
1076
1087
 
1077
1088
  class Org_model_Mixin():
@@ -2390,13 +2401,24 @@ class Dekomp_Mixin():
2390
2401
  mfrml = model(self.allvar[varnavn]['frml'],
2391
2402
  funks=self.funks) # calculate the formular
2392
2403
  print_per = mfrml.smpl(start_, end_, altdf_)
2404
+
2405
+ old_start, old_end = altdf_.index.slice_locs(
2406
+ print_per[0], print_per[-1])
2407
+ new_start = max(0, old_start-1)
2408
+ new_end = min(len(self.basedf.index), old_end)
2409
+ calc_per = self.basedf.index[new_start:new_end]
2410
+
2411
+ # print(print_per)
2412
+ # print(calc_per)
2413
+
2414
+
2393
2415
  vars = mfrml.allvar.keys()
2394
2416
  varterms = [(term.var, int(term.lag) if term.lag else 0)
2395
2417
  for term in mfrml.allvar[varnavn]['terms'] if term.var and not (term.var == varnavn and term.lag == '')]
2396
2418
  # now we have droped dublicate terms and sorted
2397
2419
  sterms = sorted(set(varterms), key=lambda x: varterms.index(x))
2398
2420
  # find all the eksperiments to be performed
2399
- eksperiments = [(vt, t) for vt in sterms for t in print_per]
2421
+ eksperiments = [(vt, t) for vt in sterms for t in calc_per]
2400
2422
  if time_att:
2401
2423
  ...
2402
2424
  smallalt = altdf_.loc[:, vars].copy(deep=True) # for speed
@@ -2420,10 +2442,8 @@ class Dekomp_Mixin():
2420
2442
  alldf[e], e[1], e[1], silent=True) for e in eksperiments}
2421
2443
  # dataframes with the effect of each update
2422
2444
  diffres = {e: smallalt - allres[e] for e in eksperiments}
2423
- diffres_growth = {e: smallalt.pct_change() - allres[e].pct_change() for e in eksperiments}
2424
2445
  # we are only interested in the efect on the left hand variable
2425
2446
  res = {e: diffres[e].loc[e[1], varnavn] for e in eksperiments}
2426
- res_growth = {e: diffres_growth[e].loc[e[1], varnavn] for e in eksperiments}
2427
2447
  # the resulting dataframe
2428
2448
  multi = pd.MultiIndex.from_tuples([e[0] for e in eksperiments], names=[
2429
2449
  'Variable', 'lag']).drop_duplicates()
@@ -2431,10 +2451,21 @@ class Dekomp_Mixin():
2431
2451
  att_level = pd.DataFrame(index=multi, columns=print_per)
2432
2452
  for e in eksperiments:
2433
2453
  att_level.at[e[0], e[1]] = res[e]
2454
+ att_level = att_level.loc[:,print_per]
2455
+
2456
+ experiment_values_dict = {e: allres[e].loc[e[1], varnavn] for e in eksperiments}
2457
+ experiment_values = pd.DataFrame(index=multi, columns=calc_per).astype(float)
2458
+ for e in eksperiments:
2459
+ experiment_values.at[e[0], e[1]] = experiment_values_dict[e]
2434
2460
 
2435
- att_growth = pd.DataFrame(index=multi, columns=print_per)
2461
+ original_values_dict = {e: alldf[e].loc[e[1] , varnavn] for e in eksperiments}
2462
+ original_values = pd.DataFrame(index=multi, columns=calc_per).astype(float)
2436
2463
  for e in eksperiments:
2437
- att_growth.at[e[0], e[1]] = res_growth[e]*100.
2464
+ original_values.at[e[0], e[1]] = original_values_dict[e]
2465
+
2466
+
2467
+ att_growth = ((original_values.pct_change(axis=1) - experiment_values.pct_change(axis=1))*100.).loc[:,print_per]
2468
+
2438
2469
 
2439
2470
  # a dataframe with some summaries
2440
2471
  diff_level = pd.DataFrame(index=multi, columns=print_per)
@@ -2462,30 +2493,33 @@ class Dekomp_Mixin():
2462
2493
 
2463
2494
 
2464
2495
  #
2465
- att_pct = (att_level / (difendo[print_per]) *(abs(difendo[print_per])>0.000001) * 100).sort_values(
2496
+ att_pct = (att_level / (difendo[print_per]) *((abs(difendo[print_per])>0.001)) * 100.).sort_values(
2466
2497
  print_per[-1], ascending=False) # each contrinution in pct of total change
2498
+ # att_pct = (att_level / (difendo[print_per]) *
2499
+ # ((abs(difendo) > 0.001))).sort_values(
2500
+ # print_per[-1], ascending=False) # each contrinution in pct of total change
2467
2501
  # breakpoint()
2468
2502
  residual = att_pct.sum() - 100
2469
2503
  att_pct.loc[('Total', 0), print_per] = att_pct.sum()
2470
2504
  att_pct.loc[('Residual', 0), print_per] = residual
2471
2505
  if lprint:
2472
2506
  print('\nFormula :', mfrml.allvar[varnavn]['frml'], '\n')
2473
- print(diff_level.to_string(
2507
+ print(diff_level.to_string(na_rep=' ',
2474
2508
  float_format=lambda x: '{0:10.2f}'.format(x)))
2475
- print('\n Contributions to differende for ', varnavn)
2476
- print(att_level.to_string(
2509
+ print('\n Contributions to difference for ', varnavn)
2510
+ print(att_level.to_string(na_rep=' ',
2477
2511
  float_format=lambda x: '{0:10.2f}'.format(x)))
2478
- print('\n Share of contributions to differende for ', varnavn)
2479
- print(att_pct.to_string(
2480
- float_format=lambda x: '{0:10.0f}%'.format(x)))
2512
+ print('\n Share of contributions to difference for ', varnavn)
2513
+ print(att_pct.to_string(na_rep=' ',
2514
+ float_format=lambda x: '{0:9.0f}%'.format(x)))
2481
2515
 
2482
2516
  print('\n Difference in growth rate', varnavn)
2483
- print(print(diff_growth.to_string(
2484
- float_format=lambda x: '{0:10.1f}%'.format(x))))
2517
+ print(print(diff_growth.to_string(na_rep=' ',
2518
+ float_format=lambda x: '{0:9.1f}%'.format(x))))
2485
2519
 
2486
2520
  print('\n Contribution to growth rate', varnavn)
2487
- print(att_growth.to_string(
2488
- float_format=lambda x: '{0:10.1f}%'.format(x)))
2521
+ print(att_growth.to_string(na_rep=' ',
2522
+ float_format=lambda x: '{0:9.1f}%'.format(x)))
2489
2523
 
2490
2524
  att_pct = att_pct[att_pct.columns].astype(float)
2491
2525
  dekomp_res_name = namedtuple('dekompres', 'diff_level, att_level, att_pct, ,diff_growth , att_growth')
@@ -2705,7 +2739,7 @@ class Dekomp_Mixin():
2705
2739
  # # breakpoint()
2706
2740
  # ddf0 = join_name_lag(xx[2] if pct else xx[1]).pipe(
2707
2741
  # lambda df: df.loc[[i for i in df.index if i != 'Total'], :])
2708
- print(f'{self.current_per=}')
2742
+ # print(f'{self.current_per=}')
2709
2743
  ddf0 = self.get_att_pct(varnavn,lag=lag,time_att=time_att) if pct else self.get_att_level(varnavn,lag=lag)
2710
2744
  if rename:
2711
2745
  ddf0 = ddf0.rename(index= self.var_description)
@@ -4982,7 +5016,7 @@ class Display_Mixin():
4982
5016
  dfs = self.keep_var_dict(pat, start, end, start_ofset, end_ofset)
4983
5017
 
4984
5018
  if showtype == 'growth':
4985
- dfs = {v: vdf.pct_change()*100. for v, vdf in dfs.items()}
5019
+ dfs = {v: vdf.astype('float').pct_change()*100. for v, vdf in dfs.items()}
4986
5020
 
4987
5021
  elif showtype == 'change':
4988
5022
  dfs = {v: vdf.diff() for v, vdf in dfs.items()}
@@ -5048,7 +5082,7 @@ class Display_Mixin():
5048
5082
 
5049
5083
 
5050
5084
  if showtype == 'growth':
5051
- dfs = {v: vdf.pct_change()*100. for v, vdf in dfs.items()}
5085
+ dfs = {v: vdf.astype('float').pct_change()*100. for v, vdf in dfs.items()}
5052
5086
 
5053
5087
  elif showtype == 'qoq_ar':
5054
5088
  dfs = {v: ((1.+vdf.pct_change())**4.-1.)*100. for v, vdf in dfs.items()}
@@ -223,33 +223,81 @@ def wf2_to_clean(wf2name,modelname='',save_file = False,freq='A'):
223
223
 
224
224
  @dataclass
225
225
  class GrabWfModel():
226
- '''This class takes a world bank model specification, variable data and variable description
227
- and transform it to ModelFlow business language
228
-
229
- args:
230
- filename : any = '' #wf1 name
231
- modelname : any = ''
232
- freq : str = 'A'
233
- eviews_run_lines : list =field(default_factory=list)
234
- model_all_about : dict = field(default_factory=dict)
235
- start : any = None # start of testing if not overruled by mfmsa
236
- end : any = None # end of testing if not overruled by mfmsa
237
- country_trans : any = lambda x:x[:] # function which transform model specification
238
- country_df_trans : any = lambda x:x # function which transforms initial dataframe
239
- make_fitted : bool = False # if True, a clean equation for fittet variables is created
240
- fit_start : any = 2000 # start of fittet model
241
- fit_end : any = None # end of fittet model unless overruled by mfmsa
242
- do_add_factor_calc : bool = True # calculate the add factors
243
- test_frml : str ='' # a testmodel as string if used no wf processing
244
- disable_progress : bool = False # Disable progress bar
245
- save_file : bool = False # save information to file
246
- model_description : str = '' # model description
247
- cty : str = '' # country ISO code like PAK, default to 3 first letter in modelname
248
- cty_name : str = '' # country name like Pakistan, default to standard mapping in ISO standard
249
- var_groups : dict = field(default_factory=dict,init=False) # var_groups
250
- extra_var_descriptions : dict = field(default_factory=dict) # extra variable descriptions
226
+ """
227
+ This class takes a World Bank model specification, variable data, and variable description,
228
+ and transforms it into ModelFlow business language.
251
229
 
252
- '''
230
+ Args:
231
+ filename : any = '' # wf1 name
232
+ modelname : any = ''
233
+ freq : str = 'A'
234
+ eviews_run_lines : list = field(default_factory=list)
235
+ model_all_about : dict = field(default_factory=dict)
236
+ start : any = None # start of testing if not overruled by mfmsa
237
+ end : any = None # end of testing if not overruled by mfmsa
238
+ country_trans : any = lambda x:x[:] # function which transforms model specification
239
+ country_df_trans : any = lambda x:x # function which transforms initial dataframe
240
+ make_fitted : bool = False # if True, a clean equation for fitted variables is created
241
+ fit_start : any = 2000 # start of fitted model
242
+ fit_end : any = None # end of fitted model unless overruled by mfmsa
243
+ do_add_factor_calc : bool = True # calculate the add factors
244
+ test_frml : str = '' # a test model as string; if used, no wf processing
245
+ disable_progress : bool = False # disable progress bar
246
+ save_file : bool = False # save information to file
247
+ model_description : str = '' # model description
248
+ cty : str = '' # country ISO code like PAK, defaults to first 3 letters of modelname
249
+ cty_name : str = '' # country name like Pakistan, default via ISO mapping
250
+ var_groups : dict = field(default_factory=dict, init=False) # variable groups
251
+ extra_var_descriptions : dict = field(default_factory=dict) # extra variable descriptions
252
+
253
+ Methods:
254
+ __post_init__():
255
+ Initialize and process the model, transform equations, perform syntax checks,
256
+ and set up the model and data for simulation and analysis.
257
+
258
+ print_frml(pat='*', eviews=''):
259
+ Print model equations matching a wildcard pattern and optional EViews content filter.
260
+
261
+ trans_eviews(rawmodel):
262
+ (staticmethod) Convert EViews-style equations into ModelFlow syntax.
263
+
264
+ var_description (property):
265
+ Return enriched variable descriptions combining WF1 file, WB defaults, and extras.
266
+
267
+ wb_default_descriptions (property):
268
+ Load default World Bank variable descriptions from an online repository.
269
+
270
+ mfmsa_options (property):
271
+ Return the raw MFMSA options XML string.
272
+
273
+ mfmsa_options_dict (property):
274
+ Parse and return MFMSA options as a nested dictionary.
275
+
276
+ mfmsa_start_end (property):
277
+ Retrieve start and end periods from MFMSA metadata.
278
+
279
+ mfmsa_country (property):
280
+ Retrieve the country ISO code from MFMSA metadata.
281
+
282
+ mfmsa_quasiIdentities (property):
283
+ Return a set of quasi-identity variable names from MFMSA.
284
+
285
+ var_groups_default (property):
286
+ Provide default variable groupings for World Bank models.
287
+
288
+ dfmodel (property):
289
+ Return the transformed and enriched dataframe for model calculation.
290
+
291
+ __call__():
292
+ Return the processed model object and base input dataframe.
293
+
294
+ test_model(start=None, end=None, maxvar=1_000_000, maxerr=100, tol=0.0001,
295
+ showall=False, showinput=False, nofit=True):
296
+ Compare model calculations against input data to validate model fidelity.
297
+
298
+ iso_countries (property):
299
+ Return a dictionary mapping ISO country codes to country names.
300
+ """
253
301
 
254
302
  filename : any = '' #wf1 name
255
303
  modelname : any = ''
@@ -482,7 +530,8 @@ class GrabWfModel():
482
530
  rawmodel2 = rawmodel1.replace('^','**').replace('""',' ').replace('"',' ').\
483
531
  replace('@EXP','exp').replace('@RECODE','recode').replace('@MOVAV','movavg').replace('@LOGIT','logit_inverse') \
484
532
  .replace('@MEAN(@PC(','@AVERAGE_GROWTH((').replace('@PCY','PCT_GROWTH').replace('@PC','PCT_GROWTH')\
485
- .replace('@PMAX','MAX').replace('@TREND','EVIEWS_TREND').replace('@ABS','ABS')
533
+ .replace('@PMAX','MAX').replace('@TREND','EVIEWS_TREND').replace('@ABS','ABS').replace('@SQRT(','SQRT(')\
534
+ .replace('@PMAX(','MAX(') .replace('@CNORM(','NORMCDF(')
486
535
  # @ELEM and @DURING
487
536
  # @ELEM and @DURING
488
537
  rawmodel3 = nz.elem_trans(rawmodel2)
@@ -167,12 +167,17 @@ def preprocess(udtryk,funks=[]):
167
167
  while pct_match := funk_in('PCT_GROWTH',udtryk_up):
168
168
  forpc,pcudtryk,efterpc=funk_find_arg(pct_match,udtryk_up)
169
169
  udtryk_up=f'{forpc} (100 * ( ({pcudtryk}) / ({lagone(pcudtryk,funks=funks)}) -1)) {efterpc}'
170
+
171
+ while pct_match := funk_in('PCY',udtryk_up):
172
+ forpc,pcudtryk,efterpc=funk_find_arg(pct_match,udtryk_up)
173
+ udtryk_up=f'{forpc} (100 * ( ({pcudtryk}) / ({lagone(pcudtryk,funks=funks,laglead=-4)}) -1)) {efterpc}'
170
174
 
171
175
  while diff_match := funk_in('DIFF' , udtryk_up):
172
176
  fordif,difudtryk_up,efterdif=funk_find_arg(diff_match,udtryk_up)
173
177
  udtryk_up=fordif+'(('+difudtryk_up+')-('+lagone(difudtryk_up+'',funks=funks)+'))'+efterdif
174
178
 
175
179
  while diff_match := funk_in('D' , udtryk_up):
180
+ print(f'{udtryk_up} on D')
176
181
  fordif,difudtryk_up,efterdif=funk_find_arg(diff_match,udtryk_up)
177
182
  difudtryk_up = difudtryk_up.replace(' ','').replace(',0,1','') if difudtryk_up.endswith(',0,1') else difudtryk_up
178
183
  udtryk_up=fordif+'(('+difudtryk_up+')-('+lagone(difudtryk_up+'',funks=funks)+'))'+efterdif
@@ -9,17 +9,20 @@ To define Jupyter widgets show variables.
9
9
  import pandas as pd
10
10
  import ipywidgets as widgets
11
11
 
12
- try:
13
- from ipysheet import sheet, cell, current
14
- from ipysheet.pandas_loader import from_dataframe, to_dataframe
15
- except:
16
- ...
17
- # print('No ipysheet in notebook version 7')
12
+ # try:
13
+ # from ipysheet import sheet, cell, current
14
+ # from ipysheet.pandas_loader import from_dataframe, to_dataframe
15
+ # except:
16
+ # ...
17
+ # print('No ipysheet ')
18
18
  from IPython.display import display, clear_output,Latex, Markdown
19
19
  from dataclasses import dataclass,field
20
20
  import matplotlib.pylab as plt
21
21
 
22
-
22
+ try:
23
+ from ipydatagrid import DataGrid
24
+ except Exception as e:
25
+ print( 'no update sheets',e)
23
26
 
24
27
  from modelclass import insertModelVar
25
28
  from modelclass import model
@@ -74,41 +77,36 @@ class tabwidget:
74
77
 
75
78
  @dataclass
76
79
  class sheetwidget:
77
- ''' class defining a widget which updates from a sheet '''
78
- df_var : pd.DataFrame = field(default_factory=pd.DataFrame) # definition
79
- trans : any = lambda x : x # renaming of variables
80
- transpose : bool = False # orientation of dataframe
81
- expname : str = "Carbon tax rate, US$ per tonn "
82
-
80
+ ''' Class defining a widget with a data grid (using ipydatagrid) '''
81
+ df_var: pd.DataFrame = field(default_factory=pd.DataFrame)
82
+ trans: any = lambda x: x # Translation of variable names
83
+ transpose: bool = False # If the dataframe should be transposed
84
+ heading: str = ""
83
85
 
84
86
  def __post_init__(self):
85
- ...
86
-
87
- self.wexp = widgets.Label(value = self.expname,layout={'width':'54%'})
88
-
89
-
90
87
  newnamedf = self.df_var.copy().rename(columns=self.trans)
91
- self.org_df_var = self.newnamedf.T if self.transpose else newnamedf
92
-
93
- self.wsheet = sheet(from_dataframe(self.org_df_var),column_resizing=True)
94
- self.org_values = [c.value for c in self.wsheet.cells]
95
- self.datawidget=widgets.VBox([self.wexp,self.wsheet]) if len(self.expname) else self.wsheet
88
+ self.org_df_var = newnamedf.T if self.transpose else newnamedf
89
+
90
+ column_widths = {col: max(len(col), 10) * 9 for col in self.org_df_var.columns} # Adjust column width dynamically
91
+ self.data_grid = DataGrid(pd.DataFrame(self.org_df_var),
92
+ column_widths=column_widths, enable_filters=False,enable_sort=False,
93
+ editable=True, index_name = 'year')
94
+ self.org_values = self.org_df_var.copy()
95
+
96
+ self.datawidget = widgets.VBox([widgets.Label(value=self.heading), self.data_grid]) if len(self.heading) else self.data_grid
96
97
 
97
- def update_df(self,df,current_per=None):
98
- # breakpoint()
99
- self.df_new_var = to_dataframe(self.wsheet).T if self.transpose else to_dataframe(self.wsheet)
100
- self.df_new_var.columns = self.df_var.columns
101
- self.df_new_var.index = self.df_var.index
98
+ def update_df(self, df, current_per=None):
99
+ updated_df = pd.DataFrame(self.data_grid.data)
100
+ if self.transpose:
101
+ updated_df = updated_df.T
102
102
 
103
- 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
104
- pass
103
+ updated_df.columns = self.df_var.columns
104
+ updated_df.index = self.df_var.index
105
+ df.loc[updated_df.index, updated_df.columns] = df.loc[updated_df.index, updated_df.columns] + updated_df
105
106
  return df
106
-
107
-
108
- def reset(self,g):
109
- for c,v in zip(self.wsheet.cells,self.org_values):
110
- c.value = v
111
-
107
+
108
+ def reset(self, g):
109
+ self.data_grid.data = pd.DataFrame(self.org_values)
112
110
 
113
111
 
114
112
  @dataclass