behave-fire 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 (57) hide show
  1. behave_fire/__init__.py +70 -0
  2. behave_fire/_auto_namespace.py +138 -0
  3. behave_fire/_auto_routing.py +148 -0
  4. behave_fire/_auto_state.py +132 -0
  5. behave_fire/_backend_contract.py +216 -0
  6. behave_fire/_ownership.py +118 -0
  7. behave_fire/_version.py +29 -0
  8. behave_fire/auto.py +775 -0
  9. behave_fire/behave.py +1180 -0
  10. behave_fire/components/__init__.py +189 -0
  11. behave_fire/components/behave_units.py +966 -0
  12. behave_fire/components/crown.py +595 -0
  13. behave_fire/components/fine_dead_fuel_moisture_tool.py +172 -0
  14. behave_fire/components/fire_size.py +341 -0
  15. behave_fire/components/fuel_models.py +985 -0
  16. behave_fire/components/fuel_models_array.py +135 -0
  17. behave_fire/components/ignite.py +195 -0
  18. behave_fire/components/mortality.py +235 -0
  19. behave_fire/components/safety.py +69 -0
  20. behave_fire/components/slope_tool.py +214 -0
  21. behave_fire/components/species_master_table.py +406 -0
  22. behave_fire/components/spot.py +155 -0
  23. behave_fire/components/surface.py +1039 -0
  24. behave_fire/components/vapor_pressure_deficit_calculator.py +80 -0
  25. behave_fire/python/__init__.py +21 -0
  26. behave_fire/rust/__init__.py +26 -0
  27. behave_fire/rust/_bridge.py +333 -0
  28. behave_fire/rust/_component_api4.py +272 -0
  29. behave_fire/rust/_contracts.py +89 -0
  30. behave_fire/rust/_model_api4.py +220 -0
  31. behave_fire/rust/_numeric.py +195 -0
  32. behave_fire/rust/_serialization.py +49 -0
  33. behave_fire/rust/_threads.py +68 -0
  34. behave_fire/rust/behave_units.py +720 -0
  35. behave_fire/rust/core.py +960 -0
  36. behave_fire/rust/crown.py +289 -0
  37. behave_fire/rust/fine_dead_fuel_moisture_tool.py +31 -0
  38. behave_fire/rust/fire_size.py +198 -0
  39. behave_fire/rust/fuel_models.py +492 -0
  40. behave_fire/rust/fuel_models_array.py +90 -0
  41. behave_fire/rust/grid.py +336 -0
  42. behave_fire/rust/ignite.py +56 -0
  43. behave_fire/rust/mortality.py +59 -0
  44. behave_fire/rust/safety.py +25 -0
  45. behave_fire/rust/slope_tool.py +160 -0
  46. behave_fire/rust/species_master_table.py +312 -0
  47. behave_fire/rust/spot.py +53 -0
  48. behave_fire/rust/surface.py +431 -0
  49. behave_fire/rust/vapor_pressure_deficit_calculator.py +25 -0
  50. behave_fire-0.1.0.dist-info/METADATA +697 -0
  51. behave_fire-0.1.0.dist-info/RECORD +57 -0
  52. behave_fire-0.1.0.dist-info/WHEEL +5 -0
  53. behave_fire-0.1.0.dist-info/licenses/LICENSE +22 -0
  54. behave_fire-0.1.0.dist-info/licenses/LICENSES/Intel-SVML-BSD-3-Clause.txt +66 -0
  55. behave_fire-0.1.0.dist-info/licenses/LICENSES/NumPy-BSD-3-Clause.txt +30 -0
  56. behave_fire-0.1.0.dist-info/licenses/NOTICE +38 -0
  57. behave_fire-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,70 @@
