MoPyRegtest 0.6.0__tar.gz → 0.7.0rc1__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.6.0 → mopyregtest-0.7.0rc1/MoPyRegtest.egg-info}/PKG-INFO +7 -7
  2. {mopyregtest-0.6.0/MoPyRegtest.egg-info → mopyregtest-0.7.0rc1}/PKG-INFO +7 -7
  3. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/README.md +6 -6
  4. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/cli.py +37 -10
  5. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/generator.py +17 -5
  6. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/metrics.py +74 -1
  7. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/modelicaregressiontest.py +40 -11
  8. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/setup.py +1 -1
  9. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_cli.py +3 -3
  10. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_compare_results.py +52 -0
  11. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_metrics.py +75 -0
  12. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/LICENSE +0 -0
  13. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/MoPyRegtest.egg-info/SOURCES.txt +0 -0
  14. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/MoPyRegtest.egg-info/dependency_links.txt +0 -0
  15. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/MoPyRegtest.egg-info/entry_points.txt +0 -0
  16. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/MoPyRegtest.egg-info/requires.txt +0 -0
  17. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/MoPyRegtest.egg-info/top_level.txt +0 -0
  18. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/__init__.py +0 -0
  19. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/templates/omc/model_import.mos.template +0 -0
  20. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/templates/omc/model_simulate.mos.template +0 -0
  21. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/mopyregtest/utils.py +0 -0
  22. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/setup.cfg +0 -0
  23. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_check_success.py +0 -0
  24. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_modelerror.py +0 -0
  25. {mopyregtest-0.6.0 → mopyregtest-0.7.0rc1}/tests/test_unify_timestamps.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MoPyRegtest
