flame-components 0.2.0__cp314-cp314-win_amd64.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.
- flame_components/__init__.py +33 -0
- flame_components/_backend.py +41 -0
- flame_components/_blocks.py +59 -0
- flame_components/_equations.py +193 -0
- flame_components/_native.cp314-win_amd64.pyd +0 -0
- flame_components/_native_bridge.py +183 -0
- flame_components/_precision.py +237 -0
- flame_components/_utils.py +95 -0
- flame_components/core.py +351 -0
- flame_components-0.2.0.dist-info/METADATA +278 -0
- flame_components-0.2.0.dist-info/RECORD +13 -0
- flame_components-0.2.0.dist-info/WHEEL +4 -0
- flame_components-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Flame Components — fire behavior calculations for surface and crown fires.
|
|
3
|
+
|
|
4
|
+
Public API is implemented in :mod:`flame_components.core`; this module
|
|
5
|
+
re-exports it.
|
|
6
|
+
"""
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version('flame-components')
|
|
11
|
+
except PackageNotFoundError:
|
|
12
|
+
# Package is not installed (e.g. running directly from a source checkout)
|
|
13
|
+
__version__ = 'unknown'
|
|
14
|
+
|
|
15
|
+
from flame_components.core import (
|
|
16
|
+
flame_component_array_multiprocessing,
|
|
17
|
+
get_flame_depth,
|
|
18
|
+
get_flame_height,
|
|
19
|
+
get_flame_length,
|
|
20
|
+
get_flame_residence_time,
|
|
21
|
+
get_flame_tilt,
|
|
22
|
+
get_mid_flame_ws,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
'flame_component_array_multiprocessing',
|
|
27
|
+
'get_flame_depth',
|
|
28
|
+
'get_flame_height',
|
|
29
|
+
'get_flame_length',
|
|
30
|
+
'get_flame_residence_time',
|
|
31
|
+
'get_flame_tilt',
|
|
32
|
+
'get_mid_flame_ws',
|
|
33
|
+
]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Resolve the Python backend and load the optional native extension on demand."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
from types import ModuleType
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from numpy import geterr
|
|
8
|
+
|
|
9
|
+
_NATIVE_MODULE = "flame_components._native"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load_native() -> ModuleType:
|
|
13
|
+
"""Load the optional extension and report how to install it if absent."""
|
|
14
|
+
try:
|
|
15
|
+
return import_module(_NATIVE_MODULE)
|
|
16
|
+
except ModuleNotFoundError as error:
|
|
17
|
+
if error.name != _NATIVE_MODULE:
|
|
18
|
+
raise
|
|
19
|
+
raise ImportError(
|
|
20
|
+
"Install a Flame Components wheel with the Rust backend, or use backend='python'."
|
|
21
|
+
) from error
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def resolve_backend(backend: str) -> Literal["python", "rust"]:
|
|
25
|
+
"""Validate the requested backend and select a concrete implementation."""
|
|
26
|
+
if not isinstance(backend, str) or backend not in ("auto", "rust", "python"):
|
|
27
|
+
raise ValueError("backend must be one of auto, rust, python")
|
|
28
|
+
if backend == "rust":
|
|
29
|
+
load_native()
|
|
30
|
+
return "rust"
|
|
31
|
+
if backend == "auto":
|
|
32
|
+
try:
|
|
33
|
+
import_module(_NATIVE_MODULE)
|
|
34
|
+
except ModuleNotFoundError as error:
|
|
35
|
+
if error.name != _NATIVE_MODULE:
|
|
36
|
+
raise
|
|
37
|
+
return "python"
|
|
38
|
+
if any(mode in {"raise", "call", "log", "print"} for mode in geterr().values()):
|
|
39
|
+
return "python"
|
|
40
|
+
return "rust"
|
|
41
|
+
return "python"
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Partition array inputs and collect calculation results in row order."""
|
|
2
|
+
|
|
3
|
+
import multiprocessing as mp
|
|
4
|
+
|
|
5
|
+
from numpy import ndarray
|
|
6
|
+
|
|
7
|
+
from . import _utils
|
|
8
|
+
|
|
9
|
+
_FUNCTION_NAMES = {
|
|
10
|
+
"midflame_ws": "get_mid_flame_ws",
|
|
11
|
+
"flame_length": "get_flame_length",
|
|
12
|
+
"flame_height": "get_flame_height",
|
|
13
|
+
"flame_tilt": "get_flame_tilt",
|
|
14
|
+
"flame_residence": "get_flame_residence_time",
|
|
15
|
+
"flame_depth": "get_flame_depth",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def prepare_blocks(flame_function: str, num_processors: int, kwargs: dict) -> tuple[str, int, int]:
|
|
20
|
+
"""Validate the function and inputs before the facade handles the processor count."""
|
|
21
|
+
_utils.check_choice("flame_function", flame_function, _FUNCTION_NAMES)
|
|
22
|
+
row_count = _utils.common_row_count(kwargs)
|
|
23
|
+
num_processors = _utils.check_int("num_processors", num_processors)
|
|
24
|
+
return _FUNCTION_NAMES[flame_function], row_count, num_processors
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _multiprocessing_worker(function_name: str, backend: str, kwargs: dict):
|
|
28
|
+
"""Calculate one block with the backend selected by the parent process."""
|
|
29
|
+
from . import core
|
|
30
|
+
|
|
31
|
+
function = getattr(core, function_name)
|
|
32
|
+
return function(backend=backend, **kwargs)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def calculate_blocks(
|
|
36
|
+
function_name: str,
|
|
37
|
+
row_count: int,
|
|
38
|
+
num_processors: int,
|
|
39
|
+
block_size: int | None,
|
|
40
|
+
backend: str,
|
|
41
|
+
kwargs: dict,
|
|
42
|
+
) -> list:
|
|
43
|
+
"""Split the arrays on their first axis and dispatch the ordered blocks."""
|
|
44
|
+
if block_size is None:
|
|
45
|
+
block_size = max(1, row_count // num_processors)
|
|
46
|
+
else:
|
|
47
|
+
block_size = _utils.check_int("block_size", block_size, minimum=1)
|
|
48
|
+
|
|
49
|
+
tasks = []
|
|
50
|
+
for start in range(0, row_count, block_size):
|
|
51
|
+
rows = slice(start, start + block_size)
|
|
52
|
+
block = {
|
|
53
|
+
key: value[rows] if isinstance(value, ndarray) else value
|
|
54
|
+
for key, value in kwargs.items()
|
|
55
|
+
}
|
|
56
|
+
tasks.append((function_name, backend, block))
|
|
57
|
+
|
|
58
|
+
with mp.Pool(processes=min(num_processors, len(tasks))) as pool:
|
|
59
|
+
return pool.starmap(_multiprocessing_worker, tasks)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""NumPy reference equations operating on validated, normalized inputs."""
|
|
2
|
+
|
|
3
|
+
from numpy import degrees, ma, pi, radians
|
|
4
|
+
from numpy.ma import arccos, arcsin, arctan, log, power, sin, sqrt
|
|
5
|
+
|
|
6
|
+
# Published correlations of flame length with fire intensity (from Finney and Grumstrup 2023)
|
|
7
|
+
LENGTH_MODELS = {
|
|
8
|
+
# Fire = No wind, flat
|
|
9
|
+
'Fons_NOWIND': (0.024018, 2 / 3), # Fons et al. (1963); Source = Cribs; Lab
|
|
10
|
+
'Thomas_NOWIND': (0.026700, 2 / 3), # Thomas (1963); Source = Cribs; Lab + Field
|
|
11
|
+
'Yuana_NOWIND': (0.034000, 2 / 3), # Yuana and Cox (1996); Source = Gas slot burner; Lab
|
|
12
|
+
'Barbon_NOWIND': (0.062000, 0.5336), # Yuana and Cox (1996); Source = Pine needles; Lab + Field
|
|
13
|
+
# Fire = Backing
|
|
14
|
+
'Nelson_BACK': (0.027973, 2 / 3), # Nelson (1980); Source = Needles; Lab + Field
|
|
15
|
+
'Fernandes_BACK': (0.029000, 0.7240), # Fernandes et al. (2009); Source = Pine Needles; Field
|
|
16
|
+
'Clark_BACK': (0.001600, 1.7450), # Clark (1983); Source = Grass; Field
|
|
17
|
+
'Vega_BACK': (0.087000, 0.4930), # Vega et al. (1998); Source = Shrubs; Field
|
|
18
|
+
# Fire = Heading
|
|
19
|
+
'Byram_HEAD': (0.0775, 0.4600), # Byram (1959); Source = Needles; Field
|
|
20
|
+
'Anderson1_HEAD': (0.013876, 0.6510), # Anderson et al. (1966); Source = Lodgepole pine slash; Field
|
|
21
|
+
'Anderson2_HEAD': (0.008800, 0.6700), # Anderson et al. (1996); Source = Douglas-fir slash; Field
|
|
22
|
+
'Newman_HEAD': (0.05770, 0.5000), # Newman (1974); Source = Unkn; Field
|
|
23
|
+
'Sneewujagt_HEAD': (0.037680, 0.5000), # Sneewujagt and Frandsen (1977); Source = Needles; Field
|
|
24
|
+
'Nelson1_HEAD': (0.044230, 0.5000), # Nelson (1980); Source = Needles; Field
|
|
25
|
+
'Clark_HEAD': (0.000722, 0.9934), # Clark (1983); Source = Grass; Field
|
|
26
|
+
'Nelson2_HEAD': (0.047500, 0.4930), # Nelson and Adkins (1986); Source = Needles/Palmetto; Lab + Field
|
|
27
|
+
'VanWilgen_HEAD': (0.046000, 0.4128), # Van Wilgen (1986); Source = Grass; Field
|
|
28
|
+
'Burrows_HEAD': (0.040480, 0.5740), # Burrows (1994, p. 102); Source = Needles; Field
|
|
29
|
+
'MarsdenSmedley_HEAD': (0.148, 0.403), # Marsden-Smedley and Catchpole (1995); Source = Button grass; Field
|
|
30
|
+
'Weise1_HEAD': (0.016000, 0.7000), # Weise and Biging (1996); Source = Excelsior & birch stir sticks; Lab
|
|
31
|
+
'Catchpole_HEAD': (0.032500, 0.5600), # Catchpole et al. (1998); Source = Heath; Field
|
|
32
|
+
'Fernandes1_HEAD': (0.051600, 0.4530), # Fernandes et al. (2000); Source = Shrubs; Field
|
|
33
|
+
'Butler_HEAD': (0.017500, 2 / 3), # Butler et al. (2004); Source = Crownfire (add to avg. stand ht); Unkn
|
|
34
|
+
'Fernandes_HEAD': (0.045000, 0.5430), # Fernandes et al. (2009); Source = Needles; Field
|
|
35
|
+
'Nelson3_HEAD': (0.014200, 2 / 3), # Nelson et al. (2012); Source = Needles/southern Fuel; Lab
|
|
36
|
+
'Nelson4_HEAD': (0.015500, 2 / 3), # Nelson et al. (2012); Source = Needles/southern Fuel; Field
|
|
37
|
+
'Weise2_HEAD': (0.2000000, 0.3400), # Weise et al. (2016); Source = Chaparral; Lab
|
|
38
|
+
'Davies_HEAD': (0.220000, 0.2900), # Davies et al. (2019); Source = Heathlands; Field
|
|
39
|
+
'Finney_HEAD': (0.01051, 0.774, 0.161) # Finney and Grumstrup (2023); Source = Gas slot burner; Lab
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# Preserve the original selector for existing callers.
|
|
44
|
+
LENGTH_MODELS["Barbon_iNOWIND"] = LENGTH_MODELS["Barbon_NOWIND"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def prepare_mid_flame_ws(wind_speed, canopy_ht, canopy_baseht, units):
|
|
48
|
+
# Convert input units
|
|
49
|
+
if units == 'SI':
|
|
50
|
+
wind_speed = wind_speed / (3.6 * 1.15) # convert 10m (km/hr) windspeed to 20ft equivalent (1.15) and m/s (3.6)
|
|
51
|
+
canopy_ht = canopy_ht * 3.28084 # convert height in meters to feet
|
|
52
|
+
canopy_baseht = canopy_baseht * 3.28084 # convert cbh in meters to feet
|
|
53
|
+
elif units == 'IMP':
|
|
54
|
+
wind_speed = wind_speed / 2.23694 # convert mi/h to m/s
|
|
55
|
+
|
|
56
|
+
return wind_speed, canopy_ht, canopy_baseht, bool(ma.any(canopy_ht == 0))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def mid_flame_ws(wind_speed, canopy_cover, canopy_ht, canopy_baseht):
|
|
60
|
+
canopy_ht = ma.where(canopy_ht == 0,
|
|
61
|
+
0.5 * 3.28084,
|
|
62
|
+
canopy_ht)
|
|
63
|
+
|
|
64
|
+
crown_ratio = (canopy_ht - canopy_baseht) / canopy_ht # calculate crown ratio
|
|
65
|
+
f = crown_ratio * canopy_cover / 300
|
|
66
|
+
|
|
67
|
+
# Calculate the mid-flame wind speed
|
|
68
|
+
midflame_ws = ma.where(f <= 5,
|
|
69
|
+
# Calculate unsheltered midflame windspeed
|
|
70
|
+
# ws * 0.4
|
|
71
|
+
wind_speed * 1.83 / log((20 + (0.36 * canopy_ht)) / (0.13 * canopy_ht)),
|
|
72
|
+
# Calculate sheltered midflame windspeed
|
|
73
|
+
wind_speed * 0.555 / (
|
|
74
|
+
sqrt(f * canopy_ht) * log((20 + (0.36 * canopy_ht)) / (0.13 * canopy_ht))))
|
|
75
|
+
|
|
76
|
+
return midflame_ws
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def flame_length_parameters(model):
|
|
80
|
+
return LENGTH_MODELS[model]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def flame_length(model, fire_intensity, flame_depth):
|
|
84
|
+
model_params = flame_length_parameters(model)
|
|
85
|
+
|
|
86
|
+
if model == 'Finney_HEAD':
|
|
87
|
+
fl = (model_params[0] *
|
|
88
|
+
power(fire_intensity, model_params[1]) /
|
|
89
|
+
power(flame_depth, model_params[2]))
|
|
90
|
+
else:
|
|
91
|
+
fl = model_params[0] * power(fire_intensity, model_params[1])
|
|
92
|
+
|
|
93
|
+
return fl
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def flame_height(model, flame_length, fire_type, fire_intensity, midflame_ws, flame_tilt, slope_angle, slope_units):
|
|
97
|
+
if model == 'Nelson':
|
|
98
|
+
# Calculate fire parameter (a)
|
|
99
|
+
a = ma.where(ma.isin(fire_type, [1, 2]),
|
|
100
|
+
# parameter for experimental lab and field fires (Nelson and Adkins 1986; Nelson et al. 2012)
|
|
101
|
+
1 / 360,
|
|
102
|
+
# parameter for crown fires (Butler et al. 2004)
|
|
103
|
+
0.0175)
|
|
104
|
+
|
|
105
|
+
# Calculate height
|
|
106
|
+
height = ma.where(midflame_ws == 0,
|
|
107
|
+
flame_length,
|
|
108
|
+
a * fire_intensity / midflame_ws)
|
|
109
|
+
|
|
110
|
+
# Rescale height to match flame length if it is predicted to exceed flame length
|
|
111
|
+
height = ma.where(height > flame_length,
|
|
112
|
+
flame_length,
|
|
113
|
+
height)
|
|
114
|
+
|
|
115
|
+
else: # model == 'Finney':
|
|
116
|
+
# Convert slope to radians
|
|
117
|
+
if slope_units == 'percent':
|
|
118
|
+
slope_rad = arctan(slope_angle / 100)
|
|
119
|
+
elif slope_units == 'degrees':
|
|
120
|
+
slope_rad = radians(slope_angle)
|
|
121
|
+
else:
|
|
122
|
+
raise ValueError('Unable to calculate flame height - Slope tilt')
|
|
123
|
+
|
|
124
|
+
# Convert flame tilt so it is relative to horizontal
|
|
125
|
+
tilt_h = pi / 2 - radians(flame_tilt)
|
|
126
|
+
|
|
127
|
+
height = ma.where(slope_angle <= 1,
|
|
128
|
+
flame_length * sin(tilt_h),
|
|
129
|
+
# Calculate Finney and Martin (1992) flame height
|
|
130
|
+
flame_length * sin(tilt_h - slope_rad) / sin(radians(90) - slope_rad))
|
|
131
|
+
|
|
132
|
+
return height
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def flame_tilt(model, flame_length, flame_height, slope_angle, slope_units, wind_speed, wind_speed_units, canopy_ht):
|
|
136
|
+
# Calculate flame tilt angle (radians)
|
|
137
|
+
if model == 'Standard':
|
|
138
|
+
tilt_v = arccos(flame_height / flame_length)
|
|
139
|
+
elif model == 'Finney':
|
|
140
|
+
# Convert slope to radians
|
|
141
|
+
if slope_units == 'percent':
|
|
142
|
+
slope_rad = arctan(slope_angle / 100)
|
|
143
|
+
elif slope_units == 'degrees':
|
|
144
|
+
slope_rad = radians(slope_angle)
|
|
145
|
+
else:
|
|
146
|
+
raise ValueError('Unable to calculate flame tilt - Invalid slope units provided')
|
|
147
|
+
|
|
148
|
+
# Calculate Finney and Martin (1992) flame tilt angle
|
|
149
|
+
# This equation calculates tilt relative to horizontal (tilting up from horizontal flat ground)
|
|
150
|
+
tilt_h = arcsin(radians(flame_height * degrees(sin(radians(90) - slope_rad)) / flame_length)) + slope_rad
|
|
151
|
+
tilt_v = ma.where(flame_height == flame_length,
|
|
152
|
+
0,
|
|
153
|
+
# Get equivalent tilt relative to vertical rather than horizontal (tilting down from vertical)
|
|
154
|
+
pi / 2 - tilt_h)
|
|
155
|
+
|
|
156
|
+
else: # model == 'Butler':
|
|
157
|
+
# THIS MODEL (Butler et al. 2004) IS MADE FOR TILT OF CROWN FIRES
|
|
158
|
+
# ONLY REQUIRES 10m WIND SPEED AS AN INPUT
|
|
159
|
+
# ONLY USE FOR CROWN FIRES, OTHERWISE TILT WILL BE TOO LOW
|
|
160
|
+
|
|
161
|
+
# Convert wind speed units if necessary
|
|
162
|
+
if wind_speed_units == 'kph':
|
|
163
|
+
wind_speed = wind_speed / 3.6 # convert kilometers/hour to meters/second
|
|
164
|
+
elif wind_speed_units == 'mph':
|
|
165
|
+
wind_speed = wind_speed / 2.23694 # convert miles/hour to meters/second
|
|
166
|
+
|
|
167
|
+
# Wind speed at the top of the forest canopy (Albini and Baughman 1979; Butler et al. 2004)
|
|
168
|
+
uc = wind_speed / (3.6 * (1 + log(1 + (28 / canopy_ht))))
|
|
169
|
+
|
|
170
|
+
# acceleration of gravity (m/s^2)
|
|
171
|
+
g = 9.81
|
|
172
|
+
|
|
173
|
+
# Calculate Butler et al. (2004) flame tilt angle
|
|
174
|
+
# This equation already calculates tilt relative to vertical rather than horizontal
|
|
175
|
+
tilt_v = arctan(sqrt((3 * power(uc, 3)) / (2 * g * 10)))
|
|
176
|
+
|
|
177
|
+
return degrees(tilt_v)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def flame_residence_time(ros, fuel_consumption, midflame_ws, units):
|
|
181
|
+
# Calculate flame residence time
|
|
182
|
+
res_time = (0.39 * power(fuel_consumption, 0.25) * power(midflame_ws, 1.51)) / (ros / 60)
|
|
183
|
+
if units == 'min':
|
|
184
|
+
res_time = res_time / 60
|
|
185
|
+
|
|
186
|
+
return res_time
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def flame_depth(ros, res_time):
|
|
190
|
+
# Calculate flame depth
|
|
191
|
+
fd = ros * res_time
|
|
192
|
+
|
|
193
|
+
return fd
|
|
Binary file
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Convert normalized NumPy buffers to and from the Rust extension."""
|
|
2
|
+
|
|
3
|
+
from itertools import zip_longest
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from numpy import ma
|
|
7
|
+
|
|
8
|
+
from . import _backend, _equations, _precision
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _high_rank_shape(args):
|
|
12
|
+
arrays = [arg for arg in args if isinstance(arg, np.ndarray)]
|
|
13
|
+
# The native array view supports at most 32 dimensions. NumPy 2 allows 64.
|
|
14
|
+
if not any(array.ndim > 32 for array in arrays):
|
|
15
|
+
return None
|
|
16
|
+
shapes = [array.shape for array in arrays]
|
|
17
|
+
result = []
|
|
18
|
+
for dimensions in zip_longest(*(reversed(shape) for shape in shapes), fillvalue=1):
|
|
19
|
+
lengths = {length for length in dimensions if length != 1}
|
|
20
|
+
if len(lengths) > 1:
|
|
21
|
+
operands = " ".join(map(str, shapes))
|
|
22
|
+
raise ValueError(f"operands could not be broadcast together with shapes {operands} ")
|
|
23
|
+
result.append(next(iter(lengths), 1))
|
|
24
|
+
return tuple(reversed(result))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _buffers(array, dtype, *, round_to=None, shape=None):
|
|
28
|
+
data = ma.getdata(array)
|
|
29
|
+
mask = ma.getmaskarray(array)
|
|
30
|
+
if round_to is not None:
|
|
31
|
+
with np.errstate(all="ignore"):
|
|
32
|
+
data = data.astype(round_to, copy=False)
|
|
33
|
+
if shape is not None:
|
|
34
|
+
data = np.broadcast_to(data, shape).reshape(-1)
|
|
35
|
+
mask = np.broadcast_to(mask, shape).reshape(-1)
|
|
36
|
+
return np.require(data, dtype=dtype, requirements="A"), np.require(mask, requirements="A")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _restore_shape(result, shape):
|
|
40
|
+
if shape is None:
|
|
41
|
+
return result
|
|
42
|
+
data, mask, substituted = result
|
|
43
|
+
return data.reshape(shape), mask.reshape(shape), substituted
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _return_array(data, mask, dtype):
|
|
47
|
+
with np.errstate(all="ignore"):
|
|
48
|
+
return ma.array(data.astype(dtype, copy=False), mask=mask, copy=False)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_extended(dtype):
|
|
52
|
+
return dtype.kind == "f" and dtype.itemsize > 8
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _extended_buffers(array, dtype):
|
|
56
|
+
data = np.require(ma.getdata(array), dtype=dtype, requirements=("A", "C"))
|
|
57
|
+
# Keep data and mask ranks fixed even at NumPy's maximum logical rank.
|
|
58
|
+
packet = data.reshape(-1, 1).view(np.uint8)
|
|
59
|
+
mask = np.require(ma.getmaskarray(array).reshape(-1), requirements="A")
|
|
60
|
+
return packet, mask, array.shape
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _extended(native, equation, args, precision, equality=None):
|
|
64
|
+
dtype = np.dtype(np.longdouble)
|
|
65
|
+
info = np.finfo(dtype)
|
|
66
|
+
expected = (dtype.itemsize, info.nmant + 1, info.minexp, info.maxexp)
|
|
67
|
+
if native.extended_format() != expected:
|
|
68
|
+
raise TypeError("The Rust backend does not support this platform's NumPy longdouble format")
|
|
69
|
+
buffers = tuple(
|
|
70
|
+
_extended_buffers(arg, dtype) if isinstance(arg, np.ndarray) else arg
|
|
71
|
+
for arg in args
|
|
72
|
+
)
|
|
73
|
+
if equality is not None:
|
|
74
|
+
equality = (*_buffers(equality.reshape(-1), np.dtype("bool")), equality.shape)
|
|
75
|
+
data, mask, shape, substituted = native.extended(
|
|
76
|
+
equation, buffers, precision, equality=equality
|
|
77
|
+
)
|
|
78
|
+
return data.view(dtype).reshape(shape), mask.reshape(shape), substituted
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _depth(native, args):
|
|
82
|
+
dtype = np.result_type(*(ma.getdata(arg) for arg in args))
|
|
83
|
+
if _is_extended(dtype):
|
|
84
|
+
return _extended(native, "flame_depth", args, None), dtype
|
|
85
|
+
shape = _high_rank_shape(args)
|
|
86
|
+
if dtype == np.dtype("float16"):
|
|
87
|
+
# NumPy rounds the inputs before multiplying. Their product then fits
|
|
88
|
+
# exactly in binary32 until it is rounded back to binary16.
|
|
89
|
+
buffers = (_buffers(arg, np.dtype("float32"), round_to=dtype, shape=shape) for arg in args)
|
|
90
|
+
else:
|
|
91
|
+
buffers = (_buffers(arg, dtype.newbyteorder("="), shape=shape) for arg in args)
|
|
92
|
+
return _restore_shape(native.flame_depth(*buffers), shape), dtype
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _active_inputs(equation, args):
|
|
96
|
+
# Caller validation has already checked supplied optional arguments.
|
|
97
|
+
if equation == "flame_length" and args[0] != "Finney_HEAD":
|
|
98
|
+
return (*args[:2], None)
|
|
99
|
+
if equation == "flame_height":
|
|
100
|
+
if args[0] == "Nelson":
|
|
101
|
+
return (*args[:5], None, None, None)
|
|
102
|
+
return (*args[:2], None, None, None, *args[5:])
|
|
103
|
+
if equation == "flame_tilt":
|
|
104
|
+
if args[0] == "Standard":
|
|
105
|
+
return (*args[:3], None, None, None, None, None)
|
|
106
|
+
if args[0] == "Finney":
|
|
107
|
+
return (*args[:5], None, None, None)
|
|
108
|
+
return (args[0], None, None, None, None, *args[5:])
|
|
109
|
+
return args
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _finney_equality(length, height):
|
|
113
|
+
# Equality must use the original NumPy dtypes before Rust receives f64 inputs.
|
|
114
|
+
try:
|
|
115
|
+
if _high_rank_shape((length, height)) is None:
|
|
116
|
+
np.broadcast_shapes(length.shape, height.shape)
|
|
117
|
+
except ValueError:
|
|
118
|
+
# Let the Rust kernel report the incompatible operands in equation order.
|
|
119
|
+
return None
|
|
120
|
+
return height == length
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _raise_broadcast_error(equation, args, fallback):
|
|
124
|
+
"""Preserve the first failing operation for incompatible high-rank shapes."""
|
|
125
|
+
with np.errstate(all="ignore"):
|
|
126
|
+
if equation == "mid_flame_ws":
|
|
127
|
+
speed, cover, canopy, base, units = args
|
|
128
|
+
speed, canopy, base, substituted = _equations.prepare_mid_flame_ws(
|
|
129
|
+
speed, canopy, base, units
|
|
130
|
+
)
|
|
131
|
+
try:
|
|
132
|
+
_equations.mid_flame_ws(speed, cover, canopy, base)
|
|
133
|
+
except ValueError as error:
|
|
134
|
+
error.substituted_canopy_height = substituted
|
|
135
|
+
raise
|
|
136
|
+
else:
|
|
137
|
+
getattr(_equations, equation)(*args)
|
|
138
|
+
raise fallback
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run(equation, *args):
|
|
142
|
+
native = _backend.load_native()
|
|
143
|
+
if equation == "flame_length_parameters":
|
|
144
|
+
return native.flame_length_parameters(*args), False
|
|
145
|
+
|
|
146
|
+
if equation == "flame_depth":
|
|
147
|
+
result, dtype = _depth(native, args)
|
|
148
|
+
else:
|
|
149
|
+
args = _active_inputs(equation, args)
|
|
150
|
+
parameters = _equations.LENGTH_MODELS[args[0]] if equation == "flame_length" else None
|
|
151
|
+
precision, dtype = _precision.metadata(equation, args, parameters)
|
|
152
|
+
equality = (
|
|
153
|
+
_finney_equality(args[1], args[2])
|
|
154
|
+
if equation == "flame_tilt" and args[0] == "Finney" else None
|
|
155
|
+
)
|
|
156
|
+
wide_inputs = any(
|
|
157
|
+
isinstance(arg, np.ndarray) and _is_extended(arg.dtype) for arg in args
|
|
158
|
+
)
|
|
159
|
+
if wide_inputs:
|
|
160
|
+
result = _extended(native, equation, args, precision, equality)
|
|
161
|
+
else:
|
|
162
|
+
try:
|
|
163
|
+
shape = _high_rank_shape(args)
|
|
164
|
+
except ValueError as error:
|
|
165
|
+
_raise_broadcast_error(equation, args, error)
|
|
166
|
+
inputs = tuple(
|
|
167
|
+
_buffers(arg, np.dtype("float64"), shape=shape) if isinstance(arg, np.ndarray) else arg
|
|
168
|
+
for arg in args
|
|
169
|
+
)
|
|
170
|
+
options = {} if precision is None else {"precision": precision}
|
|
171
|
+
if equality is not None:
|
|
172
|
+
options["equality"] = _buffers(equality, np.dtype("bool"), shape=shape)
|
|
173
|
+
result = _restore_shape(getattr(native, equation)(*inputs, **options), shape)
|
|
174
|
+
if shape is not None and 0 in shape and equation == "mid_flame_ws":
|
|
175
|
+
# Substitution is reported even if later broadcasting yields no cells.
|
|
176
|
+
data, mask, substituted = result
|
|
177
|
+
result = data, mask, substituted or bool(ma.any(args[2] == 0))
|
|
178
|
+
|
|
179
|
+
data, mask, substituted = result
|
|
180
|
+
if equation == "flame_depth" and data.ndim == 0 and bool(mask):
|
|
181
|
+
# Masked scalar multiplication returns NumPy's float64 masked sentinel.
|
|
182
|
+
dtype = np.dtype("float64")
|
|
183
|
+
return _return_array(data, mask, dtype), substituted
|