-
Notifications
You must be signed in to change notification settings - Fork 1
/
cffbps_cupy.py
1922 lines (1694 loc) · 75.3 KB
/
cffbps_cupy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Modified to use CuPy for GPU acceleration.
Created on Thur Dec 26 20:45:00 2024
@author: Gregory A. Greene
"""
__author__ = ['Gregory A. Greene']
import os
from typing import Union, Optional
from operator import itemgetter
import numpy as np
import cupy as cp
import rasterio as rio
from datetime import datetime as dt
import ProcessRasters
# Define lookup tables as in the original code
fbpFTCode_NumToAlpha_LUT = {
1: 'C1', 2: 'C2', 3: 'C3', 4: 'C4', 5: 'C5', 6: 'C6',
7: 'C7', 8: 'D1', 9: 'D2', 10: 'M1', 11: 'M2', 12: 'M3',
13: 'M4', 14: 'O1a', 15: 'O1b', 16: 'S1', 17: 'S2', 18: 'S3',
19: 'NF', 20: 'WA'
}
fbpFTCode_AlphaToNum_LUT = {
'C1': 1, 'C2': 2, 'C3': 3, 'C4': 4, 'C5': 5, 'C6': 6,
'C7': 7, 'D1': 8, 'D2': 9, 'M1': 10, 'M2': 11, 'M3': 12,
'M4': 13, 'O1a': 14, 'O1b': 15, 'S1': 16, 'S2': 17, 'S3': 18,
'NF': 19, 'WA': 20
}
def convert_grid_codes(fuel_type_array: cp.ndarray) -> cp.ndarray:
"""
Function to convert array grid code values for compatibility.
:param fuel_type_array: CFFBPS fuel type array
:return: modified fuel_type_array
"""
fuel_type_array = cp.where(
fuel_type_array == 19, 20,
cp.where(
fuel_type_array == 13, 19,
cp.where(
fuel_type_array == 12, 13,
cp.where(
fuel_type_array == 11, 12,
cp.where(
fuel_type_array == 10, 11,
cp.where(fuel_type_array == 9, 10, fuel_type_array)
)
)
)
)
)
return fuel_type_array
def getSeasonGrassCuring(season: str,
province: str,
subregion: str = None) -> int:
"""
Function returns a default grass curing code based on season, province, and subregion
:param season: annual season ("spring", "summer", "fall", "winter")
:param province: province being assessed ("AB", "BC")
:param subregion: British Columbia subregions ("southeast", "other")
:return: grass curing percent (%); "None" is returned if season or province are invalid
"""
if province == 'AB':
# Default seasonal grass curing values for Alberta
# These curing rates are recommended by Neal McLoughlin to align with Alberta Wildfire knowledge and practices
gc_dict = {
'spring': 75,
'summer': 40,
'fall': 60,
'winter': 100
}
elif province == 'BC':
if subregion == 'southeast':
# Default seasonal grass curing values for southeastern British Columbia
gc_dict = {
'spring': 100,
'summer': 90,
'fall': 90,
'winter': 100
}
else:
# Default seasonal grass curing values for British Columbia
gc_dict = {
'spring': 100,
'summer': 60,
'fall': 85,
'winter': 100
}
else:
gc_dict = {}
return gc_dict.get(season.lower(), None)
# Replace NumPy arrays with CuPy arrays within the FBP class and associated methods
class FBP:
"""
Class to model fire behavior with the Canadian Forest Fire Behavior Prediction System.
Modified to use CuPy for GPU acceleration.
"""
def __init__(self):
# Initialize CFFBPS input parameters
self.fuel_type = None
self.wx_date = None
self.lat = None
self.long = None
self.elevation = None
self.slope = None
self.aspect = None
self.ws = None
self.wd = None
self.ffmc = None
self.bui = None
self.pc = None
self.pdf = None
self.gfl = None
self.gcf = None
self.out_request = None
self.convert_fuel_type_codes = None
# Array verification parameter
self.return_array = None
self.ref_array = None
self.ref_array_nan = None
self.initialized = False
# Initialize multiprocessing block variable
self.block = None
# Initialize weather parameters
self.isi = None
self.m = None
self.fF = None
self.fW = None
# Initialize slope effect parameters
self.a = None
self.b = None
self.c = None
self.rsz = None
self.isz = None
self.sf = None
self.rsf = None
self.isf = None
self.rsi = None
self.wse1 = None
self.wse2 = None
self.wse = None
self.wsx = None
self.wsy = None
self.wsv = None
self.raz = None
# Initialize BUI effect parameters
self.q = None
self.bui0 = None
self.be = None
self.be_max = None
# Initialize surface parameters
self.cf = None
self.ffc = None
self.wfc = None
self.sfc = None
self.rss = None
# Initialize foliar moisture content parameters
self.latn = None
self.dj = None
self.d0 = None
self.nd = None
self.fmc = None
self.fme = None
# Initialize crown and total fuel consumed parameters
self.cbh = None
self.csfi = None
self.rso = None
self.rsc = None
self.cfb = None
self.cfl = None
self.cfc = None
self.tfc = None
# Initialize the back fire rate of spread parameters
self.bfW = None
self.brsi = None
self.bisi = None
self.bros = None
# Initialize default CFFBPS output parameters
self.fire_type = None
self.hfros = None
self.hfi = None
# Initialize other parameters
self.sfros = None
self.cfros = None
# ### Lists for CFFBPS Crown Fire Metric variables
self.csfiVarList = ['cbh', 'fmc']
self.rsoVarList = ['csfi', 'sfc']
self.cfbVarList = ['cfros', 'rso']
self.cfcVarList = ['cfb', 'cfl']
self.cfiVarList = ['cfros', 'cfc']
# CFFBPS Canopy Base Height & Canopy Fuel Load Lookup Table (cbh, cfl, ht)
self.fbpCBH_CFL_HT_LUT = {
1: (2, 0.75, 10),
2: (3, 0.8, 7),
3: (8, 1.15, 18),
4: (4, 1.2, 10),
5: (18, 1.2, 25),
6: (7, 1.8, 14),
7: (10, 0.5, 20),
8: (0, 0, 0),
9: (0, 0, 0),
10: (6, 0.8, 13),
11: (6, 0.8, 13),
12: (6, 0.8, 8),
13: (6, 0.8, 8),
14: (0, 0, 0),
15: (0, 0, 0),
16: (0, 0, 0),
17: (0, 0, 0),
18: (0, 0, 0)
}
# CFFBPS Surface Fire Rate of Spread Parameters (a, b, c, q, BUI0, be_max)
self.rosParams = {
1: (90, 0.0649, 4.5, 0.9, 72, 1.076), # C-1
2: (110, 0.0282, 1.5, 0.7, 64, 1.321), # C-2
3: (110, 0.0444, 3, 0.75, 62, 1.261), # C-3
4: (110, 0.0293, 1.5, 0.8, 66, 1.184), # C-4
5: (30, 0.0697, 4, 0.8, 56, 1.220), # C-5
6: (30, 0.08, 3, 0.8, 62, 1.197), # C-6
7: (45, 0.0305, 2, 0.85, 106, 1.134), # C-7
8: (30, 0.0232, 1.6, 0.9, 32, 1.179), # D-1
9: (30, 0.0232, 1.6, 0.9, 32, 1.179), # D-2
10: (0.8, 50, 1.250), # M-1
11: (0.8, 50, 1.250), # M-2
12: (120, 0.0572, 1.4, 0.8, 50, 1.250), # M-3
13: (100, 0.0404, 1.48, 0.8, 50, 1.250), # M-4
14: (190, 0.0310, 1.4, 1, None, 1), # O-1a
15: (250, 0.0350, 1.7, 1, None, 1), # O-1b
16: (75, 0.0297, 1.3, 0.75, 38, 1.460), # S-1
17: (40, 0.0438, 1.7, 0.75, 63, 1.256), # S-2
18: (55, 0.0829, 3.2, 0.75, 31, 1.590) # S-3
}
def _checkArray(self) -> None:
"""
Function to check if any of the input parameters are CuPy arrays and handle them.
:return: None
"""
# ### CHECK FOR CUPY ARRAYS IN INPUT PARAMETERS
input_list = [
self.fuel_type, self.lat, self.long,
self.elevation, self.slope, self.aspect,
self.ws, self.wd, self.ffmc, self.bui,
self.pc, self.pdf,
self.gfl, self.gcf
]
# Check if any inputs are CuPy arrays
if any(isinstance(data, cp.ndarray) for data in input_list):
self.return_array = True
# Get indices of input parameters that are CuPy arrays
array_indices = [i for i in range(len(input_list)) if isinstance(input_list[i], cp.ndarray)]
# If more than one array, verify they are all the same shape
if len(array_indices) > 1:
# Extract arrays
arrays = itemgetter(*array_indices)(input_list)
if isinstance(arrays, cp.ndarray): # Single array case
arrays = [arrays]
# Verify all arrays have the same shape
shapes = {arr.shape for arr in arrays}
if len(shapes) > 1:
raise ValueError(f'All arrays must have the same dimensions. '
f'The following range of dimensions exists: {shapes}')
# Get the first input array
first_array = input_list[array_indices[0]]
# Handle conversion of string-based fuel types
if (array_indices[0] == 0) and ('<U' in str(first_array.dtype)):
# Convert string representations to numeric codes
convert_to_numeric = cp.vectorize(fbpFTCode_AlphaToNum_LUT.get)
converted_fuel_type = convert_to_numeric(self.fuel_type)
if None in converted_fuel_type:
raise ValueError('Unknown fuel type code found, conversion failed.')
self.fuel_type = converted_fuel_type.astype(cp.float32)
first_array = self.fuel_type
# Create reference arrays with manual masking
mask = cp.isnan(first_array)
self.ref_array = cp.where(mask, cp.nan, cp.full(first_array.shape, 0, dtype=cp.float32))
self.ref_array_nan = cp.where(mask, cp.nan, cp.full(first_array.shape, cp.nan, dtype=cp.float32))
else:
# Single array case, still set ref_array and ref_array_nan
first_array = input_list[array_indices[0]]
mask = cp.isnan(first_array)
self.ref_array = cp.where(mask, cp.nan, 0).astype(cp.float32)
self.ref_array_nan = cp.where(mask, cp.nan, cp.nan).astype(cp.float32)
else:
self.return_array = False
# Default ref_array and ref_array_nan for scalar inputs
fuel_type = self.fuel_type
if isinstance(fuel_type, np.ndarray):
if '<U' in str(self.fuel_type.dtype):
# Convert using np.vectorize
convert_to_numeric = np.vectorize(fbpFTCode_AlphaToNum_LUT.get)
fuel_type = convert_to_numeric(fuel_type).astype(np.uint16)
elif isinstance(fuel_type, str):
fuel_type = fbpFTCode_AlphaToNum_LUT.get(self.fuel_type)
mask = cp.isnan(cp.array([fuel_type], dtype=cp.float32))
self.ref_array = cp.where(mask, 0, cp.array([fuel_type], dtype=cp.float32))
self.ref_array_nan = cp.where(mask, cp.nan, cp.array([fuel_type], dtype=cp.float32))
return
def _verifyInputs(self) -> None:
"""
Function to verify and convert input parameters to CuPy arrays.
"""
# Verify fuel_type
if not isinstance(self.fuel_type, (int, str, cp.ndarray)):
raise TypeError('fuel_type must be an int, string, or CuPy ndarray')
elif isinstance(self.fuel_type, cp.ndarray):
if self.fuel_type.dtype.kind == 'U': # Check if it's a string array
convert_to_numeric = cp.vectorize(fbpFTCode_AlphaToNum_LUT.get)
self.fuel_type = convert_to_numeric(self.fuel_type).astype(cp.uint16)
self.fuel_type = cp.asarray(self.fuel_type, dtype=cp.float32)
elif isinstance(self.fuel_type, str):
self.fuel_type = cp.asarray([fbpFTCode_AlphaToNum_LUT.get(self.fuel_type)], dtype=cp.float32)
else:
self.fuel_type = cp.asarray([self.fuel_type], dtype=cp.float32)
# Convert from cffdrs R fuel type grid codes to the grid codes used in this module
if self.convert_fuel_type_codes:
self.fuel_type = convert_grid_codes(self.fuel_type)
# Verify wx_date
if not isinstance(self.wx_date, int):
raise TypeError('wx_date must be an int')
try:
date_string = str(self.wx_date)
dt.strptime(f'{date_string[:4]}-{date_string[4:6]}-{date_string[6:]}', '%Y-%m-%d')
except ValueError:
raise ValueError('wx_date must be formatted as: YYYYMMDD')
# Verify lat and long
for attr in ['lat', 'long']:
value = getattr(self, attr)
if not isinstance(value, (int, float, cp.ndarray)):
raise TypeError(f'{attr} must be an int, float, or CuPy ndarray')
setattr(self, attr, cp.asarray(value, dtype=cp.float32))
# Verify other numeric inputs
for attr in ['elevation', 'slope', 'aspect', 'ws', 'wd', 'ffmc', 'bui']:
value = getattr(self, attr)
if not isinstance(value, (int, float, cp.ndarray)):
raise TypeError(f'{attr} must be an int, float, or CuPy ndarray')
setattr(self, attr, cp.asarray(value, dtype=cp.float32))
# Verify optional inputs
for attr, default in [('pc', 50), ('pdf', 35), ('gfl', 0.35), ('gcf', 80)]:
value = getattr(self, attr, default)
if value is None:
value = default
if not isinstance(value, (int, float, cp.ndarray)):
raise TypeError(f'{attr} must be an int, float, or CuPy ndarray')
setattr(self, attr, cp.asarray(value, dtype=cp.float32))
def initialize(self,
fuel_type: Union[int, str, cp.ndarray] = None,
wx_date: int = None,
lat: Union[float, int, cp.ndarray] = None,
long: Union[float, int, cp.ndarray] = None,
elevation: Union[float, int, cp.ndarray] = None,
slope: Union[float, int, cp.ndarray] = None,
aspect: Union[float, int, cp.ndarray] = None,
ws: Union[float, int, cp.ndarray] = None,
wd: Union[float, int, cp.ndarray] = None,
ffmc: Union[float, int, cp.ndarray] = None,
bui: Union[float, int, cp.ndarray] = None,
pc: Optional[Union[float, int, cp.ndarray]] = 50,
pdf: Optional[Union[float, int, cp.ndarray]] = 35,
gfl: Optional[Union[float, int, cp.ndarray]] = 0.35,
gcf: Optional[Union[float, int, cp.ndarray]] = 80,
out_request: Optional[Union[list, tuple]] = None,
convert_fuel_type_codes: Optional[bool] = False) -> None:
"""
Initialize the FBP object with the provided parameters.
:param fuel_type: CFFBPS fuel type (numeric code: 1-20)
Model 1: C-1 fuel type ROS model
Model 2: C-2 fuel type ROS model
Model 3: C-3 fuel type ROS model
Model 4: C-4 fuel type ROS model
Model 5: C-5 fuel type ROS model
Model 6: C-6 fuel type ROS model
Model 7: C-7 fuel type ROS model
Model 8: D-1 fuel type ROS model
Model 9: D-2 fuel type ROS model
Model 10: M-1 fuel type ROS model
Model 11: M-2 fuel type ROS model
Model 12: M-3 fuel type ROS model
Model 13: M-4 fuel type ROS model
Model 14: O-1a fuel type ROS model
Model 15: O-1b fuel type ROS model
Model 16: S-1 fuel type ROS model
Model 17: S-2 fuel type ROS model
Model 18: S-3 fuel type ROS model
Model 19: Non-fuel (NF)
Model 20: Water (WA)
:param wx_date: Date of weather observation (used for fmc calculation) (YYYYMMDD)
:param lat: Latitude of area being modelled (Decimal Degrees, floating point)
:param long: Longitude of area being modelled (Decimal Degrees, floating point)
:param elevation: Elevation of area being modelled (m)
:param slope: Ground slope angle/tilt of area being modelled (%)
:param aspect: Ground slope aspect/azimuth of area being modelled (degrees)
:param ws: Wind speed (km/h @ 10m height)
:param wd: Wind direction (degrees, direction wind is coming from)
:param ffmc: CFFWIS Fine Fuel Moisture Code
:param bui: CFFWIS Buildup Index
:param pc: Percent conifer (%, value from 0-100)
:param pdf: Percent dead fir (%, value from 0-100)
:param gfl: Grass fuel load (kg/m^2)
:param gcf: Grass curing factor (%, value from 0-100)
:param out_request: Tuple or list of CFFBPS output variables
# Default output variables
fire_type = Type of fire predicted to occur (surface, intermittent crown, active crown)
hfros = Head fire rate of spread (m/min)
hfi = head fire intensity (kW/m)
# Weather variables
ws = Observed wind speed (km/h)
wd = Wind azimuth/direction (degrees)
m = Moisture content equivalent of the FFMC (%, value from 0-100+)
fF = Fine fuel moisture function in the ISI
fW = Wind function in the ISI
isi = Final ISI, accounting for wind and slope
# Slope + wind effect variables
a = Rate of spread equation coefficient
b = Rate of spread equation coefficient
c = Rate of spread equation coefficient
RSZ = Surface spread rate with zero wind on level terrain
SF = Slope factor
RSF = spread rate with zero wind, upslope
ISF = ISI, with zero wind upslope
RSI = Initial spread rate without BUI effect
WSE1 = Original slope equivalent wind speed value
WSE2 = New slope equivalent sind speed value for cases where WSE1 > 40 (capped at max of 112.45)
WSE = Slope equivalent wind speed
WSX = Net vectorized wind speed in the x-direction
WSY = Net vectorized wind speed in the y-direction
WSV = (aka: slope-adjusted wind speed) Net vectorized wind speed (km/h)
RAZ = (aka: slope-adjusted wind direction) Net vectorized wind direction (degrees)
# BUI effect variables
q = Proportion of maximum rate of spread at BUI equal to 50
bui0 = Average BUI for each fuel type
BE = Buildup effect on spread rate
be_max = Maximum allowable BE value
# Surface fuel variables
ffc = Estimated forest floor consumption
wfc = Estimated woody fuel consumption
sfc = Estimated total surface fuel consumption
# Foliar moisture content variables
latn = Normalized latitude
d0 = Julian date of minimum foliar moisture content
nd = number of days between modelled fire date and d0
fmc = foliar moisture content
fme = foliar moisture effect
# Critical crown fire threshold variables
csfi = critical intensity (kW/m)
rso = critical rate of spread (m/min)
# Crown fuel parameters
cbh = Height to live crown base (m)
cfb = Crown fraction burned (proportion, value ranging from 0-1)
cfl = Crown fuel load (kg/m^2)
cfc = Crown fuel consumed
:param convert_fuel_type_codes: Convert from CFS cffdrs R fuel type grid codes
to the grid codes used in this module
"""
self.fuel_type = fuel_type
self.wx_date = wx_date
self.lat = lat
self.long = long
self.elevation = elevation
self.slope = slope
self.aspect = aspect
self.ws = ws
self.wd = wd
self.ffmc = ffmc
self.bui = bui
self.pc = pc
self.pdf = pdf
self.gfl = gfl
self.gcf = gcf
self.out_request = out_request
self.convert_fuel_type_codes = convert_fuel_type_codes
# Verify input parameters
self._checkArray()
self._verifyInputs()
# Initialize weather parameters
self.isi = self.ref_array
self.m = self.ref_array
self.fF = self.ref_array
self.fW = self.ref_array
# Initialize slope effect parameters
self.a = self.ref_array
self.b = self.ref_array
self.c = self.ref_array
self.rsz = self.ref_array
self.isz = self.ref_array
self.sf = self.ref_array
self.rsf = self.ref_array
self.isf = self.ref_array
self.rsi = self.ref_array
self.wse1 = self.ref_array
self.wse2 = self.ref_array
self.wse = self.ref_array
self.wsx = self.ref_array
self.wsy = self.ref_array
self.wsv = self.ref_array
self.raz = self.ref_array
# Initialize BUI effect parameters
self.q = self.ref_array
self.bui0 = self.ref_array
self.be = self.ref_array
self.be_max = self.ref_array
# Initialize surface parameters
self.cf = self.ref_array
self.ffc = cp.full_like(self.ref_array, cp.nan, dtype=cp.float32)
self.wfc = cp.full_like(self.ref_array, cp.nan, dtype=cp.float32)
self.sfc = cp.full_like(self.ref_array, cp.nan, dtype=cp.float32)
self.rss = self.ref_array
# Initialize foliar moisture content parameters
self.latn = self.ref_array
self.dj = self.ref_array
self.d0 = self.ref_array
self.nd = self.ref_array
self.fmc = self.ref_array
self.fme = self.ref_array
# Initialize crown and total fuel consumed parameters
self.cbh = self.ref_array
self.csfi = self.ref_array
self.rso = self.ref_array
self.rsc = self.ref_array
self.cfb = self.ref_array
self.cfl = self.ref_array
self.cfc = self.ref_array
self.tfc = self.ref_array
# Initialize the back fire rate of spread parameters
self.bfW = self.ref_array
self.brsi = self.ref_array
self.bisi = self.ref_array
self.bros = self.ref_array
# Initialize default CFFBPS output parameters
self.fire_type = self.ref_array
self.hfros = self.ref_array
self.hfi = self.ref_array
# Initialize other parameters
self.sfros = self.ref_array
self.cfros = self.ref_array
# List of required parameters
required_params = [
'fuel_type', 'wx_date', 'lat', 'long', 'elevation', 'slope', 'aspect', 'ws', 'wd', 'ffmc', 'bui'
]
# Check for missing required parameters
missing_params = [param for param in required_params if getattr(self, param) is None]
if missing_params:
raise ValueError(f"Missing required parameters: {missing_params}")
# Set initialized to True
self.initialized = True
def invertWindAspect(self):
"""
Function to invert/flip wind direction and aspect by 180 degrees using CuPy
:return: None
"""
# Invert wind direction by 180 degrees
self.wd = cp.where(self.wd > 180,
self.wd - 180,
self.wd + 180)
# Invert aspect by 180 degrees
self.aspect = cp.where(self.aspect > 180,
self.aspect - 180,
self.aspect + 180)
return
def calcSF(self) -> None:
"""
Function to calculate the slope factor using CuPy
:return: None
"""
# Calculate the slope factor with CuPy
self.sf = cp.where(self.slope < 70,
cp.exp(3.533 * cp.power((self.slope / 100), 1.2)),
10)
return
def calcISZ(self) -> None:
"""
Function to calculate the initial spread index with no wind/no slope effects.
"""
self.m = (250 * (59.5 / 101) * (101 - self.ffmc)) / (59.5 + self.ffmc)
self.fF = (91.9 * cp.exp(-0.1386 * self.m)) * (1 + (cp.power(self.m, 5.31) / (4.93 * cp.power(10, 7))))
self.isz = 0.208 * self.fF
def calcFMC(self,
lat: Optional[float] = None,
long: Optional[float] = None,
elevation: Optional[float] = None,
wx_date: Optional[int] = None) -> None:
"""
Function to calculate foliar moisture content (FMC) and foliar moisture effect (FME) using CuPy.
:return: None
"""
if lat is not None:
self.lat = lat
if long is not None:
self.long = long
if elevation is not None:
self.elevation = elevation
if wx_date is not None:
self.wx_date = wx_date
# Calculate normalized latitude
self.latn = cp.where((self.elevation is not None) & (self.elevation > 0),
43 + (33.7 * cp.exp(-0.0351 * (150 - cp.abs(self.long)))),
46 + (23.4 * cp.exp(-0.036 * (150 - cp.abs(self.long)))))
# Calculate date of minimum foliar moisture content (D0)
self.d0 = cp.round(cp.where((self.elevation is not None) & (self.elevation > 0),
142.1 * (self.lat / self.latn) + (0.0172 * self.elevation),
151 * (self.lat / self.latn)), 0)
# Calculate Julian date (Dj)
self.dj = cp.where(cp.isfinite(self.latn),
dt.strptime(str(self.wx_date), '%Y%m%d').timetuple().tm_yday,
0)
# Number of days between Dj and D0 (ND)
self.nd = cp.abs(self.dj - self.d0)
# Calculate foliar moisture content (FMC)
self.fmc = cp.where(self.nd < 30,
85 + (0.0189 * (self.nd ** 2)),
cp.where(self.nd < 50,
32.9 + (3.17 * self.nd) - (0.0288 * (self.nd ** 2)),
120))
# Calculate foliar moisture effect (FME)
self.fme = 1000 * cp.power(1.5 - (0.00275 * self.fmc), 4) / (460 + (25.9 * self.fmc))
return
def calcISI_RSI_BE(self, ftype: int) -> None:
"""
Function to calculate the slope-/wind-adjusted Initial Spread Index (ISI),
rate of spread (RSI), and the BUI buildup effect (BE) using CuPy.
:param ftype: The numeric FBP fuel type code.
:return: None
"""
def _calcISI_slopeWind() -> None:
# Calculate the slope equivalent wind speed (for lower wind speeds)
self.wse1 = cp.where(self.fuel_type == ftype,
(1 / 0.05039) * cp.log(self.isf / (0.208 * self.fF)),
self.wse1)
# Calculate the slope equivalent wind speed (for higher wind speeds)
self.wse2 = cp.where(self.fuel_type == ftype,
cp.where(self.isf < (0.999 * 2.496 * self.fF),
28 - (1 / 0.0818) * cp.log(1 - (self.isf / (2.496 * self.fF))),
112.45),
self.wse2)
# Assign slope equivalent wind speed
self.wse = cp.where(self.fuel_type == ftype,
cp.where(self.wse1 <= 40, self.wse1, self.wse2),
self.wse)
# Calculate vector magnitude in x-direction
self.wsx = cp.where(self.fuel_type == ftype,
(self.ws * cp.sin(cp.radians(self.wd))) +
(self.wse * cp.sin(cp.radians(self.aspect))),
self.wsx)
# Calculate vector magnitude in y-direction
self.wsy = cp.where(self.fuel_type == ftype,
(self.ws * cp.cos(cp.radians(self.wd))) +
(self.wse * cp.cos(cp.radians(self.aspect))),
self.wsy)
# Calculate the net effective wind speed
self.wsv = cp.where(self.fuel_type == ftype,
cp.sqrt(cp.power(self.wsx, 2) + cp.power(self.wsy, 2)),
self.wsv)
# Calculate the net effective wind direction (RAZ)
self.raz = cp.where(self.fuel_type == ftype,
cp.where(self.wsx < 0,
360 - cp.degrees(cp.arccos(self.wsy / self.wsv)),
cp.degrees(cp.arccos(self.wsy / self.wsv))),
self.raz)
# Calculate the wind function of the ISI equation
self.fW = cp.where(self.fuel_type == ftype,
cp.where(self.wsv > 40,
12 * (1 - cp.exp(-0.0818 * (self.wsv - 28))),
cp.exp(0.05039 * self.wsv)),
self.fW)
# Calculate the new ISI with slope and wind effects
self.isi = cp.where(self.fuel_type == ftype,
0.208 * self.fW * self.fF,
self.isi)
# Calculate the back fire wind function
self.bfW = cp.where(self.fuel_type == ftype,
cp.exp(-0.05039 * self.wsv),
self.bfW)
# Calculate the ISI associated with the back fire rate of spread
self.bisi = self.bfW * self.fF * 0.208
# Ensure all self attributes are CuPy arrays
self.fuel_type = cp.asarray(self.fuel_type)
self.isf = cp.asarray(self.isf)
self.fF = cp.asarray(self.fF)
self.ws = cp.asarray(self.ws)
self.wd = cp.asarray(self.wd)
self.aspect = cp.asarray(self.aspect)
# ### CFFBPS ROS models
if ftype not in [10, 11]:
# Get fuel type-specific fixed rate of spread parameters
self.a, self.b, self.c, self.q, self.bui0, self.be_max = self.rosParams[ftype]
if ftype in [14, 15]:
# ## Process O-1a/b fuel types...
self.cf = cp.where(
self.fuel_type == ftype,
cp.where(self.gcf < 58.8,
0.005 * (cp.exp(0.061 * self.gcf) - 1),
0.176 + (0.02 * (self.gcf - 58.8))),
self.cf
)
# Calculate no slope/no wind rate of spread
self.rsz = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.isz), self.c) * self.cf,
self.rsz
)
# Calculate rate of spread with slope effect
self.rsf = cp.where(
self.fuel_type == ftype,
self.rsz * self.sf,
self.rsf
)
# Calculate initial spread index with slope effect
self.isf = cp.where(
self.fuel_type == ftype,
cp.where(
1 - cp.power(self.rsf / (self.cf * self.a), 1 / self.c) >= 0.01,
cp.log(1 - cp.power(self.rsf / (self.cf * self.a), 1 / self.c)) / -self.b,
cp.log(0.01) / -self.b
),
self.isf
)
# Calculate slope effects on wind and ISI
_calcISI_slopeWind()
# Calculate head fire rate of spread with slope and wind effects
self.rsi = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.isi), self.c) * self.cf,
self.rsi
)
# Calculate back fire rate of spread with slope and wind effects
self.brsi = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.bisi), self.c) * self.cf,
self.brsi
)
# Calculate Buildup Effect (BE)
self.be = cp.where(
self.fuel_type == ftype,
1,
self.be
)
elif ftype in [12, 13]:
# ## Process M-3/4 fuel types...
if ftype == 12:
# Get D1 parameters
a_d1_2, b_d1_2, c_d1_2, q_d1_2, bui0_d1_2, be_max_d1_2 = self.rosParams[8]
else:
# Get D2 parameters (technically the same as D1)
a_d1_2, b_d1_2, c_d1_2, q_d1_2, bui0_d1_2, be_max_d1_2 = self.rosParams[9]
# Get RSZ and ISF
rsz_d1_2 = cp.where(
self.fuel_type == ftype,
a_d1_2 * cp.power(1 - cp.exp(-b_d1_2 * self.isz), c_d1_2),
0
)
rsf_d1_2 = cp.where(
self.fuel_type == ftype,
rsz_d1_2 * self.sf,
0
)
isf_d1_2 = cp.where(
self.fuel_type == ftype,
cp.where(
(1 - cp.power(rsf_d1_2 / a_d1_2, 1 / c_d1_2)) >= 0.01,
cp.log(1 - cp.power(rsf_d1_2 / a_d1_2, 1 / c_d1_2)) / -b_d1_2,
cp.log(0.01) / -b_d1_2
),
0
)
# Calculate no slope/no wind rate of spread
self.rsz = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.isz), self.c),
self.rsz
)
# Calculate rate of spread with slope effect (no wind)
self.rsf = cp.where(
self.fuel_type == ftype,
self.rsz * self.sf,
self.rsf
)
# Calculate initial spread index with slope effect (no wind)
self.isf = cp.where(
self.fuel_type == ftype,
cp.where(
(1 - cp.power(self.rsf / self.a, 1 / self.c)) >= 0.01,
(self.pdf / 100) * (cp.log(1 - cp.power(self.rsf / self.a, 1 / self.c)) / -self.b) +
(1 - self.pdf / 100) * isf_d1_2,
cp.log(0.01) / -self.b
),
self.isf
)
# Calculate slope effects on wind and ISI
_calcISI_slopeWind()
# Calculate head fire rate of spread with slope and wind effects for D1
rsi_d1 = cp.where(
self.fuel_type == ftype,
a_d1_2 * cp.power(1 - cp.exp(-b_d1_2 * self.isi), c_d1_2),
0
)
# Calculate back fire rate of spread with slope and wind effects for D1
brsi_d1 = cp.where(
self.fuel_type == ftype,
a_d1_2 * cp.power(1 - cp.exp(-b_d1_2 * self.bisi), c_d1_2),
0
)
# Calculate rate of spread with slope and wind effects
if ftype == 13:
# D1 Fuel Type Head Fire RSI
self.rsi = cp.where(
self.fuel_type == ftype,
((self.pdf / 100) * self.a * cp.power(1 - cp.exp(-self.b * self.isi), self.c) +
(1 - self.pdf / 100) * rsi_d1),
self.rsi
)
# D1 Fuel Type Back Fire RSI
self.brsi = cp.where(
self.fuel_type == ftype,
((self.pdf / 100) * self.a * cp.power(1 - cp.exp(-self.b * self.bisi), self.c) +
(1 - self.pdf / 100) * brsi_d1),
self.brsi
)
else:
# D2 Fuel Type Head Fire RSI
self.rsi = cp.where(
self.fuel_type == ftype,
((self.pdf / 100) * self.a * cp.power(1 - cp.exp(-self.b * self.isi), self.c) +
0.2 * (1 - self.pdf / 100) * rsi_d1),
self.rsi
)
# D2 Fuel Type Back Fire RSI
self.brsi = cp.where(
self.fuel_type == ftype,
((self.pdf / 100) * self.a * cp.power(1 - cp.exp(-self.b * self.bisi), self.c) +
0.2 * (1 - self.pdf / 100) * brsi_d1),
self.brsi
)
# Calculate Buildup Effect (BE)
self.be = cp.where(
self.fuel_type == ftype,
cp.where(
self.bui == 0,
0,
cp.exp(50 * cp.log(self.q) * ((1 / self.bui) - (1 / self.bui0)))
),
self.be
)
else:
# ## Process all other fuel types...
# Calculate no slope/no wind rate of spread
self.rsz = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.isz), self.c),
self.rsz
)
# Calculate rate of spread with slope effect
self.rsf = cp.where(
self.fuel_type == ftype,
self.rsz * self.sf,
self.rsf
)
# Calculate initial spread index with slope effect
isf_numer = cp.where(
self.fuel_type == ftype,
(1 - cp.power(self.rsf / self.a, 1 / self.c)),
0
)
np.seterr(divide='ignore') # Suppress divide warnings for log
self.isf = cp.where(
self.fuel_type == ftype,
cp.where(
isf_numer >= 0.01,
cp.log(isf_numer) / -self.b,
cp.log(0.01) / -self.b
),
self.isf
)
np.seterr(divide='warn') # Restore divide warnings
# Calculate slope effects on wind and ISI
_calcISI_slopeWind()
# Calculate head fire rate of spread with slope and wind effects
self.rsi = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.isi), self.c),
self.rsi
)
# Calculate back fire rate of spread with slope and wind effects
self.brsi = cp.where(
self.fuel_type == ftype,
self.a * cp.power(1 - cp.exp(-self.b * self.bisi), self.c),
self.brsi
)