OpenSimula 0.8.10__tar.gz → 0.9.0__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 (83) hide show
  1. {opensimula-0.8.10/src/opensimula.egg-info → opensimula-0.9.0}/PKG-INFO +11 -1
  2. {opensimula-0.8.10 → opensimula-0.9.0}/README.md +8 -0
  3. {opensimula-0.8.10 → opensimula-0.9.0}/pyproject.toml +8 -1
  4. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Project.py +37 -1
  5. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Building.py +7 -1
  6. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/__init__.py +2 -0
  7. opensimula-0.9.0/src/opensimula/editor/results.py +295 -0
  8. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/static/editor.css +177 -1
  9. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/static/editor.js +539 -60
  10. opensimula-0.9.0/src/opensimula/editor/static/plotly3d.js +1966 -0
  11. opensimula-0.9.0/src/opensimula/editor/static/results.css +360 -0
  12. opensimula-0.9.0/src/opensimula/editor/static/results.js +4 -0
  13. opensimula-0.9.0/src/opensimula/gui/__init__.py +69 -0
  14. opensimula-0.9.0/src/opensimula/gui/app.py +213 -0
  15. {opensimula-0.8.10 → opensimula-0.9.0/src/opensimula.egg-info}/PKG-INFO +11 -1
  16. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula.egg-info/SOURCES.txt +9 -0
  17. opensimula-0.9.0/src/opensimula.egg-info/entry_points.txt +2 -0
  18. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula.egg-info/requires.txt +3 -0
  19. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Case_600FF.py +11 -3
  20. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Case_610.py +4 -4
  21. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_HVAC_DX_system.py +11 -11
  22. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_HVAC_FAN_COIL_water_system.py +10 -10
  23. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Project.py +16 -0
  24. opensimula-0.9.0/test/test_gui.py +65 -0
  25. opensimula-0.9.0/test/test_results_viewer.py +178 -0
  26. {opensimula-0.8.10 → opensimula-0.9.0}/LICENSE +0 -0
  27. {opensimula-0.8.10 → opensimula-0.9.0}/setup.cfg +0 -0
  28. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Child.py +0 -0
  29. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Component.py +0 -0
  30. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Iterative_process.py +0 -0
  31. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Message.py +0 -0
  32. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Parameter_container.py +0 -0
  33. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Parameters.py +0 -0
  34. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Simulation.py +0 -0
  35. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/Variable.py +0 -0
  36. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/__init__.py +0 -0
  37. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Building_surface.py +0 -0
  38. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Calculator.py +0 -0
  39. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Chiller_heat_pump.py +0 -0
  40. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Construction.py +0 -0
  41. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/DX_unit.py +0 -0
  42. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Day_schedule.py +0 -0
  43. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Fan.py +0 -0
  44. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/File_data.py +0 -0
  45. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/File_met.py +0 -0
  46. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Frame.py +0 -0
  47. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Glazing.py +0 -0
  48. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/HVAC_DX_system.py +0 -0
  49. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/HVAC_MZW_system.py +0 -0
  50. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/HVAC_SZW_system.py +0 -0
  51. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/HVAC_perfect_system.py +0 -0
  52. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/HVAC_water_system.py +0 -0
  53. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Material.py +0 -0
  54. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Opening.py +0 -0
  55. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Opening_type.py +0 -0
  56. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Pump.py +0 -0
  57. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Solar_surface.py +0 -0
  58. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Space.py +0 -0
  59. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Space_type.py +0 -0
  60. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Surface.py +0 -0
  61. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Test_component.py +0 -0
  62. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Water_coil.py +0 -0
  63. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Week_schedule.py +0 -0
  64. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/Year_schedule.py +0 -0
  65. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/components/__init__.py +0 -0
  66. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/schema.py +0 -0
  67. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/validation.py +0 -0
  68. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/editor/widget.py +0 -0
  69. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/visual_3D/Environment_3D.py +0 -0
  70. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula/visual_3D/Polygon_3D.py +0 -0
  71. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula.egg-info/dependency_links.txt +0 -0
  72. {opensimula-0.8.10 → opensimula-0.9.0}/src/opensimula.egg-info/top_level.txt +0 -0
  73. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Calculator.py +0 -0
  74. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Construction.py +0 -0
  75. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_File_data.py +0 -0
  76. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_File_met.py +0 -0
  77. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_HVAC_DX_Equipment.py +0 -0
  78. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_HVAC_water_system_process.py +0 -0
  79. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Iterative_process.py +0 -0
  80. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_Schedules.py +0 -0
  81. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_editor_schema.py +0 -0
  82. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_editor_widget.py +0 -0
  83. {opensimula-0.8.10 → opensimula-0.9.0}/test/test_underground_repeated_simulation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: opensimula
