-
Notifications
You must be signed in to change notification settings - Fork 1
/
marginal_covariance_analysis.py
executable file
·1989 lines (1840 loc) · 65.7 KB
/
marginal_covariance_analysis.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
#!/usr/bin/env python
# ~*~ coding: utf8 ~*~
# pylint: disable=invalid-name
"""Find marginal covariances in space and time."""
from __future__ import division, print_function
import calendar
import datetime
import inspect
import itertools
import operator
import re
try:
from typing import List
except ImportError:
pass
import bottleneck as bn
import cartopy.crs as ccrs
import dask.array as da
import dask.config
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyproj
import scipy.optimize
import xarray
from bottleneck import nansum
from numpy import cos, exp, newaxis, sin, square
from statsmodels.tools.eval_measures import aic, aicc, bic, hqic
from statsmodels.tsa.stattools import acf, acovf
from correlation_utils import count_pairs
# import pymc3 as pm
MINUTES_PER_HOUR = 60
HOURS_PER_DAY = 24
MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY
DAYS_PER_DAY = 1
DAYS_PER_YEAR = 365.2425
HOURS_PER_YEAR = HOURS_PER_DAY * DAYS_PER_YEAR
DAYS_PER_WEEK = 7
MONTHS_PER_YEAR = 12
GLOBE = ccrs.Globe(semimajor_axis=6370000, semiminor_axis=6370000)
PROJECTION = ccrs.LambertConformal(
standard_parallels=(30, 60),
central_latitude=40,
central_longitude=-96,
globe=GLOBE,
)
GEOD = pyproj.Geod(sphere=True, a=6370000)
PI_OVER_DAY = np.pi / DAYS_PER_DAY
TWO_PI_OVER_DAY = 2 * PI_OVER_DAY
PI_OVER_YEAR = np.pi / DAYS_PER_YEAR
TWO_PI_OVER_YEAR = 2 * PI_OVER_YEAR
FOUR_PI_OVER_YEAR = 4 * PI_OVER_YEAR
PSU = "Pennsylvania State University Department of Meteorology and Atmospheric Science"
UTC = datetime.timezone.utc
# from pytz import UTC
NOW = datetime.datetime.now(UTC)
NOW_ISO = NOW.isoformat()
dask.config.update(
dask.config.config, {"array": {"chunk-size": "2GiB"}, "scheduler": "threads"}
)
arry = da.arange(100)
arry = arry[np.newaxis, :] + arry[::-1, np.newaxis]
############################################################
# From ameriflux_base_to_netcdf
AMF_BASE_VAR_NAME_REGEX = re.compile(
r"^(?P<physical_name>\w+?)(?P<quality_flag1>_SSITC_TEST)?(?:_PI)?(?:_QC)?"
r"(?:_F)?(?:_IU)?(?P<loc_rep_agg>_\d+_\d+_(?:\d+|A)|_\d+)?(?:_(?:SD|N))?$"
)
NOW_TIME = datetime.datetime.now(UTC).replace(microsecond=0, second=0, minute=0)
NOW = NOW_TIME.isoformat()
def harmonize_variables(ds_lst):
# type: (List[xarray.Dataset]) -> List[xarray.Dataset]
"""Make sure the datasets have the same variables."""
variable_dims = {
name: da.variables[name].dims for da in ds_lst for name in da.variables
}
coord_list = frozenset(name for dataset in ds_lst for name in dataset.coords)
ancillary_variables = {
name: dict(zip(dataset.variables[name].dims, dataset.variables[name].shape))
for dataset in ds_lst
for data_var in dataset.data_vars.values()
for name in data_var.attrs.get("ancillary_variables", "").split()
if name in data_var.coords
}
result = [dataset.copy() for dataset in ds_lst if arry.size > 0]
for dataset in result:
for variable_name, variable_dim_list in variable_dims.items():
if variable_name not in dataset.variables and all(
dim in dataset.dims for dim in variable_dim_list
):
new_variable = (
variable_dim_list,
np.full(
tuple(
dataset.dims[variable_dim_name]
for variable_dim_name in variable_dim_list
),
np.nan,
dtype="f4",
),
)
if variable_name not in coord_list:
dataset[variable_name] = new_variable
else:
dataset.coords[variable_name] = new_variable
for aux_name, aux_dims in ancillary_variables.items():
if aux_name not in dataset.coords:
dataset.coords[aux_name] = (
aux_dims,
np.full(
tuple(dataset.dims[aux_dim_name] for aux_dim_name in aux_dims),
np.nan,
dtype="f4",
),
)
elif "site" not in dataset.coords[aux_name].dims:
dataset.coords[aux_name] = dataset.coords[aux_name].expand_dims(
aux_dims
)
return result
def take_var_from_ds(source_dataset, flux_var, apply_qc=False):
# type: (xarray.Dataset, str, bool) -> xarray.DataArray
"""Take var from the dataset, dropping irrelevant aux vars.
Parameters
----------
source_dataset : xarray.Dataset
The dataset from which to take the variable
flux_var : str
The flux variable to extract
apply_qc : bool
Drop data with bad QC? (>=2)
Returns
-------
xarray.DataArray
"""
result = source_dataset[flux_var]
to_drop = [
name
for name in source_dataset.coords
if re.sub(AMF_BASE_VAR_NAME_REGEX, r"\g<physical_name>\g<loc_rep_agg>", name)
not in [flux_var, name]
]
result = result.drop_vars(to_drop)
if apply_qc:
result = result.where("SSITC_TEST < 2")
return result
def save_dataset_netcdf(dataset, filename):
# type: (xarray.Dataset, str) -> None
"""Save the dataset as a netcdf.
Parameters
----------
dataset : xarray.Dataset
Dataset to save
filename : str
Name to save it under
"""
# Avoid propagating changes to caller. I could probably achieve a
# similar effect with dataset.set_coords().
dataset = dataset.copy()
date_index = dataset.indexes["TIMESTAMP_START"]
dataset.coords["time_bnds"] = xarray.DataArray(
np.column_stack(
[date_index.to_array(), date_index.to_array() + np.array(1, dtype="m8[h]")]
),
dims=("TIMESTAMP_START", "bnds2"),
attrs=dict(standard_name="time", coverage_content_type="coordinate"),
)
# dataset.coords["TIMESTAMP_START"] = xarray.DataArray(
# period_index.start_time,
# dims="TIMESTAMP_START",
# attrs=dict(
# standard_name="time",
# axis="T",
# bounds="time_bnds",
# long_name="start_of_observation_period",
# coverage_content_type="coordinate",
# freq=period_index.freqstr,
# ),
# )
# # if resolution == "half_hour":
# # dataset.attrs["time_coverage_resolution"] = "P0000-00-00T00:30:00"
# # else:
# # dataset.attrs["time_coverage_resolution"] = "P0000-00-00T01:00:00"
# dataset.attrs["time_coverage_resolution"] = period_index.freq.delta.isoformat()
dataset.attrs["time_coverage_resolution"] = "P0000-00-00T01:00:00"
dataset.attrs["time_coverage_start"] = str(
min(dataset.coords["TIMESTAMP_START"].values)
)
dataset.attrs["time_coverage_end"] = str(
max(dataset.coords["TIMESTAMP_START"].values)
)
dataset.attrs["time_coverage_duration"] = operator.sub(
*dataset.indexes["TIMESTAMP_START"][[-1, 0]]
).isoformat()
dataset.coords["time_written"] = NOW_TIME.time().isoformat()
dataset.coords["date_written"] = NOW_TIME.date().isoformat()
# It's around 50MB/variable, which I can get away without compressing.
# If I'm wrong, I can use NCO to change the chunksizes and compress.
encoding = {
name: {"_FillValue": -9999, "zlib": False} for name in dataset.data_vars
}
encoding.update({name: {"_FillValue": None} for name in dataset.coords})
# Set units for time variables with bounds
for coord_name in dataset.coords:
if "bounds" not in dataset.coords[coord_name].attrs:
continue
if "M8" in dataset.coords[coord_name].dtype.str:
start_time = dataset.coords[coord_name].values[0]
encoding[coord_name]["units"] = "minutes since {:s}".format(str(start_time))
encoding[dataset.coords[coord_name].attrs["bounds"]]["units"] = encoding[
coord_name
]["units"]
dataset.to_netcdf(
filename,
encoding=encoding,
format="NETCDF4",
mode="w",
)
############################################################
# Read in flux data
print("Reading AmeriFlux data", flush=True)
DATA_MERGED = False
if not DATA_MERGED:
amf_hour_ds = xarray.open_dataset(
"/abl/s0/Continent/dfw5129/ameriflux_netcdf/ameriflux_base_data/output/"
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_hour_data.nc4",
chunks={"TIMESTAMP_START": 2 * int(HOURS_PER_YEAR)},
).load()
# # It would appear the only way to get a PeriodIndex into a Dataset
# # is by conversion from a DataFame
# amf_hour_ds.coords["TIMESTAMP_START"] = (
# ("TIMESTAMP_START",),
# amf_hour_ds.indexes["TIMESTAMP_START"].to_period("1H"),
# amf_hour_ds.coords["TIMESTAMP_START"].attrs,
# amf_hour_ds.coords["TIMESTAMP_START"].encoding,
# )
print("Reading more AmeriFlux data", flush=True)
HALF_HOUR_DATA_RESAMPLED = True
if not HALF_HOUR_DATA_RESAMPLED:
amf_half_hour_ds = xarray.open_dataset(
"/abl/s0/Continent/dfw5129/ameriflux_netcdf/ameriflux_base_data/output/"
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_half_hour_data"
".nc4",
chunks={"TIMESTAMP_START": 2 * int(2 * HOURS_PER_YEAR)},
).load()
# # amf_half_hour_ds.coords["TIMESTAMP_START"] = (
# # ("TIMESTAMP_START",),
# # amf_half_hour_ds.indexes["TIMESTAMP_START"].to_period("1H"),
# # amf_half_hour_ds.coords["TIMESTAMP_START"].attrs,
# # amf_half_hour_ds.coords["TIMESTAMP_START"].encoding,
# # )
# time_attrs = amf_half_hour_ds.coords["TIMESTAMP_START"].attrs
# amf_half_hour_ds.indexes["TIMESTAMP_START"] = amf_half_hour_ds.indexes[
# "TIMESTAMP_START"
# ].to_period("1H")
# amf_half_hour_ds.coords["TIMESTAMP_START"].attrs.update(time_attrs)
# del time_attrs
print("Resampling half-hour data", flush=True)
amf_half_hour_ds = amf_half_hour_ds.resample(TIMESTAMP_START="1H").mean()
print("Rechunking half-hour data", flush=True)
amf_half_hour_ds.transpose("site", "TIMESTAMP_START").load()
# .chunk(
# {"site": 20, "TIMESTAMP_START": -1}
# )
print("Loading half-hour data", flush=True)
amf_half_hour_ds = amf_half_hour_ds.persist()
print("Writing half-hour data to disk", flush=True)
save_dataset_netcdf(
amf_half_hour_ds,
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_half_hour_data_"
"resampled_to_hourly.nc4",
)
else:
amf_half_hour_ds = xarray.open_dataset(
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_half_hour_data_"
"resampled_to_hourly.nc4"
)
print("Combining AmeriFlux data", flush=True)
amf_ds = (
xarray.concat(
harmonize_variables(
[
amf_hour_ds,
amf_half_hour_ds,
]
),
dim="site",
fill_value=np.nan,
)
# .chunk({"ameriflux_tower_location": 25, "TIMESTAMP_START": -1})
.persist()
)
print("Saving AmeriFlux data", flush=True)
save_dataset_netcdf(
amf_ds,
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_hourly_resampled.nc4",
)
else:
amf_ds = xarray.open_dataset(
"AmeriFlux_all_CO2_fluxes_with_single_estimate_per_tower_hourly_resampled.nc4"
).persist()
print(amf_ds.coords)
print("Reading CASA data", flush=True)
casa_ds = (
xarray.open_mfdataset(
(
"/abl/s0/Continent/dfw5129/casa_downscaling/"
"20??-??_downscaled_CASA_L2_Ensemble_Mean_Biogenic_NEE_Ameriflux.nc4"
),
combine="by_coords",
chunks={"ameriflux_tower_location": 20},
)
.transpose("ameriflux_tower_location", "time")
.persist()
)
print(casa_ds.coords)
# Pull out matching flux data
print("Finding matching data points", flush=True)
sites_in_both = sorted(
list(set(casa_ds.coords["SiteFID"].values) & set(amf_ds.coords["site"].values))
)
times_in_both = pd.DatetimeIndex(
sorted(
list(
set(casa_ds.coords["time"].values)
& set(amf_ds.coords["TIMESTAMP_START"].values)
)
)
)
print("Extracting matching data points", flush=True)
amf_data_rect = (
amf_ds["ameriflux_carbon_dioxide_flux_estimate"]
.sel(site=sites_in_both, TIMESTAMP_START=times_in_both)
.astype(np.float32)
.transpose("site", "TIMESTAMP_START")
.load()
)
casa_data_rect = (
casa_ds["NEE"]
.set_index(ameriflux_tower_location="SiteFID")
.sel(
ameriflux_tower_location=sites_in_both,
time=times_in_both,
)
.astype(np.float32)
.load()
)
for name in list(casa_data_rect.coords):
if name not in casa_ds.coords:
del casa_data_rect.coords[name]
print("Creating big dataset", flush=True)
matching_data_ds = (
xarray.Dataset(
{
"ameriflux_fluxes": amf_data_rect,
"casa_fluxes": casa_data_rect.rename(
ameriflux_tower_location="site",
time="TIMESTAMP_START",
)
.transpose("site", "TIMESTAMP_START")
.drop_vars("UTC_OFFSET"),
},
)
.persist()
.rename(TIMESTAMP_START="time")
)
matching_data_ds["flux_difference"] = (
matching_data_ds["ameriflux_fluxes"] - matching_data_ds["casa_fluxes"]
)
matching_data_ds["flux_difference"].attrs.update(
{
"long_name": "ameriflux_carbon_dioxide_flux_minus_casa_carbon_dioxide_flux",
"units": "umol/m^2/s",
}
)
# matching_data_ds.coords["time_bnds"] = amf_hour_ds.coords["time_bnds"]
# matching_data_ds.coords["TIMESTAMP_START"].attrs.update(
# {"valid_min": 0,
# "valid_max": 15 * HOURS_PER_YEAR}
# )
matching_data_ds.attrs.update(
dict(
history=(
"created from processed Ameriflux data files and "
"500m CASA outputs downscaled using ERA5"
),
institution=PSU,
title="Ameriflux minus CASA carbon dioxide flux differences",
acknowledgement=(
"CASA: ACT-America\nERA5: ECMWF\n"
"AmeriFlux Towers: {ameriflux_sources:s}"
).format(
ameriflux_sources=""
),
cdm_data_type="Station",
Conventions="CF-1.7,ACDD-1.3",
creator_email="[email protected]",
creator_institution=PSU,
creator_name="Daniel Wesloh",
creator_type="person",
date_metadata_modified=NOW_ISO,
date_modified=NOW_ISO,
date_created=NOW_ISO,
date_written=NOW_TIME.date().isoformat(),
time_written=NOW_TIME.time().replace(microsecond=0).isoformat(),
geospatial_lat_min=matching_data_ds.coords["Latitude"].min().values,
geospatial_lat_max=matching_data_ds.coords["Latitude"].max().values,
geospatial_lat_units="degrees_north",
geospatial_lon_min=matching_data_ds.coords["Longitude"].min().values,
geospatial_lon_max=matching_data_ds.coords["Longitude"].max().values,
geospatial_lon_units="degrees_east",
product_version=1,
program="NASA EVS",
project="Atmospheric Carbon and Transport-America",
source=(
"CASA from Yu et al. (2020), retrieved from ORNL; "
"AmeriFlux data from various contributors"
),
standard_name_vocabulary="CF Standard Name table v70",
time_coverage_start=matching_data_ds.indexes["time"][0].isoformat(),
time_coverage_end=matching_data_ds.indexes["time"][-1].isoformat(),
time_coverage_duration=(
matching_data_ds.indexes["time"][-1] - matching_data_ds.indexes["time"][0]
).isoformat(),
# "P0006-08-30T00:00:00",
time_coverage_resolution="PT1H",
ncei_template_version="NCEI_NetCDF_TimeSeries_Orthogonal_Template_v2.0",
featureType="timeSeries",
)
)
encoding = {
name: {"_FillValue": -99, "zlib": True} for name in matching_data_ds.data_vars
}
encoding.update({name: {"_FillValue": None} for name in matching_data_ds.coords})
encoding["time"]["units"] = "hours since 2003-01-01T00:00:00+00:00"
encoding["time"]["dtype"] = np.int32
print("Saving big dataset", flush=True)
matching_data_ds.to_netcdf(
"ameriflux-and-casa-matching-data.nc4",
encoding=encoding,
engine="h5netcdf",
)
matching_data_ds.coords["month"] = matching_data_ds.coords["time"].dt.month
matching_data_ds.coords["hour"] = matching_data_ds.coords["time"].dt.hour
matching_data_ds.coords["month_hour"] = (
matching_data_ds.coords["month"] * 1000 + matching_data_ds.coords["hour"]
)
matching_data_month_hour_long = matching_data_ds.groupby("month_hour").mean()
matching_data_month_hour_long.coords["month"] = (
matching_data_month_hour_long.coords["month_hour"] // 1000
)
matching_data_month_hour_long.coords["hour"] = (
matching_data_month_hour_long.coords["month_hour"] % 1000
)
matching_data_month_hour_ds = matching_data_month_hour_long.set_index(
month_hour=["month", "hour"]
).unstack()
matching_data_month_ds = matching_data_ds.groupby("month").mean()
matching_data_month_hour_ds.coords["climatology_bounds_approximation"] = (
["month", "hour", "bounds2"],
np.array(
[
[
[
pd.Timestamp(
"2003-{month.values:02d}-01T{hour.values:02d}:00:00+00:00".format(
month=month, hour=hour
)
),
pd.Timestamp(
"2018-{month.values:02d}-28T{hour.values:02d}:00:00+00:00".format(
month=month, hour=hour
)
),
]
for hour in matching_data_month_hour_ds.coords["hour"]
]
for month in matching_data_month_hour_ds.coords["month"]
]
).astype("M8[ns]"),
{"standard_name": "climatology_bounds"},
)
matching_data_month_ds.coords["climatology_bounds_approximation"] = (
["month", "bounds2"],
np.array(
[
[
pd.Timestamp(
"2003-{month.values:02d}-01T00:00:00+00:00".format(month=month)
),
pd.Timestamp(
"2018-{month.values:02d}-28T23:59:59+00:00".format(month=month)
),
]
for month in matching_data_month_hour_ds.coords["month"]
]
).astype("M8[ns]"),
{"standard_name": "climatology_bounds"},
)
del encoding["time"], encoding["height"]
matching_data_month_hour_ds.to_netcdf(
"ameriflux-and-casa-all-towers-daily-cycle-by-month.nc4",
encoding={
key: val
for key, val in encoding.items()
if key in matching_data_month_hour_ds.variables
},
engine="h5netcdf",
)
matching_data_month_ds.to_netcdf(
"ameriflux-and-casa-all-towers-seasonal-cycle.nc4",
encoding={
key: val
for key, val in encoding.items()
if key in matching_data_month_ds.variables
},
engine="h5netcdf",
)
amf_data = (
amf_data_rect.stack(data_point=("site", "TIMESTAMP_START"))
.dropna("data_point")
.persist()
)
casa_data = (
casa_data_rect.sel(
ameriflux_tower_location=amf_data.coords["site"],
time=amf_data.coords["TIMESTAMP_START"],
)
.dropna("data_point")
.persist()
)
# Find differences
difference = (amf_data.load() - casa_data.load()).dropna("data_point").persist()
coords = np.empty((difference.shape[0], 3), dtype=np.float32)
values = np.array(difference.values, dtype=np.float32)
data_times_int = (
difference.coords["TIMESTAMP_START"].values.astype("M8[m]").astype("i8")
)
data_times_int -= data_times_int[0]
coords[:, 0] = data_times_int.astype(np.float32)
coords[:, 0] /= MINUTES_PER_DAY
# Set to map coordinates in meters
coords[:, 1:] = PROJECTION.transform_points(
PROJECTION.as_geodetic(),
difference.coords["Longitude"].values,
difference.coords["Latitude"].values,
)[:, :2]
# Convert to kilometers
coords[:, 1:] /= 1e3
to_delete = [
coord_name
for coord_name in difference.coords
if (
coord_name not in difference.dims
and "LOCATION" not in coord_name
and "lat" not in coord_name.lower()
and "lon" not in coord_name.lower()
)
]
for coord_name in to_delete:
del difference.coords[coord_name]
hour_data = np.column_stack([coords, values.astype(np.float32)])
# assert amf_data.attrs["units"] == "umol/m2/s"
# assert casa_data.attrs["units"] == "umol/m2/s"
hour_df = pd.DataFrame(
hour_data, columns=["time_days", "x_km", "y_km", "flux_diff_umol_m2_s"]
)
hour_df.to_csv("ameriflux_minus_casa_all_towers.csv")
############################################################
# Find distances between all pairs of points
# Will be in meters
distance_matrix = pd.DataFrame(
index=amf_ds.indexes["site"], columns=amf_ds.indexes["site"], dtype=np.float64
)
vegtype_match_matrix = pd.DataFrame(
index=amf_ds.indexes["site"], columns=amf_ds.indexes["site"], dtype=bool
)
koeppen_match_matrix = pd.DataFrame(
index=amf_ds.indexes["site"], columns=amf_ds.indexes["site"], dtype=bool
)
site_coords = amf_ds.coords["site"].load()
# Very slow
GEOD_line_length = GEOD.line_length
for site1, site2 in itertools.product(site_coords, site_coords):
site1_name = site1.values[()]
site2_name = site2.values[()]
distance_matrix.loc[site1_name, site2_name] = GEOD_line_length(
[site1.coords["LOCATION_LONG"], site2.coords["LOCATION_LONG"]],
[site1.coords["LOCATION_LAT"], site2.coords["LOCATION_LAT"]],
)
vegtype_match_matrix.loc[site1_name, site2_name] = (
site1.coords["IGBP"].values == site2.coords["IGBP"].values
)
koeppen_match_matrix.loc[site1_name, site2_name] = (
amf_ds.coords["CLIMATE_KOEPPEN"].sel(site=site1_name).values
== amf_ds.coords["CLIMATE_KOEPPEN"].sel(site=site2_name).values
)
# Convert distance to kilometers
# Will improve conditioning of later problems
distance_matrix /= 1000
distance_matrix.to_csv("ameriflux-all-towers-distance-matrix-km.csv")
vegtype_match_matrix.to_csv("ameriflux-all-towers-vegetation-type-match-matrix.csv")
koeppen_match_matrix.to_csv(
"ameriflux-all-towers-koeppen-classification-match-matrix.csv"
)
############################################################
# Make a times-by-sites array of the differences
difference_df_rect = difference.to_dataframe(
name="ameriflux_minus_casa_hour_towers_umol_m2_s"
)["ameriflux_minus_casa_hour_towers_umol_m2_s"].unstack(0)
difference_df_rect.to_csv("ameriflux-minus-casa-all-towers-difference-data-rect.csv")
difference_xarray = difference.to_dataset(
name="ameriflux_minus_casa_carbon_dioxide_flux"
)
difference_rect_xarray = difference_xarray.unstack("data_point")
for name in ("LOCATION_LAT", "LOCATION_LONG", "LOCATION_ELEV", "Longitude", "Latitude"):
difference_rect_xarray.coords[name] = difference_rect_xarray.coords[name].mean(
"TIMESTAMP_START"
)
difference_rect_xarray[
"ameriflux_minus_casa_carbon_dioxide_flux"
] = difference_rect_xarray["ameriflux_minus_casa_carbon_dioxide_flux"].astype(
np.float32
)
difference_rect_xarray["ameriflux_minus_casa_carbon_dioxide_flux"].attrs.update(
dict(
units="umol/m2/s",
long_name="ameriflux_minus_casa_surface_upward_mole_flux_of_carbon_dioxide",
coverage_content_type="modelResult",
)
)
for name in ("LOCATION_LAT", "Latitude"):
difference_rect_xarray.coords[name].attrs.update(
dict(
units="degrees_north",
standard_name="latitude",
long_name="latitude",
valid_range=(0.0, 90.0),
)
)
for name in ("LOCATION_LONG", "Longitude"):
difference_rect_xarray.coords[name].attrs.update(
dict(
units="degrees_east",
standard_name="longitude",
long_name="longitude",
valid_range=(-180.0, 360.0),
)
)
difference_rect_xarray.coords["site_id"] = difference_rect_xarray.coords["site"]
difference_rect_xarray.coords["site_id"].attrs.update(
dict(
cf_role="timeseries_id",
long_name="AmeriFlux_station_id",
)
)
difference_rect_xarray.coords["site"] = np.arange(difference_rect_xarray.dims["site"])
difference_rect_xarray.coords["TIMESTAMP_START"].attrs.update(
dict(
axis="T",
standard_name="time",
long_name="start_of_ameriflux_averaging_window",
bounds="time_bnds",
)
)
for name in (
"IGBP",
"CLIMATE_KOEPPEN",
"SITE_NAME",
"IGBP_COMMENT",
"LOCATION_ELEV",
"TERRAIN",
"SITE_DESC",
"time_bnds",
):
difference_rect_xarray.coords[name] = amf_ds.coords[name]
for name in ("SITE_FUNDING", "ACKNOWLEDGEMENT"):
difference_rect_xarray.coords["AMERIFLUX_" + name] = amf_ds.coords[name]
difference_rect_xarray.attrs.update(
dict(
history=(
"created from processed Ameriflux data files and "
"500m CASA outputs downscaled using ERA5"
),
institution=PSU,
title="Ameriflux minus CASA carbon dioxide flux differences",
acknowledgement=(
"CASA: ACT-America\nERA5: ECMWF\n"
"AmeriFlux Towers: {ameriflux_sources:s}"
).format(
ameriflux_sources=""
),
cdm_data_type="Station",
Conventions="CF-1.7,ACDD-1.3",
creator_email="[email protected]",
creator_institution=PSU,
creator_name="Daniel Wesloh",
creator_type="person",
date_metadata_modified=NOW_ISO,
date_modified=NOW_ISO,
date_created=NOW_ISO,
date_written=NOW_TIME.date().isoformat(),
time_written=NOW_TIME.time().replace(microsecond=0).isoformat(),
geospatial_lat_min=difference_rect_xarray.coords["Latitude"].min().values,
geospatial_lat_max=difference_rect_xarray.coords["Latitude"].max().values,
geospatial_lat_units="degrees_north",
geospatial_lon_min=difference_rect_xarray.coords["Longitude"].min().values,
geospatial_lon_max=difference_rect_xarray.coords["Longitude"].max().values,
geospatial_lon_units="degrees_east",
product_version=1,
program="NASA EVS",
project="Atmospheric Carbon and Transport-America",
source=(
"CASA from Yu et al. (2020), retrieved from ORNL; "
"AmeriFlux data from various contributors"
),
standard_name_vocabulary="CF Standard Name table v70",
time_coverage_start=difference_rect_xarray.indexes["TIMESTAMP_START"][
0
].isoformat(),
time_coverage_end=difference_rect_xarray.indexes["TIMESTAMP_START"][
-1
].isoformat(),
time_coverage_duration=(
difference_rect_xarray.indexes["TIMESTAMP_START"][-1]
- difference_rect_xarray.indexes["TIMESTAMP_START"][0]
).isoformat(),
# "P0006-08-30T00:00:00",
time_coverage_resolution="PT1H",
ncei_template_version="NCEI_NetCDF_TimeSeries_Orthogonal_Template_v2.0",
featureType="timeSeries",
)
)
encoding = {
name: {"_FillValue": -99, "zlib": True} for name in difference_rect_xarray.data_vars
}
encoding.update({name: {"_FillValue": None} for name in difference_rect_xarray.coords})
# _LOGGER.info(
print(difference_rect_xarray)
difference_rect_xarray.to_netcdf(
"ameriflux_minus_casa_hour_tower_data.nc4",
encoding=encoding,
format="NETCDF4_CLASSIC",
)
bn_nansum = bn.nansum
np_square = np.square
np_exp = np.exp
############################################################
# Look at spatial correlations
length_opt = scipy.optimize.minimize_scalar(
fun=lambda length, corr, dist: bn_nansum(np_square(corr - np_exp(-dist / length))),
args=(
difference_df_rect.corr().values,
distance_matrix.loc[
difference_df_rect.columns, difference_df_rect.columns
].values,
),
bounds=(1, 1e4),
method="bounded",
)
print("Optimizing length alone:\n", length_opt)
length_with_nugget_opt = scipy.optimize.minimize(
fun=lambda params, corr, dist: bn_nansum(
np_square(corr - (params[0] * np_exp(-dist / params[1]) + (1 - params[0])))
),
# Nondimensional, kilometers
x0=[0.8, 200],
args=(
difference_df_rect.corr().values,
distance_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
].values,
),
)
print(
"Optimizing length with nugget effect:",
"\nWeight on correlated part:",
length_with_nugget_opt.x[0],
"\nCorrelation length:",
length_with_nugget_opt.x[1],
"\nConvergence:",
length_with_nugget_opt.success,
length_with_nugget_opt.message,
"\nInverse Hessian:\n",
length_with_nugget_opt.hess_inv,
)
# Scatter plot of actual correlations and line plots of candidates
plotting_distances = np.linspace(
0, np.ceil(distance_matrix.max().max() / 250) * 250, 100
)
fig, axes = plt.subplots(2, 1, sharex=True, sharey=True)
axes[0].scatter(
distance_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
].values.flat,
difference_df_rect.corr().values.flat,
c=vegtype_match_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
].values.flat,
# marker=koeppen_match_matrix.values.flat,
)
axes[0].axhline(0)
axes[0].set_ylabel("Empirical correlations")
# axes[1].plot(plotting_distances, np.exp(-plotting_distances / length_opt))
# axes[1].plot("Exponential fit")
axes[1].plot(
plotting_distances,
1
+ length_with_nugget_opt.x[0]
* np.expm1(-plotting_distances / length_with_nugget_opt.x[1]),
)
axes[0].set_xlim(0, plotting_distances[-1])
axes[0].set_ylim(-0.5, 1)
fig.savefig("ameriflux-minus-casa-all-towers-spatial-correlations.pdf")
plt.close(fig)
distance_matrix_matched = distance_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
]
corr_matrix = difference_df_rect.corr()
correlations_not_nan = ~corr_matrix.isna()
fig, axes = plt.subplots(3, 1, sharex=True, sharey=True)
axes[0].hist2d(
distance_matrix_matched.values[correlations_not_nan.values].reshape(-1),
corr_matrix.values[correlations_not_nan.values].reshape(-1),
range=[[0, plotting_distances[-1]], [-1, 1]],
bins=[30, 10],
# marginals=True,
# extent=(0, plotting_distances[-1], -1, 1),
)
matching_vegtype_index = vegtype_match_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
]
axes[1].hist2d(
distance_matrix_matched.values[
matching_vegtype_index & correlations_not_nan
].reshape(-1),
corr_matrix.values[matching_vegtype_index & correlations_not_nan].reshape(-1),
range=[[0, plotting_distances[-1]], [-1, 1]],
bins=[30, 10],
# marginals=True,
# extent=(0, plotting_distances[-1], -1, 1),
)
matching_koeppen_index = koeppen_match_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
]
axes[2].hist2d(
distance_matrix_matched.values[
matching_koeppen_index & correlations_not_nan
].reshape(-1),
corr_matrix.values[matching_koeppen_index & correlations_not_nan].reshape(-1),
range=[[0, plotting_distances[-1]], [-1, 1]],
bins=[30, 10],
# marginals=True,
# extent=(0, plotting_distances[-1], -1, 1),
)
fig.savefig("ameriflux-minus-casa-hexbin-spatial-correlations.png")
plt.close(fig)
fig, axes = plt.subplots(3, 4, sharex=True, sharey=True)
axes_flat = axes.reshape(-1, order="C")
df_index_months = difference_df_rect.index.month
for month_index in range(MONTHS_PER_YEAR):
month_number = month_index + 1
month_data = difference_df_rect.loc[df_index_months == month_number, :]
ax = axes_flat[month_index]
ax.hist2d(
distance_matrix.loc[
difference_df_rect.columns,
difference_df_rect.columns,
].values.reshape(-1),
month_data.corr().values.reshape(-1),
range=[[0, plotting_distances[-1]], [-1, 1]],
bins=[30, 10],
# '.'
)
ax.set_title(calendar.month_name[month_number])
ax.axhline(0)
ax.set_xlim(0, plotting_distances[-1])
ax.set_ylim(-0.5, 1)
fig.savefig("ameriflux-minus-casa-all-towers-spatial-correlations-by-month.pdf")
plt.close(fig)
############################################################
# Find temporal autocorrelations, autocovariances, and pairs per lag.
acovf_index = pd.timedelta_range(start=0, freq="1H", periods=int(24 * 365.2425 * 17))
acovf_data = pd.DataFrame(index=acovf_index)
acf_data = pd.DataFrame(index=acovf_index)
# acf_width = pd.DataFrame(index=acovf_index)
pair_counts = pd.DataFrame(index=acovf_index)
for column in difference_df_rect.columns:
print(column)
col_data = difference_df_rect.loc[:, column].dropna()
if col_data.shape[0] == 0:
continue
col_data = col_data.resample("1H").mean()
acovf_col = acovf(col_data, missing="conservative", adjusted=True, fft=True)
nlags = len(acovf_col)
acovf_data.loc[acovf_index[:nlags], column] = acovf_col
acf_col = acf(
col_data, missing="conservative", nlags=nlags, adjusted=True, fft=True
)
acf_data.loc[acovf_index[:nlags], column] = acf_col
# varacf = np.ones(nlags + 1) / col_data.count()
# (
# np.ones(acf_data.shape) / acf_data.count()[np.newaxis, :]
# * (1 + 2 * acf_data.cumsum() ** 2)
# )
# acf_width.loc[acovf_index[:nlags], column] = confint[:, 1] - confint[:, 0]
pair_counts.loc[acovf_index[:nlags], column] = count_pairs(col_data)[:nlags]
to_fit = acf_data.loc[~acf_data.isna().all(axis=1), :]
time_in_days = to_fit.index.values.astype("m8[h]").astype(np.int64) / 24
acf_data.to_csv("ameriflux-minus-casa-hour-towers-autocorrelation-functions.csv")
pair_counts.to_csv("ameriflux-minus-casa-hour-towers-pair-counts.csv")
acovf_data.to_csv("ameriflux-minus-casa-hour-towers-autocovariance-functions.csv")
# corr_to_fit, time_in_days = np.broadcast_arrays(to_fit.values, time_in_days[:, newaxis])
# not_nan = np.isfinite(corr_to_fit)
# corr_to_fit = corr_to_fit[not_nan]
# time_in_days = time_in_days[not_nan]
single_time_opt = scipy.optimize.minimize_scalar(
lambda length, acorr, times: nansum(
square(acorr - exp(-times / length)[:, newaxis])