ModelFlowIb 2.67__tar.gz → 2.69__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.
- {modelflowib-2.67 → modelflowib-2.69}/ModelFlowIb.egg-info/PKG-INFO +1 -1
- {modelflowib-2.67 → modelflowib-2.69}/PKG-INFO +1 -1
- {modelflowib-2.67 → modelflowib-2.69}/modelmf.py +38 -38
- {modelflowib-2.67 → modelflowib-2.69}/modelwidget_input.py +167 -266
- {modelflowib-2.67 → modelflowib-2.69}/pyproject.toml +1 -1
- {modelflowib-2.67 → modelflowib-2.69}/ModelFlowIb.egg-info/SOURCES.txt +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/ModelFlowIb.egg-info/dependency_links.txt +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/ModelFlowIb.egg-info/requires.txt +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/ModelFlowIb.egg-info/top_level.txt +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelBLfunk.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_Excel.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_cvx.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_doable.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_dynare.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_financial_stability.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_ifrs9.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_latex.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_latex_class.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/model_run_numba.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelclass.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelclass2.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelconstruct.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldash.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldashboot.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldashsidebar.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldekom.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldiff.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeldisplay.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelestimation.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelfeedback.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelgrab.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelgrabwf2.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelhelp.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelinvert.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeljupyter.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeljupytermagic.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelmacrograb.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelmanipulation.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelnet.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelnewton.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelnormalize.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelpattern.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelpatternrev.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelreport.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelsandbox.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelsandbox_Mixin.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeltodo.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeluserfunk.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modeluserfunk_old.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelvis.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelwidget.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelwidget_input_old.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/modelwidget_shinypy.py +0 -0
- {modelflowib-2.67 → modelflowib-2.69}/setup.cfg +0 -0
|
@@ -230,48 +230,48 @@ if not hasattr(pd.DataFrame,'mf'):
|
|
|
230
230
|
print('hello from ibloc')
|
|
231
231
|
return
|
|
232
232
|
|
|
233
|
-
def
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
233
|
+
def mfquery_0(pat, df):
|
|
234
|
+
'''
|
|
235
|
+
Returns a DataFrame with columns matching the pattern(s), case-insensitive.
|
|
236
|
+
The pattern can be a string or a list of patterns.
|
|
237
|
+
Wildcards: * and ?
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
pat (string or list of strings)
|
|
241
|
+
df (DataFrame)
|
|
242
|
+
Returns:
|
|
243
|
+
DataFrame subset
|
|
244
|
+
'''
|
|
245
|
+
if isinstance(pat, list):
|
|
246
|
+
patterns = pat
|
|
247
|
+
else:
|
|
248
|
+
patterns = [pat]
|
|
249
|
+
|
|
250
|
+
# Lowercase lookup for case-insensitive matching
|
|
251
|
+
col_map = {str(c) .lower(): c for c in df.columns}
|
|
252
|
+
lower_cols = list(col_map.keys())
|
|
253
|
+
|
|
254
|
+
seen = set()
|
|
255
|
+
names = []
|
|
256
|
+
|
|
257
|
+
for p in patterns:
|
|
258
|
+
for up in p.lower().split():
|
|
259
|
+
for v in fnmatch.filter(lower_cols, up):
|
|
260
|
+
orig = col_map[v]
|
|
261
|
+
if orig not in seen:
|
|
262
|
+
seen.add(orig)
|
|
263
|
+
names.append(orig)
|
|
264
|
+
|
|
265
|
+
return df.loc[:, names]
|
|
266
|
+
|
|
267
|
+
|
|
268
268
|
@pd.api.extensions.register_dataframe_accessor("mfquery")
|
|
269
|
-
class
|
|
269
|
+
class mfquery:
|
|
270
270
|
def __init__(self, pandas_obj):
|
|
271
271
|
self._obj = pandas_obj
|
|
272
|
-
|
|
272
|
+
|
|
273
273
|
def __call__(self, pat):
|
|
274
|
-
return
|
|
274
|
+
return mfquery_0(pat, self._obj)
|
|
275
275
|
|
|
276
276
|
|
|
277
277
|
def f(a):
|
|
@@ -204,7 +204,6 @@ from __future__ import annotations
|
|
|
204
204
|
from abc import ABC, abstractmethod
|
|
205
205
|
from copy import copy
|
|
206
206
|
from dataclasses import dataclass, field
|
|
207
|
-
from pathlib import Path
|
|
208
207
|
from typing import Any, Callable, Dict, List, Tuple
|
|
209
208
|
|
|
210
209
|
import pandas as pd
|
|
@@ -227,9 +226,11 @@ from ipywidgets import (
|
|
|
227
226
|
Tab,
|
|
228
227
|
Text,
|
|
229
228
|
VBox,
|
|
230
|
-
Box,
|
|
229
|
+
Box,Output
|
|
231
230
|
)
|
|
232
231
|
|
|
232
|
+
from ipydatagrid import DataGrid
|
|
233
|
+
from ipydatagrid import TextRenderer
|
|
233
234
|
|
|
234
235
|
import matplotlib.pyplot as plt
|
|
235
236
|
|
|
@@ -237,18 +238,28 @@ import matplotlib.pyplot as plt
|
|
|
237
238
|
# Optional dependency: ipydatagrid
|
|
238
239
|
# ---------------------------------------------------------------------------
|
|
239
240
|
|
|
240
|
-
try:
|
|
241
|
-
from ipydatagrid import DataGrid
|
|
242
|
-
from ipydatagrid import TextRenderer
|
|
243
|
-
_HAVE_IPYDATAGRID = True
|
|
244
|
-
except Exception:
|
|
245
|
-
DataGrid = object # type: ignore
|
|
246
|
-
TextRenderer = object # type: ignore
|
|
247
|
-
_HAVE_IPYDATAGRID = False
|
|
248
241
|
|
|
249
242
|
from modelhelp import debug_var
|
|
250
243
|
|
|
244
|
+
WIDGET_REGISTRY = {}
|
|
251
245
|
|
|
246
|
+
def register_widget(cls):
|
|
247
|
+
WIDGET_REGISTRY[cls.__name__] = cls
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
return cls
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# safe helper near the top of the file
|
|
254
|
+
def _detect_render_mode() -> str:
|
|
255
|
+
try:
|
|
256
|
+
from IPython import get_ipython
|
|
257
|
+
ip = get_ipython()
|
|
258
|
+
if ip is not None and 'google.colab' in str(ip):
|
|
259
|
+
return 'colab'
|
|
260
|
+
except Exception:
|
|
261
|
+
pass
|
|
262
|
+
return 'classic'
|
|
252
263
|
# ---------------------------------------------------------------------------
|
|
253
264
|
# ABC interfaces
|
|
254
265
|
# ---------------------------------------------------------------------------
|
|
@@ -274,7 +285,7 @@ class WidgetABC(ABC):
|
|
|
274
285
|
|
|
275
286
|
|
|
276
287
|
class ContainerWidgetABC(WidgetABC):
|
|
277
|
-
"""A widget that contains
|
|
288
|
+
"""A widget that contains basic widgets as children """
|
|
278
289
|
|
|
279
290
|
@property
|
|
280
291
|
@abstractmethod
|
|
@@ -332,7 +343,7 @@ class SingleWidgetBase(WidgetABC):
|
|
|
332
343
|
@dataclass
|
|
333
344
|
class ContainerWidgetBase(ContainerWidgetABC):
|
|
334
345
|
"""
|
|
335
|
-
Base for container
|
|
346
|
+
Base for container which contains widgets
|
|
336
347
|
|
|
337
348
|
Subclasses should build:
|
|
338
349
|
- ``self._children``: list of :class:`WidgetABC`
|
|
@@ -370,36 +381,68 @@ class ContainerWidgetBase(ContainerWidgetABC):
|
|
|
370
381
|
# Factory
|
|
371
382
|
# ---------------------------------------------------------------------------
|
|
372
383
|
|
|
373
|
-
def make_widget(widgetdef_or_type, widgetdict=None,render_mode = 'classic'):
|
|
374
|
-
"""
|
|
375
|
-
Instantiate a widget from a definition.
|
|
376
384
|
|
|
377
|
-
|
|
378
|
-
|
|
385
|
+
def make_widget(widgetdef_or_type, widgetdict=None, render_mode=None):
|
|
386
|
+
"""
|
|
387
|
+
Create and return a widget instance from a widget type and definition.
|
|
379
388
|
|
|
380
|
-
|
|
381
|
-
|
|
389
|
+
The function resolves the widget class name from the requested widget type
|
|
390
|
+
and rendering mode, looks it up in ``WIDGET_REGISTRY``, instantiates it with
|
|
391
|
+
``widgetdict``, and verifies that the created object inherits from
|
|
392
|
+
``WidgetABC``.
|
|
382
393
|
|
|
383
394
|
Parameters
|
|
384
395
|
----------
|
|
385
|
-
widgetdef_or_type:
|
|
386
|
-
Either the widget type
|
|
387
|
-
``
|
|
388
|
-
widgetdict:
|
|
389
|
-
|
|
396
|
+
widgetdef_or_type : str or tuple[str, dict]
|
|
397
|
+
Either the widget type as a string, or a ``(widgettype, widgetdict)``
|
|
398
|
+
pair. If ``widgetdict`` is not provided, this argument must be the pair.
|
|
399
|
+
widgetdict : dict, optional
|
|
400
|
+
Dictionary with the widget configuration passed to the widget class
|
|
401
|
+
constructor. If omitted, ``widgetdef_or_type`` is expected to contain
|
|
402
|
+
both the widget type and the widget definition.
|
|
403
|
+
render_mode : {"classic", "colab"}, optional
|
|
404
|
+
Rendering mode used to select the widget class name. If omitted, the
|
|
405
|
+
mode is detected automatically: ``"colab"`` when running in Google
|
|
406
|
+
Colab, otherwise ``"classic"``.
|
|
390
407
|
|
|
391
408
|
Returns
|
|
392
409
|
-------
|
|
393
410
|
WidgetABC
|
|
394
|
-
|
|
411
|
+
An instantiated widget object.
|
|
395
412
|
|
|
396
413
|
Raises
|
|
397
414
|
------
|
|
398
415
|
KeyError
|
|
399
|
-
If
|
|
416
|
+
If the resolved widget class name is not found in ``WIDGET_REGISTRY``.
|
|
400
417
|
TypeError
|
|
401
|
-
If the
|
|
418
|
+
If the instantiated object does not inherit from ``WidgetABC``.
|
|
419
|
+
|
|
420
|
+
Notes
|
|
421
|
+
-----
|
|
422
|
+
For ``render_mode="classic"``, the class name is resolved as
|
|
423
|
+
``f"{widgettype}widget"``.
|
|
424
|
+
|
|
425
|
+
For other render modes, the class name is usually also
|
|
426
|
+
``f"{widgettype}widget"``, except for ``widgettype == "tab"``, where the
|
|
427
|
+
Colab-specific class name ``f"colab{widgettype}widget"`` is used.
|
|
428
|
+
|
|
429
|
+
Examples
|
|
430
|
+
--------
|
|
431
|
+
Create a widget from a type and config::
|
|
432
|
+
|
|
433
|
+
w = make_widget("sheet", {"title": "Overview"})
|
|
434
|
+
|
|
435
|
+
Create a widget from a ``(type, config)`` tuple::
|
|
436
|
+
|
|
437
|
+
w = make_widget(("sheet", {"title": "Overview"}))
|
|
438
|
+
|
|
439
|
+
Force Colab rendering::
|
|
440
|
+
|
|
441
|
+
w = make_widget("tab", {"tabs": [...]}, render_mode="colab")
|
|
402
442
|
"""
|
|
443
|
+
if render_mode is None:
|
|
444
|
+
render_mode = _detect_render_mode()
|
|
445
|
+
|
|
403
446
|
if widgetdict is None:
|
|
404
447
|
widgettype, widgetdict = widgetdef_or_type
|
|
405
448
|
else:
|
|
@@ -407,26 +450,30 @@ def make_widget(widgetdef_or_type, widgetdict=None,render_mode = 'classic'):
|
|
|
407
450
|
|
|
408
451
|
if render_mode == 'classic':
|
|
409
452
|
clsname = f"{widgettype}widget"
|
|
410
|
-
else:
|
|
411
|
-
if widgettype ==
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
453
|
+
else:
|
|
454
|
+
clsname = f"colab{widgettype}widget" if widgettype == "tab" else f"{widgettype}widget"
|
|
455
|
+
|
|
456
|
+
try:
|
|
457
|
+
cls = WIDGET_REGISTRY[clsname]
|
|
458
|
+
except KeyError as e:
|
|
459
|
+
print(f"Unknown widget class: {clsname[:-6]}. These are alloved:"+
|
|
460
|
+
'\n' + '\n'.join(v[:-6] for v in WIDGET_REGISTRY.keys() ))
|
|
461
|
+
|
|
462
|
+
raise KeyError(f"Unknown widget class: {clsname[:-6]}") from e
|
|
415
463
|
|
|
416
|
-
cls = globals()[clsname]
|
|
417
464
|
obj = cls(widgetdict)
|
|
418
465
|
|
|
419
|
-
# Runtime interface validation (useful with dynamic factory)
|
|
420
466
|
if not isinstance(obj, WidgetABC):
|
|
421
|
-
raise TypeError(
|
|
467
|
+
raise TypeError(
|
|
468
|
+
f"{clsname} must inherit WidgetABC/ContainerWidgetABC (got {type(obj)!r})."
|
|
469
|
+
)
|
|
422
470
|
|
|
423
471
|
return obj
|
|
424
|
-
|
|
425
|
-
|
|
426
472
|
# ---------------------------------------------------------------------------
|
|
427
473
|
# Container widgets
|
|
428
474
|
# ---------------------------------------------------------------------------
|
|
429
475
|
|
|
476
|
+
@register_widget
|
|
430
477
|
@dataclass
|
|
431
478
|
class basewidget(ContainerWidgetBase):
|
|
432
479
|
"""
|
|
@@ -441,7 +488,7 @@ class basewidget(ContainerWidgetBase):
|
|
|
441
488
|
self._children = [make_widget(widgettype, widgetdict) for widgettype, widgetdict in self.content]
|
|
442
489
|
self._datawidget = VBox([child.datawidget for child in self._children])
|
|
443
490
|
|
|
444
|
-
|
|
491
|
+
@register_widget
|
|
445
492
|
@dataclass
|
|
446
493
|
class tabwidget(ContainerWidgetBase):
|
|
447
494
|
"""
|
|
@@ -477,7 +524,7 @@ class tabwidget(ContainerWidgetBase):
|
|
|
477
524
|
for i, title in enumerate(tab_titles):
|
|
478
525
|
self._datawidget.set_title(i, title)
|
|
479
526
|
|
|
480
|
-
|
|
527
|
+
@register_widget
|
|
481
528
|
@dataclass
|
|
482
529
|
class colabtabwidget(ContainerWidgetBase):
|
|
483
530
|
"""
|
|
@@ -567,6 +614,8 @@ def df_to_grid(df,dec):
|
|
|
567
614
|
)
|
|
568
615
|
return wsheet
|
|
569
616
|
|
|
617
|
+
|
|
618
|
+
@register_widget
|
|
570
619
|
@dataclass
|
|
571
620
|
class sheetwidget(SingleWidgetBase):
|
|
572
621
|
"""
|
|
@@ -624,7 +673,7 @@ class sheetwidget(SingleWidgetBase):
|
|
|
624
673
|
self.dec = int(self.content.get("dec", 2))
|
|
625
674
|
self.transpose = bool(self.widgetdef.get("transpose", True))
|
|
626
675
|
if not self.transpose:
|
|
627
|
-
raise
|
|
676
|
+
raise NotImplementedError("Non-transposed sheetwidget is not implemented yet.")
|
|
628
677
|
self.wexp = Label(value=self.heading, layout={"width": "54%"})
|
|
629
678
|
|
|
630
679
|
newnamedf = self.df_var.copy().rename(columns=self.trans)
|
|
@@ -681,7 +730,7 @@ class sheetwidget(SingleWidgetBase):
|
|
|
681
730
|
|
|
682
731
|
case _:
|
|
683
732
|
raise ValueError(
|
|
684
|
-
f"Unsupported operator {self.
|
|
733
|
+
f"Unsupported operator {self.op!r} in sheetwidget mapping for {self.heading!r}."
|
|
685
734
|
)
|
|
686
735
|
|
|
687
736
|
|
|
@@ -689,7 +738,7 @@ class sheetwidget(SingleWidgetBase):
|
|
|
689
738
|
def reset(self, g: Any) -> None:
|
|
690
739
|
self.wsheet.data = self.org_values
|
|
691
740
|
|
|
692
|
-
|
|
741
|
+
@register_widget
|
|
693
742
|
@dataclass
|
|
694
743
|
class slidewidget(SingleWidgetBase):
|
|
695
744
|
"""
|
|
@@ -810,7 +859,7 @@ class slidewidget(SingleWidgetBase):
|
|
|
810
859
|
line_des = g["owner"].description
|
|
811
860
|
self.current_values[line_des]["value"] = g["new"]
|
|
812
861
|
|
|
813
|
-
|
|
862
|
+
@register_widget
|
|
814
863
|
@dataclass
|
|
815
864
|
class sumslidewidget(SingleWidgetBase):
|
|
816
865
|
"""
|
|
@@ -916,8 +965,13 @@ class sumslidewidget(SingleWidgetBase):
|
|
|
916
965
|
return self._datawidget
|
|
917
966
|
|
|
918
967
|
def reset(self, g: Any) -> None:
|
|
919
|
-
|
|
920
|
-
|
|
968
|
+
self._in_programmatic_update = True
|
|
969
|
+
try:
|
|
970
|
+
for i, (_, cont) in enumerate(self.content.items()):
|
|
971
|
+
self.wset[i].value = cont["value"]
|
|
972
|
+
finally:
|
|
973
|
+
self._in_programmatic_update = False
|
|
974
|
+
|
|
921
975
|
|
|
922
976
|
def update_df(self, df: pd.DataFrame, current_per: Any = None) -> None:
|
|
923
977
|
# If not provided, operate on the full index
|
|
@@ -948,7 +1002,7 @@ class sumslidewidget(SingleWidgetBase):
|
|
|
948
1002
|
raise ValueError(
|
|
949
1003
|
f"Unsupported operator {op!r} in sumslide mapping for {var!r}."
|
|
950
1004
|
)
|
|
951
|
-
def
|
|
1005
|
+
def _on_slider_change_old (self, g: dict) -> None:
|
|
952
1006
|
"""Maintain the sum constraint when a slider changes."""
|
|
953
1007
|
if self._in_programmatic_update:
|
|
954
1008
|
return
|
|
@@ -969,7 +1023,7 @@ class sumslidewidget(SingleWidgetBase):
|
|
|
969
1023
|
|
|
970
1024
|
sumall = sum(allvalues)
|
|
971
1025
|
|
|
972
|
-
if round(sum(allvalues),
|
|
1026
|
+
if round(sum(allvalues),6) == round(self.maxsum,6) :
|
|
973
1027
|
return
|
|
974
1028
|
|
|
975
1029
|
sumslack = sum(v for v, slack in zip(allvalues, self.slacklines) if slack)
|
|
@@ -1001,8 +1055,53 @@ class sumslidewidget(SingleWidgetBase):
|
|
|
1001
1055
|
self.wset[i].value = v
|
|
1002
1056
|
|
|
1003
1057
|
self._in_programmatic_update = False
|
|
1004
|
-
|
|
1058
|
+
|
|
1059
|
+
def _on_slider_change(self, g: dict) -> None:
|
|
1060
|
+
"""Maintain the sum constraint when a slider changes."""
|
|
1061
|
+
if self._in_programmatic_update:
|
|
1062
|
+
return
|
|
1005
1063
|
|
|
1064
|
+
line_des = g["owner"].description
|
|
1065
|
+
line_index = list(self.current_values.keys()).index(line_des)
|
|
1066
|
+
self.current_values[line_des]["value"] = g["new"]
|
|
1067
|
+
|
|
1068
|
+
values = [v["value"] for v in self.current_values.values()]
|
|
1069
|
+
slacklines = [cb.value for cb in self.wslackval]
|
|
1070
|
+
|
|
1071
|
+
# Ensure at least one slack variable
|
|
1072
|
+
if not any(slacklines):
|
|
1073
|
+
self.wslackval[-1].value = True
|
|
1074
|
+
slacklines = [cb.value for cb in self.wslackval]
|
|
1075
|
+
|
|
1076
|
+
total = sum(values)
|
|
1077
|
+
if round(total, 6) == round(self.maxsum, 6):
|
|
1078
|
+
return
|
|
1079
|
+
|
|
1080
|
+
slack_count = slacklines.count(True)
|
|
1081
|
+
adjustment = (self.maxsum - total) / slack_count
|
|
1082
|
+
|
|
1083
|
+
newvalues = []
|
|
1084
|
+
for value, is_slack, cont in zip(values, slacklines, self.current_values.values()):
|
|
1085
|
+
candidate = value + adjustment if is_slack else value
|
|
1086
|
+
candidate = max(cont["min"], min(candidate, cont["max"]))
|
|
1087
|
+
newvalues.append(candidate)
|
|
1088
|
+
|
|
1089
|
+
# Final correction on the changed slider to hit maxsum exactly
|
|
1090
|
+
gap = self.maxsum - sum(newvalues)
|
|
1091
|
+
cont = list(self.current_values.values())[line_index]
|
|
1092
|
+
newvalues[line_index] = max(
|
|
1093
|
+
cont["min"],
|
|
1094
|
+
min(newvalues[line_index] + gap, cont["max"])
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
self._in_programmatic_update = True
|
|
1098
|
+
try:
|
|
1099
|
+
for widget, value in zip(self.wset, newvalues):
|
|
1100
|
+
widget.value = value
|
|
1101
|
+
finally:
|
|
1102
|
+
self._in_programmatic_update = False
|
|
1103
|
+
|
|
1104
|
+
@register_widget
|
|
1006
1105
|
@dataclass
|
|
1007
1106
|
class radiowidget(SingleWidgetBase):
|
|
1008
1107
|
"""
|
|
@@ -1063,7 +1162,7 @@ class radiowidget(SingleWidgetBase):
|
|
|
1063
1162
|
selected_variable = cont[wradio.index][1]
|
|
1064
1163
|
df.loc[current_per, selected_variable] = 1
|
|
1065
1164
|
|
|
1066
|
-
|
|
1165
|
+
@register_widget
|
|
1067
1166
|
@dataclass
|
|
1068
1167
|
class checkwidget(SingleWidgetBase):
|
|
1069
1168
|
"""
|
|
@@ -1112,208 +1211,8 @@ class checkwidget(SingleWidgetBase):
|
|
|
1112
1211
|
df.loc[current_per, variable] = 1.0 if wcheck.value else 0.0
|
|
1113
1212
|
|
|
1114
1213
|
|
|
1115
|
-
# ---------------------------------------------------------------------------
|
|
1116
|
-
# Wrapper for shiny integration
|
|
1117
|
-
# ---------------------------------------------------------------------------
|
|
1118
|
-
|
|
1119
|
-
@dataclass
|
|
1120
|
-
class shinywidget(SingleWidgetBase):
|
|
1121
|
-
"""
|
|
1122
|
-
Wrapper widget used when running under Shiny.
|
|
1123
|
-
|
|
1124
|
-
It simply exposes a child widget's ``datawidget`` while delegating
|
|
1125
|
-
``update_df`` and ``reset``.
|
|
1126
|
-
"""
|
|
1127
|
-
|
|
1128
|
-
inner: WidgetABC = field(init=False)
|
|
1129
|
-
_datawidget: Any = field(init=False)
|
|
1130
|
-
|
|
1131
|
-
def __post_init__(self) -> None:
|
|
1132
|
-
super().__post_init__()
|
|
1133
|
-
inner_type = self.content["type"]
|
|
1134
|
-
inner_def = self.content["widgetdef"]
|
|
1135
|
-
self.inner = make_widget(inner_type, inner_def)
|
|
1136
|
-
self._datawidget = self.inner.datawidget
|
|
1137
|
-
|
|
1138
|
-
@property
|
|
1139
|
-
def datawidget(self) -> Any:
|
|
1140
|
-
return self._datawidget
|
|
1141
|
-
|
|
1142
|
-
def update_df(self, df: pd.DataFrame, current_per: Any) -> None:
|
|
1143
|
-
self.inner.update_df(df, current_per)
|
|
1144
|
-
|
|
1145
|
-
def reset(self, g: Any) -> None:
|
|
1146
|
-
self.inner.reset(g)
|
|
1147
|
-
|
|
1148
1214
|
|
|
1149
1215
|
|
|
1150
|
-
@dataclass
|
|
1151
|
-
class keep_plot_widget_no_colab:
|
|
1152
|
-
"""
|
|
1153
|
-
Interactive plotting widget for ModelFlow model instances.
|
|
1154
|
-
|
|
1155
|
-
This widget reads scenario solutions from ``mmodel.keep_solutions`` and lets
|
|
1156
|
-
the user select variables/scenarios to visualize.
|
|
1157
|
-
|
|
1158
|
-
The implementation here follows the structure from the legacy module; the
|
|
1159
|
-
main changes are docstrings, minor cleanups, and stable defaults.
|
|
1160
|
-
|
|
1161
|
-
Parameters
|
|
1162
|
-
----------
|
|
1163
|
-
mmodel:
|
|
1164
|
-
Model instance with attributes typically present in ModelFlow:
|
|
1165
|
-
``basedf``, ``lastdf``, ``keep_solutions`` (dict of DataFrames),
|
|
1166
|
-
``set_smpl`` / ``set_smpl_relative`` context managers, and plotting helpers.
|
|
1167
|
-
smpl:
|
|
1168
|
-
Optional (start, end) sample passed to ``mmodel.set_smpl``.
|
|
1169
|
-
selectfrom:
|
|
1170
|
-
Variable selection pattern/string.
|
|
1171
|
-
vline:
|
|
1172
|
-
Optional vertical lines to draw.
|
|
1173
|
-
"""
|
|
1174
|
-
|
|
1175
|
-
mmodel: Any
|
|
1176
|
-
smpl: Tuple[str, str] = ("", "")
|
|
1177
|
-
relativ_start: int = 0
|
|
1178
|
-
selected: str = ""
|
|
1179
|
-
selectfrom: str = "*"
|
|
1180
|
-
showselectfrom: bool = True
|
|
1181
|
-
legend: bool = False
|
|
1182
|
-
dec: str = ""
|
|
1183
|
-
use_descriptions: bool = True
|
|
1184
|
-
select_width: str = ""
|
|
1185
|
-
select_height: str = "200px"
|
|
1186
|
-
vline: Any = None
|
|
1187
|
-
var_groups: dict = field(default_factory=dict)
|
|
1188
|
-
use_var_groups: bool = True
|
|
1189
|
-
add_var_name: bool = False
|
|
1190
|
-
short: Any = 0
|
|
1191
|
-
select_scenario: bool = True
|
|
1192
|
-
displaytype: str = "tab"
|
|
1193
|
-
save_location: str = "./graph"
|
|
1194
|
-
switch: bool = False
|
|
1195
|
-
use_smpl: bool = False
|
|
1196
|
-
init_dif: bool = False
|
|
1197
|
-
prefix_dict: dict = field(default_factory=dict, init=False)
|
|
1198
|
-
|
|
1199
|
-
datawidget: VBox = field(init=False)
|
|
1200
|
-
keep_wiz_figs: Dict[str, Any] = field(default_factory=dict, init=False)
|
|
1201
|
-
|
|
1202
|
-
def __post_init__(self) -> None:
|
|
1203
|
-
# The original implementation is large; we keep the main structure.
|
|
1204
|
-
# To avoid import-time matplotlib costs, plotting remains inside callbacks.
|
|
1205
|
-
minper = self.mmodel.lastdf.index[0]
|
|
1206
|
-
maxper = self.mmodel.lastdf.index[-1]
|
|
1207
|
-
options = [(ind, nr) for nr, ind in enumerate(self.mmodel.lastdf.index)]
|
|
1208
|
-
self.old_current_per = copy(self.mmodel.current_per)
|
|
1209
|
-
|
|
1210
|
-
self.select_scenario = False if self.switch else self.select_scenario
|
|
1211
|
-
|
|
1212
|
-
with self.mmodel.set_smpl(*self.smpl):
|
|
1213
|
-
with self.mmodel.set_smpl_relative(self.relativ_start, 0):
|
|
1214
|
-
show_per = copy(list(self.mmodel.current_per)[:])
|
|
1215
|
-
self.mmodel.current_per = copy(self.old_current_per)
|
|
1216
|
-
|
|
1217
|
-
self.save_dialog = savefigs_widget(location=self.save_location)
|
|
1218
|
-
|
|
1219
|
-
# Variables available in all kept solutions
|
|
1220
|
-
allkeepvar = [set(df.columns) for df in self.mmodel.keep_solutions.values()]
|
|
1221
|
-
keepvar = sorted(allkeepvar[0].intersection(*allkeepvar[1:])) if allkeepvar else []
|
|
1222
|
-
|
|
1223
|
-
wselectfrom = Text(
|
|
1224
|
-
value=self.selectfrom,
|
|
1225
|
-
placeholder="Type something",
|
|
1226
|
-
description="Display variables:",
|
|
1227
|
-
layout={"width": "65%"},
|
|
1228
|
-
style={"description_width": "30%"},
|
|
1229
|
-
)
|
|
1230
|
-
wselectfrom.layout.visibility = "visible" if self.showselectfrom else "hidden"
|
|
1231
|
-
|
|
1232
|
-
self.wxopen = Checkbox(
|
|
1233
|
-
value=False,
|
|
1234
|
-
description="Allow save figures",
|
|
1235
|
-
disabled=False,
|
|
1236
|
-
)
|
|
1237
|
-
|
|
1238
|
-
self.wscenario = SelectMultiple(
|
|
1239
|
-
options=list(self.mmodel.keep_solutions.keys()),
|
|
1240
|
-
value=tuple(list(self.mmodel.keep_solutions.keys())[:2]),
|
|
1241
|
-
description="Scenarios:",
|
|
1242
|
-
layout={"width": "40%", "height": self.select_height},
|
|
1243
|
-
style={"description_width": "30%"},
|
|
1244
|
-
)
|
|
1245
|
-
|
|
1246
|
-
self.wvariables = SelectMultiple(
|
|
1247
|
-
options=keepvar,
|
|
1248
|
-
value=tuple(keepvar[: min(8, len(keepvar))]),
|
|
1249
|
-
description="Variables:",
|
|
1250
|
-
layout={"width": "60%", "height": self.select_height},
|
|
1251
|
-
style={"description_width": "20%"},
|
|
1252
|
-
)
|
|
1253
|
-
|
|
1254
|
-
# Trigger button to (re)draw
|
|
1255
|
-
self.wplot = Button(description="Update plot")
|
|
1256
|
-
self.wplot.style.button_color = "LightBlue"
|
|
1257
|
-
|
|
1258
|
-
# Main layout
|
|
1259
|
-
top = HBox([wselectfrom, self.wxopen])
|
|
1260
|
-
sels = HBox([self.wscenario, self.wvariables]) if self.select_scenario else HBox([self.wvariables])
|
|
1261
|
-
self.datawidget = VBox([top, sels, self.wplot])
|
|
1262
|
-
|
|
1263
|
-
# Save dialog binding
|
|
1264
|
-
def _get_figs() -> Dict[str, Any]:
|
|
1265
|
-
return self.keep_wiz_figs
|
|
1266
|
-
self.save_dialog.bind(_get_figs)
|
|
1267
|
-
|
|
1268
|
-
def _toggle_save(_):
|
|
1269
|
-
if self.wxopen.value:
|
|
1270
|
-
self.datawidget.children = tuple(list(self.datawidget.children) + [self.save_dialog.datawidget])
|
|
1271
|
-
else:
|
|
1272
|
-
self.datawidget.children = tuple([c for c in self.datawidget.children if c is not self.save_dialog.datawidget])
|
|
1273
|
-
|
|
1274
|
-
self.wxopen.observe(_toggle_save, names="value")
|
|
1275
|
-
|
|
1276
|
-
def _on_plot(_):
|
|
1277
|
-
self.trigger(None)
|
|
1278
|
-
|
|
1279
|
-
self.wplot.on_click(_on_plot)
|
|
1280
|
-
|
|
1281
|
-
# Initial plot attempt
|
|
1282
|
-
if self.init_dif:
|
|
1283
|
-
self.trigger(None)
|
|
1284
|
-
|
|
1285
|
-
def trigger(self, g: Any) -> None:
|
|
1286
|
-
"""
|
|
1287
|
-
Build/update figures based on current selections.
|
|
1288
|
-
|
|
1289
|
-
The legacy module called into ModelFlow plotting helpers. Here we keep a
|
|
1290
|
-
lightweight default: plot the selected scenario DataFrames using pandas
|
|
1291
|
-
.plot() if matplotlib is available. If your ``mmodel`` provides richer
|
|
1292
|
-
plotting, you can adapt this method.
|
|
1293
|
-
"""
|
|
1294
|
-
import matplotlib.pyplot as plt # local import
|
|
1295
|
-
|
|
1296
|
-
scenarios = list(self.wscenario.value) if self.select_scenario else list(self.mmodel.keep_solutions.keys())[:1]
|
|
1297
|
-
variables = list(self.wvariables.value)
|
|
1298
|
-
|
|
1299
|
-
self.keep_wiz_figs = {}
|
|
1300
|
-
|
|
1301
|
-
for var in variables:
|
|
1302
|
-
fig, ax = plt.subplots()
|
|
1303
|
-
for scn in scenarios:
|
|
1304
|
-
df = self.mmodel.keep_solutions[scn]
|
|
1305
|
-
if var in df.columns:
|
|
1306
|
-
df[var].plot(ax=ax, label=scn)
|
|
1307
|
-
ax.set_title(var)
|
|
1308
|
-
if self.legend:
|
|
1309
|
-
ax.legend()
|
|
1310
|
-
self.keep_wiz_figs[var] = fig
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
# ---------------------------------------------------------------------------
|
|
1314
|
-
# Scenario runner (input -> update -> run -> keep plot)
|
|
1315
|
-
# ---------------------------------------------------------------------------
|
|
1316
|
-
|
|
1317
1216
|
@dataclass
|
|
1318
1217
|
class updatewidget:
|
|
1319
1218
|
''' class to input and run a model
|
|
@@ -1322,8 +1221,8 @@ class updatewidget:
|
|
|
1322
1221
|
|
|
1323
1222
|
'''
|
|
1324
1223
|
|
|
1325
|
-
mmodel :
|
|
1326
|
-
datawidget :
|
|
1224
|
+
mmodel : Any # a model
|
|
1225
|
+
datawidget : Any # a widget to update from
|
|
1327
1226
|
basename : str ='Business as usual'
|
|
1328
1227
|
keeppat : str = '*'
|
|
1329
1228
|
varpat : str ='*'
|
|
@@ -1333,19 +1232,24 @@ class updatewidget:
|
|
|
1333
1232
|
lwreset : bool = True
|
|
1334
1233
|
lwsetbas : bool = True
|
|
1335
1234
|
outputwidget : str = 'jupviz'
|
|
1336
|
-
display_first :
|
|
1235
|
+
display_first :Any = None
|
|
1337
1236
|
# to the plot widget
|
|
1338
1237
|
|
|
1339
1238
|
vline : list = field(default_factory=list)
|
|
1340
1239
|
relativ_start : int = 0
|
|
1341
1240
|
short :bool = False
|
|
1342
|
-
|
|
1241
|
+
render_mode : Any = None
|
|
1343
1242
|
|
|
1344
|
-
exodif :
|
|
1243
|
+
exodif : Any = field(default_factory=pd.DataFrame) # definition
|
|
1345
1244
|
|
|
1346
1245
|
|
|
1347
1246
|
|
|
1348
1247
|
def __post_init__(self):
|
|
1248
|
+
if self.render_mode is None:
|
|
1249
|
+
self.render_mode = _detect_render_mode()
|
|
1250
|
+
|
|
1251
|
+
|
|
1252
|
+
|
|
1349
1253
|
self.baseline = self.mmodel.basedf.copy()
|
|
1350
1254
|
self.wrun = Button(description="Run scenario")
|
|
1351
1255
|
self.wrun .on_click(self.run)
|
|
@@ -1400,7 +1304,7 @@ class updatewidget:
|
|
|
1400
1304
|
selectfrom = self.varpat,
|
|
1401
1305
|
vline=self.vline,relativ_start=self.relativ_start,
|
|
1402
1306
|
short = self.short,
|
|
1403
|
-
render_mode = self.
|
|
1307
|
+
render_mode = self.render_mode)
|
|
1404
1308
|
|
|
1405
1309
|
# self.wtotal = VBox([self.datawidget.datawidget,winputstring,wbut,
|
|
1406
1310
|
# self.keep_ui.datawidget])
|
|
@@ -1453,7 +1357,7 @@ class updatewidget:
|
|
|
1453
1357
|
vline=self.vline,
|
|
1454
1358
|
relativ_start=self.relativ_start,
|
|
1455
1359
|
short=self.short,
|
|
1456
|
-
render_mode = self.
|
|
1360
|
+
render_mode = self.render_mode
|
|
1457
1361
|
)
|
|
1458
1362
|
|
|
1459
1363
|
self.wtotal.children = [
|
|
@@ -1465,6 +1369,9 @@ class updatewidget:
|
|
|
1465
1369
|
|
|
1466
1370
|
|
|
1467
1371
|
def setbasis(self,g):
|
|
1372
|
+
if not hasattr(self, "current_experiment"):
|
|
1373
|
+
return
|
|
1374
|
+
|
|
1468
1375
|
self.mmodel.keep_solutions={self.current_experiment:self.mmodel.keep_solutions[self.current_experiment]}
|
|
1469
1376
|
|
|
1470
1377
|
self.mmodel.keep_exodif[self.current_experiment] = self.exodif
|
|
@@ -1554,13 +1461,7 @@ class savefigs_widget:
|
|
|
1554
1461
|
wextensions, wsavelocation])
|
|
1555
1462
|
|
|
1556
1463
|
|
|
1557
|
-
from dataclasses import dataclass, field
|
|
1558
|
-
import matplotlib.pyplot as plt
|
|
1559
1464
|
|
|
1560
|
-
from ipywidgets import (
|
|
1561
|
-
VBox, HBox, HTML, Text, Checkbox, Select, SelectMultiple,
|
|
1562
|
-
SelectionRangeSlider, RadioButtons, Layout, Output, Tab, Accordion
|
|
1563
|
-
)
|
|
1564
1465
|
|
|
1565
1466
|
|
|
1566
1467
|
@dataclass
|
|
@@ -1949,7 +1850,8 @@ class keep_plot_widget:
|
|
|
1949
1850
|
|
|
1950
1851
|
def _render_figures_classic(self, figs: dict) -> None:
|
|
1951
1852
|
figlist = [
|
|
1952
|
-
|
|
1853
|
+
# HTML(fig_to_image(a_fig), width='100%', format='svg', layout=Layout(width='90%'))
|
|
1854
|
+
HTML(value = fig_to_image(a_fig), layout=Layout(width='90%'))
|
|
1953
1855
|
for key, a_fig in figs.items()
|
|
1954
1856
|
]
|
|
1955
1857
|
|
|
@@ -1987,9 +1889,8 @@ class keep_plot_widget:
|
|
|
1987
1889
|
self.out_widget.layout.visibility = 'hidden'
|
|
1988
1890
|
|
|
1989
1891
|
class shinywidget:
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
a_widget : any # The datawidget to wrap
|
|
1892
|
+
"""Placeholder for a future Shiny wrapper."""
|
|
1893
|
+
a_widget : Any # The datawidget to wrap
|
|
1993
1894
|
widget_id : str
|
|
1994
1895
|
|
|
1995
1896
|
def __post_init__(self):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|