MoPyRegtest 0.4.1__tar.gz → 0.5.1__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 (25) hide show
  1. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/LICENSE +1 -1
  2. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1/MoPyRegtest.egg-info}/PKG-INFO +3 -3
  3. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/MoPyRegtest.egg-info/SOURCES.txt +1 -0
  4. {MoPyRegtest-0.4.1/MoPyRegtest.egg-info → mopyregtest-0.5.1}/PKG-INFO +3 -3
  5. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/README.md +2 -2
  6. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/cli.py +20 -4
  7. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/generator.py +19 -4
  8. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/metrics.py +12 -0
  9. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/modelicaregressiontest.py +235 -28
  10. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/setup.py +1 -1
  11. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/tests/test_cli.py +81 -0
  12. mopyregtest-0.5.1/tests/test_compare_results.py +106 -0
  13. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/tests/test_metrics.py +5 -1
  14. mopyregtest-0.5.1/tests/test_modelerror.py +46 -0
  15. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/tests/test_unify_timestamps.py +5 -1
  16. MoPyRegtest-0.4.1/tests/test_compare_results.py +0 -58
  17. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/MoPyRegtest.egg-info/dependency_links.txt +0 -0
  18. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/MoPyRegtest.egg-info/entry_points.txt +0 -0
  19. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/MoPyRegtest.egg-info/requires.txt +0 -0
  20. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/MoPyRegtest.egg-info/top_level.txt +0 -0
  21. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/__init__.py +0 -0
  22. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/templates/omc/model_import.mos.template +0 -0
  23. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/templates/omc/model_simulate.mos.template +0 -0
  24. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/mopyregtest/utils.py +0 -0
  25. {MoPyRegtest-0.4.1 → mopyregtest-0.5.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2020 Philipp Emanuel Stelzig
3
+ Copyright (c) 2019--2024 Philipp Emanuel Stelzig
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: MoPyRegtest
3
- Version: 0.4.1
3
+ Version: 0.5.1
4
4
  Summary: A Python enabled simple regression testing framework for Modelica models
5
5
  Home-page: https://github.com/pstelzig/mopyregtest
6
6
  Author: Philipp Emanuel Stelzig
@@ -83,7 +83,7 @@ has a detailed explanation on how to automatically generate tests.
83
83
  ## Prerequisites
84
84
  To use MoPyRegtest you need to have
85
85
  * a [Python 3](https://www.python.org/) distribution including the modules [`unittest`](https://docs.python.org/3/library/unittest.html), [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/),
86
- * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.21), and
86
+ * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.22), and
87
87
  * the OpenModelica compiler executable `omc` must be accessible via the `PATH` variable.
88
88
 
89
89
  ## Installation using pip3
@@ -134,7 +134,7 @@ knows where to find `mopyregtest` as installed by pip. To find out the location,
134
134
  not confirm to proceed. The uninstallation will tell you which files pip would remove upon uninstalling MoPyRegtest,
135
135
  including the `mopyregtest` executable (or `mopyregtest.exe` under Windows) and its location.
136
136
 
137
- ```bash
137
+ ```
138
138
  Found existing installation: MoPyRegtest 0.4.0rc1
139
139
  Uninstalling MoPyRegtest-0.4.0rc1:
140
140
  Would remove:
@@ -18,4 +18,5 @@ mopyregtest/templates/omc/model_simulate.mos.template
18
18
  tests/test_cli.py
19
19
  tests/test_compare_results.py
20
20
  tests/test_metrics.py
21
+ tests/test_modelerror.py
21
22
  tests/test_unify_timestamps.py
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: MoPyRegtest
3
- Version: 0.4.1
3
+ Version: 0.5.1
4
4
  Summary: A Python enabled simple regression testing framework for Modelica models
5
5
  Home-page: https://github.com/pstelzig/mopyregtest
6
6
  Author: Philipp Emanuel Stelzig
@@ -83,7 +83,7 @@ has a detailed explanation on how to automatically generate tests.
83
83
  ## Prerequisites
84
84
  To use MoPyRegtest you need to have
85
85
  * a [Python 3](https://www.python.org/) distribution including the modules [`unittest`](https://docs.python.org/3/library/unittest.html), [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/),
86
- * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.21), and
86
+ * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.22), and
87
87
  * the OpenModelica compiler executable `omc` must be accessible via the `PATH` variable.
88
88
 
89
89
  ## Installation using pip3
@@ -134,7 +134,7 @@ knows where to find `mopyregtest` as installed by pip. To find out the location,
134
134
  not confirm to proceed. The uninstallation will tell you which files pip would remove upon uninstalling MoPyRegtest,
135
135
  including the `mopyregtest` executable (or `mopyregtest.exe` under Windows) and its location.
136
136
 
137
- ```bash
137
+ ```
138
138
  Found existing installation: MoPyRegtest 0.4.0rc1
139
139
  Uninstalling MoPyRegtest-0.4.0rc1:
140
140
  Would remove:
@@ -67,7 +67,7 @@ has a detailed explanation on how to automatically generate tests.
67
67
  ## Prerequisites
68
68
  To use MoPyRegtest you need to have
