blocksim 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.
blocksim/__init__.py ADDED
@@ -0,0 +1,524 @@
1
+ # ruff: noqa: F401, F403
2
+ """
3
+ blocksim -- hybrid dynamical system (block diagram) simulation.
4
+
5
+ Importing this package is CHEAP: nothing but the logging helpers is loaded
6
+ up front. Every block library is pulled in lazily, on first use of a name
7
+ it exports (PEP 562 module __getattr__), so a script that only builds an
8
+ ODE model never pays for scipy.signal, the FMU bridge or the F-16 model.
9
+
10
+ from blocksim import System, Simulator, Integrator # loads core,
11
+ # sources, math,
12
+ # continuous only
13
+
14
+ The names and the modules they come from are listed in
15
+ `_SUBMODULE_EXPORTS` below. It is a static map on purpose -- discovering
16
+ it at import time would mean importing everything, which is the cost this
17
+ exists to avoid. `test/test_lazy_imports.py` regenerates it from each
18
+ module's `__all__` and fails if the two have drifted apart, so adding a
19
+ block means adding it to that module's `__all__` and here.
20
+ """
21
+
22
+ import importlib
23
+ from typing import TYPE_CHECKING
24
+
25
+ from ._logging import (
26
+ get_logger,
27
+ enable_logging,
28
+ disable_logging,
29
+ set_log_level,
30
+ SUBSYSTEMS,
31
+ )
32
+
33
+ _SUBMODULE_EXPORTS = {
34
+ "core": (
35
+ "AlgebraicGroup",
36
+ "AlgebraicLoopError",
37
+ "AlgebraicSolver",
38
+ "Block",
39
+ "BlockData",
40
+ "BlockOrderError",
41
+ "BlockSpec",
42
+ "Clock",
43
+ "Connection",
44
+ "DynamicClock",
45
+ "EventHandler",
46
+ "FeedbackLoop",
47
+ "FsolveAlgebraicSolver",
48
+ "ListClock",
49
+ "MassMatrixError",
50
+ "NotImplementedFunctionError",
51
+ "PartialOutputs",
52
+ "PeriodicClock",
53
+ "Port",
54
+ "PortBundle",
55
+ "PortRef",
56
+ "Region",
57
+ "ScaledAlgebraicSolver",
58
+ "Scheduler",
59
+ "SchedulerEvent",
60
+ "ScipySolver",
61
+ "SimulationResult",
62
+ "Simulator",
63
+ "SimulatorResult",
64
+ "Solver",
65
+ "SolverResult",
66
+ "StopSimulation",
67
+ "SubSystem",
68
+ "System",
69
+ "WiringError",
70
+ "get_index",
71
+ "make_signals2",
72
+ ),
73
+ "sources": (
74
+ "BandLimitedWhiteNoise",
75
+ "Chirp",
76
+ "Constant",
77
+ "Equation",
78
+ "FromFile",
79
+ "Pulse",
80
+ "Ramp",
81
+ "Random",
82
+ "Repeating",
83
+ "RepeatingStair",
84
+ "Sawtooth",
85
+ "Sine",
86
+ "Square",
87
+ "Step",
88
+ "Triangular",
89
+ ),
90
+ "math": (
91
+ "Abs",
92
+ "Gain",
93
+ "MathFunction",
94
+ "Sign",
95
+ "Sum",
96
+ ),
97
+ "continuous": (
98
+ "Derivative",
99
+ "Integrator",
100
+ "IntegratorLimited",
101
+ "PIDController",
102
+ "SecondOrderIntegrator",
103
+ "SecondOrderIntegratorLimited",
104
+ "StateSpace",
105
+ "TransferFunction",
106
+ "TransportDelay",
107
+ "ZeroPole",
108
+ ),
109
+ "discrete": (
110
+ "Delay",
111
+ "Difference",
112
+ "DiscreteDerivative",
113
+ "DiscreteFIRFilter",
114
+ "DiscreteFilter",
115
+ "DiscretePIDController",
116
+ "DiscreteSpaceState",
117
+ "DiscreteTimeIntegrator",
118
+ "DiscreteTransferFunction",
119
+ "DiscreteZeroPole",
120
+ "TappedDelay",
121
+ "UnitDelay",
122
+ "VariableIntegerDelay",
123
+ "ZeroOrderHolder",
124
+ ),
125
+ "discontinuities": (
126
+ "CoulombAndViscousFriction",
127
+ "CoulombViscousFriction",
128
+ "DeadZone",
129
+ "PWM",
130
+ "Relay",
131
+ "Saturation",
132
+ ),
133
+ "propulsion": (
134
+ "Balance",
135
+ "Burner",
136
+ "Compressor",
137
+ "Duct",
138
+ "EngineLoopSolver",
139
+ "FlightCondition",
140
+ "Inlet",
141
+ "Nozzle",
142
+ "Plenum",
143
+ "PowerOfftake",
144
+ "STATION",
145
+ "STATION_UNITS",
146
+ "Shaft",
147
+ "Splitter",
148
+ "Turbine",
149
+ "compressor_map",
150
+ "seed_algebraic_loops",
151
+ "station_ports",
152
+ "turbine_map",
153
+ ),
154
+ "table": (
155
+ "LookupTable1D",
156
+ "LookupTable2D",
157
+ "MapTable",
158
+ ),
159
+ "thermo": (
160
+ "DRY_AIR",
161
+ "FlowRegime",
162
+ "GasModel",
163
+ "P_REF",
164
+ "PerfectGas",
165
+ "StaticState",
166
+ "T_REF",
167
+ "TotalState",
168
+ "WalshFletcherGas",
169
+ "corrected_flow",
170
+ "corrected_speed",
171
+ "delta_ratio",
172
+ "isentropic_total",
173
+ "static_from_area",
174
+ "static_from_mach",
175
+ "static_from_ps",
176
+ "theta_ratio",
177
+ "total_from_pT",
178
+ "total_from_ph",
179
+ "total_from_static_mach",
180
+ ),
181
+ "fusion": (
182
+ "FusedSystem",
183
+ "FusionError",
184
+ "fuse",
185
+ "symbolic_registry",
186
+ ),
187
+ "fmu": (
188
+ "FMUCoSimulation",
189
+ "FMUModelExchange",
190
+ ),
191
+ "simulator_claude": (
192
+ "ClaudeAlgebraicSolver",
193
+ "ClaudeSolver",
194
+ "SimulatorClaude",
195
+ "brentq",
196
+ ),
197
+ "control": (
198
+ "KalmanFilter",
199
+ "SaturationDynamic",
200
+ ),
201
+ "robotics": (
202
+ "DifferentialDrive",
203
+ "PurePursuit",
204
+ ),
205
+ "aerospace": (
206
+ "RigidBody6DOF",
207
+ "StandardAtmosphere",
208
+ ),
209
+ "astro": (
210
+ "AtmosphericDrag",
211
+ "EARTH_J2",
212
+ "EARTH_MU",
213
+ "EARTH_RADIUS",
214
+ "ExponentialAtmosphere",
215
+ "J2Gravity",
216
+ "ReactionWheel",
217
+ "SpacecraftAttitude",
218
+ "TwoBody",
219
+ "circular_speed",
220
+ "elements_to_state",
221
+ "kepler_equation",
222
+ "orbital_period",
223
+ "state_to_elements",
224
+ "vis_viva",
225
+ ),
226
+ "power": (
227
+ "Exciter",
228
+ "Governor",
229
+ "Grid",
230
+ "Network",
231
+ "PowerFlowError",
232
+ "PowerFlowResult",
233
+ "SynchronousMachine",
234
+ "ZIPLoad",
235
+ "power_flow",
236
+ "to_dq",
237
+ "to_network",
238
+ ),
239
+ "process": (
240
+ "DistillationColumn",
241
+ "Reactor",
242
+ "StreamMixer",
243
+ "StreamSplitter",
244
+ "Tank",
245
+ "Valve",
246
+ "relative_volatility_equilibrium",
247
+ ),
248
+ "structural": (
249
+ "BeamModes",
250
+ "FiniteElementBeam",
251
+ "LumpedChain",
252
+ "ModalBody",
253
+ "rayleigh_damping",
254
+ ),
255
+ "driveline": (
256
+ "Clutch",
257
+ "Differential",
258
+ "EngineMap",
259
+ "FinalDrive",
260
+ "Gear",
261
+ "RotationalInertia",
262
+ "TorqueConverter",
263
+ "TorsionalSpring",
264
+ "reflect_inertia",
265
+ ),
266
+ "thermal": (
267
+ "Advection",
268
+ "Conduction",
269
+ "Convection",
270
+ "HeatExchanger",
271
+ "Material",
272
+ "Radiation",
273
+ "ThermalMass",
274
+ "conductance_of_slab",
275
+ "exchanger_effectiveness",
276
+ ),
277
+ "electrical": (
278
+ "Battery",
279
+ "Circuit",
280
+ "ClarkePark",
281
+ "DCMachine",
282
+ "InductionMachine",
283
+ "InverseClarkePark",
284
+ "Netlist",
285
+ "PMSM",
286
+ "SingularCircuitError",
287
+ ),
288
+ "hydraulics": (
289
+ "Accumulator",
290
+ "Cylinder",
291
+ "DirectionalValve",
292
+ "Fluid",
293
+ "HydraulicMotor",
294
+ "Line",
295
+ "Orifice",
296
+ "Pump",
297
+ "ReliefValve",
298
+ "Volume",
299
+ "cavitation_gate",
300
+ "orifice_flow",
301
+ ),
302
+ "radar": (
303
+ "ChirpGenerator",
304
+ "FreeSpaceLoss",
305
+ ),
306
+ "atmosphere": (
307
+ "GAMMA_AIR",
308
+ "P_SEA_LEVEL",
309
+ "R_AIR",
310
+ "T_SEA_LEVEL",
311
+ "density_slug_ft3",
312
+ "standard_atmosphere",
313
+ "standard_atmosphere_imperial",
314
+ ),
315
+ "avionics": (
316
+ "ARINC429_HIGH_SPEED",
317
+ "ARINC429_LOW_SPEED",
318
+ "Arinc429Label",
319
+ "Arinc429Receiver",
320
+ "Arinc429Transmitter",
321
+ "Arinc429Word",
322
+ "MilStd1553Bus",
323
+ "MilStd1553BusController",
324
+ "MilStd1553Message",
325
+ "MilStd1553RemoteTerminal",
326
+ "decode_arinc429",
327
+ "encode_arinc429_bcd",
328
+ "encode_arinc429_bnr",
329
+ "wire_1553",
330
+ "wire_arinc429",
331
+ ),
332
+ "comm": (
333
+ "MultipathChannel",
334
+ "QAMDemodulator",
335
+ "QAMModulator",
336
+ ),
337
+ "gemini": (
338
+ "GeminiAlgebraicSolver",
339
+ "GeminiSolverResult",
340
+ "SimulatorGemini",
341
+ "fsolve_gemini",
342
+ "integrate_gemini",
343
+ "rk45_step",
344
+ ),
345
+ "analysis": (
346
+ "LinearModel",
347
+ "Margins",
348
+ "SensitivityResult",
349
+ "StepInfo",
350
+ "append",
351
+ "balanced_reduction",
352
+ "bode",
353
+ "controllability_matrix",
354
+ "damp",
355
+ "dcgain",
356
+ "feedback",
357
+ "frequency_response",
358
+ "gramians",
359
+ "hankel_singular_values",
360
+ "is_controllable",
361
+ "is_observable",
362
+ "linearize",
363
+ "loop_gain",
364
+ "lqe",
365
+ "lqr",
366
+ "margins",
367
+ "negate",
368
+ "observability_matrix",
369
+ "parallel",
370
+ "poles",
371
+ "sensitivity",
372
+ "series",
373
+ "static_gain",
374
+ "steady_state",
375
+ "step_info",
376
+ "step_response",
377
+ "trim",
378
+ "zeros",
379
+ ),
380
+ "distributed": (
381
+ "BoundaryInput",
382
+ "CouplingStrategy",
383
+ "DistributedResult",
384
+ "DistributedSimulator",
385
+ "DistributedSystem",
386
+ "GaussSeidelCoupling",
387
+ "JacobiCoupling",
388
+ ),
389
+ "mechanics": ("ConstrainedMechanism",),
390
+ "f16": (
391
+ "F16",
392
+ "atmosphere_imperial",
393
+ ),
394
+ "f16_hifi": ("F16Hifi",),
395
+ "jsbsim": (
396
+ "JSBSimAerodynamics",
397
+ "JSBSimAircraft",
398
+ "JSBSimModel",
399
+ "UnsupportedElement",
400
+ "aero_properties",
401
+ "jsbsim_root",
402
+ "list_aircraft",
403
+ "load_jsbsim",
404
+ ),
405
+ "rotation": (
406
+ "body_to_inertial",
407
+ "euler_from_quaternion",
408
+ "inertia_and_inverse",
409
+ "normalize_quaternion",
410
+ "quaternion_from_euler",
411
+ "quaternion_rate",
412
+ ),
413
+ "manipulator": (
414
+ "GRAVITY_EARTH",
415
+ "Joint",
416
+ "JointTrajectory",
417
+ "Link",
418
+ "Manipulator",
419
+ "RigidBodyTree",
420
+ "load_urdf",
421
+ "rpy_to_matrix",
422
+ ),
423
+ "vehicle": (
424
+ "FialaTire",
425
+ "FourWheelAssembly",
426
+ "LongitudinalDriver",
427
+ "SteeringManeuver",
428
+ "VehicleAssembly",
429
+ "VehicleBody3DOF",
430
+ "VehicleBody4Wheel",
431
+ "Wheel",
432
+ "four_wheel_vehicle",
433
+ "rear_wheel_drive_vehicle",
434
+ ),
435
+ }
436
+
437
+ #: submodules reachable as `blocksim.<name>` after a bare `import blocksim`.
438
+ #: The last two are not star-imported into the top-level namespace (their
439
+ #: names are deliberately kept behind `blocksim.symbolic` / `blocksim.auxiliar`).
440
+ _SUBMODULES = frozenset(_SUBMODULE_EXPORTS) | {"symbolic", "auxiliar", "_logging"}
441
+
442
+ #: name -> owning submodule, flattened once at import (pure dict work, no
443
+ #: imports) so a lookup is O(1) rather than a scan over the libraries.
444
+ _MODULE_OF_NAME = {
445
+ name: module for module, names in _SUBMODULE_EXPORTS.items() for name in names
446
+ }
447
+
448
+ _EAGER = [
449
+ "get_logger",
450
+ "enable_logging",
451
+ "disable_logging",
452
+ "set_log_level",
453
+ "SUBSYSTEMS",
454
+ "hello",
455
+ ]
456
+
457
+ __all__ = sorted(_MODULE_OF_NAME) + _EAGER
458
+
459
+
460
+ def __getattr__(name):
461
+ """Import the submodule that owns `name`, on first use (PEP 562).
462
+
463
+ The resolved object is written into this module's globals, so the
464
+ second and later lookups are ordinary global lookups and never reach
465
+ here again.
466
+ """
467
+ module = _MODULE_OF_NAME.get(name)
468
+ if module is not None:
469
+ value = getattr(importlib.import_module(f".{module}", __name__), name)
470
+ globals()[name] = value
471
+ return value
472
+ if name in _SUBMODULES:
473
+ value = importlib.import_module(f".{name}", __name__)
474
+ globals()[name] = value
475
+ return value
476
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
477
+
478
+
479
+ def __dir__():
480
+ """Everything importable from the package, loaded or not."""
481
+ return sorted(set(__all__) | _SUBMODULES)
482
+
483
+
484
+ if TYPE_CHECKING: # so type checkers and IDEs still see the real names
485
+ from .aerospace import *
486
+ from .atmosphere import *
487
+ from .analysis import *
488
+ from .avionics import *
489
+ from .comm import *
490
+ from .continuous import *
491
+ from .control import *
492
+ from .core import *
493
+ from .discontinuities import *
494
+ from .discrete import *
495
+ from .distributed import *
496
+ from .astro import *
497
+ from .driveline import *
498
+ from .electrical import *
499
+ from .thermal import *
500
+ from .hydraulics import *
501
+ from .jsbsim import *
502
+ from .rotation import *
503
+ from .process import *
504
+ from .structural import *
505
+ from .f16 import *
506
+ from .f16_hifi import *
507
+ from .fmu import *
508
+ from .fusion import *
509
+ from .gemini import *
510
+ from .manipulator import *
511
+ from .math import *
512
+ from .mechanics import *
513
+ from .radar import *
514
+ from .robotics import *
515
+ from .simulator_claude import *
516
+ from .sources import *
517
+ from .propulsion import *
518
+ from .table import *
519
+ from .thermo import *
520
+ from .vehicle import *
521
+
522
+
523
+ def hello() -> str:
524
+ return "Hello from blocksim!"
blocksim/_logging.py ADDED
@@ -0,0 +1,125 @@
1
+ """
2
+ Central logging for blocksim.
3
+
4
+ The library follows the standard "library logging" convention: it attaches a
5
+ NullHandler to the package root and emits NOTHING until an application (or the
6
+ convenience helpers below) turns it on. Loggers are namespaced by subsystem
7
+ under `blocksim.*`, so debugging can be switched on or off per part of the
8
+ library:
9
+
10
+ import blocksim
11
+ blocksim.enable_logging("DEBUG") # everything
12
+ blocksim.enable_logging("DEBUG", "simulator") # just the run/region loop
13
+ blocksim.set_log_level("INFO", "fmu") # FMU lifecycle at INFO
14
+ blocksim.disable_logging("scheduler") # mute the clock scheduler
15
+ blocksim.disable_logging() # mute the whole library
16
+
17
+ Performance: logging lives only on cold/warm paths -- run/compile dispatch,
18
+ region boundaries, event handling, solver-call boundaries, FMU lifecycle,
19
+ analysis iterations. The hot inner paths (`_compute_outputs`, `derivative`,
20
+ per-block evaluation, per-solver-step) carry NO logging, so a disabled logger
21
+ never appears there. Where a message is emitted, it uses lazy %-formatting
22
+ (the message is only rendered when the level is enabled), and any expensive
23
+ detail is guarded by `logger.isEnabledFor(...)`.
24
+ """
25
+
26
+ import logging
27
+ import sys
28
+
29
+ __all__ = [
30
+ "get_logger",
31
+ "enable_logging",
32
+ "disable_logging",
33
+ "set_log_level",
34
+ "SUBSYSTEMS",
35
+ ]
36
+
37
+ PACKAGE = "blocksim"
38
+
39
+ #: named subsystem loggers (blocksim.<name>), for discoverability
40
+ SUBSYSTEMS = (
41
+ "system", # wiring, compile, algebraic-loop condensation
42
+ "simulator", # run() dispatch, region loop, recording
43
+ "scheduler", # clocks, tick merging, region boundaries
44
+ "solver", # ODE backend calls, event location
45
+ "events", # zero-crossing detection / handler firing
46
+ "fmu", # FMU instantiate / step / event protocol
47
+ "analysis", # trim / linearize / sensitivity
48
+ "gemini", # the Gemini simulator variant
49
+ )
50
+
51
+ _root = logging.getLogger(PACKAGE)
52
+ _root.addHandler(logging.NullHandler()) # silent by default (library default)
53
+
54
+ _console_handler = None # attached lazily by enable_logging
55
+
56
+
57
+ def get_logger(subsystem=None):
58
+ """Return the package logger, or the child `blocksim.<subsystem>`.
59
+
60
+ Modules call this once at import time, e.g.
61
+ from ._logging import get_logger
62
+ log = get_logger("simulator")
63
+ """
64
+ if subsystem is None:
65
+ return _root
66
+ return logging.getLogger(f"{PACKAGE}.{subsystem}")
67
+
68
+
69
+ def _coerce_level(level):
70
+ if isinstance(level, str):
71
+ resolved = logging.getLevelName(level.upper())
72
+ if not isinstance(resolved, int):
73
+ raise ValueError(f"unknown log level {level!r}")
74
+ return resolved
75
+ return int(level)
76
+
77
+
78
+ def set_log_level(level, subsystem=None):
79
+ """Set the logging level for the whole library or one subsystem WITHOUT
80
+ touching handlers -- use this when the application configures its own
81
+ logging handlers and only wants blocksim's verbosity changed.
82
+
83
+ level
84
+ int, or a name like "DEBUG" / "INFO" / "WARNING"
85
+
86
+ subsystem
87
+ None (whole library) or one of SUBSYSTEMS (any `blocksim.*`
88
+ child name is accepted)
89
+ """
90
+ get_logger(subsystem).setLevel(_coerce_level(level))
91
+
92
+
93
+ def enable_logging(
94
+ level="DEBUG", subsystem=None, *, stream=None, fmt=None, datefmt=None
95
+ ):
96
+ """Turn blocksim logging ON with a self-contained console handler.
97
+
98
+ Attaches a StreamHandler to the package root once (default: stderr) and
99
+ routes blocksim's records solely through it (propagation to the root
100
+ logger is disabled, so this never double-prints alongside a script's
101
+ logging.basicConfig). Then raises the level of the whole library, or of
102
+ a single subsystem when `subsystem` is given.
103
+
104
+ For integration with an application's own handlers, prefer set_log_level.
105
+ """
106
+ global _console_handler
107
+ if _console_handler is None:
108
+ _console_handler = logging.StreamHandler(stream or sys.stderr)
109
+ _console_handler.setLevel(logging.NOTSET) # loggers do the gating
110
+ _console_handler.setFormatter(
111
+ logging.Formatter(
112
+ fmt or "%(levelname)-7s %(name)s: %(message)s", datefmt=datefmt
113
+ )
114
+ )
115
+ _root.addHandler(_console_handler)
116
+ _root.propagate = False # sole sink -> no dupes
117
+ set_log_level(level, subsystem)
118
+ return get_logger(subsystem)
119
+
120
+
121
+ def disable_logging(subsystem=None):
122
+ """Silence blocksim logging (whole library or one subsystem) by raising
123
+ its level above CRITICAL. Handlers are left in place, so a later
124
+ enable_logging / set_log_level re-enables instantly."""
125
+ get_logger(subsystem).setLevel(logging.CRITICAL + 1)