nervus 0.1.0__py3-none-any.whl

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 (357) hide show
  1. nervus/__init__.py +35 -0
  2. nervus/advisor.py +258 -0
  3. nervus/analysis.py +527 -0
  4. nervus/blocks/__init__.py +236 -0
  5. nervus/blocks/automotive_electrics.py +243 -0
  6. nervus/blocks/can_blocks.py +826 -0
  7. nervus/blocks/chart.py +696 -0
  8. nervus/blocks/chart_model.py +349 -0
  9. nervus/blocks/continuous.py +389 -0
  10. nervus/blocks/control.py +210 -0
  11. nervus/blocks/diagnostics.py +250 -0
  12. nervus/blocks/discontinuities.py +215 -0
  13. nervus/blocks/discrete.py +521 -0
  14. nervus/blocks/electrical.py +497 -0
  15. nervus/blocks/fmi.py +184 -0
  16. nervus/blocks/hydraulic.py +222 -0
  17. nervus/blocks/logic.py +159 -0
  18. nervus/blocks/lookup.py +364 -0
  19. nervus/blocks/math_ops.py +306 -0
  20. nervus/blocks/mechanical.py +384 -0
  21. nervus/blocks/physical_ports.py +25 -0
  22. nervus/blocks/ports.py +381 -0
  23. nervus/blocks/registry.py +48 -0
  24. nervus/blocks/routing.py +183 -0
  25. nervus/blocks/semiconductors.py +267 -0
  26. nervus/blocks/sensors.py +146 -0
  27. nervus/blocks/signal_builder.py +220 -0
  28. nervus/blocks/sinks.py +95 -0
  29. nervus/blocks/sources.py +338 -0
  30. nervus/blocks/user.py +101 -0
  31. nervus/can.py +240 -0
  32. nervus/canbus.py +346 -0
  33. nervus/circuit.py +102 -0
  34. nervus/cli.py +57 -0
  35. nervus/codegen/__init__.py +23 -0
  36. nervus/codegen/a2l.py +180 -0
  37. nervus/codegen/fmu.py +302 -0
  38. nervus/codegen/functions.py +164 -0
  39. nervus/codegen/generator.py +1245 -0
  40. nervus/codegen/integer.py +490 -0
  41. nervus/codegen/misra.py +87 -0
  42. nervus/codegen/sil.py +182 -0
  43. nervus/codegen/templates.py +1263 -0
  44. nervus/core/__init__.py +46 -0
  45. nervus/core/block.py +436 -0
  46. nervus/core/datatypes.py +229 -0
  47. nervus/core/diagram.py +472 -0
  48. nervus/core/dictionary.py +150 -0
  49. nervus/core/errors.py +43 -0
  50. nervus/core/expressions.py +189 -0
  51. nervus/core/layout.py +106 -0
  52. nervus/core/params.py +154 -0
  53. nervus/core/requirements.py +234 -0
  54. nervus/core/sample_time.py +75 -0
  55. nervus/core/settings.py +83 -0
  56. nervus/core/signals.py +106 -0
  57. nervus/core/testcase.py +111 -0
  58. nervus/core/types.py +28 -0
  59. nervus/core/workspace.py +292 -0
  60. nervus/coverage.py +245 -0
  61. nervus/cycles.py +66 -0
  62. nervus/data/cycles/ftp75.csv +1877 -0
  63. nervus/data/cycles/wltc_class3b.csv +1803 -0
  64. nervus/examples/abs_braking.nervus +697 -0
  65. nervus/examples/abs_braking.py +220 -0
  66. nervus/examples/active_filter.nervus +236 -0
  67. nervus/examples/buck_converter.nervus +274 -0
  68. nervus/examples/can_network.nervus +928 -0
  69. nervus/examples/can_network.py +218 -0
  70. nervus/examples/charging_system.nervus +595 -0
  71. nervus/examples/charging_system.py +189 -0
  72. nervus/examples/circuits.py +214 -0
  73. nervus/examples/coolant_fan.nervus +367 -0
  74. nervus/examples/coolant_fan.py +113 -0
  75. nervus/examples/coupled_tanks.nervus +616 -0
  76. nervus/examples/coupled_tanks.py +165 -0
  77. nervus/examples/cruise_control.nervus +255 -0
  78. nervus/examples/cruise_control.py +91 -0
  79. nervus/examples/cruise_tolerance.py +71 -0
  80. nervus/examples/data/chassis.dbc +44 -0
  81. nervus/examples/data/idle_requirements.csv +6 -0
  82. nervus/examples/data/vehicle.dbc +28 -0
  83. nervus/examples/dc_motor_lab.py +203 -0
  84. nervus/examples/dc_motor_position.nervus +402 -0
  85. nervus/examples/dc_motor_speed.nervus +472 -0
  86. nervus/examples/drive_cycle.nervus +1135 -0
  87. nervus/examples/drive_cycle.py +288 -0
  88. nervus/examples/electronic_throttle.nervus +690 -0
  89. nervus/examples/electronic_throttle.py +190 -0
  90. nervus/examples/engine_comparison.nervus +1107 -0
  91. nervus/examples/engine_library.py +222 -0
  92. nervus/examples/engine_modes.nervus +696 -0
  93. nervus/examples/engine_modes.py +209 -0
  94. nervus/examples/ev_range.nervus +1146 -0
  95. nervus/examples/ev_range.py +106 -0
  96. nervus/examples/fixed_point_sensor.nervus +321 -0
  97. nervus/examples/fixed_point_sensor.py +86 -0
  98. nervus/examples/fmi_exchange.py +85 -0
  99. nervus/examples/fmi_plant.nervus +257 -0
  100. nervus/examples/fuel_film.nervus +1073 -0
  101. nervus/examples/fuel_film.py +239 -0
  102. nervus/examples/gear_shift.nervus +2007 -0
  103. nervus/examples/gear_shift.py +446 -0
  104. nervus/examples/generated/ECU/ECU.a2l +70 -0
  105. nervus/examples/generated/ECU/ECU.c +66 -0
  106. nervus/examples/generated/ECU/ECU.h +60 -0
  107. nervus/examples/generated/ECU/main_example.c +23 -0
  108. nervus/examples/generated/cruise_monte_carlo.csv +201 -0
  109. nervus/examples/generated/idle_coverage.html +5 -0
  110. nervus/examples/generated/idle_traceability.html +9 -0
  111. nervus/examples/idle_requirements.nervus +800 -0
  112. nervus/examples/idle_requirements.py +73 -0
  113. nervus/examples/idle_speed_control.nervus +712 -0
  114. nervus/examples/idle_speed_control.py +200 -0
  115. nervus/examples/ignition_knock.nervus +876 -0
  116. nervus/examples/ignition_knock.py +209 -0
  117. nervus/examples/injector_driver.nervus +506 -0
  118. nervus/examples/injector_driver.py +139 -0
  119. nervus/examples/inverted_pendulum.nervus +470 -0
  120. nervus/examples/inverted_pendulum.py +173 -0
  121. nervus/examples/lambda_control.nervus +885 -0
  122. nervus/examples/lambda_control.py +232 -0
  123. nervus/examples/library/engine_parts.nervlib +464 -0
  124. nervus/examples/mass_spring_damper_pid.nervus +329 -0
  125. nervus/examples/mass_spring_damper_pid.py +116 -0
  126. nervus/examples/ntc_sensor.nervus +938 -0
  127. nervus/examples/ntc_sensor.py +226 -0
  128. nervus/examples/obd_ecu.nervus +690 -0
  129. nervus/examples/obd_ecu.py +179 -0
  130. nervus/examples/rc_filter.nervus +225 -0
  131. nervus/examples/rc_rlc.py +137 -0
  132. nervus/examples/rectifier.nervus +233 -0
  133. nervus/examples/relay_driver.nervus +302 -0
  134. nervus/examples/rlc_circuit.nervus +247 -0
  135. nervus/examples/starter_motor.nervus +484 -0
  136. nervus/examples/starter_motor.py +131 -0
  137. nervus/examples/throttle_ecu.nervus +414 -0
  138. nervus/examples/throttle_ecu.py +154 -0
  139. nervus/examples/throttle_pi.nervus +278 -0
  140. nervus/examples/throttle_pi.py +115 -0
  141. nervus/examples/throttle_tight.nervcal +10 -0
  142. nervus/examples/traction_control.nervus +814 -0
  143. nervus/examples/traction_control.py +194 -0
  144. nervus/examples/truck.nervus +800 -0
  145. nervus/examples/truck.py +217 -0
  146. nervus/examples/xcp_calibration.a2l +33 -0
  147. nervus/examples/xcp_calibration.nervus +425 -0
  148. nervus/examples/xcp_calibration.py +142 -0
  149. nervus/examples/xcp_tool.py +67 -0
  150. nervus/examples.py +30 -0
  151. nervus/gui/__init__.py +6 -0
  152. nervus/gui/__main__.py +5 -0
  153. nervus/gui/app.py +42 -0
  154. nervus/gui/controllers/__init__.py +6 -0
  155. nervus/gui/controllers/codegen_controller.py +87 -0
  156. nervus/gui/controllers/commands.py +565 -0
  157. nervus/gui/controllers/editor_controller.py +681 -0
  158. nervus/gui/controllers/file_controller.py +91 -0
  159. nervus/gui/controllers/simulation_controller.py +134 -0
  160. nervus/gui/controllers/test_controller.py +93 -0
  161. nervus/gui/models/__init__.py +4 -0
  162. nervus/gui/models/diagram_model.py +327 -0
  163. nervus/gui/models/simulation_model.py +99 -0
  164. nervus/gui/qtfix.py +33 -0
  165. nervus/gui/resources/__init__.py +0 -0
  166. nervus/gui/resources/figures/__init__.py +0 -0
  167. nervus/gui/resources/figures/abs_braking.png +0 -0
  168. nervus/gui/resources/figures/can_arbitration.png +0 -0
  169. nervus/gui/resources/figures/can_frame.png +0 -0
  170. nervus/gui/resources/figures/can_network.png +0 -0
  171. nervus/gui/resources/figures/charging_system.png +0 -0
  172. nervus/gui/resources/figures/chart-editor-transition.png +0 -0
  173. nervus/gui/resources/figures/chart-editor.png +0 -0
  174. nervus/gui/resources/figures/chart_engine_modes.png +0 -0
  175. nervus/gui/resources/figures/chart_hierarchy.png +0 -0
  176. nervus/gui/resources/figures/circuits.png +0 -0
  177. nervus/gui/resources/figures/coolant_fan.png +0 -0
  178. nervus/gui/resources/figures/counter.png +0 -0
  179. nervus/gui/resources/figures/cruise_tolerance.png +0 -0
  180. nervus/gui/resources/figures/datatype_conversion.png +0 -0
  181. nervus/gui/resources/figures/dead_zone.png +0 -0
  182. nervus/gui/resources/figures/debounce.png +0 -0
  183. nervus/gui/resources/figures/diagnostic_monitor.png +0 -0
  184. nervus/gui/resources/figures/discrete_filter.png +0 -0
  185. nervus/gui/resources/figures/discrete_integrator.png +0 -0
  186. nervus/gui/resources/figures/drive_cycle.png +0 -0
  187. nervus/gui/resources/figures/drive_cycle_block.png +0 -0
  188. nervus/gui/resources/figures/edge_detect.png +0 -0
  189. nervus/gui/resources/figures/engine_comparison.png +0 -0
  190. nervus/gui/resources/figures/engine_modes.png +0 -0
  191. nervus/gui/resources/figures/ev_range.png +0 -0
  192. nervus/gui/resources/figures/first-model-1-blocks.png +0 -0
  193. nervus/gui/resources/figures/first-model-2-wired.png +0 -0
  194. nervus/gui/resources/figures/first-model-3-parameters.png +0 -0
  195. nervus/gui/resources/figures/first-model-4-scope.png +0 -0
  196. nervus/gui/resources/figures/first-model-5-inspector.png +0 -0
  197. nervus/gui/resources/figures/fixed_point_sensor.png +0 -0
  198. nervus/gui/resources/figures/fmi_exchange.png +0 -0
  199. nervus/gui/resources/figures/from_workspace.png +0 -0
  200. nervus/gui/resources/figures/fuel_film.png +0 -0
  201. nervus/gui/resources/figures/gain_modes.png +0 -0
  202. nervus/gui/resources/figures/gear_shift.png +0 -0
  203. nervus/gui/resources/figures/idle_speed_control.png +0 -0
  204. nervus/gui/resources/figures/ignition_knock.png +0 -0
  205. nervus/gui/resources/figures/injector_driver.png +0 -0
  206. nervus/gui/resources/figures/integrator_limits.png +0 -0
  207. nervus/gui/resources/figures/lab_coupled_tanks.png +0 -0
  208. nervus/gui/resources/figures/lab_dc_motor.png +0 -0
  209. nervus/gui/resources/figures/lab_inverted_pendulum.png +0 -0
  210. nervus/gui/resources/figures/lab_mass_spring_damper.png +0 -0
  211. nervus/gui/resources/figures/lambda_trims.png +0 -0
  212. nervus/gui/resources/figures/lookup_1d.png +0 -0
  213. nervus/gui/resources/figures/lookup_2d.png +0 -0
  214. nervus/gui/resources/figures/mux_demux.png +0 -0
  215. nervus/gui/resources/figures/ntc_divider.png +0 -0
  216. nervus/gui/resources/figures/ntc_fault.png +0 -0
  217. nervus/gui/resources/figures/obd_ecu.png +0 -0
  218. nervus/gui/resources/figures/physical_models.png +0 -0
  219. nervus/gui/resources/figures/pid_anti_windup.png +0 -0
  220. nervus/gui/resources/figures/pid_structure.png +0 -0
  221. nervus/gui/resources/figures/prelookup.png +0 -0
  222. nervus/gui/resources/figures/pulse.png +0 -0
  223. nervus/gui/resources/figures/ramp.png +0 -0
  224. nervus/gui/resources/figures/rate_limiter.png +0 -0
  225. nervus/gui/resources/figures/rate_transition.png +0 -0
  226. nervus/gui/resources/figures/rc_rlc.png +0 -0
  227. nervus/gui/resources/figures/relay.png +0 -0
  228. nervus/gui/resources/figures/saturation.png +0 -0
  229. nervus/gui/resources/figures/sensor_model.png +0 -0
  230. nervus/gui/resources/figures/signal-editor.png +0 -0
  231. nervus/gui/resources/figures/sine.png +0 -0
  232. nervus/gui/resources/figures/step.png +0 -0
  233. nervus/gui/resources/figures/sum_signs.png +0 -0
  234. nervus/gui/resources/figures/switch.png +0 -0
  235. nervus/gui/resources/figures/traction_control.png +0 -0
  236. nervus/gui/resources/figures/transfer_function.png +0 -0
  237. nervus/gui/resources/figures/truck.png +0 -0
  238. nervus/gui/resources/figures/unit_delay.png +0 -0
  239. nervus/gui/resources/figures/xcp_calibration.png +0 -0
  240. nervus/gui/resources/figures/xcp_live.png +0 -0
  241. nervus/gui/resources/figures/zero_order_hold.png +0 -0
  242. nervus/gui/resources/help/__init__.py +0 -0
  243. nervus/gui/resources/help/analysis.md +38 -0
  244. nervus/gui/resources/help/can.md +195 -0
  245. nervus/gui/resources/help/codegen.md +193 -0
  246. nervus/gui/resources/help/coming_from_simulink.md +106 -0
  247. nervus/gui/resources/help/concepts.md +120 -0
  248. nervus/gui/resources/help/datatypes.md +62 -0
  249. nervus/gui/resources/help/editor.md +146 -0
  250. nervus/gui/resources/help/getting_started.md +86 -0
  251. nervus/gui/resources/help/libraries.md +84 -0
  252. nervus/gui/resources/help/model_files.md +41 -0
  253. nervus/gui/resources/help/obd.md +201 -0
  254. nervus/gui/resources/help/physical.md +203 -0
  255. nervus/gui/resources/help/shortcuts.md +32 -0
  256. nervus/gui/resources/help/simulation.md +62 -0
  257. nervus/gui/resources/help/statecharts.md +197 -0
  258. nervus/gui/resources/help/subsystems.md +167 -0
  259. nervus/gui/resources/help/testing.md +151 -0
  260. nervus/gui/resources/help/tutorial_abs.md +74 -0
  261. nervus/gui/resources/help/tutorial_can_network.md +61 -0
  262. nervus/gui/resources/help/tutorial_charging_system.md +75 -0
  263. nervus/gui/resources/help/tutorial_circuits.md +104 -0
  264. nervus/gui/resources/help/tutorial_component_libraries.md +78 -0
  265. nervus/gui/resources/help/tutorial_coolant_fan.md +58 -0
  266. nervus/gui/resources/help/tutorial_coupled_tanks.md +75 -0
  267. nervus/gui/resources/help/tutorial_dc_motor.md +79 -0
  268. nervus/gui/resources/help/tutorial_drive_cycle.md +100 -0
  269. nervus/gui/resources/help/tutorial_engine_modes.md +78 -0
  270. nervus/gui/resources/help/tutorial_ev_range.md +76 -0
  271. nervus/gui/resources/help/tutorial_first_model.md +176 -0
  272. nervus/gui/resources/help/tutorial_fixed_point.md +68 -0
  273. nervus/gui/resources/help/tutorial_fmi.md +80 -0
  274. nervus/gui/resources/help/tutorial_fuel_film.md +61 -0
  275. nervus/gui/resources/help/tutorial_gear_shift.md +157 -0
  276. nervus/gui/resources/help/tutorial_idle.md +88 -0
  277. nervus/gui/resources/help/tutorial_ignition.md +69 -0
  278. nervus/gui/resources/help/tutorial_injector_driver.md +82 -0
  279. nervus/gui/resources/help/tutorial_inverted_pendulum.md +82 -0
  280. nervus/gui/resources/help/tutorial_lambda.md +97 -0
  281. nervus/gui/resources/help/tutorial_mass_spring_damper.md +87 -0
  282. nervus/gui/resources/help/tutorial_model_to_code.md +109 -0
  283. nervus/gui/resources/help/tutorial_ntc_sensor.md +71 -0
  284. nervus/gui/resources/help/tutorial_obd_diagnostics.md +76 -0
  285. nervus/gui/resources/help/tutorial_physical.md +73 -0
  286. nervus/gui/resources/help/tutorial_rc_rlc.md +70 -0
  287. nervus/gui/resources/help/tutorial_requirements_testing.md +94 -0
  288. nervus/gui/resources/help/tutorial_robustness_monte_carlo.md +94 -0
  289. nervus/gui/resources/help/tutorial_sensor_diagnostics.md +59 -0
  290. nervus/gui/resources/help/tutorial_traction.md +64 -0
  291. nervus/gui/resources/help/tutorial_truck.md +51 -0
  292. nervus/gui/resources/help/tutorial_xcp_calibration.md +98 -0
  293. nervus/gui/resources/help/tutorials.md +142 -0
  294. nervus/gui/resources/help/verification.md +129 -0
  295. nervus/gui/resources/help/workspace.md +155 -0
  296. nervus/gui/theme.py +246 -0
  297. nervus/gui/views/__init__.py +1 -0
  298. nervus/gui/views/advisor_dialog.py +73 -0
  299. nervus/gui/views/analysis_dialog.py +330 -0
  300. nervus/gui/views/can_trace_dialog.py +139 -0
  301. nervus/gui/views/canvas.py +743 -0
  302. nervus/gui/views/chart_editor.py +856 -0
  303. nervus/gui/views/codegen_dialog.py +191 -0
  304. nervus/gui/views/completer.py +61 -0
  305. nervus/gui/views/console_panel.py +173 -0
  306. nervus/gui/views/data_inspector.py +268 -0
  307. nervus/gui/views/diagnostics.py +88 -0
  308. nervus/gui/views/dictionary_panel.py +124 -0
  309. nervus/gui/views/glyphs.py +160 -0
  310. nervus/gui/views/help_browser.py +145 -0
  311. nervus/gui/views/icons.py +123 -0
  312. nervus/gui/views/items.py +637 -0
  313. nervus/gui/views/library.py +182 -0
  314. nervus/gui/views/main_window.py +1266 -0
  315. nervus/gui/views/mask_dialog.py +95 -0
  316. nervus/gui/views/math_render.py +70 -0
  317. nervus/gui/views/obd_dialog.py +351 -0
  318. nervus/gui/views/properties.py +395 -0
  319. nervus/gui/views/requirements_panel.py +185 -0
  320. nervus/gui/views/routing.py +211 -0
  321. nervus/gui/views/scope_window.py +121 -0
  322. nervus/gui/views/settings_dialog.py +125 -0
  323. nervus/gui/views/signal_editor.py +515 -0
  324. nervus/gui/views/sweep_dialog.py +403 -0
  325. nervus/gui/views/test_manager.py +510 -0
  326. nervus/gui/views/usages_dialog.py +44 -0
  327. nervus/gui/views/variant_dialog.py +112 -0
  328. nervus/gui/views/workspace_panel.py +210 -0
  329. nervus/help.py +187 -0
  330. nervus/io/__init__.py +5 -0
  331. nervus/io/model_file.py +311 -0
  332. nervus/library.py +185 -0
  333. nervus/mdf.py +98 -0
  334. nervus/obd.py +464 -0
  335. nervus/obd_can.py +213 -0
  336. nervus/obd_sim.py +208 -0
  337. nervus/physical/network.py +587 -0
  338. nervus/py.typed +0 -0
  339. nervus/sim/__init__.py +7 -0
  340. nervus/sim/compiler.py +834 -0
  341. nervus/sim/flatten.py +167 -0
  342. nervus/sim/result.py +179 -0
  343. nervus/sim/simulator.py +597 -0
  344. nervus/simulink.py +425 -0
  345. nervus/solvers/__init__.py +13 -0
  346. nervus/solvers/fixed.py +32 -0
  347. nervus/solvers/variable.py +89 -0
  348. nervus/spice.py +368 -0
  349. nervus/sweep.py +177 -0
  350. nervus/testing.py +259 -0
  351. nervus/tutorials.py +205 -0
  352. nervus/xcp.py +300 -0
  353. nervus-0.1.0.dist-info/METADATA +208 -0
  354. nervus-0.1.0.dist-info/RECORD +357 -0
  355. nervus-0.1.0.dist-info/WHEEL +4 -0
  356. nervus-0.1.0.dist-info/entry_points.txt +2 -0
  357. nervus-0.1.0.dist-info/licenses/LICENSE +21 -0