69
69
  * a [Python 3](https://www.python.org/) distribution including the modules [`unittest`](https://docs.python.org/3/library/unittest.html), [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/),
70
- * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.21), and
70
+ * a working [OpenModelica](https://www.openmodelica.org/) installation (version 1.13.0 or later, works also for latest 1.22), and
71
71
  * the OpenModelica compiler executable `omc` must be accessible via the `PATH` variable.
72
72
 
73
73
  ## Installation using pip3
@@ -118,7 +118,7 @@ knows where to find `mopyregtest` as installed by pip. To find out the location,
118
118
  not confirm to proceed. The uninstallation will tell you which files pip would remove upon uninstalling MoPyRegtest,
119
119
  including the `mopyregtest` executable (or `mopyregtest.exe` under Windows) and its location.
120
120
 
121
- ```bash
121
+ ```
122
122
  Found existing installation: MoPyRegtest 0.4.0rc1
123
123
  Uninstalling MoPyRegtest-0.4.0rc1:
124
124
  Would remove:
@@ -22,6 +22,8 @@ def metric_str_to_func(m: str):
22
22
  return metrics.Lp_dist
23
23
  elif m == "Linfty_dist":
24
24
  return metrics.Linfty_dist
25
+ elif m == "abs_dist_ptwise":
26
+ return metrics.abs_dist_ptwise
25
27
  else:
26
28
  raise ValueError("Invalid value for metric")
27
29
 
@@ -34,7 +36,17 @@ def generate(args):
34
36
  models_in_package = args.models_in_package.split(",")
35
37
 
36
38
  if args.references is not None:
37
- references = {r.split(":")[0] : r.split(":")[1] for r in args.references.split(",")}
39
+ ref_pairs = args.references.split(",")
40
+ references = {}
41
+ for i in range(0, len(ref_pairs)):
42
+ sep_idx = ref_pairs[i].find(":")
43
+ if sep_idx == -1 or sep_idx == len(ref_pairs[i])-1:
44
+ raise ValueError(f"The argument {args.references} has no valid reference string format. "
45
+ "Must be like <model name1>:</path/to/ref1.csv>,<model name2>:</path/to/ref2.csv>")
46
+
47
+ k = ref_pairs[i][0:sep_idx]
48
+ v = ref_pairs[i][sep_idx+1:]
49
+ references[k] = v
38
50
  else:
39
51
  references = None
40
52
 
@@ -91,7 +103,8 @@ def parse_args(cmd_args):
91
103
  help="Metric to be used. Choose here from predefined values. "
92
104
  "For user-defined metrics please consider creating the tests with a dedicated script. "
93
105
  "If omitted, the default is norm_infty_dist",
94
- choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist"], default="norm_infty_dist")
106
+ choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise"],
107
+ default="norm_infty_dist")
95
108
  generate_parser.add_argument("--tol", type=float,
96
109
  help="Absolute tolerance up to which deviation in the comparison metric is accepted",
97
110
  default=1e-7)
@@ -109,7 +122,7 @@ def parse_args(cmd_args):
109
122
  compare_parser.add_argument("--metric", type=str,
110
123
  help="Metric to be used. Choose here from predefined values. "
111
124
  "For user-defined metrics please consider creating the tests with a dedicated script.",
112
- choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist"],
125
+ choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise"],
113
126
  default="norm_infty_dist")
114
127
  compare_parser.add_argument("--validated-cols", type=str,
115
128
  help="Comma separated list like <var name 1>,<var name 2>. "
@@ -127,4 +140,7 @@ def parse_args(cmd_args):
127
140
 
128
141
 
129
142
  def main():
130
- parse_args(sys.argv[1:])
143
+ if len(sys.argv) <= 1:
144
+ parse_args(["--help"])
145
+ else:
146
+ parse_args(sys.argv[1:])
@@ -10,6 +10,7 @@ import shutil
10
10
  import os
11
11
  import pathlib
12
12
  import tempfile
13
+ import sys
13
14
 
14
15
  from . import metrics
15
16
  from . import utils
@@ -97,7 +98,7 @@ if __name__ == '__main__':
97
98
  metric : function or str
98
99
  Metric to be used in result comparison. Important: If the metric is given as a funtion, one must use one
99
100
  of the predefined metrics, i.e. mopyregtest.metrics.norm_p_dist, mopyregtest.metrics.norm_infty_dist,
100
- mopyregtest.metrics.Lp_dist or mopyregtest.metrics.Linfty_dist.
101
+ mopyregtest.metrics.Lp_dist, mopyregtest.metrics.Linfty_dist, or mopyregtest.metrics.abs_dist_ptwise.
101
102
 
102
103
  If a user-defined metric shall be used, the code must be passed as a string!
103
104
  tol : float
@@ -123,7 +124,9 @@ if __name__ == '__main__':
123
124
  self.modelica_version = modelica_version
124
125
  self.dependencies = dependencies
125
126
  if (callable(metric) and
126
- metric in [metrics.norm_p_dist, metrics.norm_infty_dist, metrics.Lp_dist, metrics.Linfty_dist]):
127
+ metric in [metrics.norm_p_dist, metrics.norm_infty_dist,
128
+ metrics.Lp_dist, metrics.Linfty_dist,
129
+ metrics.abs_dist_ptwise]):
127
130
  self.metric = f"mopyregtest.metrics.{metric.__name__}"
128
131
  elif type(metric) == str:
129
132
  self.metric = metric
@@ -166,11 +169,23 @@ if __name__ == '__main__':
166
169
  result_folder=tmp_res_folder, tool=tool,
167
170
  modelica_version=self.modelica_version,
168
171
  dependencies=self.dependencies)