3
- Version: 0.8.10
3
+ Version: 0.9.0
4
4
  Summary: Component-based time simulation environment in Python
5
5
  Author: Luis Pérez-Lombard, Ismael R. Maestre
6
6
  Author-email: "Juan F. Coronel" <jfc@us.es>
@@ -20,6 +20,8 @@ Requires-Dist: psychrolib>=2.5.0
20
20
  Requires-Dist: scipy>=1.16.2
21
21
  Requires-Dist: shapely>=2.1.1
22
22
  Requires-Dist: tqdm>=4.67.1
23
+ Provides-Extra: gui
24
+ Requires-Dist: marimo>=0.19.0; extra == "gui"
23
25
  Dynamic: license-file
24
26
 
25
27
  ![Logo](https://jfcoronel.github.io/OpenSimula/img/logo_opensimula.png)
@@ -127,6 +129,14 @@ each component's own schema, together with an interactive 3D view of the buildin
127
129
 
128
130
  ![Project editor example](https://jfcoronel.github.io/OpenSimula/img/editor_3d.png)
129
131
 
132
+ The editor, a results viewer and a Simulate button also come together in an app that opens in
133
+ the browser, with no notebook to write ([details](https://jfcoronel.github.io/OpenSimula/user_guide/#opensimula-app)):
134
+
135
+ ```bash
136
+ pip install "opensimula[gui]"
137
+ opensimula gui project.json
138
+ ```
139
+
130
140
  ## Component types
131
141
 
132
142
  Components are grouped by what they define:
@@ -103,6 +103,14 @@ each component's own schema, together with an interactive 3D view of the buildin
103
103
 
104
104
  ![Project editor example](https://jfcoronel.github.io/OpenSimula/img/editor_3d.png)
105
105
 
106
+ The editor, a results viewer and a Simulate button also come together in an app that opens in
107
+ the browser, with no notebook to write ([details](https://jfcoronel.github.io/OpenSimula/user_guide/#opensimula-app)):
108
+
109
+ ```bash
110
+ pip install "opensimula[gui]"
111
+ opensimula gui project.json
112
+ ```
113
+
106
114
  ## Component types
107
115
 
108
116
  Components are grouped by what they define:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "opensimula"
3
- version = "0.8.10"
3
+ version = "0.9.0"
4
4
  requires-python = ">=3.12"
5
5
  authors = [
6
6
  { name="Juan F. Coronel", email="jfc@us.es" },
@@ -27,6 +27,13 @@ dependencies = [
27
27
  "tqdm>=4.67.1",
28
28
  ]
29
29
 
30
+ [project.optional-dependencies]
31
+ # the app started by `opensimula gui`
32
+ gui = ["marimo>=0.19.0"]
33
+
34
+ [project.scripts]
35
+ opensimula = "opensimula.gui:main"
36
+
30
37
  [dependency-groups]
31
38
  dev = [
32
39
  "ipykernel>=6.30.1",
@@ -499,13 +499,21 @@ class Project(Parameter_container):
499
499
 
500
500
  return errors
501
501
 
502
- def simulate(self):
502
+ def simulate(self, progress=None):
503
503
  """Run the time simulation of the project
504
504
 
505
505
  Orders the components, runs pre_simulation() on them and then, for each of the
506
506
  `n_time_steps` time steps, the pre-iteration, the iterations until every component
507
507
  converges (at most `n_max_iteration`) and the post-iteration. Results are stored in
508
508
  the variables of the components.
509
+
510
+ The progress is printed with a tqdm bar; `progress` reports it elsewhere as well,
511
+ such as a progress bar of a notebook or an app.
512
+
513
+ Args:
514
+ progress (callable, optional): called after each time step as
515
+ `progress(step, n_time_steps)`, with step from 1 to n_time_steps.
516
+ Defaults to None.
509
517
  """
510
518
  n = self.parameter("n_time_steps").value
511
519
  date = dt.datetime.strptime(
@@ -585,6 +593,8 @@ class Project(Parameter_container):
585
593
  self._sim_df.at[i, "converged"] = converge
586
594
  self._post_iteration_(i, date, daylight_saving, converge)
587
595
  date = date + dt.timedelta(0, delta_t)
596
+ if progress is not None:
597
+ progress(i + 1, n)
588
598
 
589
599
  n_not_converged = (
590
600
  len(self._sim_df["converged"]) - self._sim_df["converged"].sum()
@@ -675,6 +685,32 @@ class Project(Parameter_container):
675
685
 
676
686
  return ProjectEditor(self)
677
687
 
688
+ def results(self, *variables, height=600, chart_height=300, show_3d=False):
689
+ """Interactive viewer of the simulation results.
690
+
691
+ Returns an anywidget that works in Jupyter and, wrapped in
692
+ mo.ui.anywidget(), in Marimo: the variables of the components are listed
693
+ on the left and the selected ones plotted on the right, one chart per
694
+ unit, with the frequency, aggregation and interval chosen in its toolbar.
695
+
696
+ Args:
697
+ *variables (str): variables to show from the start, as
698
+ "component.variable", e.g. "spaces_1.temperature".
699
+ height (int, optional): height of the whole widget, in pixels. Defaults to 600.
700
+ chart_height (int, optional): height of each chart, in pixels. Defaults to 300.
701
+ show_3d (bool, optional): show the 3D view of the project above the
702
+ charts; clicking a surface there opens its variables. Defaults to False.
703
+
704
+ Returns:
705
+ ResultsViewer: widget; its dataframe() method returns what it shows.
706
+ """
707
+ from opensimula.editor import ResultsViewer
708
+
709
+ viewer = ResultsViewer(self, height=height, chart_height=chart_height, show_3d=show_3d)
710
+ if variables:
711
+ viewer.select(*variables)
712
+ return viewer
713
+
678
714
  def create_3D_environment(self, env_3D):
679
715
  """Add the polygons of the project's surfaces and openings to a 3D environment
680
716
 
@@ -498,8 +498,14 @@ class Building(Component):
498
498
  self.TS_vector = np.matmul(self.KS_inv_matrix, self.FS_vector) - np.matmul(self.KS_inv_matrix, np.matmul(self.KSZ_matrix,T_spaces))
499
499
 
500
500
  # Store TS
501
+ # Openings too: their T_s1 (and, for interior ones, T_s0) is only known here,
502
+ # and Opening.post_iteration() computes T_s0 and the heat fluxes from it.
501
503
  for i in range(self._n_surfaces):
502
- if self.surfaces[i].parameter("type").value == "Building_surface" and self.surfaces[i].parameter("surface_type").value != "VIRTUAL":
504
+ surface = self.surfaces[i]
505
+ s_type = surface.parameter("type").value
506
+ if s_type == "Opening" or (
507
+ s_type == "Building_surface" and surface.parameter("surface_type").value != "VIRTUAL"
508
+ ):
503
509
  if self.sides[i] == 0:
504
510
  self.surfaces[i].variable("T_s0").values[time_i] = self.TS_vector[i]
505
511
  else:
@@ -5,11 +5,13 @@ from opensimula.editor.schema import (
5
5
  project_json_schema,
6
6
  )
7
7
  from opensimula.editor.validation import format_errors, validate_document
8
+ from opensimula.editor.results import ResultsViewer
8
9
  from opensimula.editor.widget import ProjectEditor, default_schema
9
10
 
10
11
  __all__ = [
11
12
  "SCHEMA_DIALECT",
12
13
  "ProjectEditor",
14
+ "ResultsViewer",
13
15
  "component_types",
14
16
  "default_schema",
15
17
  "format_errors",
@@ -0,0 +1,295 @@
1
+ """Interactive viewer of the simulation results.
2
+
3
+ Built on anywidget, like the project editor, so it works in Jupyter (Lab,
4
+ Notebook 7, VS Code, Colab) and, wrapped in mo.ui.anywidget(), in Marimo::
5
+
6
+ viewer = project.results()
7
+
8
+ The components and their variables are listed on the left; the selected
9
+ variables are plotted on the right, one chart per unit, after resampling them
10
+ to the chosen frequency. The data is prepared here in Python and only the
11
+ points to draw are sent to the browser.
12
+
13
+ The "3D" button shows the geometry of the project above the charts: clicking a
14
+ surface opens it, and its spaces, in the list of variables, and the surfaces
15
+ and spaces whose variables are plotted are drawn in the colour of their series.
16
+ """
17
+
18
+ import math
19
+ import pathlib
20
+
21
+ import anywidget
22
+ import numpy as np
23
+ import pandas as pd
24
+ import traitlets
25
+
26
+ _STATIC = pathlib.Path(__file__).parent / "static"
27
+
28
+ # Periods labelled by their start, so a month is drawn on its first day
29
+ FREQUENCIES = {"none": None, "hourly": "h", "daily": "D", "monthly": "MS", "yearly": "YS"}
30
+ AGGREGATIONS = ["mean", "sum", "max", "min"]
31
+ # of the colour variable of the 3D view; "instant" follows the cursor of the charts
32
+ STATISTICS = ["mean", "max", "min", "instant"]
33
+ MAX_SERIES = 8 # one per hue of the categorical palette
34
+
35
+
36
+ class ResultsViewer(anywidget.AnyWidget):
37
+ """Viewer of the variables of a simulated project.
38
+
39
+ Args:
40
+ project (Project): simulated project whose variables are shown.
41
+
42
+ Attributes:
43
+ selection (list): selected variables, each a dict with "component",
44
+ "variable" and "slot" (its colour, kept while it stays selected).
45
+ frequency (str): "none", "hourly", "daily", "monthly" or "yearly".
46
+ aggregation (str): "mean", "sum", "max" or "min", used when resampling.
47
+ interval (list): [start, end] as ISO dates ("2001-06-01"), or empty for
48
+ the whole simulation.
49
+ height (int): height of the whole widget, in pixels.
50
+ chart_height (int): height of each chart, in pixels.
51
+ show_3d (bool): whether the 3D view of the project is shown.
52
+ color_variable (str): variable of the surfaces that colours the 3D
53
+ view ("T_s0", "q_sol1"...), or "" for the colours of the series.
54
+ color_statistic (str): "mean", "max" or "min" of that variable over
55
+ the interval shown, or "instant" for its value at the time under
56
+ the cursor of the charts.
57
+ """
58
+
59
+ _esm = _STATIC / "results.js"
60
+ _css = _STATIC / "results.css"
61
+
62
+ catalog = traitlets.List([]).tag(sync=True)
63
+ selection = traitlets.List([]).tag(sync=True)
64
+ frequency = traitlets.Unicode("none").tag(sync=True)
65
+ aggregation = traitlets.Unicode("mean").tag(sync=True)
66
+ interval = traitlets.List([]).tag(sync=True)
67
+ period = traitlets.List([]).tag(sync=True)
68
+ series = traitlets.List([]).tag(sync=True)
69
+ message = traitlets.Unicode("").tag(sync=True)
70
+ height = traitlets.Int(600).tag(sync=True)
71
+ chart_height = traitlets.Int(300).tag(sync=True)
72
+ show_3d = traitlets.Bool(False).tag(sync=True)
73
+ # filled the first time the 3D view is opened, not before
74
+ geometry = traitlets.Dict({}).tag(sync=True)
75
+ color_variable = traitlets.Unicode("").tag(sync=True)
76
+ color_statistic = traitlets.Unicode("mean").tag(sync=True)
77
+ # {"variable", "statistic", "unit", "values": {component: value}}, or for
78
+ # "instant" {"variable", "statistic", "unit", "names": [...], "x": [...]}
79
+ # with the series in surface_series: float32, one row per name, NaN where
80
+ # missing, at the frequency of the charts. Binary, as it can be large.
81
+ surface_values = traitlets.Dict({}).tag(sync=True)
82
+ surface_series = traitlets.Bytes(b"").tag(sync=True)
83
+
84
+ def __init__(self, project, **kwargs):
85
+ super().__init__(**kwargs)
86
+ self._project_ = project
87
+ self.refresh()
88
+ self.observe(self._update_series_, names=["selection", "frequency", "aggregation", "interval"])
89
+ self.on_msg(self._on_message_)
90
+ self.observe(
91
+ self._update_surface_values_,
92
+ names=["color_variable", "color_statistic", "interval", "geometry", "frequency", "aggregation"],
93
+ )
94
+
95
+ @property
96
+ def project(self):
97
+ """The project whose results are shown."""
98
+ return self._project_
99
+
100
+ def refresh(self):
101
+ """Reload the list of variables from the project, after simulating it again."""
102
+ n = self._project_.parameter("n_time_steps").value
103
+ catalog = []
104
+ for component in self._project_.component_list():
105
+ variables = [
106
+ {"name": key, "unit": var.unit}
107
+ for key, var in component.variable_dict().items()
108
+ if var.values is not None and len(var.values) == n
109
+ ]
110
+ if variables:
111
+ catalog.append({
112
+ "name": component.parameter("name").value,
113
+ "type": component.parameter("type").value,
114
+ "variables": variables,
115
+ })
116
+ self.catalog = catalog
117
+ dates = self._dates_()
118
+ self.period = [dates.iloc[0].isoformat(), dates.iloc[-1].isoformat()] if len(dates) else []
119
+ if not catalog:
120
+ self.message = "No results: simulate the project first."
121
+ if self.geometry:
122
+ self.geometry = self._project_.geometry_dict()
123
+ self._update_surface_values_()
124
+ names = {(c["name"], v["name"]) for c in catalog for v in c["variables"]}
125
+ kept = [s for s in self.selection if (s["component"], s["variable"]) in names]
126
+ if kept != self.selection:
127
+ self.selection = kept
128
+ else:
129
+ self._update_series_()
130
+
131
+ def select(self, *variables):
132
+ """Select variables from Python, each as "component.variable".
133
+
134
+ Example:
135
+ viewer.select("spaces_1.temperature", "system.Q_sensible")
136
+ """
137
+ selection = list(self.selection)
138
+ used = {s["slot"] for s in selection}
139
+ available = {(c["name"], v["name"]) for c in self.catalog for v in c["variables"]}
140
+ for text in variables:
141
+ component, _, variable = text.partition(".")
142
+ if (component, variable) not in available:
143
+ raise ValueError(f"{text}: no such variable with results in the project")
144
+ if any(s["component"] == component and s["variable"] == variable for s in selection):
145
+ continue
146
+ free = [i for i in range(MAX_SERIES) if i not in used]
147
+ if not free:
148
+ raise ValueError(f"At most {MAX_SERIES} variables can be shown at the same time")
149
+ selection.append({"component": component, "variable": variable, "slot": free[0]})
150
+ used.add(free[0])
151
+ self.selection = selection
152
+
153
+ def dataframe(self):
154
+ """The selected variables as shown: resampled and cut to the interval.
155
+
156
+ Returns:
157
+ pandas.DataFrame: one column per variable, "component.variable [unit]",
158
+ indexed by date.
159
+ """
160
+ columns = {}
161
+ for item in self.selection:
162
+ data = self._data_(item["component"], item["variable"])
163
+ if data is not None:
164
+ values, unit = data
165
+ label = f"{item['component']}.{item['variable']}"
166
+ columns[f"{label} [{unit}]" if unit else label] = values
167
+ return pd.DataFrame(columns)
168
+
169
+ # ____________________ 3D view ____________________
170
+
171
+ def _on_message_(self, widget, content, buffers):
172
+ """The front end asks for the 3D view when it is first opened: the
173
+ geometry, and the plotly bundle if the page does not have it yet."""
174
+ if not isinstance(content, dict) or content.get("type") != "load-3d":
175
+ return
176
+ if not self.geometry:
177
+ self.geometry = self._project_.geometry_dict()
178
+ if not content.get("has_plotly"):
179
+ self.send({"type": "plotly"}, [(_STATIC / "plotly3d.js").read_bytes()])
180
+
181
+ def _update_surface_values_(self, change=None):
182
+ """One value per surface of the 3D view: the statistic of the colour
183
+ variable over the interval shown."""
184
+ if self.color_statistic not in STATISTICS:
185
+ self.color_statistic = "mean"
186
+ return
187
+ variable = self.color_variable
188
+ if not variable or not self.geometry:
189
+ if self.surface_values:
190
+ self.surface_values = {}
191
+ self.surface_series = b""
192
+ return
193
+ if self.color_statistic == "instant":
194
+ self._update_surface_series_(variable)
195
+ return
196
+ if change is not None and change["name"] in ("frequency", "aggregation"):
197
+ return # the statistics are of the values not resampled
198
+ values, unit = {}, ""
199
+ for name in sorted({mesh["component"] for mesh in self.geometry.get("meshes", [])}):
200
+ data = self._raw_(name, variable)
201
+ if data is None:
202
+ continue
203
+ series, unit = data
204
+ series = series[pd.notna(series)]
205
+ if len(series):
206
+ values[name] = float(getattr(series, self.color_statistic)())
207
+ self.surface_series = b""
208
+ self.surface_values = {
209
+ "variable": variable,
210
+ "statistic": self.color_statistic,
211
+ "unit": unit,
212
+ "values": values,
213
+ }
214
+
215
+ def _update_surface_series_(self, variable):
216
+ """The series of the colour variable of every surface, resampled like the
217
+ charts, for the 3D view to follow the cursor."""
218
+ names, rows, unit, index = [], [], "", None
219
+ for name in sorted({mesh["component"] for mesh in self.geometry.get("meshes", [])}):
220
+ data = self._data_(name, variable)
221
+ if data is None:
222
+ continue
223
+ series, unit = data
224
+ names.append(name)
225
+ rows.append(series.to_numpy(dtype=float))
226
+ index = series.index
227
+ x = [t.timestamp() for t in index.tz_localize("UTC")] if index is not None else []
228
+ matrix = np.array(rows, dtype=np.float32).reshape(len(rows), len(x))
229
+ # bytes before the dict: the front end redraws on the change of the dict
230
+ self.surface_series = matrix.tobytes()
231
+ self.surface_values = {
232
+ "variable": variable,
233
+ "statistic": "instant",
234
+ "unit": unit,
235
+ "names": names,
236
+ "x": x,
237
+ }
238
+
239
+ # ____________________ data ____________________
240
+
241
+ def _dates_(self):
242
+ return pd.Series(pd.to_datetime(self._project_.dates()))
243
+
244
+ def _raw_(self, component_name, variable_name):
245
+ """Values of one variable in the interval, not resampled, and its unit,
246
+ or None if missing."""
247
+ component = self._project_.component(component_name)
248
+ if component is None or variable_name not in component.variable_dict():
249
+ return None
250
+ variable = component.variable(variable_name)
251
+ n = self._project_.parameter("n_time_steps").value
252
+ if variable.values is None or len(variable.values) != n:
253
+ return None
254
+ values = pd.Series(variable.values, index=pd.DatetimeIndex(self._dates_()), dtype=float)
255
+ if len(self.interval) == 2:
256
+ start, end = pd.Timestamp(self.interval[0]), pd.Timestamp(self.interval[1])
257
+ values = values[(values.index >= start) & (values.index < end + pd.Timedelta(days=1))]
258
+ return values, variable.unit
259
+
260
+ def _data_(self, component_name, variable_name):
261
+ """Resampled values of one variable and its unit, or None if missing."""
262
+ data = self._raw_(component_name, variable_name)
263
+ if data is None:
264
+ return None
265
+ values, unit = data
266
+ rule = FREQUENCIES.get(self.frequency)
267
+ if rule is not None and len(values):
268
+ values = getattr(values.resample(rule), self.aggregation)()
269
+ return values, unit
270
+
271
+ def _update_series_(self, change=None):
272
+ if self.frequency not in FREQUENCIES:
273
+ self.frequency = "none"
274
+ return
275
+ if self.aggregation not in AGGREGATIONS:
276
+ self.aggregation = "mean"
277
+ return
278
+ series = []
279
+ for item in self.selection:
280
+ data = self._data_(item["component"], item["variable"])
281
+ if data is None:
282
+ continue
283
+ values, unit = data
284
+ series.append({
285
+ "component": item["component"],
286
+ "variable": item["variable"],
287
+ "slot": item["slot"],
288
+ "unit": unit,
289
+ # seconds since the epoch, the time axis of the chart
290
+ "x": [t.timestamp() for t in values.index.tz_localize("UTC")],
291
+ "y": [None if not math.isfinite(v) else float(v) for v in values.to_numpy()],
292
+ })
293
+ self.series = series
294
+ if self.catalog:
295
+ self.message = ""
@@ -301,7 +301,8 @@
301
301
 
302
302
  /* On its own it takes the whole column, and there is nothing above to divide
303
303
  it from. */
304
- .osm-editor:not(.show-form) .osm-view {
304
+ .osm-editor:not(.show-form) .osm-view,
305
+ .osm-editor:not(.show-form) .osm-graph {
305
306
  flex: 1;
306
307
  border-top: none;
307
308
  }
@@ -314,6 +315,7 @@
314
315
  }
315
316
 
316
317
  .osm-view[hidden],
318
+ .osm-graph[hidden],
317
319
  .osm-detail[hidden] {
318
320
  display: none;
319
321
  }
@@ -386,3 +388,177 @@
386
388
  color: #cf222e;
387
389
  background: #ffebe9;
388
390
  }
391
+
392
+ /* ---------- graph view of the components ---------- */
393
+
394
+ /* The lower panel, like the 3D view: one or the other. */
395
+ .osm-graph {
396
+ flex: 0 0 400px;
397
+ min-height: 180px;
398
+ display: flex;
399
+ flex-direction: column;
400
+ border-top: 1px solid #d0d7de;
401
+ background: #fff;
402
+ }
403
+
404
+ .osm-graph-buttons {
405
+ display: flex;
406
+ gap: 0.2rem;
407
+ }
408
+
409
+ .osm-graph-buttons button {
410
+ padding: 0 0.45rem;
411
+ border: 1px solid #d0d7de;
412
+ border-radius: 3px;
413
+ background: #fff;
414
+ font: inherit;
415
+ font-size: 0.8rem;
416
+ color: #1f2328;
417
+ cursor: pointer;
418
+ }
419
+
420
+ .osm-graph-buttons button:hover {
421
+ background: #eaeef2;
422
+ }
423
+
424
+ .osm-graph-legend {
425
+ margin-left: auto;
426
+ display: flex;
427
+ flex-wrap: wrap;
428
+ gap: 0.1rem 0.7rem;
429
+ }
430
+
431
+ .osm-graph-family {
432
+ display: inline-flex;
433
+ align-items: center;
434
+ gap: 0.25rem;
435
+ padding: 0.05rem 0.3rem;
436
+ border: 1px solid transparent;
437
+ border-radius: 4px;
438
+ background: none;
439
+ font: inherit;
440
+ color: inherit;
441
+ cursor: pointer;
442
+ }
443
+
444
+ .osm-graph-family:hover {
445
+ border-color: #d0d7de;
446
+ }
447
+
448
+ .osm-graph-family.off {
449
+ opacity: 0.4;
450
+ text-decoration: line-through;
451
+ }
452
+
453
+ .osm-graph-family i {
454
+ width: 4px;
455
+ height: 12px;
456
+ border-radius: 2px;
457
+ }
458
+
459
+ .osm-graph-canvas {
460
+ flex: 1;
461
+ min-height: 0;
462
+ overflow: hidden;
463
+ position: relative;
464
+ }
465
+
466
+ .osm-graph-svg {
467
+ width: 100%;
468
+ height: 100%;
469
+ display: block;
470
+ cursor: grab;
471
+ user-select: none;
472
+ font-family: inherit;
473
+ }
474
+
475
+ .osm-graph-svg.dragging {
476
+ cursor: grabbing;
477
+ }
478
+
479
+ .osm-graph-box {
480
+ cursor: pointer;
481
+ }
482
+
483
+ .osm-graph-frame {
484
+ fill: #fff;
485
+ stroke: #d0d7de;
486
+ stroke-width: 1;
487
+ }
488
+
489
+ .osm-graph-box:hover .osm-graph-frame {
490
+ stroke: #8c959f;
491
+ }
492
+
493
+ .osm-graph-box.selected .osm-graph-frame {
494
+ stroke: #1f2328;
495
+ stroke-width: 2;
496
+ }
497
+
498
+ .osm-graph-box.group .osm-graph-frame {
499
+ fill: #ddf4ff;
500
+ stroke: #54aeff;
501
+ stroke-width: 1.5;
502
+ stroke-dasharray: 4 3;
503
+ }
504
+
505
+ .osm-graph-box.group:hover .osm-graph-frame {
506
+ stroke: #0969da;
507
+ }
508
+
509
+ .osm-graph-box.group .osm-graph-type,
510
+ .osm-graph-box.group .osm-graph-foot {
511
+ fill: #0969da;
512
+ }
513
+
514
+ .osm-graph-box.dim {
515
+ opacity: 0.35;
516
+ }
517
+
518
+ .osm-graph-name {
519
+ font-size: 12px;
520
+ font-weight: 600;
521
+ fill: #1f2328;
522
+ }
523
+
524
+ .osm-graph-type,
525
+ .osm-graph-foot {
526
+ font-size: 10.5px;
527
+ fill: #57606a;
528
+ }
529
+
530
+ .osm-graph-sep {
531
+ stroke: #eaeef2;
532
+ }
533
+
534
+ .osm-graph-row {
535
+ font-size: 11px;
536
+ fill: #1f2328;
537
+ }
538
+
539
+ .osm-graph-key {
540
+ fill: #57606a;
541
+ }
542
+
543
+ .osm-graph-edge {
544
+ fill: none;
545
+ stroke: #8c959f;
546
+ stroke-width: 1.2;
547
+ }
548
+
549
+ .osm-graph-edge.active {
550
+ stroke: #1f2328;
551
+ stroke-width: 2;
552
+ }
553
+
554
+ .osm-graph-edge.dim {
555
+ opacity: 0.2;
556
+ }
557
+
558
+ .osm-graph-arrow {
559
+ fill: #8c959f;
560
+ }
561
+
562
+ .osm-graph-arrow.active {
563
+ fill: #1f2328;
564
+ }