nervus/__init__.py ADDED
@@ -0,0 +1,35 @@
1
+ """Nervus: open-source block-diagram modeling and simulation in Python."""
2
+
3
+ from nervus import blocks
4
+ from nervus.core import (
5
+ Block,
6
+ Diagram,
7
+ ModelError,
8
+ ParameterError,
9
+ ParameterSet,
10
+ SimulationError,
11
+ SimulationSettings,
12
+ Workspace,
13
+ )
14
+ from nervus.io import load, save
15
+ from nervus.sim import SimResult, compile_diagram, simulate
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ __all__ = [
20
+ "Block",
21
+ "Diagram",
22
+ "ModelError",
23
+ "ParameterError",
24
+ "ParameterSet",
25
+ "SimResult",
26
+ "SimulationError",
27
+ "SimulationSettings",
28
+ "Workspace",
29
+ "__version__",
30
+ "blocks",
31
+ "compile_diagram",
32
+ "load",
33
+ "save",
34
+ "simulate",
35
+ ]
nervus/advisor.py ADDED
@@ -0,0 +1,258 @@
1
+ """Model Advisor: static checks for modelling practices that matter in ECU software.
2
+
3
+ These are not errors (the model compiles and simulates), but they are common sources of bugs or of code
4
+ that is hard to review. Run it from the editor (Analysis → Model Advisor) or from Python::
5
+
6
+ from nervus.advisor import advise
7
+ for f in advise(model):
8
+ print(f)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable, Iterator
14
+ from dataclasses import dataclass
15
+
16
+ import numpy as np
17
+
18
+ from nervus.core.block import Block
19
+ from nervus.core.diagram import Diagram
20
+ from nervus.core.errors import NervusError
21
+ from nervus.core.expressions import names_in
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Finding:
26
+ rule: str
27
+ severity: str # "warning" or "info"
28
+ message: str
29
+ blocks: tuple[str, ...] = ()
30
+
31
+ def __str__(self) -> str:
32
+ where = f" [{', '.join(self.blocks)}]" if self.blocks else ""
33
+ return f"{self.severity.upper():7s} {self.rule}: {self.message}{where}"
34
+
35
+
36
+ RULES: dict[str, tuple[str, Callable[[Diagram, dict[str, object]], Iterator[Finding]]]] = {}
37
+
38
+
39
+ def rule(
40
+ rule_id: str, description: str
41
+ ) -> Callable[[Callable[..., Iterator[Finding]]], Callable[..., Iterator[Finding]]]:
42
+ def deco(fn: Callable[..., Iterator[Finding]]) -> Callable[..., Iterator[Finding]]:
43
+ RULES[rule_id] = (description, fn)
44
+ return fn
45
+
46
+ return deco
47
+
48
+
49
+ def _types(diagram: Diagram) -> dict[str, object]:
50
+ """Compiled facts used by several rules (empty if the model does not compile)."""
51
+ from nervus.sim.compiler import compile_diagram
52
+
53
+ try:
54
+ m = compile_diagram(diagram)
55
+ except NervusError:
56
+ return {}
57
+ in_types = {}
58
+ in_kinds = {}
59
+ for i, name in enumerate(m.names):
60
+ in_types[name] = [m.out_types[s][p] for s, p in m.inputs[i]]
61
+ in_kinds[name] = [(m.kinds[s], m.blocks[s]) for s, _p in m.inputs[i]]
62
+ return {"model": m, "in_types": in_types, "in_kinds": in_kinds}
63
+
64
+
65
+ @rule("float-equality", "== or != on floating-point signals")
66
+ def _float_equality(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
67
+ in_types: dict[str, list[object]] = facts.get("in_types", {}) # type: ignore[assignment]
68
+ for path, b in d.walk():
69
+ if b.type_id in ("logic.relational", "logic.compare_to_constant") and b.params["operator"] in ("==", "!="):
70
+ types = in_types.get(path, [])
71
+ if not types or any(not (t.is_integer or t.kind == "boolean") for t in types): # type: ignore[attr-defined]
72
+ yield Finding(
73
+ "float-equality",
74
+ "warning",
75
+ f"'{b.params['operator']}' on a floating-point signal is fragile: rounding makes exact "
76
+ "equality unlikely. Compare with a tolerance, or convert to an integer type first.",
77
+ (path,),
78
+ )
79
+
80
+
81
+ @rule("division", "Product blocks that divide (division by zero)")
82
+ def _division(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
83
+ for path, b in d.walk():
84
+ if b.type_id == "math.product" and "/" in b.params["ops"]:
85
+ yield Finding(
86
+ "division",
87
+ "info",
88
+ "this block divides; make sure the divisor can never be zero (e.g. "
89
+ "limit it with a Saturation or MinMax).",
90
+ (path,),
91
+ )
92
+
93
+
94
+ @rule("chart-unreachable", "chart states that can never be entered")
95
+ def _chart_unreachable(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
96
+ for path, b in d.walk():
97
+ spec = getattr(b, "spec", None)
98
+ if b.type_id != "charts.state_chart" or spec is None:
99
+ continue
100
+ targets = {t.target for t in spec.transitions} | spec.default_entered()
101
+ for k, s in enumerate(spec.states):
102
+ if k not in targets:
103
+ yield Finding(
104
+ "chart-unreachable",
105
+ "warning",
106
+ f"state '{s.name}' has no incoming transition and is not an initial state, so it is never active.",
107
+ (path,),
108
+ )
109
+
110
+
111
+ @rule("chart-shadowed", "chart transitions after an unconditional one")
112
+ def _chart_shadowed(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
113
+ for path, b in d.walk():
114
+ spec = getattr(b, "spec", None)
115
+ if b.type_id != "charts.state_chart" or spec is None:
116
+ continue
117
+ seen_true: set[int] = set()
118
+ for t in spec.transitions:
119
+ if t.source in seen_true:
120
+ yield Finding(
121
+ "chart-shadowed",
122
+ "warning",
123
+ f"transition {spec.states[t.source].name} -> {spec.states[t.target].name} comes after an "
124
+ "always-true transition from the same state and can never fire.",
125
+ (path,),
126
+ )
127
+ if t.guard_src.strip().lower() in ("true", "1"):
128
+ seen_true.add(t.source)
129
+
130
+
131
+ @rule("antiwindup", "PI controllers with output limits but no anti-windup")
132
+ def _antiwindup(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
133
+ for path, b in d.walk():
134
+ if b.type_id in ("control.pid", "control.discrete_pid"):
135
+ p = b.params
136
+ limited = np.isfinite(p["upper"]) or np.isfinite(p["lower"])
137
+ if p["I"] != 0 and limited and p["anti_windup"] == "none":
138
+ yield Finding(
139
+ "antiwindup",
140
+ "warning",
141
+ "the output is limited but anti_windup is 'none': the integral "
142
+ "term winds up while saturated and causes overshoot. Use 'clamping'.",
143
+ (path,),
144
+ )
145
+ if p["I"] != 0 and not limited:
146
+ yield Finding(
147
+ "antiwindup",
148
+ "info",
149
+ "the controller has an integral term but no output limits; real "
150
+ "actuators saturate, so model the limits.",
151
+ (path,),
152
+ )
153
+
154
+
155
+ @rule("implicit-sampling", "discrete blocks reading continuous signals directly")
156
+ def _implicit_sampling(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
157
+ from nervus.sim.compiler import Kind
158
+
159
+ in_kinds: dict[str, list[tuple[object, Block]]] = facts.get("in_kinds", {}) # type: ignore[assignment]
160
+ m = facts.get("model")
161
+ if m is None:
162
+ return
163
+ for i, name in enumerate(m.names): # type: ignore[attr-defined]
164
+ b = m.blocks[i] # type: ignore[attr-defined]
165
+ if m.kinds[i] is not Kind.DISCRETE or b.type_id == "discrete.zero_order_hold": # type: ignore[attr-defined]
166
+ continue
167
+ if any(
168
+ k is Kind.CONTINUOUS and src.type_id not in ("ports.inport", "sources.constant")
169
+ for k, src in in_kinds.get(name, [])
170
+ ):
171
+ yield Finding(
172
+ "implicit-sampling",
173
+ "info",
174
+ "a discrete block reads a continuous-time signal directly; put a "
175
+ "Zero-Order Hold in front so the sampling is explicit (as on the ECU).",
176
+ (name,),
177
+ )
178
+
179
+
180
+ @rule("workspace-docs", "workspace variables without unit or description")
181
+ def _workspace_docs(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
182
+ for v in d.workspace.variables:
183
+ if not v.unit or not v.description:
184
+ missing = " and ".join(x for x, ok in (("a unit", v.unit), ("a description", v.description)) if not ok)
185
+ yield Finding(
186
+ "workspace-docs",
187
+ "info",
188
+ f"workspace variable '{v.name}' has no {missing}; calibration engineers see these in the A2L file.",
189
+ )
190
+
191
+
192
+ @rule("workspace-unused", "workspace variables that no block uses")
193
+ def _workspace_unused(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
194
+ used: set[str] = set()
195
+ for _path, b in d.walk():
196
+ for expr in b.expressions.values():
197
+ used |= names_in(expr)
198
+ for v in d.workspace.variables:
199
+ if isinstance(v.value, str):
200
+ used |= names_in(v.value)
201
+ for v in d.workspace.variables:
202
+ if v.name not in used:
203
+ yield Finding("workspace-unused", "info", f"workspace variable '{v.name}' is not used by any block.")
204
+
205
+
206
+ @rule("lookup-extrapolation", "lookup tables that extrapolate linearly")
207
+ def _lookup_extrapolation(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
208
+ for path, b in d.walk():
209
+ if b.type_id in ("lookup.table_1d", "lookup.table_2d") and b.params["extrapolation"] == "linear":
210
+ yield Finding(
211
+ "lookup-extrapolation",
212
+ "info",
213
+ "linear extrapolation can give values far outside the "
214
+ "calibrated table; 'clip' is the usual choice in ECU maps.",
215
+ (path,),
216
+ )
217
+
218
+
219
+ @rule("default-names", "blocks in subsystems with default names")
220
+ def _default_names(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
221
+ import re
222
+
223
+ for path, b in d.walk():
224
+ if (
225
+ "/" in path
226
+ and b.label
227
+ and re.fullmatch(re.escape(b.label.replace(" ", "")) + r"\d*", b.name.replace(" ", ""))
228
+ ):
229
+ yield Finding(
230
+ "default-names",
231
+ "info",
232
+ f"'{b.name}' has a default name; descriptive names make generated code and reviews easier to follow.",
233
+ (path,),
234
+ )
235
+
236
+
237
+ @rule("requirements", "requirements without blocks or tests, and links to unknown requirements")
238
+ def _requirements(d: Diagram, facts: dict[str, object]) -> Iterator[Finding]:
239
+ from nervus.core.requirements import trace, unknown_links
240
+
241
+ for row in trace(d):
242
+ if row.status == "not implemented":
243
+ yield Finding("requirements", "warning", f"requirement {row.requirement.id} is not linked to any block.")
244
+ elif row.status == "not tested":
245
+ yield Finding("requirements", "warning", f"requirement {row.requirement.id} has no test case.",
246
+ tuple(row.blocks)) # fmt: skip
247
+ for msg in unknown_links(d): # "block <path> is linked ..." or "test case ..."
248
+ yield Finding("requirements", "warning", msg + ".", (msg.split()[1],) if msg.startswith("block ") else ())
249
+
250
+
251
+ def advise(diagram: Diagram, rules: list[str] | None = None) -> list[Finding]:
252
+ """Run the Model Advisor rules (all by default) and return the findings, warnings first."""
253
+ facts = _types(diagram)
254
+ findings: list[Finding] = []
255
+ for rule_id, (_desc, fn) in RULES.items():
256
+ if rules is None or rule_id in rules:
257
+ findings.extend(fn(diagram, facts))
258
+ return sorted(findings, key=lambda f: (f.severity != "warning", f.rule))