169
- regtest._import_and_simulate()
172
+
173
+ try:
174
+ regtest._import_and_simulate()
175
+ except Exception as e:
176
+ print(f"Failed to generate the test:\n\n{e}\n\n")
177
+ print("Aborting test generation.")
178
+ sys.exit(1)
170
179
 
171
180
  # Copy reference result file from temporary folder into reference target folder
172
181
  res_file = f"{model_in_package}_res.csv"
173
- shutil.copyfile(pathlib.Path(tmp_res_folder) / res_file, str(pathlib.Path(reference_folder) / res_file))
182
+ ref_src = pathlib.Path(tmp_res_folder) / res_file
183
+ ref_dst = pathlib.Path(reference_folder) / res_file
184
+
185
+ if ref_dst.exists():
186
+ os.remove(ref_dst)
187
+
188
+ shutil.copyfile(ref_src, ref_dst)
174
189
 
175
190
  # Cleanup temporary directory with simulation data
176
191
  if do_cleanup:
@@ -109,3 +109,15 @@ def Linfty_dist(f1, f2):
109
109
  _check_comparability(f1, f2)
110
110
 
111
111
  return Linfty_norm(np.vstack((f1[:, 0], f2[:, 1] - f1[:, 1])).transpose())
112
+
113
+
114
+ def func_ptwise(f1, f2, dist: callable):
115
+ _check_comparability(f1, f2)
116
+
117
+ delta = np.vstack((f1[:, 0], np.vectorize(dist)(f2[:, 1] - f1[:, 1]))).transpose()
118
+
119
+ return delta
120
+
121
+
122
+ def abs_dist_ptwise(f1, f2):
123
+ return func_ptwise(f1, f2, np.abs)
@@ -7,6 +7,8 @@ MIT License. See the project's LICENSE file.
7
7
  """
8
8
 
9
9
  import os
10
+ import re
11
+ import subprocess
10
12
  import platform
11
13
  import pathlib
12
14
  import shutil
@@ -49,11 +51,12 @@ class RegressionTest:
49
51
  dependency is an entire package, it must be the path to the respective package's package.mo.
50
52
  """
51
53
 
54
+ self.initial_cwd = os.getcwd()
55
+
52
56
  self.template_folder_path = pathlib.Path(__file__).parent.absolute() / "templates"
53
- self.package_folder_path = pathlib.Path(package_folder).absolute()
57
+ self.package_folder_path = self._make_path_absolut(package_folder)
54
58
  self.model_in_package = model_in_package
55
- self.result_folder_path = pathlib.Path(result_folder).absolute()
56
- self.initial_cwd = os.getcwd()
59
+ self.result_folder_path = self._make_path_absolut(result_folder)
57
60
  self.modelica_version = modelica_version
58
61
  self.dependencies = dependencies
59
62
 
@@ -64,6 +67,18 @@ class RegressionTest:
64
67
 
65
68
  self.result_folder_created = False
66
69
 
70
+ def _make_path_absolut(self, path):
71
+ path = os.path.expanduser(path)
72
+
73
+ if not pathlib.PurePath(path).is_absolute():
74
+ path_abs = pathlib.Path(self.initial_cwd) / path
75
+ else:
76
+ path_abs = pathlib.Path(path)
77
+
78
+ path_abs = path_abs.absolute()
79
+
80
+ return path_abs
81
+
67
82
  @staticmethod
68
83
  def _unify_timestamps(results: List[pd.DataFrame], fill_in_method="ffill"):
69
84
  """
@@ -207,19 +222,15 @@ class RegressionTest:
207
222
  pathlib.Path.mkdir(self.result_folder_path)
208
223
  self.result_folder_created = True
209
224
 
210
- os.chdir(self.result_folder_path)
211
-
212
225
  # Run the scripts for import and simulation
213
226
  self._run_model()
214
227
 
215
- os.chdir(self.initial_cwd)
216
-
217
228
  return
218
229
 
219
230
  @staticmethod
220
231
  def compare_csv_files(reference_result, simulation_result, tol=1e-7, validated_cols=[],
221
232
  metric=metrics.norm_infty_dist,
222
- unify_timestamps=True, fill_in_method="ffill"):
233
+ unify_timestamps=True, fill_in_method="ffill", write_comparison=True):
223
234
  """
224
235
  Compares two CSV files from Modelica simulation runs, one as a reference result, the other one as the actual
225
236
  simulation result.
@@ -242,6 +253,8 @@ class RegressionTest:
242
253
  See doc string of RegressionTest.compare_result
243
254
  fill_in_method : str
244
255
  See doc string of RegressionTest.compare_result
256
+ write_comparison : bool
257
+ See doc string of RegressionTest.compare_result
245
258
 
246
259
  Returns
247
260
  -------
@@ -284,19 +297,29 @@ class RegressionTest:
284
297
  for c in validated_cols:
285
298
  print("Comparing column \"{}\"".format(c))
286
299
  delta = metric(ref_data[["time", c]].values, sim_data[["time", c]].values)
287
- if np.abs(delta) >= tol:
288
- failed_cols[c] = np.abs(delta)
300
+
301
+ if type(delta) is np.ndarray:
302
+ if np.any(delta[:, 1] >= tol):
303
+ delta_gt_tol = np.where(delta >= tol, delta, 0.0)
304
+ failed_cols[c] = pd.DataFrame(data=delta_gt_tol, columns=["time", "delta"])
305
+ else:
306
+ if np.abs(delta) >= tol:
307
+ failed_cols[c] = delta
289
308
 
290
309
  if failed_cols:
310
+ if write_comparison:
311
+ RegressionTest._write_csv_comparison(reference_result, simulation_result,
312
+ failed_cols, fill_in_method)
313
+
291
314
  raise AssertionError(
292
315
  f"Values of results {simulation_result} and {reference_result} are different in columns "
293
- f"{failed_cols.keys()} by more than {tol}. The individual deviations are {failed_cols}")
316
+ f"{list(failed_cols.keys())} by more than {tol}. ")
294
317
 
295
318
  return
296
319
 
297
320
  def compare_result(self, reference_result, tol=1e-7, validated_cols=[],
298
321
  metric=metrics.norm_infty_dist,
299
- unify_timestamps=True, fill_in_method="ffill"):
322
+ unify_timestamps=True, fill_in_method="ffill", write_comparison=True):
300
323
  """
301
324
  Executes simulation and then compares the obtained result and the reference result along the
302
325
  validated columns. Throws an exception (AssertionError) if the deviation is larger or equal to tol.
@@ -312,13 +335,26 @@ class RegressionTest:
312
335
  Important: All entries of validated_cols must be present in both the reference result and the actual result.
313
336
  metric : Callable
314
337
  Metric-like function that is used to compute the distance between the reference result and the actual result
315
- produced by the simulation. Default is the infinity-norm on the difference between reference result and
316
- actual result
338
+ produced by the simulation.
339
+
340
+ The return value of the metric function MUST either be
341
+
342
+ a nonnegative scalar value (i.e. a time-wise nonlocalized deviation)
317
343
 
318
- :math:`\| r_\text{ref} - r_\{act} \|_{\infty} = \max_{t \in 1,\ldots,N} |r_\text{ref}[t] - r_\{act}[t]|`
344
+ or
345
+
346
+ an np.ndarray of shape (N,2) containing a timeseries of localized deviations between r_ref and r_act
347
+ (i.e. a time-wise localized metric evaluation).
348
+
349
+ The timestamps in a returned timeseries do not need to match those of r_ref or of r_act. Timestamp
350
+ unification will be used when plotting localized deviations.
351
+
352
+ Default is the infinity-norm on the difference between reference result and actual result.
353
+
354
+ :math:`\| r_\text{ref} - r_\text{act} \|_{\infty} = \max_{i \in 1,\ldots,N} |r_\text{ref}[t_i] - r_\text{act}[t_i]|`
319
355
 
320
356
  where :math:`r_\text{ref}, r_\text{act} \in \mathbb{R}^N` denote the reference and the actual result
321
- with timestamps :math:`t \in 1,\ldots,N`. Note that the timestamps of both results are unified using
357
+ with timestamps :math:`t_i, i \in 1,\ldots,N`. Note that the timestamps of both results are unified using
322
358
  the method _unify_timestamps.
323
359
 
324
360
  This default function is implemented in
@@ -329,6 +365,12 @@ class RegressionTest:
329
365
 
330
366
  metric=lambda r_ref, r_act: np.linalg.norm(r_ref[:, 1] - r_act[:, 1], ord=np.inf)
331
367
 
368
+ A default implementation of a metric returning a timeseries of deviations would be
369
+
370
+ metric=mopyregtest.metrics.abs_dist_ptwise
371
+
372
+ which is simply :math:`\Big\{ (t_i, |r_\text{ref}[t_i] - r_\text{act}[t_i]| : i \in 1,\ldots,N \Big\}`
373
+
332
374
  unify_timestamps : bool
333
375
  Boolean controlling whether the timestamp unification shall be called in compare_result before evaluating
334
376
  the metric. Default=True.
@@ -345,6 +387,11 @@ class RegressionTest:
345
387
  pandas.DataFrame.fillna and "interpol" uses linear interpolation
346
388
  as in pandas.DataFrame.interpol
347
389
 
390
+ write_comparison : bool
391
+ If there are result comparisons that have failed, this will trigger writing a comparison csv file to the
392
+ folder where the actual simulation result is found and be called <simulation_result_name_root>_compare.csv.
393
+ Default=True.
394
+
348
395
  Returns
349
396
  -------
350
397
  out : None
@@ -358,7 +405,7 @@ class RegressionTest:
358
405
 
359
406
  RegressionTest.compare_csv_files(reference_result, simulation_result, tol, validated_cols,
360
407
  metric,
361
- unify_timestamps, fill_in_method)
408
+ unify_timestamps, fill_in_method, write_comparison)
362
409
 
363
410
  return
364
411
 
@@ -406,6 +453,8 @@ class RegressionTest:
406
453
  out : None
407
454
 
408
455
  """
456
+ os.chdir(self.result_folder_path)
457
+
409
458
  for tool in self.tools:
410
459
  tool_executable = tool
411
460
 
@@ -441,20 +490,20 @@ class RegressionTest:
441
490
  utils.replace_in_file(self.result_folder_path / model_import_mos, repl_dict)
442
491
 
443
492
  # Run the import script and write the output of the OpenModelica Compiler (omc) to omc_output
444
- os.system(tool_executable + " {} > {}".format(model_import_mos, tool_output))
445
-
446
- # Read simulation options from the simulation_options_file
447
- model_import_output_file = open(tool_output, 'r')
448
- omc_messages = model_import_output_file.readlines()
449
- model_import_output_file.close()
493
+ proc_return = subprocess.run([tool_executable, model_import_mos], check=True, capture_output=True)
494
+ omc_messages = proc_return.stdout.decode("utf-8").strip("\'").strip("\n")
450
495
 
