-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathLMR_PSMbuild.py
1259 lines (1064 loc) · 55.3 KB
/
LMR_PSMbuild.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
"""
Module: LMR_PSMbuild.py
Stand-alone tool building linear forward models (Proxy System Models) relating surface
temperature and/or moisture to various proxy measurements, through linear regression
between proxy chronologies and historical gridded surface analyses.
This updated version uses the Pandas DataFrame version of the proxy database and
metadata, and can therefore be used on the PAGES2kS1 and NCDC pandas-formatted
proxy datafiles.
Originator : Robert Tardif | Dept. of Atmospheric Sciences, Univ. of Washington
| January 2016
Revisions:
- Included definitions related to calibration of linear PSMs for proxy records in the
NCDC database.
[R. Tardif, U. of Washington, Spring 2016]
- Included the GPCC precipitation historical dataset as a possible PSM calibration source.
[R. Tardif, U. of Washington, Spring 2016]
- Included the Dai PSDI historical dataset as a possible PSM calibration source.
[R. Tardif, U. of Washington, Spring 2016]
- Added definitions of parameters related to the calibration of bilinear (temperature/
precipitation or moisture) PSMs.
[R. Tardif, U. of Washington, June 2016]
- Added definitions related to the calibration of PSMs on the basis of a proxy record
seasonality metadata.
[ R. Tardif, Univ. of Washington, July 2016 ]
- Adjustment to specification of psm type to calibrate for compatibility with modified
classes handling use of different psms per proxy types.
[ R. Tardif, Univ. of Washington, August 2016 ]
- Added filters on proxy records based on conditions of data availability.
[ R. Tardif, Univ. of Washington, October 2016 ]
- Code modifications for more efficient calibration. Upload of calibration data
is now done once up front and passed to psm calibration functions for use on all
proxy chronologies. The original code was structured in a way that the upload
of the calibration data was performed every time a psm for a proxy chronology
was to be calibrated.
[ R. Tardif, Univ. of Washington, December 2016 ]
- Added functionalities to objectively determine the seasonality of proxy chronologies
based on the quality of the fit to calibration data.
[ R. Tardif, Univ. of Washington, December 2016 ]
- Adjustments to proxy types considered for new merged (PAGES2kv2 and NCDC)
proxy datasets.
[ R. Tardif, Univ. of Washington, May 2017 ]
- Renamed the proxy databases to less-confusing convention.
'pages' renamed as 'PAGES2kv1' and 'NCDC' renamed as 'LMRdb'
[ R. Tardif, Univ. of Washington, Sept 2017 ]
"""
import os
import numpy as np
import pickle
import datetime
from time import time
from os.path import join
from copy import deepcopy
import LMR_proxy_pandas_rework
import LMR_calibrate
psm_info = \
"""
Forward model built using a linear PSM calibrated against historical observation-based product(s) of 2m air temperature and/or precipitation/moisture.
"""
# =========================================================================================
# START: set user parameters here
# =========================================================================================
class v_core(object):
"""
High-level parameters for the PSM builder
Attributes
----------
lmr_path: str
Absolute path to central directory where the data (analyses (GISTEMP, HadCRUT...) and proxies)
are located
anom_reference_period: tuple(int)
Reference time period w.r.t. which calibration data anomalies are defined
calib_period: tuple(int)
Time period considered for the calibration
psm_type: str
Indicates the type of PSM to calibrate. For now, allows 'linear' or 'bilinear'
"""
##** BEGIN User Parameters **##
# lmr_path: where all the data is located ... model (prior), analyses (GISTEMP, HadCRUT...) and proxies.
# lmr_path = '/home/katabatic/wperkins/data/LMR'
# lmr_path = '/home/disk/kalman3/rtardif/LMR'
lmr_path = '/home/disk/kalman3/rtardif/LMRpy3'
# PSM type to calibrate: 'linear' or 'bilinear'
#psm_type = 'linear'
psm_type = 'bilinear'
# Reference period (years) w.r.t. which the anomalies in calibration data
# are to be defined.
# Use None to default to calibration dataset definition
# note: default is (1951,1980) for GISTEMP and BerkeleyEarth,
# (1961-1990) for MLOST/NOAAGlobalTemp and HadCRUT
anom_reference_period = (1951,1980)
# Period (years) over which proxy and instrumental data are to be used to
# calibrate statistical PSMs (determine regression parameters)
calib_period = (1850, 2015)
# Boolean to indicate whether upload of existing PSM data is to be performed.
# Keep False here.
load_psmobj = False
##** END User Parameters **##
def __init__(self):
self.lmr_path = self.lmr_path
self.anom_reference_period = self.anom_reference_period
self.calib_period = self.calib_period
self.psm_type = self.psm_type
try:
self.load_psmobj = self.load_psmobj
except:
pass
class v_proxies(object):
"""
Parameters for proxy data
Attributes
----------
use_from: list(str)
A list of keys for proxy classes to load from. Keys available are
stored in LMR_proxy_pandas_rework.
proxy_frac: float
Fraction of available proxy data (sites) to assimilate
"""
##** BEGIN User Parameters **##
# Which proxy database to use ?
# use_from = ['PAGES2kv1']
use_from = ['LMRdb']
##** END User Parameters **##
proxy_frac = 1.0 # this needs to remain = 1.0 if all possible proxies are to be considered for calibration
# Filtering proxy records on conditions of data availability during
# the reconstruction period.
# - Filtrering disabled if proxy_availability_filter = False.
# - If proxy_availability_filter = True, only records with
# oldest and youngest data outside or at edges of the recon. period
# are considered for assimilation.
# - Testing for record completeness through the application of a threshold
# on data availability fraction (proxy_availability_fraction parameter).
# Records with a fraction of available data (ratio of valid data over
# the maximum data expected within the reconstruction period) below the
# user-defined threshold are omitted.
# Set this threshold to 0.0 if you do not want this threshold applied.
# Set this threshold to 1.0 to prevent assimilation of records with
# any missing data within the reconstruction period.
proxy_availability_filter = False
proxy_availability_fraction = 0.0
# ---------------------
# for PAGES2kv1 proxies
# ---------------------
class _PAGES2kv1(object):
"""
Parameters for PAGES2kv1 Proxy class
Attributes
----------
datadir_proxy: str
Absolute path to proxy data
datafile_proxy: str
Absolute path to proxy records file
metafile_proxy: str
Absolute path to proxy meta data
dataformat_proxy: str
File format of the proxy data
regions: list(str)
List of proxy data regions (data keys) to use.
proxy_resolution: list(float)
List of proxy time resolutions to use
proxy_blacklist : list
A blacklist on proxy records, to eliminate specific records from
processing
proxy_order: list(str):
Order of assimilation by proxy type key
proxy_assim2: dict{ str: list(str)}
Proxy types to be assimilated.
Uses dictionary with structure {<<proxy type>>: [.. list of measuremant
tags ..] where "proxy type" is written as
"<<archive type>>_<<measurement type>>"
proxy_type_mapping: dict{(str,str): str}
Maps proxy type and measurement to our proxy type keys.
(e.g. {('Tree ring', 'TRW'): 'Tree ring_Width'} )
simple_filters: dict{'str': Iterable}
List mapping Pages2k metadata sheet columns to a list of values
to filter by.
"""
datadir_proxy = None
datafile_proxy = 'Pages2kv1_Proxies.df.pckl'
metafile_proxy = 'Pages2kv1_Metadata.df.pckl'
dataformat_proxy = 'DF'
regions = ['Antarctica', 'Arctic', 'Asia', 'Australasia', 'Europe',
'North America', 'South America']
proxy_resolution = [1.0]
proxy_timeseries_kind = 'asis' # 'anom' for anomalies (temporal mean removed) or 'asis' to keep unchanged
# DO NOT CHANGE FORMAT BELOW
proxy_order = ['Tree ring_Width',
'Tree ring_Density',
'Ice core_d18O',
'Ice core_d2H',
'Ice core_Accumulation',
'Coral_d18O',
'Coral_Luminescence',
'Lake sediment_All',
'Marine sediment_All',
'Speleothem_All']
proxy_assim2 = {
'Tree ring_Width': ['Ring width',
'Tree ring width',
'Total ring width',
'TRW'],
'Tree ring_Density': ['Maximum density',
'Minimum density',
'Earlywood density',
'Latewood density',
'MXD'],
'Ice core_d18O': ['d18O'],
'Ice core_d2H': ['d2H'],
'Ice core_Accumulation': ['Accumulation'],
'Coral_d18O': ['d18O'],
'Coral_Luminescence': ['Luminescence'],
'Lake sediment_All': ['Varve thickness',
'Thickness',
'Mass accumulation rate',
'Particle-size distribution',
'Organic matter',
'X-ray density'],
'Marine sediment_All': ['Mg/Ca'],
'Speleothem_All': ['Lamina thickness'],
}
# Specify, per proxy type, whether proxy seasonality is to be objectively determined or
# metadata contained in the proxy data files is to be used in the psm calibration.
# Lists indicating which seasons are to be considered are also specified here.
# Note: annual = [1,2,3,4,5,6,7,8,9,10,11,12]
# JJA = [6,7,8]
# JJASON = [6,7,8,9,10,11]
# DJF = [-12,1,2]
# DJFMAM = [-12,1,2,3,4,5]
proxy_psm_seasonality = {
'Tree ring_Width' : {'flag':True,
'seasons': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[6,7,8,9,10,11],[-12,1,2],[-12,1,2,3,4,5]]},
'Tree ring_Density' : {'flag':True,
'seasons': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[6,7,8,9,10,11],[-12,1,2],[-12,1,2,3,4,5]]},
'Ice core_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice core_d2H' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice core_Accumulation': {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Coral_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Coral_Luminescence' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Lake sediment_All' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Marine sediment_All' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Speleothem_All' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
}
# A blacklist on proxy records, to prevent assimilation of chronologies
# known to be duplicates.
proxy_blacklist = []
def __init__(self):
if self.datadir_proxy is None:
self.datadir_proxy = join(v_core.lmr_path, 'data', 'proxies')
else:
self.datadir_proxy = self.datadir_proxy
self.datafile_proxy = join(self.datadir_proxy,
self.datafile_proxy)
self.metafile_proxy = join(self.datadir_proxy,
self.metafile_proxy)
self.dataformat_proxy = self.dataformat_proxy
self.regions = list(self.regions)
self.proxy_resolution = self.proxy_resolution
self.proxy_timeseries_kind = self.proxy_timeseries_kind
self.proxy_order = list(self.proxy_order)
self.proxy_assim2 = deepcopy(self.proxy_assim2)
self.proxy_psm_seasonality = deepcopy(self.proxy_psm_seasonality)
self.proxy_blacklist = list(self.proxy_blacklist)
self.proxy_availability_filter = v_proxies.proxy_availability_filter
self.proxy_availability_fraction = v_proxies.proxy_availability_fraction
self.proxy_psm_type = {}
for p in self.proxy_order: self.proxy_psm_type[p] = v_core.psm_type
# Create mapping for Proxy Type/Measurement Type to type names above
self.proxy_type_mapping = {}
for ptype, measurements in self.proxy_assim2.items():
# Fetch proxy type name that occurs before underscore
type_name = ptype.split('_', 1)[0]
for measure in measurements:
self.proxy_type_mapping[(type_name, measure)] = ptype
self.simple_filters = {'PAGES 2k Region': self.regions,
'Resolution (yr)': self.proxy_resolution}
# -----------------
# for LMRdb proxies
# -----------------
class _LMRdb(object):
"""
Parameters for LMRdb proxy class
Attributes
----------
datadir_proxy: str
Absolute path to proxy data
datafile_proxy: str
Absolute path to proxy records file
metafile_proxy: str
Absolute path to proxy meta data
dataformat_proxy: str
File format of the proxy data
regions: list(str)
List of proxy data regions (data keys) to use.
proxy_resolution: list(float)
List of proxy time resolutions to use
proxy_order: list(str):
Order of assimilation by proxy type key
proxy_assim2: dict{ str: list(str)}
Proxy types to be assimilated.
Uses dictionary with structure {<<proxy type>>: [.. list of measuremant
tags ..] where "proxy type" is written as
"<<archive type>>_<<measurement type>>"
proxy_type_mapping: dict{(str,str): str}
Maps proxy type and measurement to our proxy type keys.
(e.g. {('Tree ring', 'TRW'): 'Tree ring_Width'} )
simple_filters: dict{'str': Iterable}
List mapping proxy metadata sheet columns to a list of values
to filter by.
"""
##** BEGIN User Parameters **##
# db version:
# v0.0.0: initial collection of NCDC-templated proxies, including PAGES2k2013 trees
# v0.1.0: updated collection of NCDC-templated proxies, without PAGES2k2013 trees
# but with an early version of the PAGES2k2017 (phase2) proxies converted
# in NCDC-templated text files.
# v0.2.0: merge of v0.1.0 NCDC proxies (w/o the NCDC-templated PAGES2k phase2) with
# published version (2.0.0) of the PAGES2k2017 proxies contained in a pickle
# file exported directly from the LiPD database.
# v0.3.0: second version of merged proxy db: published version (2.0.0) of the
# PAGES2k2017 proxies and additional records collected as part of LMR project.
# Lingering duplicate records in v0.2.0 were eliminated.
# v0.4.0: third version of merged proxy db: published version (2.0.0) of the
# PAGES2k2017 proxies and additional records collected as part of LMR project.
# Nearly identical to v0.3.0, tho only exception is the most recent version of
# the Palmyra d18O record (2013) replaces the older record included in the
# PAGES2k phase 2 proxies.
# v1.0.0: LMR v3.0 release updates the database version to 1.0.0.
# No changes were made to the database, the name is changing
# for consistency.
#dbversion = 'v0.0.0'
#dbversion = 'v0.1.0'
#dbversion = 'v0.2.0'
#dbversion = 'v0.3.0'
# dbversion = 'v0.4.0'
dbversion = 'v1.0.0'
datadir_proxy = None
datafile_proxy = 'LMRdb_%s_Proxies.df.pckl' %(dbversion)
metafile_proxy = 'LMRdb_%s_Metadata.df.pckl' %(dbversion)
dataformat_proxy = 'DF'
regions = ['Antarctica', 'Arctic', 'Asia', 'Australasia', 'Europe',
'North America', 'South America']
proxy_resolution = [1.0]
proxy_timeseries_kind = 'asis' # 'anom' for anomalies (temporal mean removed) or 'asis' to keep unchanged
##** END User Parameters **##
# Limit proxies to those included in the following databases
database_filter = []
# A blacklist on proxy records, to prevent processing of specific chronologies.
proxy_blacklist = []
# DO NOT CHANGE FORMAT BELOW
proxy_order = [
#old 'Tree Rings_WidthPages',
'Tree Rings_WidthPages2',
'Tree Rings_WidthBreit',
'Tree Rings_Isotopes',
'Tree Rings_Temperature',
'Corals and Sclerosponges_d18O',
'Corals and Sclerosponges_SrCa',
'Corals and Sclerosponges_Rates',
'Corals and Sclerosponges_Composite',
'Corals and Sclerosponges_Temperature',
'Ice Cores_d18O',
'Ice Cores_dD',
'Ice Cores_Accumulation',
'Ice Cores_MeltFeature',
'Lake Cores_Varve',
'Lake Cores_BioMarkers',
'Lake Cores_GeoChem',
'Lake Cores_Misc',
'Marine Cores_d18O',
'Marine Cores_tex86',
'Marine Cores_uk37',
'Bivalve_d18O',
'Speleothems_d18O',
]
proxy_assim2 = {
'Bivalve_d18O' : ['d18O'],
'Corals and Sclerosponges_d18O' : ['d18O','delta18O','d18o','d18O_stk','d18O_int','d18O_norm',
'd18o_avg','d18o_ave','dO18','d18O_4'],
'Corals and Sclerosponges_Rates': ['ext','calc','calcification','calcification rate','composite'],
'Corals and Sclerosponges_SrCa' : ['Sr/Ca','Sr_Ca','Sr/Ca_norm','Sr/Ca_anom','Sr/Ca_int'],\
'Corals and Sclerosponges_d14C' : ['d14C','d14c','ac_d14c'],
'Corals and Sclerosponges_d13C' : ['d13C','d13c','d13c_ave','d13c_ann_ave','d13C_int'],
'Corals and Sclerosponges_Sr' : ['Sr'],
'Corals and Sclerosponges_BaCa' : ['Ba/Ca'],
'Corals and Sclerosponges_CdCa' : ['Cd/Ca'],
'Corals and Sclerosponges_MgCa' : ['Mg/Ca'],
'Corals and Sclerosponges_UCa' : ['U/Ca','U/Ca_anom'],
'Corals and Sclerosponges_Pb' : ['Pb'],
'Ice Cores_d18O' : ['d18O','delta18O','delta18o','d18o','dO18',
'd18o_int','d18O_int',
'd18O_norm','d18o_norm',
'd18O_anom'],
'Ice Cores_dD' : ['deltaD','delD','dD'],
'Ice Cores_Accumulation' : ['accum','accumu'],
'Ice Cores_MeltFeature' : ['MFP','melt'],
'Lake Cores_Varve' : ['varve', 'varve_thickness', 'varve thickness','thickness'],
'Lake Cores_BioMarkers' : ['Uk37', 'TEX86', 'tex86'],
'Lake Cores_GeoChem' : ['Sr/Ca', 'Mg/Ca', 'Cl_cont'],
'Lake Cores_Misc' : ['RABD660_670','X_radiograph_dark_layer','massacum'],
'Marine Cores_d18O' : ['d18O'],
'Marine Cores_tex86' : ['tex86'],
'Marine Cores_uk37' : ['uk37','UK37'],
'Speleothems_d18O' : ['d18O'],
'Speleothems_d13C' : ['d13C'],
'Tree Rings_WidthBreit' : ['trsgi_breit'],
'Tree Rings_WidthPages2' : ['trsgi'],
#old 'Tree Rings_WidthPages' : ['TRW',
#old 'ERW',
#old 'LRW'],
'Tree Rings_WoodDensity' : ['max_d',
'min_d',
'early_d',
'earl_d',
'late_d',
'density',
'MXD'],
'Tree Rings_Isotopes' : ['d18O'],
'Tree Rings_Temperature' : ['temperature'],
'bivalve_d18O' : ['d18O'],
'borehole_Temperature' : ['temperature'],
'documents_Temperature' : ['temperature'],
'hybrid_Temperature' : ['temperature'],
}
# Specify, per proxy type, whether proxy seasonality is to be objectively determined or
# metadata contained in the proxy data files is to be used in the psm calibration.
# Lists indicating which seasons are to be considered are also specified here.
# Note: annual = [1,2,3,4,5,6,7,8,9,10,11,12]
# JJA = [6,7,8]
# JJASON = [6,7,8,9,10,11]
# DJF = [-12,1,2]
# DJFMAM = [-12,1,2,3,4,5]
proxy_psm_seasonality = {
'Bivalve_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Corals and Sclerosponges_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Corals and Sclerosponges_SrCa' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Corals and Sclerosponges_Rates': {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice Cores_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice Cores_dD' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice Cores_Accumulation' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Ice Cores_MeltFeature' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Lake Cores_Varve' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Lake Cores_BioMarkers' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Lake Cores_GeoChem' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Lake Cores_Misc' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Marine Cores_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Marine Cores_tex86' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Marine Cores_uk37' : {'flag':False,
'seasons_T': [],
'seasons_M': []},
'Tree Rings_WidthBreit' : {'flag':True,
'seasons_T': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]],
'seasons_M': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]]},
'Tree Rings_WidthPages2' : {'flag':True,
'seasons_T': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]],
'seasons_M': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]]},
# 'Tree Rings_WidthPages' : {'flag':True,
# 'seasons_T': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]],
# 'seasons_M': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]]},
'Tree Rings_WoodDensity' : {'flag':True,
'seasons_T': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]],
'seasons_M': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]]},
'Tree Rings_Isotopes' : {'flag':True,
'seasons_T': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]],
'seasons_M': [[1,2,3,4,5,6,7,8,9,10,11,12],[6,7,8],[3,4,5,6,7,8],[6,7,8,9,10,11],[-12,1,2],[-9,-10,-11,-12,1,2],[-12,1,2,3,4,5]]},
'Speleothems_d18O' : {'flag':False,
'seasons_T': [],
'seasons_M': []}
}
def __init__(self):
if self.datadir_proxy is None:
self.datadir_proxy = join(v_core.lmr_path, 'data', 'proxies')
else:
self.datadir_proxy = self.datadir_proxy
self.datafile_proxy = join(self.datadir_proxy,
self.datafile_proxy)
self.metafile_proxy = join(self.datadir_proxy,
self.metafile_proxy)
self.dbversion = self.dbversion
self.dataformat_proxy = self.dataformat_proxy
self.regions = list(self.regions)
self.proxy_resolution = self.proxy_resolution
self.proxy_timeseries_kind = self.proxy_timeseries_kind
self.proxy_order = list(self.proxy_order)
self.proxy_assim2 = deepcopy(self.proxy_assim2)
self.proxy_psm_seasonality = deepcopy(self.proxy_psm_seasonality)
self.database_filter = list(self.database_filter)
self.proxy_blacklist = list(self.proxy_blacklist)
self.proxy_availability_filter = v_proxies.proxy_availability_filter
self.proxy_availability_fraction = v_proxies.proxy_availability_fraction
self.proxy_psm_type = {}
for p in self.proxy_order: self.proxy_psm_type[p] = v_core.psm_type
self.proxy_type_mapping = {}
for ptype, measurements in self.proxy_assim2.items():
# Fetch proxy type name that occurs before underscore
type_name = ptype.split('_', 1)[0]
for measure in measurements:
self.proxy_type_mapping[(type_name, measure)] = ptype
self.simple_filters = {'Resolution (yr)': self.proxy_resolution}
# Initialize subclasses with all attributes
def __init__(self, **kwargs):
self.use_from = self.use_from
self.proxy_frac = self.proxy_frac
self.PAGES2kv1 = self._PAGES2kv1(**kwargs)
self.LMRdb = self._LMRdb(**kwargs)
class v_psm(object):
"""
Parameters for PSM classes
Attributes
----------
avgPeriod: str
PSM calibrated on annual or seasonal data: allowed tags are 'annual' or 'season'
"""
##** BEGIN User Parameters **##
# ...
load_precalib = False
# PSM calibrated on annual or seasonal data: allowed tags are 'annual' or 'season'
#avgPeriod = 'annual'
avgPeriod = 'season'
# Boolean flag indicating whether PSMs are to be calibrated using objectively-derived
# proxy seasonality instead of using the "seasonality" metadata included in the data
# files.
# Activated only if avgPeriod = 'season' above.
# If set to True, refer back to the appropriate proxy class above
# (proxy_psm_seasonality dict.) to set which proxy type(s) and associated seasons
# will be considered.
test_proxy_seasonality = False
##** END User Parameters **##
if avgPeriod == 'season':
if test_proxy_seasonality:
avgPeriod = avgPeriod+'PSM'
else:
avgPeriod = avgPeriod+'META'
class _linear(object):
"""
Parameters for the linear fit PSM.
Attributes
----------
datatag_calib: str
Source of calibration data for PSM
datadir_calib: str
Absolute path to calibration data
datafile_calib: str
Filename for calibration data
dataformat_calib: str
Data storage type for calibration data
pre_calib_datafile: str
Absolute path to precalibrated Linear PSM data
psm_r_crit: float
Usage threshold for correlation of linear PSM
"""
##** BEGIN User Parameters **##
datadir_calib = None
pre_calib_datafile = None
# Choice between:
datatag_calib = 'GISTEMP'
datafile_calib = 'gistemp1200_ERSSTv4.nc'
# or
#datatag_calib = 'NOAAGlobalTemp'
#datafile_calib = 'NOAAGlobalTemp_air.mon.anom_V4.0.1.nc'
# or
#datatag_calib = 'MLOST'
#datafile_calib = 'MLOST_air.mon.anom_V3.5.4.nc'
# or
#datatag_calib = 'HadCRUT'
#datafile_calib = 'HadCRUT.4.4.0.0.median.nc'
# or
#datatag_calib = 'BerkeleyEarth'
#datafile_calib = 'Land_and_Ocean_LatLong1.nc'
# or
#datatag_calib = 'GPCC'
#datafile_calib = 'GPCC_precip.mon.flux.1x1.v6.nc' # Precipitation flux (kg m2 s-1)
# or
#datatag_calib = 'DaiPDSI'
#datafile_calib = 'Dai_pdsi.mon.mean.selfcalibrated_185001-201412.nc'
# or
#datatag_calib = 'SPEI'
#datafile_calib = 'spei_monthly_v2.4_190001-201412.nc'
psm_r_crit = 0.0
##** END User Parameters **##
def __init__(self):
self.datatag_calib = self.datatag_calib
self.datafile_calib = self.datafile_calib
self.psm_r_crit = self.psm_r_crit
self.avgPeriod = v_psm.avgPeriod
if '-'.join(v_proxies.use_from) == 'PAGES2kv1' and 'season' in self.avgPeriod:
print('ERROR: Trying to use seasonality information with the PAGES2kv1 proxy records.')
print(' No seasonality metadata provided in that dataset. Exiting!')
print(' Change avgPeriod to "annual" in your configuration.')
raise SystemExit()
if self.datadir_calib is None:
self.datadir_calib = join(v_core.lmr_path, 'data', 'analyses')
else:
self.datadir_calib = self.datadir_calib
if self.pre_calib_datafile is None:
if '-'.join(v_proxies.use_from) == 'LMRdb':
dbversion = v_proxies._LMRdb.dbversion
filename = ('PSMs_'+'-'.join(v_proxies.use_from) +
'_' + dbversion +
'_' + self.avgPeriod +
'_' + self.datatag_calib +
'_ref' + str(v_core.anom_reference_period[0]) + '-' + str(v_core.anom_reference_period[1]) +
'_cal' + str(v_core.calib_period[0]) + '-' + str(v_core.calib_period[1]) +
'.pckl')
else:
filename = ('PSMs_' + '-'.join(v_proxies.use_from) +
'_' + self.datatag_calib +
'_ref' + str(v_core.anom_reference_period[0]) + '-' + str(v_core.anom_reference_period[1]) +
'_cal' + str(v_core.calib_period[0]) + '-' + str(v_core.calib_period[1]) +
'.pckl')
self.pre_calib_datafile = join(v_core.lmr_path,
'PSM',
filename)
else:
self.pre_calib_datafile = self.pre_calib_datafile
class _bilinear(object):
"""
Parameters for the bilinear fit PSM.
Attributes
----------
datatag_calib_T: str
Source of calibration temperature data for PSM
datadir_calib_T: str
Absolute path to calibration temperature data
datafile_calib_T: str
Filename for calibration temperature data
dataformat_calib_T: str
Data storage type for calibration temperature data
datatag_calib_P: str
Source of calibration precipitation/moisture data for PSM
datadir_calib_P: str
Absolute path to calibration precipitation/moisture data
datafile_calib_P: str
Filename for calibration precipitation/moisture data
dataformat_calib_P: str
Data storage type for calibration precipitation/moisture data
pre_calib_datafile: str
Absolute path to precalibrated Linear PSM data
psm_r_crit: float
Usage threshold for correlation of linear PSM
"""
##** BEGIN User Parameters **##
datadir_calib = None
pre_calib_datafile = None
# calibration w.r.t. temperature
# -----------------------------
# Choice between:
#
datatag_calib_T = 'GISTEMP'
datafile_calib_T = 'gistemp1200_ERSSTv4.nc'
# or
#datatag_calib_T = 'NOAAGlobalTemp'
#datafile_calib_T = 'NOAAGlobalTemp_air.mon.anom_V4.0.1.nc'
# or
#datatag_calib_T = 'MLOST'
#datafile_calib_T = 'MLOST_air.mon.anom_V3.5.4.nc'
# or
#datatag_calib_T = 'HadCRUT'
#datafile_calib_T = 'HadCRUT.4.4.0.0.median.nc'
# or
#datatag_calib_T = 'BerkeleyEarth'
#datafile_calib_T = 'Land_and_Ocean_LatLong1.nc'
# calibration w.r.t. precipitation/moisture
# ----------------------------------------
datatag_calib_P = 'GPCC'
datafile_calib_P = 'GPCC_precip.mon.flux.1x1.v6.nc'
# or
#datatag_calib_P = 'DaiPDSI'
#datafile_calib_P = 'Dai_pdsi.mon.mean.selfcalibrated_185001-201412.nc'
# or
#datatag_calib_P = 'SPEI'
#datafile_calib_P = 'spei_monthly_v2.4_190001-201412.nc'
psm_r_crit = 0.0
##** END User Parameters **##
def __init__(self):
self.datatag_calib_T = self.datatag_calib_T
self.datafile_calib_T = self.datafile_calib_T
self.datatag_calib_P = self.datatag_calib_P
self.datafile_calib_P = self.datafile_calib_P
self.psm_r_crit = self.psm_r_crit
self.avgPeriod = v_psm.avgPeriod
if '-'.join(v_proxies.use_from) == 'PAGES2kv1' and 'season' in self.avgPeriod:
print('ERROR: Trying to use seasonality information with the PAGES2kv1 proxy records.')
print(' No seasonality metadata provided in that dataset. Exiting!')
print(' Change avgPeriod to "annual" in your configuration.')
raise SystemExit()
if self.datadir_calib is None:
self.datadir_calib = join(v_core.lmr_path, 'data', 'analyses')
else:
self.datadir_calib = self.datadir_calib
if self.pre_calib_datafile is None:
if '-'.join(v_proxies.use_from) == 'LMRdb':
dbversion = v_proxies._LMRdb.dbversion
filename = ('PSMs_' + '-'.join(v_proxies.use_from) +
'_' + dbversion +
'_' + self.avgPeriod +
'_'+self.datatag_calib_T +
'_'+self.datatag_calib_P +
'_ref' + str(v_core.anom_reference_period[0]) + '-' + str(v_core.anom_reference_period[1]) +
'_cal' + str(v_core.calib_period[0]) + '-' + str(v_core.calib_period[1]) +
'.pckl')
else:
filename = ('PSMs_' + '-'.join(v_proxies.use_from) +
'_'+self.datatag_calib_T +
'_'+self.datatag_calib_P +
'_ref' + str(v_core.anom_reference_period[0]) + '-' + str(v_core.anom_reference_period[1]) +
'_cal' + str(v_core.calib_period[0]) + '-' + str(v_core.calib_period[1]) +
'.pckl')
self.pre_calib_datafile = join(v_core.lmr_path,
'PSM',
filename)
else:
self.pre_calib_datafile = self.pre_calib_datafile
# Initialize subclasses with all attributes
def __init__(self, **kwargs):
self.linear = self._linear(**kwargs)
self.bilinear = self._bilinear(**kwargs)
# =========================================================================================
# END: set user parameters here
# =========================================================================================
class config(object):
def __init__(self,core,proxies,psm):
self.core = core()
self.proxies = proxies()
self.psm = psm()
Cfg = config(v_core,v_proxies,v_psm)
# =============================================================================
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<< Main code >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# =============================================================================
def main():
begin_time = time()
proxy_database = Cfg.proxies.use_from[0]
psm_type = Cfg.core.psm_type
print('Proxies :', proxy_database)
print('PSM type :', psm_type)
print('Calib. period :', Cfg.core.calib_period)
print('Anom. ref. period :', Cfg.core.anom_reference_period)
if proxy_database == 'PAGES2kv1':
print('Proxy data location :', Cfg.proxies.PAGES2kv1.datadir_proxy)
proxy_psm_seasonality = Cfg.proxies.PAGES2kv1.proxy_psm_seasonality
elif proxy_database == 'LMRdb':
print('Proxy data location :', Cfg.proxies.LMRdb.datadir_proxy)
proxy_psm_seasonality = Cfg.proxies.LMRdb.proxy_psm_seasonality
else:
raise SystemExit('ERROR in specification of proxy database. Exiting!')
# psm type
if psm_type == 'linear':
datatag_calib = Cfg.psm.linear.datatag_calib
print('Calibration source :', datatag_calib)
psm_file = Cfg.psm.linear.pre_calib_datafile
calib_avgPeriod = Cfg.psm.linear.avgPeriod
# load calibration data
C = LMR_calibrate.calibration_assignment(datatag_calib)
C.datadir_calib = Cfg.psm.linear.datadir_calib
C.datafile_calib = Cfg.psm.linear.datafile_calib
C.anom_reference_period = Cfg.core.anom_reference_period
C.read_calibration()
elif psm_type == 'bilinear':
datatag_calib_T = Cfg.psm.bilinear.datatag_calib_T
datatag_calib_P = Cfg.psm.bilinear.datatag_calib_P
print('Calibration sources :', datatag_calib_T, '+', datatag_calib_P)
psm_file = Cfg.psm.bilinear.pre_calib_datafile
calib_avgPeriod = Cfg.psm.bilinear.avgPeriod
# load calibration data: two calibration objects, temperature and precipitation/moisture
C_T = LMR_calibrate.calibration_assignment(datatag_calib_T)
C_T.datadir_calib = Cfg.psm.bilinear.datadir_calib
C_T.datafile_calib = Cfg.psm.bilinear.datafile_calib_T
C_T.anom_reference_period = Cfg.core.anom_reference_period
C_T.read_calibration()
C_P = LMR_calibrate.calibration_assignment(datatag_calib_P)
C_P.datadir_calib = Cfg.psm.bilinear.datadir_calib
C_P.datafile_calib = Cfg.psm.bilinear.datafile_calib_P
C_P.anom_reference_period = Cfg.core.anom_reference_period
C_P.read_calibration()
else:
raise SystemExit('ERROR: problem with the specified type of psm. Exiting!')
print('PSM calibration/parameters file:', psm_file)
# corresponding file containing complete diagnostics
psm_file_diag = psm_file.replace('.pckl', '_diag.pckl')
# Check if psm_file already exists, archive it with current date/time if it exists
# and replace by new file
if os.path.isfile(psm_file):
nowstr = datetime.datetime.now().strftime("%Y%m%d:%H%M")
os.system('mv %s %s_%s.pckl' %(psm_file,psm_file.rstrip('.pckl'),nowstr) )
if os.path.isfile(psm_file_diag):
os.system('mv %s %s_%s.pckl' %(psm_file_diag,psm_file_diag.rstrip('.pckl'),nowstr) )
prox_manager = LMR_proxy_pandas_rework.ProxyManager(Cfg, Cfg.core.calib_period)
type_site_calib = prox_manager.assim_ids_by_group
print('--------------------------------------------------------------------')
print('Total proxies available: counts per proxy type:')
# count the total number of proxies
total_proxy_count = len(prox_manager.ind_assim)
for pkey, plist in sorted(type_site_calib.items()):
print('%45s : %5d' % (pkey, len(plist)))
print('--------------------------------------------------------------------')
print('%45s : %5d' % ('TOTAL', total_proxy_count))
print('--------------------------------------------------------------------')
# Loop over proxies
psm_dict = {}
psm_dict_diag = {}
for proxy_idx, Y in enumerate(prox_manager.sites_assim_proxy_objs()):
sitetag = (Y.type,Y.id)
print(' ')
print(sitetag)
# -----------------------------------------------------
# Prep: defining seasons to be tested, depending on the
# chosen configuration
# -----------------------------------------------------
if calib_avgPeriod == 'annual':
# override any proxy seasonality metadata with calendar year
seasons = [[1,2,3,4,5,6,7,8,9,10,11,12]]
if psm_type == 'bilinear':
seasons_T = seasons[:]
seasons_M = seasons[:]
elif 'season' in calib_avgPeriod:
# try to determine seasonality objectively ?