-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLMR_proxy_preprocess.py
2319 lines (1853 loc) · 105 KB
/
LMR_proxy_preprocess.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_proxy_preprocess.py
Purpose: Takes proxy data in their native format (e.g. .pckl file for PAGES2k or collection of
NCDC-templated .txt files) and generates Pandas DataFrames stored in pickle files
containing metadata and actual data from proxy records. The "pickled" DataFrames
are used as input by the Last Millennium Reanalysis software.
Currently, the data is stored as *annual averages* for original records with
subannual data.
Originator : Robert Tardif | Dept. of Atmospheric Sciences, Univ. of Washington
| January 2016
(Based on code written by Andre Perkins (U. of Washington) to handle
PAGES(2013) proxies)
Revisions :
- Addition of proxy types corresponding to "deep-times" proxy records, which are
being included in the NCDC-templated proxy collection.
[R. Tardif, U. of Washington, March 2017]
- Addition of recognized time/age definitions used in "deep-times" proxy records
and improved conversion of time/age data to year CE (convention used in LMR).
[R. Tardif, U. of Washington, March 2017]
- Improved detection & treatment of missing data, now using tags found
(or not) in each data file.
[R. Tardif, U. of Washington, March 2017]
- Added functionalities related to the merging of proxies coming from two
sources (PAGES2k phase 2 data contained in a single compressed pickle file
and "in-house" collections contained in NCDC-templated text files).
The possibility to "gaussianize" records and to calculate annual averages
on "tropical year" (Apr to Mar) or calendar year have also been implemented.
[R. Tardif, U. of Washington, Michael Erb, USC, May 2017]
- Renamed the proxy databases to less-confusing convention.
'pages' renamed as 'PAGES2kv1' and 'NCDC' renamed as 'LMRdb'
[R. Tardif, U. of Washington, Sept 2017]
"""
import glob
import os
import os.path
import numpy as np
import pandas as pd
import time as clock
from copy import deepcopy
from scipy import stats
import string
import re
import six
import ast
from os.path import join
import pickle as pickle
import gzip
import calendar
# LMR imports
from .LMR_utils import gaussianize
# =========================================================================================
class EmptyError(Exception):
print(Exception)
# =========================================================================================
# ---------------------------------------- MAIN -------------------------------------------
# =========================================================================================
def main():
# ********************************************************************************
# Section for User-defined options: begin
#
#proxy_data_source = 'PAGES2Kv1' # proxies from PAGES2k phase 1 (2013)
# --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** ---
proxy_data_source = 'LMRdb' # proxies from PAGES2k phase 2 (2017) +
# "in-house" collection in NCDC-templated files
# Determine which dataset(s) (NCDC and/or PAGES2kv2) to include in the DF.
# - Both : include_NCDC = True, include_PAGES2kphase2 = True
# - Only NCDC : include_NCDC = True, include_PAGES2kphase2 = False
# - Only PAGES2kv2 : include_NCDC = False, include_PAGES2kphase2 = True
include_NCDC = True
include_PAGES2kphase2 = True
#PAGES2kphase2file = 'PAGES2k_v2.0.0_tempOnly.pklz' # compressed version of the file
PAGES2kphase2file = 'PAGES2k_v2.0.0_tempOnly.pckl'
# version of the LMRdb proxy db to process
# - first set put together, including PAGES2k2013 trees
#LMRdb_dbversion = 'v0.0.0'
# - PAGES2k2013 trees taken out, but with NCDC-templated records from PAGES2k phase 2, version 1.9.0
#LMRdb_dbversion = 'v0.1.0'
# - NCDC collection for LMR + published PAGES2k phase 2 proxies (version 2.0.0). stored in .pklz file
#LMRdb_dbversion = 'v0.2.0'
#LMRdb_dbversion = 'v0.3.0'
# LMRdb_dbversion = 'v0.4.0'
LMRdb_dbversion = 'v1.0.0'
# File containing info on duplicates in proxy records
infoDuplicates = 'Proxy_Duplicates_PAGES2kv2_NCDC_LMR'+LMRdb_dbversion+'.xlsx'
# This option transforms all data to a Gaussian distribution. It should only be used for
# linear regressions, not physically-based PSMs.
gaussianize_data = False
# Specify the type of year to use for data averaging. "calendar year" (Jan-Dec)
# or "tropical year" (Apr-Mar)
year_type = "calendar year"
#year_type = "tropical year"
eliminate_duplicates = True
# --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** ---
#proxy_data_source = 'DTDA'
dtda_dbversion = 'v0.0.0'
# --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** --- *** ---
# datadir: directory where the original proxy datafiles are located
datadir = '/home/katabatic/wperkins/data/LMR/data/proxies/'
# outdir: directory where the proxy database files will be created
# The piece before /data/proxies should correspond to your "lmr_path" set in LMR_config.py
outdir = '/home/katabatic/wperkins/data/LMR/data/proxies/'
#
# Section for User-defined options: end
# ***************************************************************
main_begin_time = clock.time()
# first checking that input and output directories exist on disk
if not os.path.isdir(datadir):
print('ERROR: Directory <<datadir>> does not exist. Please revise your'
' entry for this user-defined parameter.')
raise SystemExit(1)
else:
# check that datadir ends with '/' -> expected thereafter
if not datadir[-1] == '/':
datadir = datadir+'/'
if not os.path.isdir(outdir):
print('ERROR: Directory <<outdir>> does not exist. Please revise your'
' entry for this user-defined parameter.')
raise SystemExit(1)
else:
# check that outdir ends with '/' -> expected thereafter
if not outdir[-1] == '/':
outdir = outdir+'/'
if proxy_data_source == 'PAGES2Kv1':
# ============================================================================
# PAGES2Kv1 proxy data -------------------------------------------------------
# ============================================================================
take_average_out = False
fname = datadir + 'Pages2k_DatabaseS1-All-proxy-records.xlsx'
meta_outfile = outdir + 'Pages2kv1_Metadata.df.pckl'
outfile = outdir + 'Pages2kv1_Proxies.df.pckl'
pages_xcel_to_dataframes(fname, meta_outfile, outfile, take_average_out)
elif proxy_data_source == 'LMRdb':
# ============================================================================
# LMRdb proxy data -----------------------------------------------------------
# ============================================================================
datadir = datadir+'LMRdb/ToPandas_'+LMRdb_dbversion+'/'
infoDuplicates = datadir+infoDuplicates
# Some checks
if not os.path.isdir(datadir):
print('ERROR: Directory % is not found. Directory structure'
' <<datadir>>/LMRdb/ToPandas_vX.Y.Z is expected.'
' Please revise your set-up.' %datadir)
raise SystemExit(1)
if eliminate_duplicates and not os.path.isfile(infoDuplicates):
print('ERROR: eliminate_duplicates parameter set to True but'
' required file %s not found! Please rectify.' %infoDuplicates)
raise SystemExit(1)
meta_outfile = outdir + 'LMRdb_'+LMRdb_dbversion+'_Metadata.df.pckl'
data_outfile = outdir + 'LMRdb_'+LMRdb_dbversion+'_Proxies.df.pckl'
# Specify all proxy types & associated proxy measurements to look for & extract from the data files
# This is to take into account all the possible different names found in the PAGES2kv2 and NCDC data files.
proxy_def = \
{
#old 'Tree Rings_WidthPages' : ['TRW','ERW','LRW'],\
'Tree Rings_WidthPages2' : ['trsgi'],\
'Tree Rings_WidthBreit' : ['trsgi'],\
'Tree Rings_WoodDensity' : ['max_d','min_d','early_d','earl_d','late_d','MXD','density'],\
'Tree Rings_Isotopes' : ['d18O'],\
'Corals and Sclerosponges_d18O' : ['d18O','delta18O','d18o','d18O_stk','d18O_int','d18O_norm','d18o_avg','d18o_ave','dO18','d18O_4'],\
'Corals and Sclerosponges_SrCa' : ['Sr/Ca','Sr_Ca','Sr/Ca_norm','Sr/Ca_anom','Sr/Ca_int'],\
'Corals and Sclerosponges_Rates' : ['ext','calc','calcification','calcification rate', 'composite'],\
'Ice Cores_d18O' : ['d18O','delta18O','delta18o','d18o','d18o_int','d18O_int','d18O_norm','d18o_norm','dO18','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'],\
'Bivalve_d18O' : ['d18O'],\
# DADT proxies
# 'Marine Cores_d18Opachyderma' : ['d18O_pachyderma'],\
# 'Marine Cores_d18Obulloides' : ['d18O_bulloides'],\
# 'Marine Cores_tex86' : ['tex86'],\
# Proxy types present in the database but which should not be included/assimilated
# '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'],\
# 'Speleothems_d13C' : ['d13C'],\
# 'Borehole_Temperature' : ['temperature'],\
# 'Hybrid_Temperature' : ['temperature'],\
# 'Documents_Temperature' : ['temperature'],\
# 'Tree Rings_Temperature' : ['temperature'],\
# 'Lake Cores_Temperature' : ['temperature'],\
# 'Marine Cores_Temperature' : ['temperature'],\
# 'Corals and Sclerosponges_Temperature' : ['temperature'],\
# 'Climate Reconstructions' : ['sst_ORSTOM','sss_ORSTOM','temp_anom'],\
}
# --- data from LMR's NCDC-templated files
if include_NCDC:
ncdc_dict = ncdc_txt_to_dict(datadir, proxy_def, year_type, gaussianize_data)
else:
ncdc_dict = []
# --- PAGES2k phase2 (2017) data
if include_PAGES2kphase2:
pages2kv2_dict = pages2kv2_pickle_to_dict(datadir, PAGES2kphase2file, proxy_def, year_type, gaussianize_data)
else:
pages2kv2_dict = []
# --- Merge datasets, scrub duplicates and write metadata & data to file
merge_dicts_to_dataframes(proxy_def, ncdc_dict, pages2kv2_dict, meta_outfile, data_outfile, infoDuplicates, eliminate_duplicates)
elif proxy_data_source == 'DTDA':
# ============================================================================
# DTDA project proxy data ----------------------------------------------------
# ============================================================================
take_average_out = False
datadir = datadir+'DTDA/'
fname = datadir + 'DTDA_proxies_'+dtda_dbversion+'.xlsx'
meta_outfile = outdir + 'DTDA_'+dtda_dbversion+'_Metadata.df.pckl'
outfile = outdir + 'DTDA_'+dtda_dbversion+'_Proxies.df.pckl'
DTDA_xcel_to_dataframes(fname, meta_outfile, outfile, take_average_out)
else:
raise SystemExit('ERROR: Unkown proxy data source! Exiting!')
elapsed_time = clock.time() - main_begin_time
print(('Build of integrated proxy database completed in %s mins' %str(elapsed_time/60.)))
# =========================================================================================
# ------------------------------------- END OF MAIN ---------------------------------------
# =========================================================================================
# =========================================================================================
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
# =========================================================================================
def compute_annual_means(time_raw,data_raw,valid_frac,year_type):
"""
Computes annual-means from raw data.
Inputs:
time_raw : Original time axis
data_raw : Original data
valid_frac : The fraction of sub-annual data necessary to create annual mean. Otherwise NaN.
year_type : "calendar year" (Jan-Dec) or "tropical year" (Apr-Mar)
Outputs: time_annual, data_annual
Authors: R. Tardif, Univ. of Washington; M. Erb, Univ. of Southern California
"""
# Check if dealing with multiple chronologies in one data stream (for NCDC files)
array_shape = data_raw.shape
if len(array_shape) == 2:
nbtimes, nbvalid = data_raw.shape
elif len(array_shape) == 1:
nbtimes, = data_raw.shape
nbvalid = 1
else:
raise SystemExit('ERROR in compute_annual_means: Unrecognized shape of data input array.')
time_between_records = np.diff(time_raw, n=1)
# Temporal resolution of the data, calculated as the mode of time difference.
time_resolution = abs(stats.mode(time_between_records)[0][0])
# check if time_resolution = 0.0 !!! sometimes adjacent records are tagged at same time ...
if time_resolution == 0.0:
print('***WARNING! Found adjacent records with same times!')
inderr = np.where(time_between_records == 0.0)
print(inderr)
time_between_records = np.delete(time_between_records,inderr)
time_resolution = abs(stats.mode(time_between_records)[0][0])
max_nb_per_year = int(1.0/time_resolution)
if time_resolution <=1.0:
proxy_resolution = int(1.0) # coarse-graining to annual
else:
proxy_resolution = int(time_resolution)
# Get rounded integer values of all years present in record.
years_all = [int(np.floor(time_raw[k])) for k in range(0,len(time_raw))]
years = list(set(years_all)) # 'set' is used to get unique values in list
years = sorted(years) # sort the list
years = np.insert(years,0,years[0]-1) # M. Erb
# bounds, for calendar year : [years_beg,years_end[
years_beg = np.asarray(years,dtype=np.float64) # inclusive lower bound
years_end = years_beg + 1. # exclusive upper bound
# If some of the time values are floats (sub-annual resolution)
# and year_type is tropical_year, adjust the years to cover the
# tropical year (Apr-Mar).
if np.equal(np.mod(time_raw,1),0).all() == False and year_type == 'tropical year':
print("Tropical year averaging...")
# modify bounds defining the "year"
for i, yr in enumerate(years):
# beginning of interval
if calendar.isleap(yr):
years_beg[i] = float(yr)+((31+29+31)/float(366))
else:
years_beg[i] = float(yr)+((31+28+31)/float(365))
# end of interval
if calendar.isleap(yr+1):
years_end[i] = float(yr+1)+((31+29+31)/float(366))
else:
years_end[i] = float(yr+1)+((31+28+31)/float(365))
time_annual = np.asarray(years,dtype=np.float64)
data_annual = np.zeros(shape=[len(years),nbvalid], dtype=np.float64)
# fill with NaNs for default values
data_annual[:] = np.NAN
# Calculate the mean of all data points with the same year.
for i in range(len(years)):
ind = [j for j, year in enumerate(time_raw) if (year >= years_beg[i]) and (year < years_end[i])]
nbdat = len(ind)
# TODO: check nb of non-NaN values !!!!! ... ... ... ... ... ...
if time_resolution <= 1.0:
frac = float(nbdat)/float(max_nb_per_year)
if frac > valid_frac:
data_annual[i,:] = np.nanmean(data_raw[ind],axis=0)
else:
if nbdat > 1:
print('***WARNING! Found multiple records in same year in data with multiyear resolution!')
print((' year= %d %d' %(years[i], nbdat)))
# Note: this calculates the mean if multiple entries found
data_annual[i,:] = np.nanmean(data_raw[ind],axis=0)
# check and modify time_annual array to reflect only the valid data present in the annual record
# for correct tagging of "Oldest" and "Youngest" data
indok = np.where(np.isfinite(data_annual))[0]
keep = np.arange(indok[0],indok[-1]+1,1)
return time_annual[keep], data_annual[keep,:], proxy_resolution
# ===================================================================================
# For PAGES2k S1 proxy data ---------------------------------------------------------
# ===================================================================================
def pages_xcel_to_dataframes(filename, metaout, dataout, take_average_out):
"""
Takes in Pages2K CSV and converts it to dataframe storage. This increases
size on disk due to the joining along the time index (lots of null values).
Makes it easier to query and grab data for the proxy experiments.
:param filename:
:param metaout:
:param dataout:
:return:
Author: Andre Perkins, Univ. of Washington
"""
# check that file <<filename>> exists
if not os.path.isfile(filename):
print('ERROR: File %s does not exist. Please make sure'
' input file is located in right directory.' %filename)
raise SystemExit(1)
meta_sheet_name = 'Metadata'
metadata = pd.read_excel(filename, meta_sheet_name)
# rename 'PAGES ID' column header to more general 'Proxy ID'
metadata.rename(columns = {'PAGES ID':'Proxy ID'},inplace=True)
metadata.to_pickle(metaout)
record_sheet_names = ['AntProxies', 'ArcProxies', 'AsiaProxies',
'AusProxies', 'EurProxies', 'NAmPol', 'NAmTR',
'SAmProxies']
for i, sheet in enumerate(record_sheet_names):
tmp = pd.read_excel(filename, sheet)
# for key, series in tmp.iteritems():
# h5store[key] = series[series.notnull()]
if i == 0:
df = tmp
else:
# SQL like table join along index
df = df.merge(tmp, how='outer', on='PAGES 2k ID')
#fix index and column name
col0 = df.columns[0]
newcol0 = df[col0][0]
df.set_index(col0, drop=True, inplace=True)
df.index.name = newcol0
df = df.ix[1:]
df.sort_index(inplace=True)
if take_average_out:
# copy of dataframe
df_tmp = df
# fill dataframe with new values where temporal averages over proxy records are subtracted
df = df_tmp.sub(df_tmp.mean(axis=0), axis=1)
# TODO: make sure year index is consecutive
#write data to file
df = df.to_sparse()
df.to_pickle(dataout)
# ===================================================================================
# For PAGES2k v2.0.0 proxy data ---------------------------------------------------------
# ===================================================================================
def pages2kv2_pickle_to_dataframes(datadir, metaout, dataout, eliminate_duplicates, year_type, gaussianize_data):
"""
Takes in a Pages2k pckl file and converts it to dataframe storage.
Authors: R. Tardif, Univ. of Washington, Jan 2016.
M. Erb, Univ. of Southern California, Feb 2017
"""
# ===============================================================================
# Upload proxy data from Pages2k v2 pickle file
# ===============================================================================
# Open the pickle file containing the Pages2k data
f = gzip.open(datadir+'PAGES2k_v2.0.0_tempOnly.pklz','rb')
pages2k_data = pickle.load(f)
f.close()
# ===============================================================================
# Produce a summary of uploaded proxy data &
# generate integrated database in pandas DataFrame format
# ===============================================================================
# Summary of the final_proxy_list
nbsites = len(pages2k_data)
print('----------------------------------------------------------------------')
print(' SUMMARY: ')
print(' Total nb of records : ', nbsites)
print(' ------------------------------------------------------')
tot = []
# Loop over proxy types specified in *main*
counter = 0
# Build up pandas DataFrame
metadf = pd.DataFrame()
headers = ['NCDC ID','Site name','Lat (N)','Lon (E)','Elev','Archive type','Proxy measurement','Resolution (yr)',\
'Oldest (C.E.)','Youngest (C.E.)','Location','climateVariable','Realm','Relation_to_climateVariable',\
'Seasonality', 'Databases']
nb = []
for counter in range(0,len(pages2k_data)):
#counter = 13 # An example of a sub-annual record
# Give each record a unique descriptive name
pages2k_data[counter]['siteID'] = "PAGES2kv2_"+pages2k_data[counter]['dataSetName']+"_"+pages2k_data[counter]['paleoData_pages2kID']+":"+pages2k_data[counter]['paleoData_variableName']
nb.append(pages2k_data[counter]['siteID'])
print("Processing metadata", counter+1, "/", len(pages2k_data), ":",
pages2k_data[counter]['paleoData_pages2kID'])
# If the time axis goes backwards (i.e. newer to older), reverse it.
if pages2k_data[counter]['year'][-1] - pages2k_data[counter]['year'][-2] < 0:
pages2k_data[counter]['year'].reverse()
pages2k_data[counter]['paleoData_values'].reverse()
# If subannual, average up to annual --------------------------------------------------------
time_raw = np.array(pages2k_data[counter]['year'],dtype=np.float)
data_raw = np.array(pages2k_data[counter]['paleoData_values'],dtype=np.float)
# Remove values where either time or data is nan.
nan_indices = np.isnan(time_raw)+np.isnan(data_raw)
time_raw = time_raw[~nan_indices]
data_raw = data_raw[~nan_indices]
valid_frac = 0.5
# Use the following function to make annual-means.
# Inputs: time_raw, data_raw, valid_frac, year_type. Outputs: time_annual, data_annual
time_annual, data_annual, proxy_resolution = compute_annual_means(time_raw,data_raw,valid_frac,year_type)
# If gaussianize_data is set to true, transform the proxy data to Gaussian.
# This option should only be used when using regressions, not physically-based PSMs.
if gaussianize_data == True:
data_annual = gaussianize.gaussianize(data_annual)
# Write the annual data to the dictionary, so they can use written to
# the data file outside of this loop.
pages2k_data[counter]['time_annual'] = time_annual
pages2k_data[counter]['data_annual'] = data_annual
# Rename the proxy types in the same convention as the NCDC dataset.
# Proxy types not renamed: bivalve, borehole, documents, hybrid
if (pages2k_data[counter]['archiveType'] == 'coral') or (pages2k_data[counter]['archiveType'] == 'sclerosponge'):
pages2k_data[counter]['archiveType'] = 'Corals and Sclerosponges'
elif pages2k_data[counter]['archiveType'] == 'glacier ice':
pages2k_data[counter]['archiveType'] = 'Ice Cores'
elif pages2k_data[counter]['archiveType'] == 'lake sediment':
pages2k_data[counter]['archiveType'] = 'Lake Cores'
elif pages2k_data[counter]['archiveType'] == 'marine sediment':
pages2k_data[counter]['archiveType'] = 'Marine Cores'
elif pages2k_data[counter]['archiveType'] == 'speleothem':
pages2k_data[counter]['archiveType'] = 'Speleothems'
elif pages2k_data[counter]['archiveType'] == 'tree':
pages2k_data[counter]['archiveType'] = 'Tree Rings'
# Rename some of the the proxy measurements to be more standard.
if (pages2k_data[counter]['archiveType'] == 'Ice Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'd18O1'):
pages2k_data[counter]['paleoData_variableName'] = 'd18O'
elif (pages2k_data[counter]['archiveType'] == 'Lake Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'temperature1'):
pages2k_data[counter]['paleoData_variableName'] = 'temperature'
elif (pages2k_data[counter]['archiveType'] == 'Lake Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'temperature3'):
pages2k_data[counter]['paleoData_variableName'] = 'temperature'
# Not all records have data for elevation. In these cases, set elevation to nan.
if 'geo_meanElev' not in pages2k_data[counter]:
pages2k_data[counter]['geo_meanElev'] = np.nan
# Ensure lon is in [0,360] domain
if pages2k_data[counter]['geo_meanLon'] < 0.0:
pages2k_data[counter]['geo_meanLon'] = 360 + pages2k_data[counter]['geo_meanLon']
# Determine the seasonality of the record.
# Seasonal names were mapped the three-month climatological seasons.
# 'early summer' was mapped to the first two months of summer only. Is this right????????????
# 'growing season' was mapped to summer.
season_orig = pages2k_data[counter]['climateInterpretation_seasonality']
if any(char.isdigit() for char in season_orig):
pages2k_data_seasonality = map(int,season_orig.split(' '))
elif season_orig == 'annual':
if year_type == 'tropical year': pages2k_data_seasonality = [4,5,6,7,8,9,10,11,12,13,14,15]
else: pages2k_data_seasonality = [1,2,3,4,5,6,7,8,9,10,11,12]
elif season_orig == 'summer':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7,8]
else: pages2k_data_seasonality = [-12,1,2]
elif season_orig == 'winter':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [-12,1,2]
else: pages2k_data_seasonality = [6,7,8]
elif season_orig == 'winter/spring':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [-12,1,2,3,4,5]
else: pages2k_data_seasonality = [6,7,8,9,10,11]
elif season_orig == 'early summer':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7]
else: pages2k_data_seasonality = [-12,1]
elif season_orig == 'growing season':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7,8]
else: pages2k_data_seasonality = [-12,1,2]
else:
if year_type == 'tropical year': pages2k_data_seasonality = [4,5,6,7,8,9,10,11,12,13,14,15]
else: pages2k_data_seasonality = [1,2,3,4,5,6,7,8,9,10,11,12]
# Spell out the name of the interpretation variable.
if pages2k_data[counter]['climateInterpretation_variable'] == 'T':
pages2k_data[counter]['climateInterpretation_variable'] = 'temperature'
# Save to a dataframe
frame = pd.DataFrame({'a':pages2k_data[counter]['siteID'], 'b':pages2k_data[counter]['geo_siteName'], 'c':pages2k_data[counter]['geo_meanLat'], \
'd':pages2k_data[counter]['geo_meanLon'], 'e':pages2k_data[counter]['geo_meanElev'], \
'f':pages2k_data[counter]['archiveType'], 'g':pages2k_data[counter]['paleoData_variableName'], \
'h':proxy_resolution, 'i':pages2k_data[counter]['time_annual'][0], 'j':pages2k_data[counter]['time_annual'][-1], \
'k':pages2k_data[counter]['geo_pages2kRegion'], 'l':pages2k_data[counter]['climateInterpretation_variable'], \
'm':pages2k_data[counter]['climateInterpretation_variableDetail'], \
'n':pages2k_data[counter]['climateInterpretation_interpDirection'], 'o':None, 'p':None}, index=[counter])
# To get seasonality & databases *lists* into columns 'o' and 'p' of DataFrame
frame.set_value(counter,'o',pages2k_data_seasonality)
frame.set_value(counter,'p',['PAGES2kv2'])
# Append to main DataFrame
metadf = metadf.append(frame)
#print ' ', '{:40}'.format(key), ' : ', len(nb)
tot.append(len(nb))
nbtot = sum(tot)
print(' ------------------------------------------------------')
print(' ','{:40}'.format('Total:'), ' : ', nbtot)
print('----------------------------------------------------------------------')
print(' ')
# Redefine column headers
metadf.columns = headers
# Write metadata to file
print('Now writing metadata to file:', metaout)
metadf.to_pickle(metaout)
# -----------------------------------------------------
# Build the proxy **data** DataFrame and output to file
# -----------------------------------------------------
print(' ')
print('Now creating & loading the data in the pandas DataFrame...')
print(' ')
for counter in range(0,len(pages2k_data)):
print("Processing metadata", counter+1, "/", len(pages2k_data), ":",
pages2k_data[counter]['paleoData_pages2kID'])
nbdata = len(pages2k_data[counter]['time_annual'])
# Load data in numpy array
frame_data = np.zeros(shape=[nbdata,2])
frame_data[:,0] = pages2k_data[counter]['time_annual']
frame_data[:,1] = pages2k_data[counter]['data_annual']
if counter == 0:
# Build up pandas DataFrame
header = ['NCDC ID', pages2k_data[counter]['siteID']]
df = pd.DataFrame({'a':frame_data[:,0], 'b':frame_data[:,1]})
df.columns = header
else:
frame = pd.DataFrame({'NCDC ID':frame_data[:,0], pages2k_data[counter]['siteID']:frame_data[:,1]})
df = df.merge(frame, how='outer', on='NCDC ID')
# Fix DataFrame index and column name
col0 = df.columns[0]
df.set_index(col0, drop=True, inplace=True)
df.index.name = 'Year C.E.'
df.sort_index(inplace=True)
# Write data to file
print('Now writing to file:', dataout)
df.to_pickle(dataout)
print(' ')
print('Done!')
# ===================================================================================
# For DTDA project proxy data -------------------------------------------------------
# ===================================================================================
def DTDA_xcel_to_dataframes(filename, metaout, dataout, take_average_out):
"""
Takes in Pages2K CSV and converts it to dataframe storage. This increases
size on disk due to the joining along the time index (lots of null values).
Makes it easier to query and grab data for the proxy experiments.
:param filename:
:param metaout:
:param dataout:
:return:
Author: Robert Tardif, Univ. of Washington
Based on pages_xcel_to_dataframes function written by
Andre Perkins (Univ. of Washington)
"""
meta_sheet_name = 'Metadata'
metadata = pd.read_excel(filename, meta_sheet_name)
# add a "Databases" column and set to LMR
metadata.loc[:,'Databases'] = '[LMR]'
# add a "Seasonality" column and set to [1,2,3,4,5,6,7,8,9,10,11,12]
metadata.loc[:,'Seasonality'] = '[1,2,3,4,5,6,7,8,9,10,11,12]'
metadata.loc[:,'Elev'] = 0.0
nbrecords = len(metadata)
# One proxy record per sheet, all named as DataXXX
record_sheet_names = ['Data'+str("{0:03d}".format(i+1)) for i in range(nbrecords)]
for i, sheet in enumerate(record_sheet_names):
pdata = pd.read_excel(filename, sheet)
# rounding age data to nearest year (Jess Tierney, pers. comm.)
age = (pdata[pdata.columns[0]][1:]).astype('float').round()
pdata[pdata.columns[0]][1:] = age
# -- just for print out - looking into time axis for each record
# age difference between consecutive data
diff = np.diff(pdata[pdata.columns[0]][1:], 1)
print('{:10s}'.format(pdata.columns[1]), ' : temporal resolution : mean=', '{:7.1f}'.format(np.mean(diff)), ' median=', '{:7.1f}'.format(np.median(diff)),\
' min=', '{:7.1f}'.format(np.min(diff)), ' max=', '{:7.1f}'.format(np.max(diff)))
resolution = np.mean(diff) # take average difference as representative "resolution"
# update resolution info in the metadata
metadata.loc[i,'Resolution (yr)'] = int(resolution)
if i == 0:
df = pdata
else:
# SQL like table join along index
df = df.merge(pdata, how='outer', on='Proxy ID')
#fix index and column name
col0 = df.columns[0]
# check time definition and convert to year CE if needed
newcol0 = df[col0][0]
if newcol0 == 'Year C.E.' or newcol0 == 'Year CE':
# do nothing
pass
elif newcol0 == 'Year BP':
newcol0 = 'Year C.E.'
df[col0][1:] = 1950. - df[col0][1:]
else:
print('Unrecognized time definition...')
raise SystemExit()
df.set_index(col0, drop=True, inplace=True)
df.index.name = newcol0
df = df.ix[1:]
df.sort_index(inplace=True)
# Checkin for duplicate ages in proxy record. If present, calculate average (Jess Tierney, pers. comm.)
df = df.astype(float)
df_f = df.groupby(df.index).mean()
if take_average_out:
# copy of dataframe
df_tmp = df_f
# fill dataframe with new values where temporal averages over proxy records are subtracted
df_f = df_tmp.sub(df_tmp.mean(axis=0), axis=1)
# TODO: make sure year index is consecutive
#write data to file
df_f.to_pickle(dataout)
# Make sure ...
metadata['Archive type'] = metadata['Archive type'].astype(str)
# Add 'Youngest (C.E.)', 'Oldest (C.E.)' 'Elev' and 'Seasonality' info to metadata
sites = list(df_f)
for s in sites:
# 'Youngest' and 'Oldest' info based on the age data
values = df_f[s]
values = values[values.notnull()]
times = values.index.values
meta_ind = metadata[metadata['Proxy ID'] == s].index
metadata.loc[meta_ind,'Oldest (C.E.)'] = np.min(times)
metadata.loc[meta_ind,'Youngest (C.E.)'] = np.max(times)
# write metadata to file
metadata.to_pickle(metaout)
# ===================================================================================
# For PAGES2k phase 2 (2017) proxy data ---------------------------------------------
# ===================================================================================
def pages2kv2_pickle_to_dict(datadir, pages2kv2_file, proxy_def, year_type, gaussianize_data):
"""
Takes in a Pages2k pickle (pklz) file and converts it to python dictionary storage.
Authors: R. Tardif, Univ. of Washington, Jan 2016.
M. Erb, Univ. of Southern California, Feb 2017
Revisions:
- Modified output, storing proxy information in dictionary returned
by the function, instead of storing in pandas dataframe dumped to
pickle file, as done in the original version by M. Erb.
[R. Tardif, U. of Washington, May 2017]
"""
valid_frac = 0.5
# ===============================================================================
# Upload proxy data from Pages2k v2 pickle file
# ===============================================================================
begin_time = clock.time()
# Open the pickle file containing the Pages2k data, if it exists in target directory
infile = os.path.join(datadir, pages2kv2_file)
if os.path.isfile(infile):
print('Data from PAGES2k phase 2:')
print((' Uploading data from %s ...' %infile))
try:
# try to read as a straight pckl file
pages2k_data = pd.read_pickle(infile)
# f = open(infile,'rb')
# pages2k_data = pickle.load(f)
# f.close()
except:
# failed to read so try as a compressed pckl (pklz) file
try:
f = gzip.open(infile,'rb')
pages2k_data = pickle.load(f)
f.close()
except:
raise SystemExit(('ERROR: Could not read the PAGES2kv2 proxy file {}'
' as a regular or compressed pickle file. Unrecognized format!').format(pages2kv2_file))
else:
raise SystemExit(('ERROR: Option to include PAGES2kv2 proxies enabled'
' but corresponding data file could not be found!'
' Please place file {} in directory {}').format(pages2kv2_file,datadir))
# Summary of the uploaded data
nbsites = len(pages2k_data)
proxy_dict_pagesv2 = {}
tot = []
nb = []
for counter in range(0,nbsites):
# Give each record a unique descriptive name
pages2k_data[counter]['siteID'] = "PAGES2kv2_"+pages2k_data[counter]['dataSetName']+\
"_"+pages2k_data[counter]['paleoData_pages2kID']+\
":"+pages2k_data[counter]['paleoData_variableName']
nb.append(pages2k_data[counter]['siteID'])
print((' Processing %s/%s : %s' %(str(counter+1), str(len(pages2k_data)), pages2k_data[counter]['paleoData_pages2kID'])))
# Look for publication title & authors
if 'NEEDS A TITLE' not in pages2k_data[counter]['pub1_title']:
pages2k_data[counter]['pub_title'] = pages2k_data[counter]['pub1_title']
pages2k_data[counter]['pub_author'] = pages2k_data[counter]['pub1_author']
else:
if 'NEEDS A TITLE' not in pages2k_data[counter]['pub2_title']:
pages2k_data[counter]['pub_title'] = pages2k_data[counter]['pub2_title']
pages2k_data[counter]['pub_author'] = pages2k_data[counter]['pub2_author']
else:
pages2k_data[counter]['pub_title'] = 'Unknown'
pages2k_data[counter]['pub_author'] = 'Unknown'
# If the time axis goes backwards (i.e. newer to older), reverse it.
if pages2k_data[counter]['year'][-1] - pages2k_data[counter]['year'][-2] < 0:
pages2k_data[counter]['year'].reverse()
pages2k_data[counter]['paleoData_values'].reverse()
# If subannual, average up to annual --------------------------------------------------------
time_raw = np.array(pages2k_data[counter]['year'],dtype=np.float)
data_raw = np.array(pages2k_data[counter]['paleoData_values'],dtype=np.float)
# Remove values where either time or data is nan.
nan_indices = np.isnan(time_raw)+np.isnan(data_raw)
time_raw = time_raw[~nan_indices]
data_raw = data_raw[~nan_indices]
# Use the following function to make annual-means.
# Inputs: time_raw, data_raw, valid_frac, year_type. Outputs: time_annual, data_annual
time_annual, data_annual, proxy_resolution = compute_annual_means(time_raw,data_raw,valid_frac,year_type)
data_annual = np.squeeze(data_annual)
# If gaussianize_data is set to true, transform the proxy data to Gaussian.
# This option should only be used when using regressions, not physically-based PSMs.
if gaussianize_data == True:
data_annual = gaussianize(data_annual)
# Write the annual data to the dictionary, so they can use written to
# the data file outside of this loop.
pages2k_data[counter]['time_annual'] = time_annual
pages2k_data[counter]['data_annual'] = data_annual
# Rename the proxy types in the same convention as the LMR's NCDC dataset.
# Proxy types not renamed, except capitalizing 1st letter: bivalve, borehole, documents, hybrid
if (pages2k_data[counter]['archiveType'] == 'coral') or (pages2k_data[counter]['archiveType'] == 'sclerosponge'):
pages2k_data[counter]['archiveType'] = 'Corals and Sclerosponges'
elif pages2k_data[counter]['archiveType'] == 'glacier ice':
pages2k_data[counter]['archiveType'] = 'Ice Cores'
elif pages2k_data[counter]['archiveType'] == 'lake sediment':
pages2k_data[counter]['archiveType'] = 'Lake Cores'
elif pages2k_data[counter]['archiveType'] == 'marine sediment':
pages2k_data[counter]['archiveType'] = 'Marine Cores'
elif pages2k_data[counter]['archiveType'] == 'speleothem':
pages2k_data[counter]['archiveType'] = 'Speleothems'
elif pages2k_data[counter]['archiveType'] == 'tree':
pages2k_data[counter]['archiveType'] = 'Tree Rings'
elif pages2k_data[counter]['archiveType'] == 'bivalve':
pages2k_data[counter]['archiveType'] = 'Bivalve'
elif pages2k_data[counter]['archiveType'] == 'borehole':
pages2k_data[counter]['archiveType'] = 'Borehole'
elif pages2k_data[counter]['archiveType'] == 'documents':
pages2k_data[counter]['archiveType'] = 'Documents'
elif pages2k_data[counter]['archiveType'] == 'hybrid':
pages2k_data[counter]['archiveType'] = 'Hybrid'
# Rename some of the the proxy measurements to be more standard.
if (pages2k_data[counter]['archiveType'] == 'Ice Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'd18O1'):
pages2k_data[counter]['paleoData_variableName'] = 'd18O'
elif (pages2k_data[counter]['archiveType'] == 'Tree Rings') and (pages2k_data[counter]['paleoData_variableName'] == 'temperature1'):
pages2k_data[counter]['paleoData_variableName'] = 'temperature'
elif (pages2k_data[counter]['archiveType'] == 'Lake Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'temperature1'):
pages2k_data[counter]['paleoData_variableName'] = 'temperature'
elif (pages2k_data[counter]['archiveType'] == 'Lake Cores') and (pages2k_data[counter]['paleoData_variableName'] == 'temperature3'):
pages2k_data[counter]['paleoData_variableName'] = 'temperature'
# Not all records have data for elevation. In these cases, set elevation to nan.
if 'geo_meanElev' not in pages2k_data[counter]:
pages2k_data[counter]['geo_meanElev'] = np.nan
# Ensure lon is in [0,360] domain
if pages2k_data[counter]['geo_meanLon'] < 0.0:
pages2k_data[counter]['geo_meanLon'] = 360 + pages2k_data[counter]['geo_meanLon']
# Determine the seasonality of the record.
# Seasonal names were mapped the three-month climatological seasons.
# 'early summer' was mapped to the first two months of summer only. Is this right????????????
# 'growing season' was mapped to summer.
season_orig = pages2k_data[counter]['climateInterpretation_seasonality']
if any(char.isdigit() for char in season_orig):
pages2k_data_seasonality = list(map(int,season_orig.split(' ')))
elif season_orig == 'annual':
if year_type == 'tropical year': pages2k_data_seasonality = [4,5,6,7,8,9,10,11,12,13,14,15]
else: pages2k_data_seasonality = [1,2,3,4,5,6,7,8,9,10,11,12]
elif season_orig == 'summer':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7,8]
else: pages2k_data_seasonality = [-12,1,2]
elif season_orig == 'winter':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [-12,1,2]
else: pages2k_data_seasonality = [6,7,8]
elif season_orig == 'winter/spring':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [-12,1,2,3,4,5]
else: pages2k_data_seasonality = [6,7,8,9,10,11]
elif season_orig == 'early summer':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7]
else: pages2k_data_seasonality = [-12,1]
elif season_orig == 'growing season':
if pages2k_data[counter]['geo_meanLat'] >= 0: pages2k_data_seasonality = [6,7,8]
else: pages2k_data_seasonality = [-12,1,2]
else:
if year_type == 'tropical year': pages2k_data_seasonality = [4,5,6,7,8,9,10,11,12,13,14,15]
else: pages2k_data_seasonality = [1,2,3,4,5,6,7,8,9,10,11,12]