451
- (start_time, stop_time, tolerance, num_intervals, interval) = omc_messages[-1].lstrip('(').rstrip(')').split(',')
496
+ (start_time, stop_time, tolerance, num_intervals, interval) = omc_messages.split("\n")[-1].lstrip('(').rstrip(')').split(',')
452
497
 
453
498
  # Modify the simulation template
454
499
  if platform.system() == 'Windows':
455
- repl_dict["SIMULATION_BINARY"] = "{}.exe".format(self.model_in_package)
500
+ sim_binary = self.model_in_package + ".bat"
501
+ repl_dict["SIMULATION_BINARY"] = sim_binary
456
502
  elif platform.system() == 'Linux':
457
- repl_dict["SIMULATION_BINARY"] = "./{}".format(self.model_in_package)
503
+ sim_binary = self.model_in_package
504
+ repl_dict["SIMULATION_BINARY"] = "./" + sim_binary
505
+ else:
506
+ raise ValueError(f"Platform {platform.system()} not supported")
458
507
  repl_dict["START_TIME"] = start_time
459
508
  repl_dict["STOP_TIME"] = stop_time
460
509
  repl_dict["TOLERANCE"] = tolerance
@@ -462,7 +511,165 @@ class RegressionTest:
462
511
 
463
512
  utils.replace_in_file(self.result_folder_path / model_simulate_mos, repl_dict)
464
513
 
514
+ # Delete old simulation binary and old simulation result
515
+ sim_result_path = self.result_folder_path / (self.model_in_package + "_res.csv")
516
+ if sim_result_path.exists():
517
+ os.remove(sim_result_path)
518
+
519
+ sim_binary_path = self.result_folder_path / sim_binary
520
+ if sim_binary_path.exists():
521
+ os.remove(sim_binary_path)
522
+
465
523
  # Run the simulation script and append the output of the OpenModelica Compiler (omc) to omc_output
466
- os.system(tool_executable + " {} >> {}".format(model_simulate_mos, tool_output))
524
+ proc_return = subprocess.run([tool_executable, model_simulate_mos], check=True, capture_output=True)
525
+ omc_messages = proc_return.stdout.decode("utf-8").strip("\'").strip("\n")
526
+
527
+ # Check output: Both simulation binary and simulation result must exist now
528
+ if not sim_binary_path.exists():
529
+ os.chdir(self.initial_cwd)
530
+
531
+ raise AssertionError(
532
+ f"The expected simulation binary at {sim_result_path} does not exist. "
533
+ + f"Please check the output from the simulation tool:\n\n{omc_messages}")
534
+
535
+ if not sim_result_path.exists():
536
+ os.chdir(self.initial_cwd)
537
+
538
+ raise AssertionError(
539
+ f"The expected simulation result at {sim_result_path} does not exist. "
540
+ + f"Please check the output from the simulation tool:\n\n{omc_messages}")
467
541
 