1
+ """
2
+ Behave Fire Behavior Model - Python and Rust implementations
3
+
4
+ This package provides vectorized (NumPy array) fire behavior modeling:
5
+ - Surface fire calculations
6
+ - Crown fire dynamics
7
+ - Tree mortality analysis
8
+ - Spot fire prediction
9
+ - Ignition potential assessment
10
+ - Safety zone calculations
11
+ - Support tools
12
+
13
+ Main entry point: the automatic BehaveRun facade in auto.py, which selects the
14
+ Python reference implementation or the native Rust extension (backend="auto",
15
+ "python", or "rust"). Explicit namespaces are behave_fire.python and
16
+ behave_fire.rust. The explicit Python compatibility class remains in behave.py.
17
+ """
18
+
19
+ from ._version import get_version as _get_version
20
+ from .auto import BehaveBackendWarning, BehaveRun, available_backends, get_backend
21
+ from .components.behave_units import (
22
+ AreaUnits,
23
+ BasalAreaUnits,
24
+ DensityUnits,
25
+ FirelineIntensityUnits,
26
+ FractionUnits,
27
+ HeatOfCombustionUnits,
28
+ HeatPerUnitAreaUnits,
29
+ HeatSinkUnits,
30
+ HeatSourceAndReactionIntensityUnits,
31
+ LengthUnits,
32
+ LoadingUnits,
33
+ PressureUnits,
34
+ SlopeUnits,
35
+ SpeedUnits,
36
+ SurfaceAreaToVolumeUnits,
37
+ TemperatureUnits,
38
+ TimeUnits,
39
+ )
40
+ from .components.fuel_models import FuelModels
41
+ from .components.species_master_table import SpeciesMasterTable
42
+
43
+ __version__ = _get_version()
44
+ __author__ = "Behave Development Team"
45
+ __all__ = [
46
+ 'BehaveRun',
47
+ 'BehaveBackendWarning',
48
+ 'available_backends',
49
+ 'get_backend',
50
+ 'FuelModels',
51
+ 'SpeciesMasterTable',
52
+ 'AreaUnits',
53
+ 'BasalAreaUnits',
54
+ 'LengthUnits',
55
+ 'LoadingUnits',
56
+ 'PressureUnits',
57
+ 'SurfaceAreaToVolumeUnits',
58
+ 'SpeedUnits',
59
+ 'FractionUnits',
60
+ 'SlopeUnits',
61
+ 'DensityUnits',
62
+ 'HeatOfCombustionUnits',
63
+ 'HeatSinkUnits',
64
+ 'HeatPerUnitAreaUnits',
65
+ 'HeatSourceAndReactionIntensityUnits',
66
+ 'FirelineIntensityUnits',
67
+ 'TemperatureUnits',
68
+ 'TimeUnits',
69
+ ]
70
+
@@ -0,0 +1,138 @@
1
+ """Signature-preserving automatic component routing without native error replay."""
2
+ import importlib
3
+ import inspect
4
+ from functools import wraps
5
+ from types import ModuleType
6
+
7
+ from ._auto_routing import capture_call, choose_backend
8
+
9
+
10
+ def _wrap_function(namespace, name, function):
11
+ """Create one public-signature wrapper around a complete counterpart call.
12
+
13
+ :param namespace: Owning routing namespace and actual-backend status.
14
+ :param name: Public attribute name.
15
+ :param function: Unchanged Python counterpart.
16
+ :return: Callable that preflights once before selecting the whole operation.
17
+ """
18
+ operation = namespace._operation_prefix + name
19
+
20
+ @wraps(function)
21
+ def routed(*args, **kwargs):
22
+ """Execute one counterpart on its owned original snapshot.
23
+
24
+ :param args: Original positional arguments.
25
+ :param kwargs: Original keyword arguments.
26
+ :return: Complete result; exceptions propagate without replay or status fabrication.
27
+ """
28
+ if namespace._preferred == 'python':
29
+ result = function(*args, **kwargs)
30
+ namespace._status['backend'] = 'python'
31
+ return result
32
+
33
+ from .auto import _warn_complex
34
+
35
+ call = capture_call(operation, function, args, kwargs)
36
+ selected = choose_backend(call, namespace._preferred)
37
+ if selected == 'python' and namespace._preferred == 'rust':
38
+ _warn_complex(operation, 3)
39
+ target = function if selected == 'python' else getattr(namespace._native_namespace(), name)
40
+ result = call.invoke(target)
41
+ namespace._status['backend'] = selected
42
+ return result
43
+
44
+ return routed
45
+
46
+
47
+ class AutoNamespace(ModuleType):
48
+ """Automatic namespace with cached preference and shared last-completed status."""
49
+
50
+ def __dir__(self):
51
+ """Expose the existing Python public inventory plus routing status.
52
+
53
+ :return: Sorted discoverable attribute names without native discovery or execution.
54
+ """
55
+ names = set(dir(self._python_namespace)) | {'backend_in_use', 'preferred_backend'}
56
+ if not self._operation_prefix and self._preferred == 'rust':
57
+ names.update(('CrownGrid', 'SurfaceGrid'))
58
+ return sorted(names)
59
+
60
+ def __getattr__(self, name):
61
+ """Resolve a counterpart or explicitly unmigrated class lazily.
62
+
63
+ :param name: Public namespace attribute.
64
+ :return: Routed function/submodule, stable registry/enum identity, or selected class.
65
+ """
66
+ if not self._operation_prefix and name == 'BehaveRun':
67
+ from .auto import BehaveRun
68
+ return BehaveRun
69
+ if not self._operation_prefix and name in ('CrownGrid', 'SurfaceGrid'):
70
+ if self._preferred != 'rust':
71
+ raise ImportError(f'{name} is Rust-only; install a compatible native wheel or build the extension.')
72
+ return getattr(self._native_namespace(), name)
73
+ try:
74
+ value = getattr(self._python_namespace, name)
75
+ except AttributeError:
76
+ if self._preferred != 'rust':
77
+ raise
78
+ return getattr(self._native_namespace(), name)
79
+ if isinstance(value, ModuleType) and not name.startswith('_'):
80
+ prefix = self._operation_prefix + name + '.'
81
+ result = AutoNamespace(self._preferred, value, self._native_path + '.' + name,
82
+ prefix, self._status)
83
+ elif inspect.isfunction(value) and not name.startswith('_'):
84
+ result = _wrap_function(self, name, value)
85
+ elif inspect.isclass(value) and name in ('FireSize', 'SlopeTool') and self._preferred == 'rust':
86
+ if name == 'FireSize':
87
+ from ._auto_state import fire_size_type
88
+ result = fire_size_type(self._status)
89
+ else:
90
+ result = getattr(self._native_namespace(), name)
91
+ elif inspect.isclass(value) and self._operation_prefix == 'behave_units.' and self._preferred == 'rust':
92
+ # Unit enum identities remain shared; unmigrated converter classes stay explicit.
93
+ result = getattr(self._native_namespace(), name)
94
+ else:
95
+ result = value
96
+ setattr(self, name, result)
97
+ return result
98
+
99
+ def __init__(self, preferred, python_namespace=None, native_path='behave_fire.rust', prefix='', status=None):
100
+ """Cache preference without importing a native calculation facade.
101
+
102
+ :param preferred: Already probed usable backend name.
103
+ :param python_namespace: Existing Python counterpart module, or the root namespace.
104
+ :param native_path: Matching explicit native module path.
105
+ :param prefix: Canonical component operation prefix.
106
+ :param status: Parent's last-completed backend status shared by child namespaces.
107
+ :return: None; initializes a lazy routing namespace.
108
+ """
109
+ python_namespace = python_namespace or importlib.import_module('behave_fire.python')
110
+ super().__init__(native_path if preferred == 'rust' else python_namespace.__name__)
111
+ self._preferred = preferred
112
+ self._python_namespace = python_namespace
113
+ self._native_path = native_path
114
+ self._operation_prefix = prefix
115
+ self._status = {'backend': preferred} if status is None else status
116
+
117
+ def _native_namespace(self):
118
+ """Load the explicitly selected facade only when a real native call needs it.
119
+
120
+ :return: Native module; import/facade errors propagate without Python fallback.
121
+ """
122
+ return importlib.import_module(self._native_path)
123
+
124
+ @property
125
+ def backend_in_use(self):
126
+ """Report the backend that completed the last direct namespace operation.
127
+
128
+ :return: Actual backend name shared across this namespace and its child modules.
129
+ """
130
+ return self._status['backend']
131
+
132
+ @property
133
+ def preferred_backend(self):
134
+ """Report the cached backend preference independently of complex fallback.
135
+
136
+ :return: Preferred backend name, python or rust.
137
+ """
138
+ return self._preferred
@@ -0,0 +1,148 @@
1
+ """Own original call values and select only verified complex Python counterparts."""
2
+ import copy
3
+ import inspect
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+
8
+ from ._ownership import _owned_inputs
9
+ from .components.fuel_models import _validate_record
10
+
11
+ # Entries are parameter/layout proofs, never a catch-and-retry permission.
12
+ # Further operations enter this table only with complete, nonzero-imaginary tests.
13
+ _COMPLEX_CAPABILITIES = {
14
+ 'surface.calculate_fire_area': {'elapsed_min': frozenset({'scalar', 'numpy-scalar', 'array', 'masked', 'boxed'})},
15
+ 'crown.calculate_crown_heat_and_intensity': {'surface_hpua': frozenset({'array', 'masked'})},
16
+ 'model.do_crown_run': {'surface_results.heat_per_unit_area': frozenset({'array', 'masked'})},
17
+ }
18
+
19
+
20
+ def _complex_sites(value, path):
21
+ """Locate complex storage without invoking custom numeric conversions.
22
+
23
+ :param value: Original owned value or container.
24
+ :param path: Argument and nested field path.
25
+ :return: Tuple of parameter paths and verified-layout identifiers.
26
+ """
27
+ if isinstance(value, np.ndarray):
28
+ if value.dtype.kind == 'c':
29
+ if type(value) not in (np.ndarray, np.ma.MaskedArray):
30
+ return ((path, 'opaque'),)
31
+ return ((path, 'masked' if np.ma.isMaskedArray(value) else 'array'),)
32
+ if value.dtype.kind == 'O':
33
+ items = np.asarray(value).reshape(-1)
34
+ found = any(isinstance(item, (complex, np.complexfloating)) for item in items)
35
+ if found:
36
+ ordinary = all(type(item) in (bool, int, float, complex) or (
37
+ isinstance(item, np.generic) and type(item) is item.dtype.type) for item in items)
38
+ layout = 'boxed' if ordinary and not np.ma.isMaskedArray(value) else 'opaque'
39
+ return ((path, layout),)
40
+ return ()
41
+ if isinstance(value, np.complexfloating):
42
+ ordinary = any(type(value) is kind for kind in (np.complex64, np.complex128, np.clongdouble))
43
+ return ((path, 'numpy-scalar' if ordinary else 'opaque'),)
44
+ if isinstance(value, complex):
45
+ return ((path, 'scalar' if type(value) is complex else 'opaque'),)
46
+ if type(value) is dict:
47
+ return tuple(site for name, item in value.items()
48
+ for site in _complex_sites(item, f'{path}.{name}'))
49
+ if type(value) in (list, tuple):
50
+ if any(_complex_sites(item, path) for item in value):
51
+ return ((path, 'sequence'),)
52
+ return ()
53
+
54
+
55
+ def capture_call(operation, function, args, kwargs):
56
+ """Bind once and own the original values before any backend-specific work.
57
+
58
+ :param operation: Canonical operation used by the verified compatibility table.
59
+ :param function: Python counterpart providing the public signature.
60
+ :param args: Original positional arguments, without an unbound self.
61
+ :param kwargs: Original keyword arguments.
62
+ :return: An owned call with unchanged dtype, masks, values, and logical shapes.
63
+ """
64
+ signature = inspect.signature(function)
65
+ if tuple(signature.parameters)[:1] == ('self',):
66
+ signature = signature.replace(parameters=tuple(signature.parameters.values())[1:])
67
+ bound = signature.bind(*args, **kwargs)
68
+ bound.apply_defaults()
69
+ original_sites = tuple(site for name, value in bound.arguments.items() for site in _complex_sites(value, name))
70
+ with _owned_inputs() as owner:
71
+ arguments = owner.snapshot(dict(bound.arguments))
72
+ sites = tuple(site for name, value in arguments.items() for site in _complex_sites(value, name))
73
+ if any(layout == 'opaque' for _, layout in original_sites):
74
+ sites = original_sites
75
+ return OwnedCall(operation, signature, arguments, sites, owner)
76
+
77
+
78
+ def choose_backend(call, preferred):
79
+ """Preflight complex support without executing or replaying either delegate.
80
+
81
+ :param call: Owned original values captured for this complete operation.
82
+ :param preferred: Already selected usable backend, python or rust.
83
+ :return: Python unchanged when already selected; otherwise Rust or a proven complex fallback.
84
+ """
85
+ if preferred not in ('python', 'rust'):
86
+ raise ValueError('preferred backend must be python or rust')
87
+ if preferred == 'python' or not call.complex_sites:
88
+ return preferred
89
+ supported = _COMPLEX_CAPABILITIES.get(call.operation, {})
90
+ for path, layout in call.complex_sites:
91
+ if layout not in supported.get(path, ()):
92
+ raise TypeError(f'Automatic complex support is not verified for {call.operation}: {path} ({layout}); '
93
+ 'select backend="python" explicitly for unsupported arithmetic.')
94
+ if call.operation == 'model.do_crown_run' and call.arguments.get('out_units'):
95
+ raise TypeError('Complex Crown output-unit conversions are not verified; select backend="python" explicitly.')
96
+ return 'python'
97
+
98
+
99
+ def snapshot_registry(fuel_models):
100
+ """Own a backend-neutral registry before constructing a native delegate.
101
+
102
+ :param fuel_models: Original Python registry or a registry with to_python().
103
+ :return: Independent neutral snapshot; unproven complex registry arithmetic raises TypeError.
104
+ """
105
+ from .components.fuel_models import FuelModels
106
+
107
+ if not isinstance(fuel_models, FuelModels) and callable(getattr(fuel_models, 'to_python', None)):
108
+ fuel_models = fuel_models.to_python()
109
+ if not isinstance(fuel_models, FuelModels):
110
+ raise TypeError('fuel_models must be a FuelModels registry or provide to_python()')
111
+ for number, record in fuel_models.fuel_models_.items():
112
+ _validate_record(number, record)
113
+ return RegistrySnapshot(copy.deepcopy(fuel_models))
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class OwnedCall:
118
+ """One signature and original input snapshot shared by preflight and execution."""
119
+
120
+ operation: str
121
+ signature: inspect.Signature
122
+ arguments: dict
123
+ complex_sites: tuple
124
+ _owner: object
125
+
126
+ def invoke(self, function):
127
+ """Execute one complete selected delegate on this exact owned snapshot.
128
+
129
+ :param function: Chosen Python or Rust callable with the public signature.
130
+ :return: Its result unchanged; delegate exceptions propagate without replay.
131
+ """
132
+ bound = inspect.BoundArguments(self.signature, self.arguments)
133
+ with _owned_inputs(self._owner) as owner:
134
+ return owner.remember(function(*bound.args, **bound.kwargs))
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class RegistrySnapshot:
139
+ """Private backend-neutral registry owner; delegates receive independent copies."""
140
+
141
+ _registry: object
142
+
143
+ def to_python(self):
144
+ """Materialize one delegate registry without exposing the frozen owner.
145
+
146
+ :return: Independent Python FuelModels preserving the captured values and metadata.
147
+ """
148
+ return copy.deepcopy(self._registry)
@@ -0,0 +1,132 @@
1
+ """Value-only FireSize migration for verified complex state operations."""
2
+ import copy
3
+ import importlib
4
+ import inspect
5
+ from functools import wraps
6
+
7
+ from ._auto_routing import _complex_sites
8
+
9
+ _SUPPORTED = frozenset({'calculate_backing_spread_rate', 'calculate_flanking_spread_rate',
10
+ 'get_eccentricity', 'get_fire_length_to_width_ratio', 'get_heading_to_backing_ratio'})
11
+
12
+
13
+ def _restore_fire_size(backend, values):
14
+ """Restore the recorded delegate without automatic backend reselection.
15
+
16
+ :param backend: Previously pinned backend.
17
+ :param values: Complete owned physical state.
18
+ :return: Automatic proxy using the recorded delegate.
19
+ """
20
+ if backend not in ('python', 'rust'):
21
+ raise ValueError('Invalid automatic FireSize backend')
22
+ module = importlib.import_module('behave_fire.' + backend)
23
+ state = AutoFireSize.__new__(AutoFireSize)
24
+ object.__setattr__(state, '_delegate', module.FireSize())
25
+ vars(state._delegate).update(values)
26
+ object.__setattr__(state, '_backend', backend)
27
+ object.__setattr__(state, '_status', {'backend': backend})
28
+ return state
29
+
30
+
31
+ def fire_size_type(status):
32
+ """Bind namespace completion reporting to an independently owned delegate.
33
+
34
+ :param status: Shared last-completed backend dictionary.
35
+ :return: FireSize-compatible automatic class.
36
+ """
37
+ return type('FireSize', (AutoFireSize,), {'_namespace_status': status, '__module__': __name__})
38
+
39
+
40
+ class AutoFireSize:
41
+ """Select Rust for real state and pin Python before proven complex operations."""
42
+
43
+ _namespace_status = None
44
+
45
+ def __getattr__(self, name):
46
+ """Forward fields or preflight a public method before invoking it once.
47
+
48
+ :param name: Delegate field or method.
49
+ :return: Value or signature-preserving bound callable.
50
+ """
51
+ target = getattr(self._delegate, name)
52
+ if not callable(target) or name.startswith('_'):
53
+ return target
54
+
55
+ @wraps(target)
56
+ def call(*args, **kwargs):
57
+ """Snapshot complete state before any supported backend migration.
58
+
59
+ :param args: Original positional inputs.
60
+ :param kwargs: Original named inputs.
61
+ :return: Delegate result; errors propagate without native replay.
62
+ """
63
+ bound = inspect.signature(target).bind(*args, **kwargs)
64
+ sites = _complex_sites(vars(self._delegate), 'state') + _complex_sites(bound.arguments, 'arguments')
65
+ if self._backend == 'rust' and sites:
66
+ if name not in _SUPPORTED or bound.arguments or any(layout not in ('scalar', 'array', 'masked') for _,
67
+ layout in sites):
68
+ raise TypeError(
69
+ f'Automatic complex state support is not verified for FireSize.{name}; '
70
+ 'select Python explicitly.')
71
+ from .auto import _warn_complex
72
+ from .components.fire_size import FireSize
73
+
74
+ values = copy.deepcopy(vars(self._delegate))
75
+ # Warning-as-error must leave the original delegate untouched.
76
+ _warn_complex('fire_size.' + name, 3)
77
+ delegate = FireSize()
78
+ vars(delegate).update(values)
79
+ object.__setattr__(self, '_delegate', delegate)
80
+ object.__setattr__(self, '_backend', 'python')
81
+ result = getattr(self._delegate, name)(*args, **kwargs)
82
+ self._status['backend'] = self._backend
83
+ return result
84
+
85
+ return call
86
+
87
+ def __init__(self):
88
+ """Create owned real Rust state without consuming a fallback warning.
89
+
90
+ :return: None; initializes the delegate and completion status.
91
+ """
92
+ from .rust import FireSize
93
+
94
+ object.__setattr__(self, '_delegate', FireSize())
95
+ object.__setattr__(self, '_backend', 'rust')
96
+ object.__setattr__(self, '_status', self._namespace_status if self._namespace_status is not None else {
97
+ 'backend': 'rust'})
98
+
99
+ def __reduce__(self):
100
+ """Serialize complete values and the pinned backend without pointers.
101
+
102
+ :return: Stable restoration callable and independent state arguments.
103
+ """
104
+ return _restore_fire_size, (self._backend, copy.deepcopy(vars(self._delegate)))
105
+
106
+ def __setattr__(self, name, value):
107
+ """Record caller state edits on the current delegate.
108
+
109
+ :param name: Public physical field or private proxy member.
110
+ :param value: Supplied value.
111
+ :return: None; updates state without scientific execution.
112
+ """
113
+ if name.startswith('_'):
114
+ object.__setattr__(self, name, value)
115
+ else:
116
+ setattr(self._delegate, name, value)
117
+
118
+ @property
119
+ def backend_in_use(self):
120
+ """Report the pinned delegate.
121
+
122
+ :return: python or rust.
123
+ """
124
+ return self._backend
125
+
126
+ @property
127
+ def requested_backend(self):
128
+ """Retain the original automatic policy.
129
+
130
+ :return: auto.
131
+ """
132
+ return 'auto'