-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcffbps.py
More file actions
2352 lines (2036 loc) · 98.3 KB
/
cffbps.py
File metadata and controls
2352 lines (2036 loc) · 98.3 KB
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 -*-
"""
Created on Mon July 22 10:00:00 2024
@author: Gregory A. Greene
"""
__author__ = ['Gregory A. Greene, map.n.trowel@gmail.com']
import os
from typing import Union, Optional
from operator import itemgetter
import numpy as np
from numpy import ma as mask
from scipy.stats import t
from datetime import datetime as dt
from multiprocessing import current_process, Pool
import psutil
# CFFBPS Fuel Type Numeric-Alphanumeric Code Lookup Table
fbpFTCode_NumToAlpha_LUT = {
1: 'C1', # C-1
2: 'C2', # C-2
3: 'C3', # C-3
4: 'C4', # C-4
5: 'C5', # C-5
6: 'C6', # C-6
7: 'C7', # C-7
8: 'D1', # D-1
9: 'D2', # D-2
10: 'M1', # M-1
11: 'M2', # M-2
12: 'M3', # M-3
13: 'M4', # M-4
14: 'O1a', # O-1a
15: 'O1b', # O-1b
16: 'S1', # S-1
17: 'S2', # S-2
18: 'S3', # S-3
19: 'NF', # NF (non-fuel)
20: 'WA' # WA (water)
}
# CFFBPS Fuel Type Alphanumeric-Numeric Code Lookup Table
fbpFTCode_AlphaToNum_LUT = {
'C1': 1, # C-1
'C2': 2, # C-2
'C3': 3, # C-3
'C4': 4, # C-4
'C5': 5, # C-5
'C6': 6, # C-6
'C7': 7, # C-7
'D1': 8, # D-1
'D2': 9, # D-2
'M1': 10, # M-1
'M2': 11, # M-2
'M3': 12, # M-3
'M4': 13, # M-4
'O1a': 14, # O-1a
'O1b': 15, # O-1b
'S1': 16, # S-1
'S2': 17, # S-2
'S3': 18, # S-3
'NF': 19, # NF (non-fuel)
'WA': 20, # WA (water)
}
# List of valid CFFBPS output parameters
valid_outputs = [
'fire_type', 'hros', 'hfi', 'fuel_type', 'ws', 'wd', 'm', 'fF', 'fW', 'ffmc', 'bui', 'isi',
'a', 'b', 'c', 'rsz', 'sf', 'rsf', 'isf', 'rsi', 'wse1', 'wse2', 'wse', 'wsx', 'wsy', 'wsv', 'raz',
'q', 'bui0', 'be', 'be_max', 'ffc', 'wfc', 'sfc', 'latn', 'dj', 'd0', 'nd', 'fmc', 'fme',
'csfi', 'rso', 'bfw', 'bisi', 'bros', 'sros', 'cros', 'cbh', 'cfb', 'cfl', 'cfc', 'tfc', 'accel', 'fi_class'
]
def convert_grid_codes(fuel_type_array: np.ndarray) -> np.ndarray:
"""
Function to convert grid code values from the cffdrs_r R package fuel type codes
to the codes used in this module.
:param fuel_type_array: CFFBPS fuel type array, containing the CFS cffdrs R version of grid codes
:return: modified fuel_type_array
"""
fuel_type_array = mask.where(
fuel_type_array == 19, 20,
mask.where(
fuel_type_array == 13, 19,
mask.where(
fuel_type_array == 12, 13,
mask.where(
fuel_type_array == 11, 12,
mask.where(
fuel_type_array == 10, 11,
mask.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)
##################################################################################################
# #### CLASS FOR CANADIAN FOREST FIRE BEHAVIOR PREDICTION SYSTEM (CFFBPS) MODELLING ####
##################################################################################################
class FBP:
"""
Class to model fire behavior with the Canadian Forest Fire Behavior Prediction System.
"""
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.d0 = None
self.dj = None
self.out_request = None
self.convert_fuel_type_codes = False
self.percentile_growth = None
# Array verification parameter
self.return_array = None
self.ref_array = None
self.initialized = False
# Initialize multiprocessing block variable
self.block = None
# Initialize unique fuel types list
self.ftypes = 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.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 backing 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.hros = None
self.hfi = None
# Initialize C-6 rate of spread parameters
self.sros = None
self.cros = None
# Initialize point ignition acceleration parameter
self.accel_param = None
# Initialize fire intensity class parameter
self.fi_class = None
# ### Lists for CFFBPS Crown Fire Metric variables
self.csfiVarList = ['cbh', 'fmc']
self.rsoVarList = ['csfi', 'sfc']
self.cfbVarList = ['cros', 'rso']
self.cfcVarList = ['cfb', 'cfl']
self.cfiVarList = ['cros', 'cfc']
# List of open fuel type codes
self.open_fuel_types = [1, 7, 9, 14, 15, 16, 17, 18]
# List of non-crowning fuel type codes
self.non_crowning_fuels = [8, 9, 14, 15, 16, 17, 18]
# 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),
19: (None, None, None),
20: (None, None, None),
}
# 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: (None, None, None, 0.8, 50, 1.250), # M-1
11: (None, None, None, 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 numpy arrays.
:return: None
"""
# ### CHECK FOR NUMPY 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
]
if any(isinstance(data, np.ndarray) for data in input_list):
self.return_array = True
# Get indices of input parameters that are arrays
array_indices = [i for i in range(len(input_list)) if isinstance(input_list[i], np.ndarray)]
# If more than one array, verify they are all the same shape
if len(array_indices) > 1:
# Verify all arrays have the same shape
arrays = itemgetter(*array_indices)(input_list)
# Ensure the result is a list
if isinstance(arrays, np.ndarray): # Single array case
arrays = [arrays]
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 first input array as a masked array
first_array = input_list[array_indices[0]]
if (array_indices[0] == 0) and ('<U' in str(first_array.dtype)):
# Convert the string representations to numeric codes using the lookup table
convert_to_numeric = np.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.')
first_array = converted_fuel_type.astype(np.int8)
self.ref_array = mask.array(
np.full(first_array.shape, 0, dtype=np.float64),
mask=np.isnan([first_array]),
fill_value=np.nan
)
self.ref_int_array = mask.array(
np.full(first_array.shape, 0, dtype=np.int8),
mask=-99
)
else:
self.return_array = False
# Get first input parameter array as a masked array
self.ref_array = mask.array(
np.array([0.0], dtype=np.float64),
mask=False,
fill_value=np.nan
)
self.ref_int_array = mask.array([0], mask=-99).astype(np.int8)
return
def _verifyInputs(self) -> None:
"""
Function to check if any of the input parameters are numpy arrays.
:return: None
"""
# ### VERIFY ALL INPUTS AND CONVERT TO MASKED NUMPY ARRAYS
# Verify fuel_type
if not isinstance(self.fuel_type, (int, str, np.ndarray)):
raise TypeError('fuel_type must be either int, string, or numpy ndarray data types')
elif isinstance(self.fuel_type, np.ndarray):
if '<U' in str(self.fuel_type.dtype):
invalid_value = np.int8(-128) # Define an explicit invalid value
# Convert using np.vectorize and replace unknown fuel types with invalid_value
convert_to_numeric = np.vectorize(lambda x: fbpFTCode_AlphaToNum_LUT.get(x, invalid_value))
self.fuel_type = convert_to_numeric(self.fuel_type).astype(np.int8)
if self.fuel_type.dtype != np.int8:
self.fuel_type = np.asarray(self.fuel_type, dtype=np.int8)
self.fuel_type = mask.array(self.fuel_type, mask=np.isnan(self.fuel_type))
elif isinstance(self.fuel_type, str):
self.fuel_type = mask.array([fbpFTCode_AlphaToNum_LUT.get(self.fuel_type)],
mask=np.isnan([fbpFTCode_AlphaToNum_LUT.get(self.fuel_type)]))
else:
self.fuel_type = mask.array([self.fuel_type], mask=np.isnan([self.fuel_type]))
# 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)
# Apply an additional mask to exclude invalid fuel types (valid range: 1-20)
valid_fuel_types = np.arange(1, 21, dtype=np.int8)
current_mask = np.ma.getmaskarray(self.fuel_type)
invalid_mask = ~np.isin(self.fuel_type.data, valid_fuel_types)
self.fuel_type = mask.array(self.fuel_type.data, mask=(current_mask | invalid_mask))
# Get unique fuel types present in the dataset
self.ftypes = [ftype for ftype in np.unique(self.fuel_type) if ftype in list(self.rosParams.keys())]
# Verify wx_date
if not isinstance(self.wx_date, int):
raise TypeError('wx_date must be int data type')
try:
date_string = str(self.wx_date)
dt.fromisoformat(f'{date_string[:4]}-{date_string[4:6]}-{date_string[6:]}')
except ValueError:
raise ValueError('wx_date must be formatted as: YYYYMMDD')
# Verify lat
if not isinstance(self.lat, (int, float, np.ndarray)):
raise TypeError('lat must be either int, float, or numpy ndarray data types')
elif isinstance(self.lat, np.ndarray):
self.lat = mask.array(self.lat, mask=np.isnan(self.lat))
else:
self.lat = mask.array([self.lat], mask=np.isnan([self.lat]))
# Verify long
if not isinstance(self.long, (int, float, np.ndarray)):
raise TypeError('long must be either int, float, or numpy ndarray data types')
elif isinstance(self.long, np.ndarray):
self.long = mask.array(self.long, mask=np.isnan(self.long))
else:
self.long = mask.array([self.long], mask=np.isnan([self.long]))
# Get absolute longitude values
self.long = np.absolute(self.long)
# Verify elevation
if not isinstance(self.elevation, (int, float, np.ndarray)):
raise TypeError('elevation must be either int, float, or numpy ndarray data types')
elif isinstance(self.elevation, np.ndarray):
self.elevation = mask.array(self.elevation, mask=np.isnan(self.elevation))
else:
self.elevation = mask.array([self.elevation], mask=np.isnan([self.elevation]))
# Verify slope
if not isinstance(self.slope, (int, float, np.ndarray)):
raise TypeError('slope must be either int, float, or numpy ndarray data types')
elif isinstance(self.slope, np.ndarray):
self.slope = mask.array(self.slope, mask=np.isnan(self.slope))
else:
self.slope = mask.array([self.slope], mask=np.isnan([self.slope]))
# Limit the lower slope value to 0
self.slope = mask.clip(self.slope, 0, None)
# Verify aspect
if not isinstance(self.aspect, (int, float, np.ndarray)):
raise TypeError('aspect must be either int, float, or numpy ndarray data types')
elif isinstance(self.aspect, np.ndarray):
self.aspect = mask.array(self.aspect, mask=np.isnan(self.aspect))
else:
self.aspect = mask.array([self.aspect], mask=np.isnan([self.aspect]))
# Set negative values to 270 degrees (assuming the represent "flat" terrain)
self.aspect = mask.where(self.aspect < 0, 270, self.aspect)
# Verify ws
if not isinstance(self.ws, (int, float, np.ndarray)):
raise TypeError('ws must be either int, float, or numpy ndarray data types')
elif isinstance(self.ws, np.ndarray):
self.ws = mask.array(self.ws, mask=np.isnan(self.ws))
else:
self.ws = mask.array([self.ws], mask=np.isnan([self.ws]))
self.ws = mask.where(self.ws < 0, 0, self.ws) # Set to 0 if negative
# Verify wd
if not isinstance(self.wd, (int, float, np.ndarray)):
raise TypeError('wd must be either int, float, or numpy ndarray data types')
elif isinstance(self.wd, np.ndarray):
self.wd = mask.array(self.wd, mask=np.isnan(self.wd))
else:
self.wd = mask.array([self.wd], mask=np.isnan([self.wd]))
# Verify ffmc
if not isinstance(self.ffmc, (int, float, np.ndarray)):
raise TypeError('ffmc must be either int, float, or numpy ndarray data types')
elif isinstance(self.ffmc, np.ndarray):
self.ffmc = mask.array(self.ffmc, mask=np.isnan(self.ffmc))
else:
self.ffmc = mask.array([self.ffmc], mask=np.isnan([self.ffmc]))
self.ffmc = mask.where(self.ffmc < 0, 0, self.ffmc) # Set to 0 if negative
# Verify bui
if not isinstance(self.bui, (int, float, np.ndarray)):
raise TypeError('bui must be either int, float, or numpy ndarray data types')
elif isinstance(self.bui, np.ndarray):
self.bui = mask.array(self.bui, mask=np.isnan(self.bui))
else:
self.bui = mask.array([self.bui], mask=np.isnan([self.bui]))
self.bui = mask.where(self.bui < 0, 0, self.bui) # Set to 0 if negative
# Verify pc
if not isinstance(self.pc, (int, float, np.ndarray)):
raise TypeError('pc must be either int, float, or numpy ndarray data types')
elif isinstance(self.pc, np.ndarray):
self.pc = mask.array(self.pc, mask=np.isnan(self.pc))
else:
if np.isnan(self.pc):
self.pc = 50 # Default to 50% if NaN
self.pc = mask.array([self.pc])
self.pc = mask.where(self.pc < 0, 0, self.pc) # Set to 0 if negative
# Verify pdf
if not isinstance(self.pdf, (int, float, np.ndarray)):
raise TypeError('pdf must be either int, float, or numpy ndarray data types')
elif isinstance(self.pdf, np.ndarray):
self.pdf = mask.array(self.pdf, mask=np.isnan(self.pdf))
else:
if np.isnan(self.pdf):
self.pdf = 35 # Default to 35% if NaN
self.pdf = mask.array([self.pdf])
self.pdf = mask.where(self.pdf < 0, 0, self.pdf) # Set to 0 if negative
# Verify gfl
if not isinstance(self.gfl, (int, float, np.ndarray)):
raise TypeError('gfl must be either int, float, or numpy ndarray data types')
elif isinstance(self.gfl, np.ndarray):
self.gfl = mask.array(self.gfl, mask=np.isnan(self.gfl))
else:
if np.isnan(self.gfl):
self.gfl = 0.35 # Default to 0.35 kg/m2 if NaN
self.gfl = mask.array([self.gfl])
self.gfl = mask.where(self.gfl < 0, 0, self.gfl) # Set to 0 if negative
# Verify gcf
if not isinstance(self.gcf, (int, float, np.ndarray)):
raise TypeError('gcf must be either int, float, or numpy ndarray data types')
elif isinstance(self.gcf, np.ndarray):
self.gcf = mask.array(self.gcf, mask=np.isnan(self.gcf))
else:
if np.isnan(self.gcf):
self.gcf = 80 # Default to 80% if NaN
self.gcf = mask.array([self.gcf])
self.gcf = mask.where(self.gcf == 0, 0.1, self.gcf) # Set to 0.1% if 0%
# Verify d0
if self.d0 is not None:
if not isinstance(self.d0, int):
raise TypeError('d0 must be int data type')
else:
self.d0 = mask.array([self.d0], mask=np.isnan([self.d0]))
# Verify dj
if self.dj is not None:
if not isinstance(self.dj, int):
raise TypeError('dj must be int data type')
else:
self.dj = mask.array([self.dj], mask=np.isnan([self.dj]))
# Verify out_request
if not isinstance(self.out_request, (list, tuple, type(None))):
raise TypeError('out_request must be a list, tuple, or None')
def initialize(self,
fuel_type: Union[int, str, np.ndarray] = None,
wx_date: Optional[int] = None,
lat: Union[float, int, np.ndarray] = None,
long: Union[float, int, np.ndarray] = None,
elevation: Union[float, int, np.ndarray] = None,
slope: Union[float, int, np.ndarray] = None,
aspect: Union[float, int, np.ndarray] = None,
ws: Union[float, int, np.ndarray] = None,
wd: Union[float, int, np.ndarray] = None,
ffmc: Union[float, int, np.ndarray] = None,
bui: Union[float, int, np.ndarray] = None,
pc: Optional[Union[float, int, np.ndarray]] = 50,
pdf: Optional[Union[float, int, np.ndarray]] = 35,
gfl: Optional[Union[float, int, np.ndarray]] = 0.35,
gcf: Optional[Union[float, int, np.ndarray]] = 80,
d0: Optional[Union[int, None]] = None,
dj: Optional[Union[int, None]] = None,
out_request: Optional[Union[list, tuple]] = None,
convert_fuel_type_codes: Optional[bool] = False,
percentile_growth: Optional[Union[float, int]] = 50) -> 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 d0: Julian date of minimum foliar moisture content (if None, it will be calculated based on latitude)
:param dj: Julian date of modelled fire (if None, it will be calculated from wx_date)
: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)
hros = 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
ffmc = Fine Fuel Moisture Code
bui = Buildup Index
isi = Final calculated 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 wind 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
# Backing fire rate of spread variables
bfW = backing fire wind speed component (km/h)
brsi = backing fire spread rate without BUI effect (m/min)
bisi = backing fire ISI without BUI effect
bros = backing fire rate of spread (m/min)
# 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 (kg/m^2)
# Final fuel parameters
tfc = Total fuel consumed
# Acceleration parameter
accel = Acceleration parameter for point source ignition
# Fire Intensity Class parameter
fi_class = Fire intensity class (1-6)
:param convert_fuel_type_codes: Convert from CFS cffdrs R fuel type grid codes
to the grid codes used in this module
:param percentile_growth: The ROS percentile growth (0-100) for the fire growth model
"""
# Initialize CFFBPS input parameters
self.fuel_type = fuel_type
self.wx_date = wx_date # For FMC calculations
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.d0 = d0 # For FMC calculations
self.dj = dj # For FMC calculations
self.out_request = out_request
self.convert_fuel_type_codes = convert_fuel_type_codes
self.percentile_growth = percentile_growth
# Verify input parameters
self._checkArray()
self._verifyInputs()
# Initialize weather parameters
self.isi = self.ref_array.copy()
self.m = self.ref_array.copy()
self.fF = self.ref_array.copy()
self.fW = self.ref_array.copy()
# Initialize slope effect parameters
self.a = self.ref_array.copy()
self.b = self.ref_array.copy()
self.c = self.ref_array.copy()
self.rsz = self.ref_array.copy()
self.isz = self.ref_array.copy()
self.sf = self.ref_array.copy()
self.rsf = self.ref_array.copy()
self.isf = self.ref_array.copy()
self.rsi = self.ref_array.copy()
self.wse1 = self.ref_array.copy()
self.wse2 = self.ref_array.copy()
self.wse = self.ref_array.copy()
self.wsx = self.ref_array.copy()
self.wsy = self.ref_array.copy()
self.wsv = self.ref_array.copy()
self.raz = self.ref_array.copy()
# Initialize BUI effect parameters
self.q = self.ref_array.copy()
self.bui0 = self.ref_array.copy()
self.be = self.ref_array.copy()
self.be_max = self.ref_array.copy()
# Initialize surface parameters
self.cf = self.ref_array.copy()
self.ffc = np.full_like(self.ref_array, np.nan, dtype=np.float64)
self.wfc = np.full_like(self.ref_array, np.nan, dtype=np.float64)
self.sfc = np.full_like(self.ref_array, np.nan, dtype=np.float64)
self.rss = self.ref_array.copy()
# Initialize foliar moisture content parameters
self.latn = self.ref_array.copy()
self.nd = self.ref_array.copy()
self.fmc = self.ref_array.copy()
self.fme = self.ref_array.copy()
# Initialize crown and total fuel consumed parameters
self.cbh = self.ref_array.copy()
self.csfi = self.ref_array.copy()
self.rso = self.ref_array.copy()
self.rsc = self.ref_array.copy()
self.cfb = self.ref_array.copy()
self.cfl = self.ref_array.copy()
self.cfc = self.ref_array.copy()
self.tfc = self.ref_array.copy()
# Initialize the backing fire rate of spread parameters
self.bfW = self.ref_array.copy()
self.brsi = self.ref_array.copy()
self.bisi = self.ref_array.copy()
self.bros = self.ref_array.copy()
# Initialize default CFFBPS output parameters
self.fire_type = self.ref_array.copy()
self.hros = self.ref_array.copy()
self.hfi = self.ref_array.copy()
# Initialize C-6 rate of spread parameters
self.sros = self.ref_array.copy()
self.cros = self.ref_array.copy()
# Initialize point ignition acceleration parameter
self.accel_param = self.ref_array.copy()
# Initialize fire intensity class parameter
self.fi_class = self.ref_int_array.copy()
# 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
return
def invertWindAspect(self):
"""
Function to invert/flip wind direction and aspect by 180 degrees
:return: None
"""
# Invert wind direction by 180 degrees
self.wd = mask.where(self.wd > 180,
self.wd - 180,
self.wd + 180)
# Invert aspect by 180 degrees
self.aspect = mask.where(self.aspect > 180,
self.aspect - 180,
self.aspect + 180)
return
def calcSF(self) -> None:
"""
Function to calculate the slope factor
:return: None
"""
self.sf = mask.where(self.slope < 70,
np.exp(3.533 * np.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
:return: None
"""
with np.errstate(invalid='ignore'):
# Calculate fine fuel moisture content in percent (default CFFBPS equation)
self.m = (250 * (59.5 / 101) * (101 - self.ffmc)) / (59.5 + self.ffmc)
# Calculate the FFMC function from ISI equation (fF)
self.fF = (91.9 * np.exp(-0.1386 * self.m)) * (1 + (np.power(self.m, 5.31) / (4.93 * np.power(10, 7))))
# Calculate no slope/no wind Initial Spread Index
self.isz = 0.208 * self.fF
return
def calcFMC(self,
d0: Optional[int] = None,
dj: Optional[int] = None,
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).
: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 = mask.where((self.elevation is not None) & (self.elevation > 0),
43 + (33.7 * np.exp(-0.0351 * (150 - np.abs(self.long)))),
46 + (23.4 * (np.exp(-0.036 * (150 - np.abs(self.long))))))
# D0 calculation
if self.d0 is None:
if d0 is None:
# Calculate date of minimum foliar moisture content (D0)
# This value is rounded to mimic the approach used in the cffdrs R package.
self.d0 = mask.MaskedArray.round(mask.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)
else:
self.d0 = mask.array(d0, mask=np.isnan(d0))
# Julian Date
if self.dj is None:
if dj is None:
# Calculate Julian date (Dj)
self.dj = mask.where(np.isfinite(self.latn),
dt.strptime(str(self.wx_date), '%Y%m%d').timetuple().tm_yday,
0)
else:
self.dj = mask.array(dj, mask=np.isnan(dj))
# Number of days between Dj and D0 (ND)
self.nd = np.absolute(self.dj - self.d0)
# Calculate foliar moisture content (FMC)
self.fmc = mask.where(self.nd < 30,
85 + (0.0189 * (self.nd ** 2)),
mask.where(self.nd < 50,
32.9 + (3.17 * self.nd) - (0.0288 * (self.nd ** 2)),
120))
# Calculate foliar moisture effect (FME)
self.fme = 1000 * np.power(1.5 - (0.00275 * self.fmc), 4) / (460 + (25.9 * self.fmc))
return
def _calcISI_slopeWind_vectorized(self) -> None:
"""
Vectorized slope and wind adjustment function for ISI and RSI.
Uses NumPy masked arrays to compute slope-equivalent wind and directional vectors across all cells.
"""
with np.errstate(invalid='ignore', divide='ignore'):
# Calculate slope-equivalent wind speeds using two formulas
self.wse1 = (1 / 0.05039) * mask.log(self.isf / (0.208 * self.fF))
self.wse2 = mask.where(
self.isf < 0.999 * 2.496 * self.fF,
28 - (1 / 0.0818) * np.log(1 - (self.isf / (2.496 * self.fF))),
112.45 # cap maximum WSE
)
# Assign slope equivalent wind speed
self.wse = mask.where(self.wse1 <= 40, self.wse1, self.wse2)
# Compute directional components for wind and slope
sin_wd = mask.sin(np.radians(self.wd))
cos_wd = mask.cos(np.radians(self.wd))
sin_asp = mask.sin(np.radians(self.aspect))
cos_asp = mask.cos(np.radians(self.aspect))
# Net wind vectors
self.wsx = self.ws * sin_wd + self.wse * sin_asp
self.wsy = self.ws * cos_wd + self.wse * cos_asp
self.wsv = mask.sqrt(self.wsx ** 2 + self.wsy ** 2)
# Wind azimuth calculation (RAZ)
acos_val = mask.clip(self.wsy / self.wsv, -1, 1)
angle_rad = mask.arccos(acos_val)
self.raz = mask.where(
self.wsx < 0,
360 - np.degrees(angle_rad),
np.degrees(angle_rad)
)
# Compute head fire and backfire wind function
self.fW = mask.where(
self.wsv > 40,
12 * (1 - np.exp(-0.0818 * (self.wsv - 28))),
np.exp(0.05039 * self.wsv)
)
self.bfW = mask.exp(-0.05039 * self.wsv)
# Final head fire and backfire ISI
self.isi = 0.208 * self.fF * self.fW
self.bisi = 0.208 * self.fF * self.bfW
return
def calcISI_RSI_BE(self) -> None:
"""
Function to calculate the slope-/wind-adjusted Initial Spread Index (ISI),
rate of spread (RSI), and the BUI buildup effect (BE) using NumPy masked arrays.
:return: None
"""
with np.errstate(divide='ignore', invalid='ignore'):
# Generate mixed-wood and grass masks
m12_mask = (self.fuel_type == 10) | (self.fuel_type == 11)
m34_mask = (self.fuel_type == 12) | (self.fuel_type == 13)
o1_mask = (self.fuel_type == 14) | (self.fuel_type == 15)
# Precompute C2 and D1 parameters
c2 = self.rosParams[2]
d1 = self.rosParams[8]