468
- return
542
+ os.chdir(self.initial_cwd)
543
+
544
+ return
545
+
546
+ @staticmethod
547
+ def _write_csv_comparison(reference_result, simulation_result, failed_cols, fill_in_method="ffill",
548
+ comparison_fname=""):
549
+ """
550
+ Writes a comparison CSV file from the result comparison of reference_result and actual simulation result,
551
+ which includes also the results for the failed variable columns in the output. Note that to have results in
552
+ one common CSV files, the timestamps must be identical. The output CSV file has a
553
+ format like:
554
+
555
+ root
556
+ |
557
+ + -- reference
558
+ |
559
+ +...
560
+ + -- actual
561
+ |
562
+ +...
563
+ + -- failed
564
+ |
565
+ + var_failed_0
566
+ |
567
+ + reference
568
+ |
569
+ + actual
570
+ |
571
+ + [delta_nonloc|delta_greater_tol]
572
+ |
573
+ + var_failed_1
574
+ |
575
+ + reference
576
+ |
577
+ + actual
578
+ |
579
+ + [delta_nonloc|delta_greater_tol]
580
+
581
+ In case of the metric used in the comparison returning a scalar value, the deviation is a constant
582
+ (because it cannot be localized), and is called delta_nonloc.
583
+
584
+ In case of metric returning a timeseries, it contains the part of the timeseries where the error exceeds the
585
+ tolerance, and is called delta_greater_tol.
586
+
587
+ Parameters
588
+ ----------
589
+ reference_result : str
590
+ Path to a reference .csv file
591
+ simulation_result : str
592
+ Path to a simulation result .csv file
593
+ failed_cols : dict
594
+ A dictionary mapping the name of the column for which comparison between r_ref and r_act failed to the
595
+ deviation delta. This delta MUST FOR ALL COLUMNS have the same type, which can either be
596
+
597
+ a nonnegative real value
598
+
599
+ or
600
+
601
+ a pandas DataFrame with columns ["time", "delta"].
602
+ fill_in_method : str
603
+ See doc string of RegressionTest.compare_result
604
+ comparison_fname : str
605
+ Path to where the output shall be written. If not specified, the output filename
606
+ is <path/to/simulation_result/simulation_result_name_root>_compare.csv
607
+
608
+ Returns
609
+ -------
610
+ out : None
611
+ """
612
+
613
+ if not comparison_fname:
614
+ comparison_fname = (pathlib.Path(simulation_result).absolute().parent /
615
+ f"{pathlib.Path(simulation_result).stem}_comparison.csv")
616
+
617
+ ref_data = pd.read_csv(filepath_or_buffer=reference_result, delimiter=',')
618
+ sim_data = pd.read_csv(filepath_or_buffer=simulation_result, delimiter=',')
619
+
620
+ # Determine if the delta in failed_cols between actual and reference is a (nonlocal) scalar or a timeseries
621
+ is_scalar = True
622
+ for v in failed_cols.values():
623
+ if type(v) is pd.DataFrame:
624
+ is_scalar = False
625
+ break
626
+
627
+ # Timestamps must be unified to have both results side by side
628
+ if is_scalar: # Only unify ref_data and sim_data, make delta a constant timeseries
629
+ data_ext = RegressionTest._unify_timestamps([ref_data, sim_data], fill_in_method)
630
+ ref_data_ext = data_ext[0]
631
+ sim_data_ext = data_ext[1]
632
+
633
+ timestamps_ext = sim_data_ext["time"].values
634
+ failed_cols_ext = {}
635
+ for c in failed_cols.keys():
636
+ delta_ext = failed_cols[c]*np.ones(shape=timestamps_ext.shape)
637
+ failed_cols_ext[c] = pd.DataFrame(data=np.vstack((timestamps_ext, delta_ext)).transpose(),
638
+ columns=["time", "delta"])
639
+ else: # Unify ref_data, sim_data and all delta timeseries
640
+ failed_keys = list(failed_cols.keys())
641
+ data_ext = RegressionTest._unify_timestamps([ref_data, sim_data] + list(failed_cols.values()))
642
+ ref_data_ext = data_ext[0]
643
+ sim_data_ext = data_ext[1]
644
+
645
+ failed_cols_ext = {}
646
+ for i in range(0, len(failed_keys)):
647
+ failed_cols_ext[failed_keys[i]] = data_ext[2+i]
648
+
649
+ # Extract the columns for time and the failed comparisons
650
+ time_data = sim_data_ext["time"]
651
+ ref_data_ext.drop(columns=["time"], inplace=True)
652
+ sim_data_ext.drop(columns=["time"], inplace=True)
653
+ for c in failed_cols_ext.keys():
654
+ failed_cols_ext[c].drop(columns=["time"], inplace=True)
655
+
656
+ failed_tseries = pd.DataFrame()
657
+ for c in failed_cols_ext.keys():
658
+ c_ref = ref_data_ext[c]
659
+ c_ref.name = f"failed.{c}.reference"
660
+ c_act = sim_data_ext[c]
661
+ c_act.name = f"failed.{c}.actual"
662
+ c_delta = failed_cols_ext[c]["delta"]
663
+ if is_scalar:
664
+ c_delta.name = f"failed.{c}.delta_nonloc"
665
+ else:
666
+ c_delta.name = f"failed.{c}.delta_greater_tol"
667
+ failed_tseries = pd.concat([failed_tseries, c_ref, c_act, c_delta], axis=1)
668
+
669
+ # Concatenate results and prepend result headers
670
+ ref_data_ext.columns = [f"reference.{c}" for c in ref_data_ext.columns]
671
+ sim_data_ext.columns = [f"actual.{c}" for c in sim_data_ext.columns]
672
+ comparison_csv = pd.concat([time_data, ref_data_ext, sim_data_ext, failed_tseries], axis=1)
673
+ comparison_csv.to_csv(comparison_fname, sep=",")
674
+
675
+ return
@@ -8,7 +8,7 @@ with open("README.md") as fh:
8
8
 
