-
Notifications
You must be signed in to change notification settings - Fork 8
/
MarsFiles.py
executable file
·1962 lines (1733 loc) · 80.7 KB
/
MarsFiles.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 python3
"""
The MarsFiles executable has functions for manipulating entire files.
The capabilities include time-shifting, binning, and regridding data,
as well as band pass filtering, tide analysis, zonal averaging, and
extracting variables from files.
The executable requires:
* ``[input_file]`` the file for manipulation
and optionally accepts:
* ``[-fv3, --fv3]`` produce MGCM ``fixed``,
``diurn``, ``average`` and ``daily`` files from Legacy output
* ``[-c, --combine]`` Combine sequential files of
the same type into one file
* ``[-t, --tshift]`` apply a time-shift to
``diurn`` files
* ``[-ba, --bin_average]`` bin MGCM ``daily`` files like
``average`` files
* ``[-bd, --bin_diurn]`` bin MGCM ``daily`` files like
``diurn`` files
* ``[-hp, --high_pass_filter]`` temporal filtering: high-pass
* ``[-lp, --low_pass_filter]`` temporal filtering: low-pass
* ``[-bp, --band_pass_filter]`` temporal filtering: band-pass
* ``[-no_trend, --no_trend]`` filter and compute amplitudes
only (use with filtering)
* ``[-hpk, --high_pass_zonal]`` spatial filtering: high-pass
* ``[-lpk, --low_pass_zonal]`` spatial filtering: low-pass
* ``[-bpk, --band_pass_zonal]`` spatial filtering: band-pass
* ``[-tidal, --tidal]`` extracts diurnal tide and its
harmonics
* ``[-reconstruct, --reconstruct]`` reconstructs the first N
harmonics
* ``[-norm, --normalize]`` provides ``-tidal`` result in
percent amplitude
* ``[-rs, --regrid_source]`` regrid a target file to match
a source file
* ``[-za, --zonal_avg]`` zonally average all variables
in a file
* ``[-include, --include]`` only include specific
variables from the target file
* ``[-e, --ext]`` create a new file with a
unique extension instead of overwriting current file
Third-party Requirements:
* ``numpy``
* ``netCDF4``
* ``sys``
* ``argparse``
* ``os``
* ``subprocess``
* ``warnings``
"""
# Make print statements appear in color
from amescap.Script_utils import (Yellow, Cyan, Red, Blue, Yellow, Nclr, Green)
# Load generic Python Modules
import sys # System commands
import argparse # Parse arguments
import os # Access operating system functions
import subprocess # Run command-line commands
import warnings # Suppress errors triggered by NaNs
import numpy as np
from netCDF4 import Dataset
# Load amesCAP modules
from amescap.Ncdf_wrapper import (Ncdf, Fort)
from amescap.FV3_utils import (tshift, daily_to_average, daily_to_diurn)
from amescap.Script_utils import (find_tod_in_diurn, FV3_file_type,
filter_vars, regrid_Ncfile,
get_longname_units, extract_path_basename)
# ======================================================================
# ARGUMENT PARSER
# ======================================================================
parser = argparse.ArgumentParser(
description=(
f"{Yellow}MarsFiles is a file manager. Use it to modify a "
f"netCDF file format.{Nclr}\n\n"
),
formatter_class = argparse.RawTextHelpFormatter
)
parser.add_argument("input_file", nargs="+",
help=(
f"A netCDF file or list of netCDF files.\n\n"
)
)
parser.add_argument("-fv3", "--fv3", nargs="+",
help=(
f"Produce MGCM ``fixed``, ``diurn``, ``average`` and "
f"``daily`` files from Legacy output.\n"
f"Available options are:\n"
f" - ``fixed`` : static fields (e.g., topography)\n"
f" - ``average``: 5-sol averages\n"
f" - ``daily`` : 5-sol continuous\n"
f" - ``diurn`` : 5-sol averages for each time of day\n"
f"{Green}Usage:\n"
f"> MarsFiles.py filename.nc -fv3 fixed\n"
f"> MarsFiles.py filename.nc -fv3 fixed diurn"
f"{Nclr}\n\n"
)
)
parser.add_argument("-c", "--combine", action="store_true",
help=(
f"Combine sequential files of the same type into one file.\n"
f"Works with all file types (``fixed``, ``average``, "
f"``daily`` and ``diurn``).\n"
f"{Yellow}Overwrites the first file in the series. "
f"To override, use --ext.{Nclr}\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_average.nc --combine"
f"{Nclr}\n\n"
)
)
parser.add_argument("-split", "--split", nargs="+",
help=(
f"Extract a range of values along a dimension. Defaults to Ls, unless "
f"otherwise specified using --dim. If the file contains multiple Mars "
f"Years of data, this function splits the file according to the Ls "
f"values from the first Mars Year.\n"
f"{Yellow}Use [-dim, --dim] to specify the dimension (see below).\n"
f"{Green}Usage:\n"
f"> MarsFiles.py 00668.atmos_average.nc --split 0 90"
f"> MarsFiles.py 00668.atmos_average.nc --split 270"
f"{Nclr}\n\n"
)
)
parser.add_argument("-dim", "--dim", type=str, default = 'areo',
help=(
f"Flag to specify the dimension to split. Acceptable values are \n"
f"areo, lat, lon, lev. For use with --split.\n"
f"{Green}Usage:\n"
f"> MarsFiles.py 00668.atmos_average.nc --split 0 90 --dim areo"
f"> MarsFiles.py 00668.atmos_average.nc --split -70 --dim lat"
f"{Nclr}\n\n"
)
)
parser.add_argument("-t", "--tshift", nargs="?", const=999, type=str,
help=(
f"Apply a time-shift to {Yellow}``diurn``{Nclr} files.\n"
"Vertically interpolated ``diurn`` files OK.\n"
f"{Yellow}Generates a new file ending in ``_T.nc``{Nclr}\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_diurn.nc --tshift\n"
f" {Blue}(outputs data for all 24 local times){Green}\n"
f"> MarsFiles.py *.atmos_diurn.nc --tshift ``3 15``"
f"\n"
f" {Blue}(outputs data for target local times only)"
f"{Nclr}\n\n"
)
)
parser.add_argument("-ba", "--bin_average", nargs="?", const=5,type=int,
help=(
f"Bin MGCM ``daily`` files like ``average`` files.\n"
f"{Yellow}Generates a new file ending in ``_to_average.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -ba\n"
f" {Blue}(NC, bin 5 days){Green}\n"
f"> MarsFiles.py *.atmos_daily_pstd.nc -ba 10\n"
f" {Blue}(bin 10 days)"
f"{Nclr}\n\n"
)
)
parser.add_argument("-bd", "--bin_diurn", action="store_true",
help=(
f"Bin MGCM ``daily`` files like ``diurn`` files.\n"
f"May be used jointly with --bin_average.\n"
f"{Yellow}Generates a new file ending in ``_to_diurn.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -bd\n"
f" {Blue}(default 5-day bin){Green}\n"
f"> MarsFiles.py *.atmos_daily_pstd.nc -bd -ba 10\n"
f" {Blue}(10-day bin){Green}\n"
f"> MarsFiles.py *.atmos_daily_pstd.nc -bd -ba 1\n"
f" {Blue}(No binning. Mimics raw Legacy output)"
f"{Nclr}\n\n"
)
)
parser.add_argument("-hpf", "--high_pass_filter", nargs="+", type=float,
help=(
f"Temporal filtering utilities: low-, high-, and "
f"band-pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_hpf.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -hpf 10.\n"
f" {Blue}(-hpf) --high_pass_filter sol_min "
f"{Nclr}\n\n"
)
)
parser.add_argument("-lpf", "--low_pass_filter", nargs="+", type=float,
help=(
f"Temporal filtering utilities: low-, high-, and "
f"band-pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_lpf.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -lpf 0.5\n"
f" {Blue}(-lpf) --low_pass_filter sol_max "
f"{Nclr}\n\n"
)
)
parser.add_argument("-bpf", "--band_pass_filter", nargs="+",
help=(
f"Temporal filtering utilities: low-, high-, and "
f"band-pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``bpf.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -hpf 0.5 10.\n"
f" {Blue}(-bpf) --band_pass_filter sol_min sol max "
f"{Nclr}\n\n"
)
)
parser.add_argument("-no_trend", "--no_trend", action="store_true",
help=(
f"Filter and compute amplitudes only.\n"
f"For use with temporal filtering utilities (``-lpf``, "
f"``-hpf``, ``-bpf``).\n"
f"{Yellow}Generates a new file ending in ``_no_trend.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -hpf 10. --no_trend\n"
f"> MarsFiles.py *.atmos_daily.nc -lpf 0.5 --no_trend\n"
f"> MarsFiles.py *.atmos_daily.nc -hpf 0.5 10. --no_trend"
f"{Nclr}\n\n"
)
)
# Decomposition in zonal harmonics, disabled for initial CAP release:
parser.add_argument("-hpk", "--high_pass_zonal", nargs="+", type=int,
help=(
f"Spatial filtering utilities: low-, high-, and "
f"band pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_hpk.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -hpk 10 --no_trend\n"
f" {Blue}(-hpk) --high_pass_zonal kmin "
f"{Nclr}\n\n"
)
)
parser.add_argument("-lpk", "--low_pass_zonal", nargs="+", type=int,
help=(
f"Spatial filtering utilities: low-, high-, and "
f"band pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_lpk.nc``\n"
f"{Green}Usage:\n"
f" > MarsFiles.py *.atmos_daily.nc -lpk 20 --no_trend\n"
f" {Blue}(-lpk) --low_pass_zonal kmax "
f"{Nclr}\n\n"
)
)
parser.add_argument("-bpk", "--band_pass_zonal", nargs="+",
help=(
f"Spatial filtering utilities: low-, high-, and "
f"band pass filters.\n"
f"Use ``--no_trend`` to compute amplitudes only.\n"
f"Data detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_bpk.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -bpk 10 20 --no_trend\n"
f" {Blue}(-bpk) --band_pass_zonal kmin kmax"
f"{Nclr}\n\n"
)
)
parser.add_argument("-tidal", "--tidal", nargs="+", type=int,
help=(
f"Performs a tidal analyis on ``diurn`` files.\n"
f"Extracts diurnal tide and its harmonics.\n"
f"N = 1 diurnal, N = 2 semi-diurnal etc.\n"
f"{Yellow}Generates a new file ending in ``_tidal.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_diurn.nc -tidal 4\n"
f" {Blue}(extracts 4 harmonics)"
f"{Nclr}\n\n"
)
)
parser.add_argument("-reconstruct", "--reconstruct", action="store_true",
help=(
f"Reconstructs the first N harmonics.\n"
f"{Yellow}Generates a new file ending in ``_reconstruct.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_diurn.nc -tidal 6 "
f"--include ps temp --reconstruct"
f"{Nclr}\n\n"
)
)
parser.add_argument("-norm", "--normalize", action="store_true",
help=(
f"Provides result in percent amplitude.\n"
f"{Yellow}Generates a new file ending in ``_norm.nc``\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_diurn.nc -tidal 6 "
f"--include ps --normalize"
f"{Nclr}\n\n"
)
)
parser.add_argument("-rs", "--regrid_source", nargs="+",
help=(
f"Regrid a target file to match a source file.\n"
f"Both source and target files should be vertically\n"
f"interpolated to the same standard grid\n"
f"(e.g. zstd, zagl, pstd, etc.).\n"
f"{Yellow}Generates a new file ending in ``_regrid.nc``\n"
f"{Green}Usage:\n"
f"> MarsInterp.py *.atmos.average_pstd.nc -rs "
f"simu2/00668.atmos_average_pstd.nc"
f"{Nclr}\n\n"
)
)
parser.add_argument("-za", "--zonal_avg", action="store_true",
help=(
f"Zonally average all variables in a file.\n"
f"{Yellow}Generates a new file ending in ``_zavg.nc``\n"
f"{Green}Usage:\n"
"> MarsFiles.py *.atmos_diurn.nc -za"
f"{Nclr}\n\n"
)
)
parser.add_argument("-include", "--include", nargs="+",
help=(
f"Flag to include only the variables listed after \n"
f"-include in the target file.\n"
f"All dimensional and 1D variables are always included.\n"
f"{Yellow}Overwrites existing target file. To override, "
f"use --ext.{Nclr}\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos_daily.nc -ba --include ps ts ucomp"
f"{Nclr}\n\n"
)
)
parser.add_argument("-e", "--ext", type=str, default = None,
help=(
f"Do not overwrite file. Append the extension provided \n"
f"after --ext to the new file.\n"
f"{Green}Usage:\n"
f"> MarsFiles.py *.atmos.average.nc --combine --ext _combined\n"
f" {Blue}(produces *.atmos.average_combined.nc)"
f"{Nclr}\n\n"
)
)
parser.add_argument("--debug", action="store_true",
help=(f"Debug flag: release the exceptions.\n\n"))
# ======================================================================
# DEFINITIONS
# ======================================================================
def combine_files(file_list, full_file_list):
"""
Concatenates sequential output files in chronological order.
:param file_list: list of file names
:type file_list: list
:param full_file_list: list of file names and full paths
:type full_file_list: list
"""
print(f"{Yellow}Using internal method for concatenation{Nclr}")
# For fixed files, deleting all but the first file has the same
# effect as combining files
num_files = len(full_file_list)
if (file_list[0][5:] == ".fixed.nc" and num_files >= 2):
rm_cmd = "rm -f "
for i in range(1, num_files):
# 1-N files ensures file number 0 is preserved
rm_cmd += f" {full_file_list[i]}"
p = subprocess.run(rm_cmd, universal_newlines = True, shell = True)
print(f"{Cyan}Cleaned all but {file_list[0]}{Nclr}")
exit()
print(f"{Cyan}Merging {num_files} files starting with {file_list[0]}..."
f"{Nclr}")
if parser.parse_args().include:
# Exclude variables NOT listed after --include
f = Dataset(file_list[0], "r")
exclude_list = filter_vars(f, parser.parse_args().include,
giveExclude = True)
f.close()
else:
exclude_list = []
# Create a temporary file ending in _tmp.nc to work in
tmp_file = f"{full_file_list[0][:-3]}_tmp.nc"
Log = Ncdf(tmp_file, "Merged file")
Log.merge_files_from_list(full_file_list, exclude_var=exclude_list)
Log.close()
# ----- Delete the files that were used for combine -----
# First, rename temporary file for the final merged file
# For Legacy netCDF files, rename using initial and end Ls
# For MGCM netCDF files, rename to the first file in the list
if file_list[0][:12] == "LegacyGCM_Ls":
ls_ini = file_list[0][12:15]
ls_end = file_list[-1][18:21]
merged_file = f"LegacyGCM_Ls{ls_ini}_Ls{ls_end}.nc"
else:
merged_file = full_file_list[0]
# Second, delete the files that were combined.
# Apply the new name created above
rm_cmd = "rm -f "
for file in full_file_list:
rm_cmd += f" {file}"
cmd_txt = f"mv {tmp_file} {merged_file}"
p = subprocess.run(rm_cmd, universal_newlines = True, shell = True)
p = subprocess.run(cmd_txt, universal_newlines = True, shell = True)
print(f"{Cyan}{merged_file} was created from a merge{Nclr}")
return
def split_files(file_list, split_dim):
"""
Extracts variables in the file along the time dimension, unless
other dimension is specified (lat or lon).
:param file_list: list of file names
:type split_dim: dimension along which to perform extraction
:returns: new file with sliced dimensions
"""
if split_dim not in ['time', 'areo', 'lat', 'lon']:
print(f"{Red}Split dimension must be one of the following:"
f" time, areo, lat, lon{Nclr}")
exit()
if split_dim == 'areo':
split_dim = 'time'
bounds = np.asarray(parser.parse_args().split).astype(float)
if len(np.atleast_1d(bounds)) > 2 or len(np.atleast_1d(bounds)) < 1:
print(f"{Red}Accepts only ONE or TWO values:"
f"[bound] to reduce one dimension to a single value"
f"[lower_bound] [upper_bound] to reduce one dimension to "
f"a range{Nclr}")
exit()
# Add path unless full path is provided
if not ("/" in file_list[0]):
input_file_name = f"{data_dir}/{file_list[0]}"
else:
input_file_name = file_list[0]
original_date = (input_file_name.split('.')[0]).split('/')[-1]
fNcdf = Dataset(input_file_name, 'r', format = 'NETCDF4_CLASSIC')
var_list = filter_vars(fNcdf, parser.parse_args().include)
# reducing_dim = fNcdf.variables[split_dim][:]
# Get file type (diurn, average, daily, etc.)
f_type, _ = FV3_file_type(fNcdf)
# Remove all single dimensions from areo (scalar_axis)
if f_type == 'diurn':
if split_dim == 'time':
# size areo = (time, tod, scalar_axis)
reducing_dim = np.squeeze(fNcdf.variables['areo'][:, 0, :]) % 360
else:
reducing_dim = np.squeeze(fNcdf.variables[split_dim][:, 0])
else:
if split_dim == 'time':
# size areo = (time, scalar_axis)
reducing_dim = np.squeeze(fNcdf.variables['areo'][:]) % 360
else:
reducing_dim = np.squeeze(fNcdf.variables[split_dim][:])
print(f"\n{Yellow}All values in dimension:\n{reducing_dim}\n")
if len(np.atleast_1d(bounds)) < 2:
indices = [(np.abs(reducing_dim - bounds[0])).argmin()]
dim_out = reducing_dim[indices]
print(f"Requested value = {bounds[0]}\n"
f"Nearest value = {dim_out[0]}\n")
else:
indices = np.where((reducing_dim >= bounds[0]) & (reducing_dim <= bounds[1]))[0]
dim_out = reducing_dim[indices]
print(f"Requested range = {bounds[0]} - {bounds[1]}\n"
f"Corresponding values = {dim_out}\n")
if len(indices) == 0:
print(f"{Red}Warning, no values were found in the range {split_dim} "
f"{bounds[0]}, {bounds[1]}) ({split_dim} values range from "
f"{reducing_dim[0]:.1f} to {reducing_dim[-1]:.1f})")
exit()
if split_dim == 'time':
time_dim = (np.squeeze(fNcdf.variables['time'][:]))[indices]
print(f"time_dim = {time_dim}")
fpath, fname = extract_path_basename(input_file_name)
if split_dim == 'time':
if len(np.atleast_1d(bounds)) < 2:
output_file_name = (f"{fpath}/{int(time_dim):05d}{fname[5:-3]}_"
f"nearest_Ls{int(bounds[0]):03d}.nc")
else:
output_file_name = (f"{fpath}/{int(time_dim[0]):05d}{fname[5:-3]}_"
f"Ls{int(bounds[0]):03d}_{int(bounds[1]):03d}.nc")
elif split_dim == 'lat':
new_bounds = [str(abs(int(b)))+"S" if b < 0 else str(int(b))+"N" for b in bounds]
if len(np.atleast_1d(bounds)) < 2:
output_file_name = (f"{fpath}/{original_date}{fname[5:-3]}_{split_dim}"
f"nearest_{new_bounds[0]}.nc")
else:
print(f"{Yellow}bounds = {bounds[0]} {bounds[1]}")
print(f"{Yellow}new_bounds = {new_bounds[0]} {new_bounds[1]}")
output_file_name = (f"{fpath}/{original_date}{fname[5:-3]}_{split_dim}"
f"{new_bounds[0]}_{new_bounds[1]}.nc")
else:
if len(np.atleast_1d(bounds)) < 2:
output_file_name = (f"{fpath}/{original_date}{fname[5:-3]}_{split_dim}"
f"nearest_{int(bounds[0]):03d}.nc")
else:
output_file_name = (f"{fpath}/{original_date}{fname[5:-3]}_{split_dim}"
f"{int(bounds[0]):03d}_{int(bounds[1]):03d}.nc")
print(f"{Cyan}new filename = {output_file_name}")
Log = Ncdf(output_file_name)
Log.copy_all_dims_from_Ncfile(fNcdf, exclude_dim = [split_dim])
if split_dim == 'time':
Log.add_dimension(split_dim, None)
else:
Log.add_dimension(split_dim, len(dim_out))
if split_dim == 'time':
Log.log_axis1D(variable_name = 'time',
DATAin = dim_out,
dim_name = 'time',
longname_txt = 'sol number',
units_txt = 'days since 0000-00-00 00:00:00',
cart_txt = 'T')
elif split_dim == 'lat':
Log.log_axis1D(variable_name = 'lat',
DATAin = dim_out,
dim_name = 'lat',
longname_txt = 'latitude',
units_txt = 'degrees_N',
cart_txt = 'T')
elif split_dim == 'lon':
Log.log_axis1D(variable_name = 'lon',
DATAin = dim_out,
dim_name = 'lon',
longname_txt = 'longitude',
units_txt = 'degrees_E',
cart_txt = 'T')
# Loop over all variables in the file
for ivar in var_list:
varNcf = fNcdf.variables[ivar]
if split_dim in varNcf.dimensions and ivar != split_dim:
# ivar is a dim of ivar but ivar is not ivar
print(f'{Cyan}Processing: {ivar}...{Nclr}')
if split_dim == 'time':
var_out = varNcf[indices, ...]
elif split_dim == 'lat' and varNcf.ndim == 5:
var_out = varNcf[:, :, :, indices, :]
elif split_dim == 'lat' and varNcf.ndim == 4:
var_out = varNcf[:, :, indices, :]
elif split_dim == 'lat' and varNcf.ndim == 3:
var_out = varNcf[:, indices, :]
elif split_dim == 'lat' and varNcf.ndim == 2:
var_out = varNcf[indices, ...]
elif split_dim == 'lon' and varNcf.ndim > 2:
var_out = varNcf[..., indices]
elif split_dim == 'lon' and varNcf.ndim == 2:
var_out = varNcf[indices, ...]
longname_txt, units_txt = get_longname_units(fNcdf, ivar)
Log.log_variable(ivar, var_out, varNcf.dimensions,
longname_txt, units_txt)
else:
# ivar is ivar OR ivar is not a dim of ivar
if (ivar in ['pfull', 'lat', 'lon', 'phalf', 'pk', 'bk',
'pstd', 'zstd', 'zagl', 'time'] and
ivar != split_dim):
# ivar is a dimension
print(f'{Cyan}Copying axis: {ivar}...{Nclr}')
Log.copy_Ncaxis_with_content(fNcdf.variables[ivar])
elif ivar != split_dim:
# ivar is not itself and not a dimension of ivar
print(f'{Cyan}Copying variable: {ivar}...{Nclr}')
Log.copy_Ncvar(fNcdf.variables[ivar])
Log.close()
fNcdf.close()
return
# ==================================================================
# Time-Shifting Implementation
# Victoria H.
# ==================================================================
def time_shift(file_list):
"""
This function converts the data in diurn files with a time_of_day_XX
dimension to universal local time.
:param file_list: list of file names
:type file_list: list
"""
if parser.parse_args().tshift == 999:
# Target local times requested by user
target_list = None
else:
target_list = np.fromstring(parser.parse_args().tshift,
dtype = float, sep=" ")
for file in file_list:
# Add path unless full path is provided
if not ("/" in file):
input_file_name = f"{data_dir}/{file}"
else:
input_file_name = file
output_file_name = f"{input_file_name[:-3]}_T.nc"
if parser.parse_args().ext:
# Append extension, if any:
output_file_name = (f"{output_file_name[:-3]}_"
f"{parser.parse_args().ext}.nc")
fdiurn = Dataset(input_file_name, "r", format = "NETCDF4_CLASSIC")
# Define a netcdf object from the netcdf wrapper module
fnew = Ncdf(output_file_name)
# Copy some dimensions from the old file to the new file
fnew.copy_all_dims_from_Ncfile(fdiurn)
# Find the "time of day" variable name
tod_name_in = find_tod_in_diurn(fdiurn)
_, zaxis = FV3_file_type(fdiurn)
# Copy some variables from the old file to the new file
fnew.copy_Ncaxis_with_content(fdiurn.variables["lon"])
fnew.copy_Ncaxis_with_content(fdiurn.variables["lat"])
fnew.copy_Ncaxis_with_content(fdiurn.variables["time"])
fnew.copy_Ncaxis_with_content(fdiurn.variables["scalar_axis"])
# Only create a vertical axis if orig. file has 3D fields
if zaxis in fdiurn.dimensions.keys():
fnew.copy_Ncaxis_with_content(fdiurn.variables[zaxis])
# Take care of TOD dimension in new file
tod_orig = np.array(fdiurn.variables[tod_name_in])
if target_list is None:
# If user does not specify which TOD(s) to do, do all 24
tod_name_out = tod_name_in
fnew.copy_Ncaxis_with_content(fdiurn.variables[tod_name_in])
# Only copy "areo" if it exists in the original file
if "areo" in fdiurn.variables.keys():
fnew.copy_Ncvar(fdiurn.variables["areo"])
else:
# If user requests specific local times, update the old
# axis as necessary
tod_name_out = f"time_of_day_{(len(target_list)):02}"
fnew.add_dim_with_content(tod_name_out, target_list,
longname_txt = "time of day",
units_txt = ("[hours since 0000-00-00 "
"00:00:00]"),
cart_txt = "")
# Create areo variable with the new size
areo_shape = fdiurn.variables["areo"].shape
areo_dims = fdiurn.variables["areo"].dimensions
# Update shape with new time_of_day
areo_shape = (areo_shape[0], len(target_list), areo_shape[2])
areo_dims = (areo_dims[0], tod_name_out, areo_dims[2])
areo_out = np.zeros(areo_shape)
for i in range(len(target_list)):
# For new target_list, e.g [3,15]
# Get the closest "time_of_day" index
j = np.argmin(np.abs(target_list[i] - tod_orig))
areo_out[:, i, 0] = fdiurn.variables["areo"][:, j, 0]
fnew.add_dim_with_content("scalar_axis", [0], longname_txt = "none",
units_txt = "none")
fnew.log_variable("areo", areo_out, areo_dims, "areo", "degrees")
# Read in 4D field(s) and do the time shift. Exclude vars
# not listed after --include in var_list
lons = np.array(fdiurn.variables["lon"])
var_list = filter_vars(fdiurn, parser.parse_args().include)
for var in var_list:
print(f"{Cyan}Processing: {var}...{Nclr}")
value = fdiurn.variables[var][:]
dims = fdiurn.variables[var].dimensions
longname_txt, units_txt = get_longname_units(fdiurn, var)
if (len(dims) >= 4):
y = dims.index("lat")
x = dims.index("lon")
t = dims.index("time")
tod = dims.index(tod_name_in)
if (len(dims) == 4):
# time, tod, lat, lon
var_val_tmp = np.transpose(value, (x, y, t, tod))
var_val_T = tshift(var_val_tmp, lons, tod_orig,
timex = target_list)
var_out = np.transpose(var_val_T, (2, 3, 1, 0))
fnew.log_variable(var, var_out,
["time", tod_name_out, "lat", "lon"],
longname_txt, units_txt)
if (len(dims) == 5):
# time, tod, Z, lat, lon
z = dims.index(zaxis)
var_val_tmp = np.transpose(value, (x, y, z, t, tod))
var_val_T = tshift(var_val_tmp, lons, tod_orig,
timex = target_list)
var_out = np.transpose(var_val_T, (3, 4, 2, 1, 0))
fnew.log_variable(var, var_out,
["time", tod_name_out, zaxis, "lat", "lon"],
longname_txt, units_txt)
fnew.close()
fdiurn.close()
return
# ======================================================================
# MAIN PROGRAM
# ======================================================================
def main():
global data_dir
file_list = parser.parse_args().input_file
data_dir = os.getcwd()
# Make a list of input files including the full path to the dir
full_file_list = []
for file in file_list:
if not ("/" in file):
full_file_list.append(f"{data_dir}/{file}")
else:
full_file_list.append(f"{file}")
if parser.parse_args().fv3 and parser.parse_args().combine:
print(f"{Red}Use --fv3 and --combine separately to avoid ambiguity")
exit()
# ==================================================================
# Conversion Legacy -> MGCM Format
# Richard U. and Alex. K.
# ==================================================================
# Convert to MGCM Output Format
if parser.parse_args().fv3:
for req_file in parser.parse_args().fv3:
if req_file not in ["fixed", "average", "daily", "diurn"]:
print(f"{Red}{req_file} is invalid. Select ``fixed``, "
f"``average``, ``daily``, or ``diurn``{Nclr}")
# lsmin = None
# lsmax = None
if full_file_list[0][-3:] == ".nc":
print("Processing Legacy MGCM netCDF files")
for f in full_file_list:
# file_name = os.path.basename(f)
# ls_l = file_name[-12:-9]
# ls_r = file_name[-6:-3]
# if lsmin is None:
# lsmin = ls_l
# else:
# lsmin = str(min(int(lsmin), int(ls_l))).zfill(3)
# if lsmax is None:
# lsmax = ls_r
# else:
# lsmax = str(max(int(lsmax), int(ls_r))).zfill(3)
make_FV3_files(f, parser.parse_args().fv3, True)
else:
print("Processing fort.11 files")
for f in full_file_list:
file_name = Fort(f)
if "fixed" in parser.parse_args().fv3:
file_name.write_to_fixed()
if "average" in parser.parse_args().fv3:
file_name.write_to_average()
if "daily" in parser.parse_args().fv3:
file_name.write_to_daily()
if "diurn" in parser.parse_args().fv3:
file_name.write_to_diurn()
elif parser.parse_args().combine:
# Combine files along the time dimension
combine_files(file_list, full_file_list)
elif parser.parse_args().split:
# Split file along the specified dimension. If none specified,
# default to time dimension
split_files(file_list, parser.parse_args().dim)
elif parser.parse_args().tshift:
# Time-shift files
time_shift(file_list)
# ==================================================================
# Bin a daily file as an average file
# Alex K.
# ==================================================================
elif (parser.parse_args().bin_average and not
parser.parse_args().bin_diurn):
# Generate output file name
bin_period = parser.parse_args().bin_average
for file in file_list:
# Add path unless full path is provided
if not ("/" in file):
input_file_name = f"{data_dir}/{file}"
else:
input_file_name = file
output_file_name = f"{input_file_name[:-3]}_to_average.nc"
# Append extension, if any:
if parser.parse_args().ext:
output_file_name = (
f"{output_file_name[:-3]}_{parser.parse_args().ext}.nc"
)
fdaily = Dataset(input_file_name, "r", format = "NETCDF4_CLASSIC")
var_list = filter_vars(fdaily, parser.parse_args().include)
time = fdaily.variables["time"][:]
time_increment = time[1] - time[0]
dt_per_day = int(np.round(1/time_increment))
dt_total = int(dt_per_day * bin_period)
bins = len(time) / (dt_per_day * bin_period)
bins_even = len(time) // dt_total
bins_left = len(time) % dt_total
if bins_left != 0:
print(f"{Yellow}*** Warning *** Requested a {bin_period}-sol "
f"bin period but the file has a total of {len(time)}"
f"timesteps ({dt_per_day} per sol) and {len(time)}/"
f"({bin_period}x{dt_per_day})={bins} is not a round "
f"number.\nWill use {bins_even} bins with "
f"{bin_period}x{dt_per_day}={dt_total} timesteps per "
f"bin ({bins_even*dt_total} timsteps total) and "
f"discard {bins_left} timesteps.{Nclr}")
# Define a netcdf object from the netcdf wrapper module
fnew = Ncdf(output_file_name)
# Copy all dimensions but time from the old file to the new file
fnew.copy_all_dims_from_Ncfile(fdaily, exclude_dim = ["time"])
# Calculate and log the new time array
fnew.add_dimension("time", None)
time_out = daily_to_average(time[:], time_increment, bin_period)
fnew.log_axis1D("time", time_out, "time",
longname_txt = "sol number",
units_txt = "days since 0000-00-00 00:00:00",
cart_txt = "T")
# Loop over all variables in the file
for ivar in var_list:
varNcf = fdaily.variables[ivar]
if "time" in varNcf.dimensions:
print(f"{Cyan}Processing: {ivar}{Nclr}")
var_out = daily_to_average(varNcf[:], time_increment,
bin_period)
longname_txt, units_txt = get_longname_units(fdaily, ivar)
fnew.log_variable(ivar, var_out, varNcf.dimensions,
longname_txt, units_txt)
else:
if ivar in ["pfull", "lat", "lon", "phalf", "pk",
"bk", "pstd", "zstd", "zagl"]:
print(f"{Cyan}Copying axis: {ivar}{Nclr}")
fnew.copy_Ncaxis_with_content(fdaily.variables[ivar])
else:
print(f"{Cyan}Copying variable: {ivar}{Nclr}")
fnew.copy_Ncvar(fdaily.variables[ivar])
fnew.close()
# ==================================================================
# Bin a daily file as a diurn file
# Alex K.
# ==================================================================
elif parser.parse_args().bin_diurn:
# Use defaut binning period of 5 days (like average files)
if parser.parse_args().bin_average is None:
bin_period = 5
else:
bin_period = parser.parse_args().bin_average
for file in file_list:
# Add path unless full path is provided
if not ("/" in file):
input_file_name = f"{data_dir}/{file}"
else:
input_file_name = file
output_file_name = f"{input_file_name[:-3]}_to_diurn.nc"
# Append extension, if any:
if parser.parse_args().ext:
output_file_name = (f"{output_file_name[:-3]}_"
f"{parser.parse_args().ext}.nc")
fdaily = Dataset(input_file_name, "r", format = "NETCDF4_CLASSIC")
var_list = filter_vars(fdaily, parser.parse_args().include)
time = fdaily.variables["time"][:]
time_increment = time[1] - time[0]
dt_per_day = int(np.round(1/time_increment))
# Define a netcdf object from the netcdf wrapper module
fnew = Ncdf(output_file_name)
# Copy all dimensions but "time" from the old file to the
# new file
fnew.copy_all_dims_from_Ncfile(fdaily, exclude_dim = ["time"])
# If no binning is requested, copy time axis as-is
fnew.add_dimension("time", None)
time_out = daily_to_average(time[:], time_increment, bin_period)
fnew.add_dim_with_content("time", time_out,
longname_txt = "sol number",
units_txt = ("days since 0000-00-00 "
"00:00:00"),
cart_txt = "T")
# Create a new time_of_day dimension
tod_name = f"time_of_day_{dt_per_day:02}"
time_tod = np.squeeze(daily_to_diurn(time[0:dt_per_day],
time[0:dt_per_day]))
tod = np.mod(time_tod*24, 24)
fnew.add_dim_with_content(tod_name, tod,
longname_txt = "time of day",
units_txt = ("hours since 0000-00-00 "
"00:00:00"),
cart_txt = "N")
# Loop over all variables in the file
for ivar in var_list:
varNcf = fdaily.variables[ivar]
if "time" in varNcf.dimensions and ivar != "time":
# If time is the dimension (not just an array)
print(f"{Cyan}Processing: {ivar}{Nclr}")
dims_in = varNcf.dimensions
dims_out = (dims_in[0],)+(tod_name,)+dims_in[1:]
var_out = daily_to_diurn(varNcf[:], time[0:dt_per_day])
if bin_period != 1:
# dt is 1 sol between two diurn timesteps
var_out = daily_to_average(var_out, 1., bin_period)
longname_txt, units_txt = get_longname_units(fdaily, ivar)
fnew.log_variable(ivar, var_out, dims_out,
longname_txt, units_txt)
else:
if ivar in ["pfull", "lat", "lon", "phalf", "pk",
"bk", "pstd", "zstd", "zagl"]:
print(f"{Cyan}Copying axis: {ivar}{Nclr}")
fnew.copy_Ncaxis_with_content(fdaily.variables[ivar])
elif ivar != "time":
print(f"{Cyan}Copying variable: {ivar}{Nclr}")
fnew.copy_Ncvar(fdaily.variables[ivar])
fnew.close()
# ==================================================================
# Transient Wave Analysis
# Alex K. & R. J. Wilson
# ==================================================================
elif (parser.parse_args().high_pass_filter or