3
- Version: 0.6.0
3
+ Version: 0.7.0rc1
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
@@ -29,7 +29,6 @@ Dynamic: summary
29
29
  [![Unit tests](https://github.com/pstelzig/mopyregtest/actions/workflows/job-unit-tests.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-unit-tests.yml)
30
30
  [![Examples](https://github.com/pstelzig/mopyregtest/actions/workflows/job-examples.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-examples.yml)
31
31
  [![Example usage in other repo](https://github.com/pstelzig/mopyregtest/actions/workflows/job-example-for-other-repo.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-example-for-other-repo.yml)
32
- [![Publish to PyPI](https://github.com/pstelzig/mopyregtest/actions/workflows/pythonpublish.yml/badge.svg)](https://pypi.org/project/MoPyRegtest/)
33
32
 
34
33
  A lightweight, CI-friendly regression testing framework for [Modelica](https://www.modelica.org/) models,
35
34
  wrapped in Python's [`unittest`](https://docs.python.org/3/library/unittest.html) module.
@@ -40,6 +39,7 @@ Uses [OpenModelica](https://www.openmodelica.org/) for model translation and sim
40
39
  - **Success-only testing** — verify that models compile, build, and simulate successfully (useful for unit test models with built-in assertions)
41
40
  - **Automatic test generation** — generate `unittest` test files for entire Modelica libraries via CLI or Python script
42
41
  - **CSV comparison** — compare two CSV result files directly from the command line
42
+ - **Builtin error metrics or self-defined** -- Builtins: Pointwise time-trajectory distances, $\mathrm{L}^p$ like function space distances, and a funnel-type distance
43
43
 
44
44
  ## Prerequisites
45
45
  - [Python 3](https://www.python.org/) with [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/)
@@ -70,10 +70,10 @@ Verify the CLI: `mopyregtest --help`
70
70
  import mopyregtest
71
71
 
72
72
  tester = mopyregtest.RegressionTest(
73
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
73
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
74
74
  model_in_package="Modelica.Electrical.Analog.Examples.HeatingRectifier",
75
75
  result_folder="./results",
76
- modelica_version="4.0.0")
76
+ modelica_version="4.1.0")
77
77
 
78
78
  tester.compare_result(reference_result="references/HeatingRectifier_res.csv", tol=1e-3)
79
79
  ```
@@ -82,7 +82,7 @@ tester.compare_result(reference_result="references/HeatingRectifier_res.csv", to
82
82
 
83
83
  ```python
84
84
  tester = mopyregtest.RegressionTest(
85
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
85
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
86
86
  model_in_package="Modelica.Blocks.Examples.Filter",
87
87
  result_folder="./results")
88
88
 
@@ -93,11 +93,11 @@ tester.check_success()
93
93
 
94
94
  ```bash
95
95
  # Regression tests
96
- mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
96
+ mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
97
97
  Modelica.Blocks.Sources.Sine,Modelica.Blocks.Sources.Step
98
98
 
99
99
  # Success-only tests
100
- mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
100
+ mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
101
101
  Modelica.Blocks.Examples.Filter
102
102
  ```
103
103
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MoPyRegtest
3
- Version: 0.6.0
3
+ Version: 0.7.0rc1
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
@@ -29,7 +29,6 @@ Dynamic: summary
29
29
  [![Unit tests](https://github.com/pstelzig/mopyregtest/actions/workflows/job-unit-tests.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-unit-tests.yml)
30
30
  [![Examples](https://github.com/pstelzig/mopyregtest/actions/workflows/job-examples.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-examples.yml)
31
31
  [![Example usage in other repo](https://github.com/pstelzig/mopyregtest/actions/workflows/job-example-for-other-repo.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-example-for-other-repo.yml)
32
- [![Publish to PyPI](https://github.com/pstelzig/mopyregtest/actions/workflows/pythonpublish.yml/badge.svg)](https://pypi.org/project/MoPyRegtest/)
33
32
 
34
33
  A lightweight, CI-friendly regression testing framework for [Modelica](https://www.modelica.org/) models,
35
34
  wrapped in Python's [`unittest`](https://docs.python.org/3/library/unittest.html) module.
@@ -40,6 +39,7 @@ Uses [OpenModelica](https://www.openmodelica.org/) for model translation and sim
40
39
  - **Success-only testing** — verify that models compile, build, and simulate successfully (useful for unit test models with built-in assertions)
41
40
  - **Automatic test generation** — generate `unittest` test files for entire Modelica libraries via CLI or Python script
42
41
  - **CSV comparison** — compare two CSV result files directly from the command line
42
+ - **Builtin error metrics or self-defined** -- Builtins: Pointwise time-trajectory distances, $\mathrm{L}^p$ like function space distances, and a funnel-type distance
43
43
 
44
44
  ## Prerequisites
45
45
  - [Python 3](https://www.python.org/) with [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/)
@@ -70,10 +70,10 @@ Verify the CLI: `mopyregtest --help`
70
70
  import mopyregtest
71
71
 
72
72
  tester = mopyregtest.RegressionTest(
73
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
73
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
74
74
  model_in_package="Modelica.Electrical.Analog.Examples.HeatingRectifier",
75
75
  result_folder="./results",
76
- modelica_version="4.0.0")
76
+ modelica_version="4.1.0")
77
77
 
78
78
  tester.compare_result(reference_result="references/HeatingRectifier_res.csv", tol=1e-3)
79
79
  ```
@@ -82,7 +82,7 @@ tester.compare_result(reference_result="references/HeatingRectifier_res.csv", to
82
82
 
83
83
  ```python
84
84
  tester = mopyregtest.RegressionTest(
85
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
85
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
86
86
  model_in_package="Modelica.Blocks.Examples.Filter",
87
87
  result_folder="./results")
88
88
 
@@ -93,11 +93,11 @@ tester.check_success()
93
93
 
94
94
  ```bash
95
95
  # Regression tests
96
- mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
96
+ mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
97
97
  Modelica.Blocks.Sources.Sine,Modelica.Blocks.Sources.Step
98
98
 
99
99
  # Success-only tests
100
- mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
100
+ mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
101
101
  Modelica.Blocks.Examples.Filter
102
102
  ```
103
103
 
@@ -4,7 +4,6 @@
4
4
  [![Unit tests](https://github.com/pstelzig/mopyregtest/actions/workflows/job-unit-tests.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-unit-tests.yml)
5
5
  [![Examples](https://github.com/pstelzig/mopyregtest/actions/workflows/job-examples.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-examples.yml)
6
6
  [![Example usage in other repo](https://github.com/pstelzig/mopyregtest/actions/workflows/job-example-for-other-repo.yml/badge.svg?branch=master)](https://github.com/pstelzig/MoPyRegtest/actions/workflows/job-example-for-other-repo.yml)
7
- [![Publish to PyPI](https://github.com/pstelzig/mopyregtest/actions/workflows/pythonpublish.yml/badge.svg)](https://pypi.org/project/MoPyRegtest/)
8
7
 
9
8
  A lightweight, CI-friendly regression testing framework for [Modelica](https://www.modelica.org/) models,
10
9
  wrapped in Python's [`unittest`](https://docs.python.org/3/library/unittest.html) module.
@@ -15,6 +14,7 @@ Uses [OpenModelica](https://www.openmodelica.org/) for model translation and sim
15
14
  - **Success-only testing** — verify that models compile, build, and simulate successfully (useful for unit test models with built-in assertions)
16
15
  - **Automatic test generation** — generate `unittest` test files for entire Modelica libraries via CLI or Python script
17
16
  - **CSV comparison** — compare two CSV result files directly from the command line
17
+ - **Builtin error metrics or self-defined** -- Builtins: Pointwise time-trajectory distances, $\mathrm{L}^p$ like function space distances, and a funnel-type distance
18
18
 
19
19
  ## Prerequisites
20
20
  - [Python 3](https://www.python.org/) with [`numpy`](https://numpy.org/) and [`pandas`](https://pandas.pydata.org/)
@@ -45,10 +45,10 @@ Verify the CLI: `mopyregtest --help`
45
45
  import mopyregtest
46
46
 
47
47
  tester = mopyregtest.RegressionTest(
48
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
48
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
49
49
  model_in_package="Modelica.Electrical.Analog.Examples.HeatingRectifier",
50
50
  result_folder="./results",
51
- modelica_version="4.0.0")
51
+ modelica_version="4.1.0")
52
52
 
53
53
  tester.compare_result(reference_result="references/HeatingRectifier_res.csv", tol=1e-3)
54
54
  ```
@@ -57,7 +57,7 @@ tester.compare_result(reference_result="references/HeatingRectifier_res.csv", to
57
57
 
58
58
  ```python
59
59
  tester = mopyregtest.RegressionTest(
60
- package_folder="~/.openmodelica/libraries/Modelica 4.0.0+maint.om",
60
+ package_folder="~/.openmodelica/libraries/Modelica 4.1.0+maint.om",
61
61
  model_in_package="Modelica.Blocks.Examples.Filter",
62
62
  result_folder="./results")
63
63
 
@@ -68,11 +68,11 @@ tester.check_success()
68
68
 
69
69
  ```bash
70
70
  # Regression tests
71
- mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
71
+ mopyregtest generate ./gen_tests MyTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
72
72
  Modelica.Blocks.Sources.Sine,Modelica.Blocks.Sources.Step
73
73
 
74
74
  # Success-only tests
75
- mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.0.0+maint.om/" \
75
+ mopyregtest generate --mode=success ./gen_tests MySimTest ~/".openmodelica/libraries/Modelica 4.1.0+maint.om/" \
76
76
  Modelica.Blocks.Examples.Filter
77
77
  ```
78
78
 
@@ -24,10 +24,26 @@ def metric_str_to_func(m: str):
24
24
  return metrics.Linfty_dist
25
25
  elif m == "abs_dist_ptwise":
26
26
  return metrics.abs_dist_ptwise
27
+ elif m == "funnel":
28
+ return metrics.funnel
27
29
  else:
28
30
  raise ValueError("Invalid value for metric")
29
31
 
30
32
 
33
+ def parse_tol(tol: str, metric):
34
+ """Parses --tol into a float, or into a (xtol, ytol) tuple if given as 'xtol,ytol' (only valid for metrics.funnel)."""
35
+ values = [float(v) for v in str(tol).split(",")]
36
+
37
+ if len(values) == 1:
38
+ return values[0]
39
+
40
+ if metric != metrics.funnel or len(values) != 2:
41
+ raise ValueError(f"Invalid tol '{tol}'. A pair 'xtol,ytol' is only allowed with the funnel metric, "
42
+ "otherwise tol must be a single float.")
43
+
44
+ return tuple(values)
45
+
46
+
31
47
  def generate(args):
32
48
  test_name = args.test_name
33
49
  test_folder = pathlib.Path(args.test_folder)
@@ -55,8 +71,11 @@ def generate(args):
55
71
  if args.metric is not None:
56
72
  metric = metric_str_to_func(args.metric)
57
73
 
74
+ tol = parse_tol(args.tol, metric)
75
+ unify_timestamps = (metric != metrics.funnel)
76
+
58
77
  gen = Generator(package_folder=package_folder, models_in_package=models_in_package,
59
- mode=mode, metric=metric, tol=args.tol)
78
+ mode=mode, metric=metric, tol=tol, unify_timestamps=unify_timestamps)
60
79
  gen.generate_tests(test_folder, test_name, result_folder, references)
61
80
 
62
81
  return
@@ -75,8 +94,12 @@ def compare(args):
75
94
  if args.metric is not None:
76
95
  metric = metric_str_to_func(args.metric)
77
96
 
97
+ tol = parse_tol(args.tol, metric)
98
+ unify_timestamps = (metric != metrics.funnel)
99
+
78
100
  RegressionTest.compare_csv_files(ref_result, act_result,
79
- args.tol, validated_cols, metric, True, args.fill_in_method)
101
+ tol, validated_cols, metric, unify_timestamps, args.fill_in_method)
102
+
80
103
 
81
104
  return
82
105
 
@@ -111,11 +134,13 @@ def parse_args(cmd_args):
111
134
  help="Metric to be used. Choose here from predefined values. "
112
135
  "For user-defined metrics please consider creating the tests with a dedicated script. "
113
136
  "If omitted, the default is norm_infty_dist",
114
- choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise"],
137
+ choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise", "funnel"],
115
138
  default="norm_infty_dist")
116
- generate_parser.add_argument("--tol", type=float,
117
- help="Absolute tolerance up to which deviation in the comparison metric is accepted",
118
- default=1e-7)
139
+ generate_parser.add_argument("--tol", type=str,
140
+ help="Absolute tolerance up to which deviation in the comparison metric is accepted. "
141
+ "If used with the funnel metric, this can be a pair '<xtol>,<ytol>', one for the allowed "
142
+ "tolerance in temporal direction, one for the allowed tolerance in value direction.",
143
+ default="1e-7")
119
144
  generate_parser.add_argument("--references", type=str,
120
145
  help="Comma separated list like <model name1>:</path/to/ref1.csv>,<model name2>:</path/to/ref2.csv>. "
121
146
  "Missing references for models here will be generated.")
@@ -130,14 +155,16 @@ def parse_args(cmd_args):
130
155
  compare_parser.add_argument("--metric", type=str,
131
156
  help="Metric to be used. Choose here from predefined values. "
132
157
  "For user-defined metrics please consider creating the tests with a dedicated script.",
133
- choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise"],
158
+ choices=["norm_p_dist", "norm_infty_dist", "Lp_dist", "Linfty_dist", "abs_dist_ptwise", "funnel"],
134
159
  default="norm_infty_dist")
135
160
  compare_parser.add_argument("--validated-cols", type=str,
136
161
  help="Comma separated list like <var name 1>,<var name 2>. "
137
162
  "If omitted, then all common column names from both CSV files will be used.")
138
- compare_parser.add_argument("--tol", type=float,
139
- help="Absolute tolerance up to which deviation in the comparison metric is accepted",
140
- default=1e-7)
163
+ compare_parser.add_argument("--tol", type=str,
164
+ help="Absolute tolerance up to which deviation in the comparison metric is accepted. "
165
+ "If used with the funnel metric, this can be a pair '<xtol>,<ytol>', one for the allowed "
166
+ "tolerance in temporal direction, one for the allowed tolerance in value direction.",
167
+ default="1e-7")
141
168
  compare_parser.add_argument("--fill-in-method", type=str,
142
169
  help="Defines the method used to fill in data when calling RegressionTest._unify_timestamps",
143
170
  choices=["ffill", "bfill", "interpolate"], default="ffill")
@@ -121,14 +121,16 @@ if __name__ == '__main__':
121
121
  metric : function or str
122
122
  Metric to be used in result comparison. Important: If the metric is given as a funtion, one must use one
123
123
  of the predefined metrics, i.e. mopyregtest.metrics.norm_p_dist, mopyregtest.metrics.norm_infty_dist,
124
- mopyregtest.metrics.Lp_dist, mopyregtest.metrics.Linfty_dist, or mopyregtest.metrics.abs_dist_ptwise.
124
+ mopyregtest.metrics.Lp_dist, mopyregtest.metrics.Linfty_dist, mopyregtest.metrics.abs_dist_ptwise,
125
+ or mopyregtest.metrics.funnel.
125
126
 
126
127
  If a user-defined metric shall be used, the code must be passed as a string!
127
- tol : float
128
- Tolerance to be used in all regression tests.
128
+ tol : float or tuple[float, float]
129
+ Tolerance to be used in all regression tests. Only with metrics.funnel this may be a tuple (xtol, ytol)
130
+ of tolerances in temporal and in value direction. Otherwise it must be a float.
129
131
  unify_timestamps : bool
130
132
  Boolean controlling whether the timestamp unification shall be called in the RegressionTest.compare_result
131
- before evaluating the metric. Default=True.
133
+ before evaluating the metric. Default=True. Must be False if metrics.funnel is used.
132
134
 
133
135
  If set to False, then the function passed in the argument "metric" will be evaluated for matching columns
134
136
  of reference and actual result. In this case the definition of the metric has to
@@ -154,12 +156,22 @@ if __name__ == '__main__':
154
156
  if (callable(metric) and
155
157
  metric in [metrics.norm_p_dist, metrics.norm_infty_dist,
156
158
  metrics.Lp_dist, metrics.Linfty_dist,
157
- metrics.abs_dist_ptwise]):
159
+ metrics.abs_dist_ptwise, metrics.funnel]):
158
160
  self.metric = f"mopyregtest.metrics.{metric.__name__}"
159
161
  elif type(metric) == str:
160
162
  self.metric = metric
161
163
  else:
162
164
  raise ValueError("metric argument not recognized")
165
+
166
+ is_funnel = self.metric == "mopyregtest.metrics.funnel"
167
+ if isinstance(tol, tuple) and not is_funnel:
168
+ raise ValueError("A tuple valued tol may only be used in conjunction with metrics.funnel. "
169
+ "Use a nonnegative scalar value instead.")
170
+
171
+ if unify_timestamps and is_funnel:
172
+ raise ValueError("metrics.funnel shall not be used together with unify_timestamps. "
173
+ "Pass unify_timestamps=False.")
174
+
163
175
  self.tol = tol
164
176
  self.unify_timestamps = unify_timestamps
165
177
  self.fill_in_method = fill_in_method
@@ -120,4 +120,77 @@ def func_ptwise(f1, f2, dist: callable):
120
120
 
121
121
 
122
122
  def abs_dist_ptwise(f1, f2):
123
- return func_ptwise(f1, f2, np.abs)
123
+ return func_ptwise(f1, f2, np.abs)
124
+
125
+
126
+ def funnel(f1, f2, xtol: float, ytol: float, fill_in_method="ffill"):
127
+ """
128
+ Builds funnel around f1's data points (t1_0,f1_0), (t1_1,f1_1),... Those are rectangles
129
+ around each of the datapoints, and extend in y-direction over [f1_i-ytol, f1_i+ytol] and
130
+ in time direction over [t1_i-xtol, t1_i+xtol]
131
+
132
+ It returns the distances w.r.t. this funnel at the time values of f2.
133
+
134
+ Then for f2's datapoints (t2_0,f2_0), (t2_1,f2_1),..., it is checked if they fall into
135
+ those rectangles.
136
+
137
+ If (t2_j, f2_j) falls into a rectangle of f1 centered at (t1_i, f1_i),
138
+ then the distance at t2_j is 0 if |f2_j - f1_i| <= ytol, otherwise |f2_j - f1_i| - ytol.
139
+ If it falls into multiple rectangles, then the acceptable range is from the lowest
140
+ boundary of any of the rectangles up to the highest bound from all those rectangles.
141
+
142
+ If (t2_j, f2_j) does not fall into a rectangle of f1, then f1 is interpolated according
143
+ to fill_in_method to have a value at t2_j, and then the returned value is
144
+ 0 if |f2_j - f1_i| <= ytol, otherwise |f2_j - f1_i| - ytol.
145
+
146
+ fill_in_method can be ffill, bfill, interpolate.
147
+ """
148
+ _check_piecewise_func(f1)
149
+ _check_piecewise_func(f2)
150
+
151
+ dist = np.zeros(shape=np.array(f2).shape)
152
+
153
+ # Number of datapoints in f1 and f2
154
+ N1 = f1.shape[0] # i iterates over f1
155
+ N2 = f2.shape[0] # j iterates over f2
156
+
157
+ t1 = f1[:, 0]
158
+ y1 = f1[:, 1]
159
+
160
+ t2 = f2[:, 0]
161
+ y2 = f2[:, 1]
162
+
163
+ # Dict mapping the data index j of f2 to the indexes i in f1 into whose rectangles t2[j] falls
164
+ hit_rectangles = {j: [i for i in range(0, N1) if abs(t1[i] - t2[j]) <= xtol] for j in range(0, N2)}
165
+
166
+ for j in range(0, N2):
167
+ if hit_rectangles[j]:
168
+ # Timepoint of f2 falls into at least one rectangle around a f1 datapoint
169
+ lower_bound = min([f1[i, 1] - ytol for i in hit_rectangles[j]])
170
+ upper_bound = max([f1[i, 1] + ytol for i in hit_rectangles[j]])
171
+ else:
172
+ # We assume f1 to be interpolated according to fill_in_method
173
+ dist[j,0] = t2[j]
174
+
175
+ if fill_in_method == "ffill":
176
+ y1_fill = y1[max(np.searchsorted(t1, t2[j], side="right") - 1, 0)]
177
+ elif fill_in_method == "bfill":
178
+ y1_fill = y1[min(np.searchsorted(t1, t2[j], side="left"), len(t1) - 1)]
179
+ elif fill_in_method == "interpolate":
180
+ y1_fill = np.interp(t2[j], t1, y1)
181
+ else:
182
+ raise ValueError("Unknown filling method for NaN values")
183
+
184
+ lower_bound = y1_fill - ytol
185
+ upper_bound = y1_fill + ytol
186
+
187
+ dist[j,0] = t2[j]
188
+
189
+ if y2[j] < lower_bound:
190
+ dist[j,1] = lower_bound - y2[j]
191
+ elif y2[j] > upper_bound:
192
+ dist[j,1] = y2[j] - upper_bound
193
+ else:
194
+ dist[j,1] = 0
195
+
196
+ return dist
@@ -7,7 +7,6 @@ MIT License. See the project's LICENSE file.
7
7
  """
8
8
 
9
9
  import os
10
- import re
11
10
  import subprocess
12
11
  import platform
13
12
  import pathlib
@@ -44,7 +43,7 @@ class RegressionTest:
44
43
  RegressionTest will search the PATH variable for omc and will execute the tests if found.
45
44
  modelica_version : str
46
45
  Version of the Modelica standard library to be loaded before the test is executed.
47
- Default is "default", other meaningful values can be "3.2.3" or "4.0.0".
46
+ Default is "default", other meaningful values can be "3.2.3" or "4.1.0".
48
47
  dependencies : None or List[str]
49
48
  Optional list of strings with names of packages that the package to be tested depends on.
50
49
  Each dependency must point to the .mo file that defines the dependency. E.g. if the
@@ -260,6 +259,12 @@ class RegressionTest:
260
259
  -------
261
260
  out : None
262
261
  """
262
+ if isinstance(tol, tuple) and metric != metrics.funnel:
263
+ raise ValueError("A tuple valued tol may only be used in conjunction with metrics.funnel. Use a nonnegative scalar value instead. ")
264
+
265
+ if unify_timestamps and metric == metrics.funnel:
266
+ raise ValueError("metrics.funnel shall not be used together with unify_timestamps since this makes the funnel trivial.")
267
+
263
268
  ref_data = pd.read_csv(filepath_or_buffer=reference_result, delimiter=',')
264
269
  sim_data = pd.read_csv(filepath_or_buffer=simulation_result, delimiter=',')
265
270
 
@@ -294,16 +299,36 @@ class RegressionTest:
294
299
  f"reference {reference_result} and simulation result {simulation_result}")
295
300
 
296
301
  failed_cols = {}
302
+ if isinstance(tol, tuple):
303
+ xtol = tol[0]
304
+ ytol = tol[1]
305
+ else:
306
+ xtol = tol
307
+ ytol = tol
308
+
297
309
  for c in validated_cols:
298
310
  print("Comparing column \"{}\"".format(c))
299
- delta = metric(ref_data[["time", c]].values, sim_data[["time", c]].values)
300
311
 
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)
312
+ if metric != metrics.funnel:
313
+ delta = metric(ref_data[["time", c]].values, sim_data[["time", c]].values)
314
+ else:
315
+ if isinstance(tol, tuple) and len(tol) >= 2:
316
+ delta = metrics.funnel(ref_data[["time", c]].values, sim_data[["time", c]].values, xtol=xtol, ytol=ytol, fill_in_method=fill_in_method)
317
+ else:
318
+ delta = metrics.funnel(ref_data[["time", c]].values, sim_data[["time", c]].values, xtol=xtol, ytol=ytol, fill_in_method=fill_in_method)
319
+
320
+ if isinstance(delta, np.ndarray):
321
+ # For pointwise metrics we compare against deviations in y-direction >= ytol
322
+ if metric != metrics.funnel and np.any(delta[:, 1] >= ytol):
323
+ delta_gt_tol = np.where(delta >= ytol, delta, 0.0)
324
+ failed_cols[c] = pd.DataFrame(data=delta_gt_tol, columns=["time", "delta"])
325
+
326
+ # For metrics.funnel we check where we reach beyond 2e-5*ytol, i.e. 1e-5 times the funnel's y-width of 2*ytol. This is for numerical stability
327
+ if metric == metrics.funnel and np.any(delta[:, 1] > 2e-5*ytol):
328
+ delta_gt_tol = np.where(delta > 2e-5*ytol, delta, 0.0)
304
329
  failed_cols[c] = pd.DataFrame(data=delta_gt_tol, columns=["time", "delta"])
305
330
  else:
306
- if np.abs(delta) >= tol:
331
+ if np.abs(delta) >= ytol:
307
332
  failed_cols[c] = delta
308
333
 
309
334
  if failed_cols:
@@ -313,7 +338,7 @@ class RegressionTest:
313
338
 
314
339
  raise AssertionError(
315
340
  f"Values of results {simulation_result} and {reference_result} are different in columns "
316
- f"{list(failed_cols.keys())} by more than {tol}. ")
341
+ f"{list(failed_cols.keys())}. ")
317
342
 
318
343
  return
319
344
 
@@ -353,8 +378,10 @@ class RegressionTest:
353
378
  ----------
354
379
  reference_result : str
355
380
  Path to a reference .csv file containing the expected results of the model
356
- tol : float
357
- Absolute tolerance up to which deviation in the comparison metric is accepted
381
+ tol : float | tuple[float,float]
382
+ Absolute tolerance up to which deviation in the comparison metric is accepted.
383
+ If metric.funnel is used, the tol might be a tuple of two floats, one for the allowed deviation in temporal
384
+ direction, one in value direction.
358
385
  validated_cols : list
359
386
  List of variable names (from the file header) in the reference .csv file that are used in the regression test
360
387
  Important: All entries of validated_cols must be present in both the reference result and the actual result.
@@ -403,6 +430,8 @@ class RegressionTest:
403
430
  If set to False, then the function passed in the argument "metric" will be evaluated for matching columns
404
431
  (from validated_cols) of reference and actual result. In this case the definition of the metric has to
405
432
  ensure that computations are meaningful, e.g. for non-matching dimensions or different timestamps.
433
+
434
+ Note: unify_timestamps must be False if used with metric=metrics.funnel. Otherwise an exception will be raised.
406
435
  fill_in_method : str
407
436
  Defines the method used to fill in data when calling RegressionTest._unify_timestamps and if results have
408
437
  different timestamps and cannot be compared pointwise.
@@ -645,7 +674,7 @@ class RegressionTest:
645
674
  # Determine if the delta in failed_cols between actual and reference is a (nonlocal) scalar or a timeseries
646
675
  is_scalar = True
647
676
  for v in failed_cols.values():
648
- if type(v) is pd.DataFrame:
677
+ if isinstance(v, pd.DataFrame):
649
678
  is_scalar = False
650
679
  break
651
680
 
@@ -8,7 +8,7 @@ with open("README.md") as fh:
8
8
 
9
9
  setuptools.setup(
10
10
  name="MoPyRegtest",
11
- version="0.6.0",
11
+ version="0.7.0-rc.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,
@@ -13,7 +13,7 @@ class TestCli(unittest.TestCase):
13
13
  cmd_args = ["generate",
14
14
  str(this_folder / "../examples/generate_tests/gen_tests1"),
15
15
  "BlocksLpDist_from_cli_1",
16
- "~/.openmodelica/libraries/Modelica 4.0.0+maint.om/",
16
+ "~/.openmodelica/libraries/Modelica 4.1.0+maint.om/",
17
17
  "Modelica.Blocks.Sources.Sine,Modelica.Blocks.Sources.ExpSine,Modelica.Blocks.Sources.Step"]
18
18
 
19
19
  cli.parse_args(cmd_args)
@@ -29,7 +29,7 @@ class TestCli(unittest.TestCase):
29
29
  "--tol=1.2e-5",
30
30
  str(this_folder / "../examples/generate_tests/gen_tests2"),
31
31
  "BlocksLpDist_from_cli_2",
32
- "~/.openmodelica/libraries/Modelica 4.0.0+maint.om/",
32
+ "~/.openmodelica/libraries/Modelica 4.1.0+maint.om/",
33
33
  "Modelica.Blocks.Sources.Sine,Modelica.Blocks.Sources.ExpSine,Modelica.Blocks.Sources.Step"]
34
34
 
35
35
  cli.parse_args(cmd_args)
@@ -47,7 +47,7 @@ class TestCli(unittest.TestCase):
47
47
  this_folder / "../examples/test_user_defined_metrics/references/SineNoisy_res.csv"),
48
48
  str(this_folder / "../examples/generate_tests/gen_tests3"),
49
49
  "BlocksAbsDistPtwise_from_cli",
50
- "~/.openmodelica/libraries/Modelica 4.0.0+maint.om/",
50
+ "~/.openmodelica/libraries/Modelica 4.1.0+maint.om/",
51
51
  "Modelica.Blocks.Sources.Sine"]
52
52
 
53
53
  cli.parse_args(cmd_args)
@@ -1,6 +1,8 @@
1
1
  import unittest
2
2
  import pathlib
3
3
  import os
4
+ import tempfile
5
+ import pandas as pd
4
6
  import mopyregtest
5
7
 
6
8
  this_folder = pathlib.Path(__file__).absolute().parent
@@ -101,6 +103,56 @@ class TestCompareResults(unittest.TestCase):
101
103
 
102
104
  return
103
105
 
106
+ def _write_step_csvs(self, folder, sim_y_at_edge):
107
+ ref = pd.DataFrame({"time": [0.0, 1.0, 2.0, 3.0], "y": [0.0, 0.0, 1.0, 1.0]})
108
+ sim = pd.DataFrame({"time": [0.0, 1.5, 3.0], "y": [0.0, sim_y_at_edge, 1.0]})
109
+
110
+ ref_path = pathlib.Path(folder) / "ref.csv"
111
+ sim_path = pathlib.Path(folder) / "sim.csv"
112
+ ref.to_csv(ref_path, index=False)
113
+ sim.to_csv(sim_path, index=False)
114
+
115
+ return ref_path, sim_path
116
+
117
+ def test_funnel(self):
118
+ """
119
+ Validate compare_csv_files with metrics.funnel for results with different timestamps: Passes if the actual
120
+ result stays inside the funnel, fails if it leaves it.
121
+ """
122
+ with tempfile.TemporaryDirectory() as tmp:
123
+ # Sim has its edge at t=1.5, i.e. within xtol=0.5 of both reference datapoints t=1 and t=2
124
+ ref_path, sim_path = self._write_step_csvs(tmp, sim_y_at_edge=1.0)
125
+ mopyregtest.RegressionTest.compare_csv_files(ref_path, sim_path, tol=(0.5, 0.01),
126
+ metric=mopyregtest.metrics.funnel,
127
+ unify_timestamps=False, write_comparison=False)
128
+
129
+ # A scalar tol is used as both xtol and ytol
130
+ mopyregtest.RegressionTest.compare_csv_files(ref_path, sim_path, tol=0.5,
131
+ metric=mopyregtest.metrics.funnel,
132
+ unify_timestamps=False, write_comparison=False)
133
+
134
+ # Value 2.0 is outside the funnel [-0.01, 1.01] around the reference
135
+ ref_path, sim_path = self._write_step_csvs(tmp, sim_y_at_edge=2.0)
136
+ self.assertRaises(AssertionError, mopyregtest.RegressionTest.compare_csv_files,
137
+ reference_result=ref_path, simulation_result=sim_path, tol=(0.5, 0.01),
138
+ metric=mopyregtest.metrics.funnel, unify_timestamps=False, write_comparison=False)
139
+
140
+ def test_funnel_invalid_arguments(self):
141
+ """
142
+ Validate that metrics.funnel cannot be combined with unify_timestamps and that a tuple valued tol is
143
+ only accepted together with metrics.funnel.
144
+ """
145
+ with tempfile.TemporaryDirectory() as tmp:
146
+ ref_path, sim_path = self._write_step_csvs(tmp, sim_y_at_edge=1.0)
147
+
148
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
149
+ reference_result=ref_path, simulation_result=sim_path, tol=(0.5, 0.01),
150
+ metric=mopyregtest.metrics.funnel, unify_timestamps=True)
151
+
152
+ self.assertRaises(ValueError, mopyregtest.RegressionTest.compare_csv_files,
153
+ reference_result=ref_path, simulation_result=sim_path, tol=(0.5, 0.01),
154
+ metric=mopyregtest.metrics.norm_infty_dist)
155
+
104
156
 
105
157
  if __name__ == '__main__':
106
158
  unittest.main()
@@ -152,6 +152,81 @@ class TestMetrics(unittest.TestCase):
152
152
 
153
153
  self.assertRaises(ValueError, mopyregtest.metrics.norm_infty_dist, f1=f1, f2=f4)
154
154
 
155
+ def test_funnel_inside_and_outside_rectangle(self):
156
+ f1 = np.array([[0.0, 0.0],
157
+ [1.0, 0.0],
158
+ [2.0, 1.0],
159
+ [3.0, 1.0]])
160
+
161
+ # Points of f2 at times that coincide with f1 (inside the time window), incl. on the value boundary
162
+ f2 = np.array([[0.0, 0.05],
163
+ [1.0, -0.1],
164
+ [2.0, 1.5],
165
+ [3.0, 0.0]])
166
+
167
+ dist = mopyregtest.metrics.funnel(f1, f2, xtol=0.1, ytol=0.1)
168
+
169
+ self.assertEqual(dist.shape, f2.shape)
170
+ np.testing.assert_array_equal(dist[:, 0], f2[:, 0])
171
+ np.testing.assert_allclose(dist[:, 1], [0.0, 0.0, 0.4, 0.9], atol=1e-12)
172
+
173
+ def test_funnel_multiple_rectangles(self):
174
+ f1 = np.array([[0.0, 0.0],
175
+ [1.0, 1.0]])
176
+
177
+ # t=0.5 lies on the time boundary of both rectangles, so the accepted range is [-ytol, 1+ytol]
178
+ f2 = np.array([[0.5, 0.6],
179
+ [0.5, 1.5],
180
+ [0.5, -0.5]])
181
+
182
+ dist = mopyregtest.metrics.funnel(f1, f2, xtol=0.5, ytol=0.1)
183
+
184
+ np.testing.assert_allclose(dist[:, 1], [0.0, 0.4, 0.4], atol=1e-12)
185
+
186
+ def test_funnel_fill_in_methods(self):
187
+ f1 = np.array([[0.0, 0.0],
188
+ [1.0, 0.0],
189
+ [2.0, 1.0],
190
+ [3.0, 1.0]])
191
+
192
+ # t=1.5 is not within xtol of any f1 timestamp, so f1 is filled in there
193
+ f2 = np.array([[0.0, 0.0],
194
+ [1.5, -0.05],
195
+ [3.0, 1.0]])
196
+
197
+ expected = {"ffill": 0.0, # f1(1.5) = 0
198
+ "bfill": 0.95, # f1(1.5) = 1
199
+ "interpolate": 0.45} # f1(1.5) = 0.5
200
+
201
+ for method, exp in expected.items():
202
+ with self.subTest(fill_in_method=method):
203
+ dist = mopyregtest.metrics.funnel(f1, f2, xtol=0.1, ytol=0.1, fill_in_method=method)
204
+ np.testing.assert_allclose(dist[:, 1], [0.0, exp, 0.0], atol=1e-12)
205
+
206
+ def test_funnel_outside_time_range_of_f1(self):
207
+ f1 = np.array([[0.0, 0.0],
208
+ [1.0, 0.0],
209
+ [2.0, 1.0],
210
+ [3.0, 1.0]])
211
+
212
+ # Outside the time range of f1 the first/last value of f1 is used
213
+ f2 = np.array([[-1.0, 0.0],
214
+ [4.0, 1.13]])
215
+
216
+ for method in ["ffill", "bfill", "interpolate"]:
217
+ with self.subTest(fill_in_method=method):
218
+ dist = mopyregtest.metrics.funnel(f1, f2, xtol=0.1, ytol=0.1, fill_in_method=method)
219
+ np.testing.assert_allclose(dist[:, 1], [0.0, 0.03], atol=1e-12)
220
+
221
+ def test_funnel_unknown_fill_in_method(self):
222
+ f1 = np.array([[0.0, 0.0],
223
+ [1.0, 0.0]])
224
+ f2 = np.array([[0.5, 0.0],
225
+ [0.75, 0.0]])
226
+
227
+ self.assertRaises(ValueError, mopyregtest.metrics.funnel, f1=f1, f2=f2, xtol=0.1, ytol=0.1,
228
+ fill_in_method="unknown")
229
+
155
230
 
156
231
  if __name__ == '__main__':
157
232
  unittest.main()
File without changes
File without changes