9
9
  setuptools.setup(
10
10
  name="MoPyRegtest",
11
- version="0.4.1",
11
+ version="0.5.1",
12
12
  author="Philipp Emanuel Stelzig",
13
13
  description="A Python enabled simple regression testing framework for Modelica models",
14
14
  long_description=long_description,
@@ -1,3 +1,4 @@
1
+ import shutil
1
2
  import unittest
2
3
  import pathlib
3
4
  from mopyregtest import cli
@@ -35,6 +36,62 @@ class TestCli(unittest.TestCase):
35
36
 
36
37
  return
37
38
 
39
+ def test_generate3(self):
40
+ """
41
+ Testing for optional arguments in CLI: mopyregtest generate
42
+ """
43
+ cmd_args = ["generate",
44
+ "--metric=abs_dist_ptwise",
45
+ "--tol=1.2e-5",
46
+ "--references=Modelica.Blocks.Sources.Sine:{}".format(
47
+ this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv"),
48
+ str(this_folder / "../examples/generate_tests/gen_tests3"),
49
+ "BlocksAbsDistPtwise_from_cli",
50
+ "~/.openmodelica/libraries/Modelica 4.0.0+maint.om/",
51
+ "Modelica.Blocks.Sources.Sine"]
52
+
53
+ cli.parse_args(cmd_args)
54
+
55
+ return
56
+
57
+ def test_generate4(self):
58
+ """
59
+ Testing for generation to fail if the simulation model for which a test is
60
+ being generated fails to build.
61
+ """
62
+ cmd_args = ["generate",
63
+ str(this_folder / "data/gentests"),
64
+ "FlawedModels_DoesNotBuild",
65
+ str(this_folder / "data/FlawedModels"),
66
+ "FlawedModels.DoesNotBuild"]
67
+
68
+ with self.assertRaises(SystemExit) as e:
69
+ cli.parse_args(cmd_args)
70
+
71
+ self.assertEqual(e.exception.code, 1)
72
+
73
+ # Clean up the generated regression tests as otherwise they will confuse unittest discovery
74
+ shutil.rmtree(this_folder / "data/gentests")
75
+
76
+ return
77
+
78
+ def test_generate5(self):
79
+ """
80
+
81
+ """
82
+ cmd_args = ["generate",
83
+ str(this_folder / "data/gentests"),
84
+ "FlawedModels_DoesNotFinish",
85
+ str(this_folder / "data/FlawedModels"),
86
+ "FlawedModels.DoesNotFinish"]
87
+
88
+ cli.parse_args(cmd_args)
89
+
90
+ # Clean up the generated regression tests as otherwise they will confuse unittest discovery
91
+ shutil.rmtree(this_folder / "data/gentests")
92
+
93
+ return
94
+
38
95
  def test_compare1(self):
39
96
  """
40
97
  Testing for default arguments in CLI: mopyregtest compare
@@ -74,6 +131,8 @@ class TestCli(unittest.TestCase):
74
131
  str(this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv")]
75
132
 
76
133
  self.assertRaises(AssertionError, cli.parse_args, cmd_args=cmd_args)
134
+ self.assertTrue(
135
+ (this_folder / "../examples/test_user_defined_metrics/references/Sine_res_comparison.csv").exists())
77
136
 
78
137
  return
79
138
 
@@ -91,3 +150,25 @@ class TestCli(unittest.TestCase):
91
150
  cli.parse_args(cmd_args)
92
151
 
93
152
  return
153
+
154
+ def test_compare5(self):
155
+ """
156
+ Testing for new metric argument abs_dist_ptwise in CLI: mopyregtest compare
157
+ """
158
+ cmd_args = ["compare",
159
+ "--metric=abs_dist_ptwise",
160
+ "--tol=2.5e-4",
161
+ "--validated-cols=y",
162
+ "--fill-in-method=interpolate",
163
+ str(this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv"),
164
+ str(this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv")]
165
+
166
+ self.assertRaises(AssertionError, cli.parse_args, cmd_args=cmd_args)
167
+ self.assertTrue(
168
+ (this_folder / "../examples/test_user_defined_metrics/references/Sine_res_comparison.csv").exists())
169
+
170
+ return
171
+
172
+
173
+ if __name__ == '__main__':
174
+ unittest.main()
@@ -0,0 +1,106 @@
1
+ import unittest
2
+ import pathlib
3
+ import os
4
+ import mopyregtest
5
+
6
+ this_folder = pathlib.Path(__file__).absolute().parent
7
+
8
+ class TestCompareResults(unittest.TestCase):
9
+ def test_time_col_ignored(self):
10
+ """
11
+ Validates that time as a validated column is ignored in the result comparison
12
+ """
13
+
14
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
15
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
16
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
17
+ validated_cols=["time"])
18
+
19
+ def test_disjoint_cols(self):
20
+ """
21
+ Validate that test of two CSV result files that have no common result variable besides time fails
22
+ """
23
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
24
+ reference_result=this_folder / "../examples/test_Modelica_Electrical_Analog_Examples/references/Modelica.Electrical.Analog.Examples.CharacteristicIdealDiodes_res.csv",
25
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv")
26
+ return
27
+
28
+ def test_validated_cols_not_contained1(self):
29
+ """
30
+ Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
31
+ result.
32
+ """
33
+
34
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
35
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
36
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
37
+ validated_cols=["y", "not_present_var"])
38
+ return
39
+
40
+ def test_validated_cols_not_contained2(self):
41
+ """
42
+ Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
43
+ result. Case: Column not contained in reference_result.
44
+ """
45
+
46
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
47
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
48
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
49
+ validated_cols=["y", "uniformNoise.y"])
50
+ return
51
+
52
+ def test_validated_cols_not_contained3(self):
53
+ """
54
+ Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
55
+ result. Case: Column not contained in simulation_result.
56
+ """
57
+
58
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
59
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
60
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
61
+ validated_cols=["y", "uniformNoise.y"])
62
+ return
63
+
64
+ def test_write_comparison_timeseries1(self):
65
+ """
66
+ Validate that writing a comparison timeseries on failed tests can be switched off using the write_comparison
67
+ argument.
68
+ """
69
+
70
+ compare_file_path = (this_folder / "../examples/test_user_defined_metrics/references/Sine_res_comparison.csv")
71
+
72
+ if compare_file_path.exists():
73
+ os.remove(compare_file_path)
74
+
75
+ self.assertRaises(AssertionError, mopyregtest.RegressionTest.compare_csv_files,
76
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
77
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
78
+ tol=1e-5,
79
+ validated_cols=["y"],
80
+ write_comparison=False)
81
+ self.assertFalse(compare_file_path.exists())
82
+
83
+ return
84
+
85
+ def test_write_comparison_timeseries2(self):
86
+ """
87
+ Validate that a comparison timeseries is written on a failed test by default.
88
+ """
89
+
90
+ compare_file_path = (this_folder / "../examples/test_user_defined_metrics/references/Sine_res_comparison.csv")
91
+
92
+ if compare_file_path.exists():
93
+ os.remove(compare_file_path)
94
+
95
+ self.assertRaises(AssertionError, mopyregtest.RegressionTest.compare_csv_files,
96
+ reference_result=this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
97
+ simulation_result=this_folder / "../examples/test_user_defined_metrics/references/Sine_res.csv",
98
+ tol=1e-5,
99
+ validated_cols=["y"])
100
+ self.assertTrue(compare_file_path.exists())
101
+
102
+ return
103
+
104
+
105
+ if __name__ == '__main__':
106
+ unittest.main()
@@ -150,4 +150,8 @@ class TestMetrics(unittest.TestCase):
150
150
 
151
151
  self.assertRaises(ValueError, mopyregtest.metrics.norm_infty_dist, f1=f1, f2=f3)
152
152
 
153
- self.assertRaises(ValueError, mopyregtest.metrics.norm_infty_dist, f1=f1, f2=f4)
153
+ self.assertRaises(ValueError, mopyregtest.metrics.norm_infty_dist, f1=f1, f2=f4)
154
+
155
+
156
+ if __name__ == '__main__':
157
+ unittest.main()
@@ -0,0 +1,46 @@
1
+ import os
2
+ import unittest
3
+ import pathlib
4
+ import mopyregtest
5
+
6
+ this_folder = pathlib.Path(__file__).absolute().parent
7
+ initial_cwd = os.getcwd()
8
+
9
+ class TestModelErrors(unittest.TestCase):
10
+ def test_build_errors(self):
11
+ # Exception in RegressionTest._import_and_simulate raised before RegressionTest switches back to initial_cwd
12
+ os.chdir(initial_cwd)
13
+
14
+ tester = mopyregtest.RegressionTest(package_folder=this_folder / "data/FlawedModels",
15
+ model_in_package="FlawedModels.DoesNotBuild",
16
+ result_folder=this_folder / "data/FlawedModels/results")
17
+
18
+ self.assertRaises(AssertionError, tester._import_and_simulate)
19
+
20
+ tester.cleanup(ask_confirmation=False)
21
+
22
+ return
23
+
24
+ def test_simulate_errors1(self):
25
+ """
26
+ This test runs a simulation model that will build and run, but the simulation will not reach the
27
+ targeted simulation end time. An error will _not_ be thrown by _import_and_simulate. This is because
28
+ for regression we do not care about simulation end times, but about reproducibility.
29
+ """
30
+
31
+ # Exception in RegressionTest._import_and_simulate raised before RegressionTest switches back to initial_cwd
32
+ os.chdir(initial_cwd)
33
+
34
+ tester = mopyregtest.RegressionTest(package_folder=this_folder / "data/FlawedModels",
35
+ model_in_package="FlawedModels.DoesNotFinish",
36
+ result_folder=this_folder / "data/FlawedModels/results")
37
+
38
+ tester._import_and_simulate()
39
+
40
+ tester.cleanup(ask_confirmation=False)
41
+
42
+ return
43
+
44
+
45
+ if __name__ == '__main__':
46
+ unittest.main()
@@ -99,4 +99,8 @@ class TestUnifyTimestamps(unittest.TestCase):
99
99
  results_ext = mopyregtest.RegressionTest._unify_timestamps([res1, res2])
100
100
 
101
101
  self.assertIsNone(pd.testing.assert_frame_equal(res1_ext_expect, results_ext[0]))
102
- self.assertIsNone(pd.testing.assert_frame_equal(res2_ext_expect, results_ext[1]))
102
+ self.assertIsNone(pd.testing.assert_frame_equal(res2_ext_expect, results_ext[1]))
103
+
104
+
105
+ if __name__ == '__main__':
106
+ unittest.main()
@@ -1,58 +0,0 @@
1
- import unittest
2
- import mopyregtest
3
-
4
- class TestCompareResults(unittest.TestCase):
5
- def test_time_col_ignored(self):
6
- """
7
- Validates that time as a validated column is ignored in the result comparison
8
- """
9
-
10
- self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
11
- reference_result="../examples/test_user_defined_metrics/references/Sine_res.csv",
12
- simulation_result="../examples/test_user_defined_metrics/references/Sine_res.csv",
13
- validated_cols=["time"])
14
-
15
- def test_disjoint_cols(self):
16
- """
17
- Validate that test of two CSV result files that have no common result variable besides time fails
18
- """
19
- self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
20
- reference_result="../examples/test_Modelica_Electrical_Analog_Examples/references/Modelica.Electrical.Analog.Examples.CharacteristicIdealDiodes_res.csv",
21
- simulation_result="../examples/test_user_defined_metrics/references/Sine_res.csv")
22
- return
23
-
24
- def test_validated_cols_not_contained1(self):
25
- """
26
- Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
27
- result.
28
- """
29
-
30
- self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
31
- reference_result="../examples/test_user_defined_metrics/references/Sine_res.csv",
32
- simulation_result="../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
33
- validated_cols=["y", "not_present_var"])
34
- return
35
-
36
- def test_validated_cols_not_contained2(self):
37
- """
38
- Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
39
- result. Case: Column not contained in reference_result.
40
- """
41
-
42
- self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
43
- reference_result="../examples/test_user_defined_metrics/references/Sine_res.csv",
44
- simulation_result="../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
45
- validated_cols=["y", "uniformNoise.y"])
46
- return
47
-
48
- def test_validated_cols_not_contained3(self):
49
- """
50
- Validate that comparison fails if not all elements of validated cols are contained in both reference and actual
51
- result. Case: Column not contained in simulation_result.
52
- """
53
-
54
- self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
55
- reference_result="../examples/test_user_defined_metrics/references/SineNoisy_res.csv",
56
- simulation_result="../examples/test_user_defined_metrics/references/Sine_res.csv",
57
- validated_cols=["y", "uniformNoise.y"])
58
- return
File without changes