-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMarsFiles.py
More file actions
executable file
·2970 lines (2654 loc) · 115 KB
/
MarsFiles.py
File metadata and controls
executable file
·2970 lines (2654 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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:
* ``[-bin, --bin_files]`` Produce MGCM 'fixed', 'diurn', 'average' and 'daily' files from Legacy output
* ``[-c, --concatenate]`` Combine sequential files of the same type into one file
* ``[-split, --split]`` Split file along a specified dimension or extracts slice at one point along the dim
* ``[-t, --time_shift]`` 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
* ``[-hpt, --high_pass_temporal]`` Temporal filter: high-pass
* ``[-lpt, --low_pass_temporal]`` Temporal filter: low-pass
* ``[-bpt, --band_pass_temporal]`` Temporal filter: band-pass
* ``[-trend, --add_trend]`` Return amplitudes only (use with temporal filters)
* ``[-hps, --high_pass_spatial]`` Spatial filter: high-pass
* ``[-lps, --low_pass_spatial]`` Spatial filter: low-pass
* ``[-bps, --band_pass_spatial]`` Spatial filter: band-pass
* ``[-tide, --tide_decomp]`` Extract diurnal tide and its harmonics
* ``[-recon, --reconstruct]`` Reconstruct the first N harmonics
* ``[-norm, --normalize]`` Provide ``-tide`` result in % amplitude
* ``[-prop, --prop_tides]`` Extract propagating tide harmonics
* ``[-regrid, --regrid_XY_to_match]`` Regrid a target file to match a source file
* ``[-zavg, --zonal_average]`` Zonally average all variables in a file
* ``[-incl, --include]`` Only include specific variables in a calculation
* ``[-ext, --extension]`` Create a new file with a unique extension instead of modifying the current file
Third-party Requirements:
* ``sys``
* ``argparse``
* ``os``
* ``warnings``
* ``re``
* ``numpy``
* ``netCDF4``
* ``shutil``
* ``functools``
* ``traceback``
"""
# 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 warnings # Suppress errors triggered by NaNs
import re # Regular expressions
import numpy as np
from netCDF4 import Dataset
import shutil # For OS-friendly file operations
import functools # For function decorators
import traceback # For printing stack traces
import shutil # For copy/pasting fixed file after -split
# Load amesCAP modules
from amescap.Ncdf_wrapper import (Ncdf, Fort)
from amescap.FV3_utils import (
time_shift_calc, daily_to_average, daily_to_diurn, get_trend_2D
)
from amescap.Script_utils import (
find_tod_in_diurn, FV3_file_type, filter_vars, regrid_Ncfile,
get_longname_unit, check_bounds
)
# ------------------------------------------------------
# EXTENSION FUNCTION
# ------------------------------------------------------
class ExtAction(argparse.Action):
"""
Custom action for argparse to handle file extensions.
This action is used to add an extension to the output file.
:param ext_content: The content to be added to the file name.
:type ext_content: str
:param parser: The parser instance to which this action belongs.
:type parser: argparse.ArgumentParser
:param args: Additional positional arguments.
:type args: tuple
:param kwargs: Additional keyword arguments.
:type kwargs: dict
:param ext_content: The content to be added to the file name
:type ext_content: str
:return: None
:rtype: None
:raises ValueError: If ext_content is not provided.
:raises TypeError: If parser is not an instance of argparse.ArgumentParser.
:raises Exception: If an error occurs during the action.
:raises AttributeError: If the parser does not have the specified attribute.
:raises ImportError: If the parser cannot be imported.
:raises RuntimeError: If the parser cannot be run.
:raises KeyError: If the parser does not have the specified key.
:raises IndexError: If the parser does not have the specified index.
:raises IOError: If the parser cannot be opened.
:raises OSError: If the parser cannot be accessed.
:raises EOFError: If the parser cannot be read.
:raises MemoryError: If the parser cannot be allocated.
:raises OverflowError: If the parser cannot be overflowed.
"""
def __init__(self, *args, ext_content=None, parser=None, **kwargs):
self.parser = parser
# Store the extension content that's specific to this argument
self.ext_content = ext_content
# For flags, we need to handle nargs=0 and default=False
if kwargs.get('nargs') == 0:
kwargs['default'] = False
kwargs['const'] = True
kwargs['nargs'] = 0
super().__init__(*args, **kwargs)
# Store this action in the parser's list of actions
# We'll use this later to set up default info values
if self.parser:
if not hasattr(self.parser, '_ext_actions'):
self.parser._ext_actions = []
self.parser._ext_actions.append(self)
def __call__(self, parser, namespace, values, option_string=None):
# Handle flags (store_true type arguments)
if self.nargs == 0:
setattr(namespace, self.dest, True)
# Handle other types
elif isinstance(values, list):
setattr(namespace, self.dest, values)
elif isinstance(values, str) and ',' in values:
# Handle comma-separated lists
setattr(namespace, self.dest, values.split(','))
else:
try:
# Try to convert to int if it's an integer argument
setattr(namespace, self.dest, int(values))
except ValueError:
setattr(namespace, self.dest, values)
# Set the extension content using the argument name
ext_attr = f"{self.dest}_ext"
setattr(namespace, ext_attr, self.ext_content)
class ExtArgumentParser(argparse.ArgumentParser):
"""
Custom ArgumentParser that handles file extensions for output files.
This class extends the argparse.ArgumentParser to add functionality
for handling file extensions in the command-line arguments.
:param args: Additional positional arguments.
:type args: tuple
:param kwargs: Additional keyword arguments.
:type kwargs: dict
:param ext_content: The content to be added to the file name.
:type ext_content: str
:param parser: The parser instance to which this action belongs.
:type parser: argparse.ArgumentParser
:return: None
:rtype: None
:raises ValueError: If ext_content is not provided.
:raises TypeError: If parser is not an instance of argparse.ArgumentParser.
:raises Exception: If an error occurs during the action.
:raises AttributeError: If the parser does not have the specified attribute.
:raises ImportError: If the parser cannot be imported.
:raises RuntimeError: If the parser cannot be run.
:raises KeyError: If the parser does not have the specified key.
:raises IndexError: If the parser does not have the specified index.
:raises IOError: If the parser cannot be opened.
:raises OSError: If the parser cannot be accessed.
:raises EOFError: If the parser cannot be read.
:raises MemoryError: If the parser cannot be allocated.
:raises OverflowError: If the parser cannot be overflowed.
"""
def parse_args(self, *args, **kwargs):
namespace = super().parse_args(*args, **kwargs)
# Then set info attributes for any unused arguments
if hasattr(self, '_ext_actions'):
for action in self._ext_actions:
ext_attr = f"{action.dest}_ext"
if not hasattr(namespace, ext_attr):
setattr(namespace, ext_attr, "")
return namespace
def debug_wrapper(func):
"""
A decorator that wraps a function with error handling
based on the --debug flag.
If the --debug flag is set, it prints the full traceback
of any exception that occurs. Otherwise, it prints a
simplified error message.
:param func: The function to wrap.
:type func: function
:return: The wrapped function.
:rtype: function
:raises Exception: If an error occurs during the function call.
:raises TypeError: If the function is not callable.
:raises ValueError: If the function is not found.
:raises NameError: If the function is not defined.
:raises AttributeError: If the function does not have the
specified attribute.
:raises ImportError: If the function cannot be imported.
:raises RuntimeError: If the function cannot be run.
:raises KeyError: If the function does not have the
specified key.
:raises IndexError: If the function does not have the
specified index.
:raises IOError: If the function cannot be opened.
:raises OSError: If the function cannot be accessed.
:raises EOFError: If the function cannot be read.
:raises MemoryError: If the function cannot be allocated.
:raises OverflowError: If the function cannot be overflowed.
:raises ZeroDivisionError: If the function cannot be divided by zero.
:raises StopIteration: If the function cannot be stopped.
:raises KeyboardInterrupt: If the function cannot be interrupted.
:raises SystemExit: If the function cannot be exited.
:raises AssertionError: If the function cannot be asserted.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
global debug
try:
return func(*args, **kwargs)
except Exception as e:
if debug:
# In debug mode, show the full traceback
print(f"{Red}ERROR in {func.__name__}: {str(e)}{Nclr}")
traceback.print_exc()
else:
# In normal mode, show a clean error message
print(f"{Red}ERROR in {func.__name__}: {str(e)}\nUse "
f"--debug for more information.{Nclr}")
return 1 # Error exit code
return wrapper
# ------------------------------------------------------
# ARGUMENT PARSER
# ------------------------------------------------------
parser = ExtArgumentParser(
prog=('MarsFiles'),
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='+',
type=argparse.FileType('rb'),
help=(f"A netCDF or fort.11 file or list of files.\n\n"))
parser.add_argument('-bin', '--bin_files', nargs='+', type=str,
choices=['fixed', 'diurn', 'average', 'daily'],
help=(
f"Produce MGCM 'fixed', 'diurn', 'average' and 'daily' "
f"files from Legacy output:\n"
f" - ``fixed`` : static fields (e.g., topography)\n"
f" - ``daily`` : instantaneous data\n"
f" - ``diurn`` : 5-sol averages binned by time of day\n"
f" - ``average``: 5-sol averages\n"
f"Works on 'fort.11' files only.\n"
f"{Green}Example:\n"
f"> MarsFiles fort.11_* -bin fixed daily diurn average\n"
f"> MarsFiles fort.11_* -bin fixed diurn"
f"{Nclr}\n\n"
)
)
parser.add_argument('-c', '--concatenate', action=ExtAction,
ext_content='_concatenated',
parser=parser,
nargs=0,
help=(
f"Combine sequential files of the same type into one file.\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Green}Example:\n"
f"> ls\n"
f"00334.atmos_average.nc 00668.atmos_average.nc\n"
f"> MarsFiles *.atmos_average.nc -c\n"
f"{Blue}Produces 00334.atmos_average_concatenated.nc and "
f"preserves all other files:{Green}\n"
f"> ls\n"
f" 00334.atmos_average.nc 00668.atmos_average.nc "
f"00334.atmos_average_concatenated.nc\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-split', '--split', nargs='+', type=float,
help=(
f"Extract one value or a range of values along a dimension.\n"
f"Defaults to ``areo`` (Ls) unless otherwise specified using "
f"-dim.\nIf a file contains multiple Mars Years of data, the "
f"function splits the file in the first Mars Year.\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_average.nc --split 0 90\n"
f"> MarsFiles 01336.atmos_average.nc --split 270\n"
f"{Yellow}Use -dim to specify the dimension:{Green}\n"
f"> MarsFiles 01336.atmos_average.nc --split 0 90 -dim lat"
f"{Nclr}\n\n"
)
)
parser.add_argument('-t', '--time_shift', action=ExtAction, type=str,
ext_content='_T',
parser=parser,
nargs="?", const=999,
help=(
f"Convert hourly binned ('diurn') files to universal local "
f"time.\nUseful for comparing data at a specific time of day "
f"across all longitudes.\nWorks on vertically interpolated "
f"files.\n"
f"Works on 'diurn' files only.\n"
f"{Yellow}Generates a new file ending in ``_T.nc``{Nclr}\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_diurn.nc -t"
f" {Blue}(outputs data for all 24 local times){Green}\n"
f"> MarsFiles 01336.atmos_diurn.nc -t '3 15'"
f" {Blue}(outputs data for target local times only)"
f"{Nclr}\n\n"
)
)
parser.add_argument('-ba', '--bin_average', action=ExtAction, type=int,
ext_content='_to_average',
parser=parser,
nargs='?', const=5,
help=(
f"Calculate 5-day averages from instantaneous data files\n"
f"(i.e., convert 'daily' files into 'average' files.\n"
f"Requires input file to be in MGCM 'daily' format.\n"
f"{Yellow}Generates a new file ending in ``_to_average.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -ba {Blue}(5-sol bin){Green}\n"
f"> MarsFiles 01336.atmos_daily.nc -ba 10 {Blue}(10-sol bin)"
f"{Nclr}\n\n"
)
)
parser.add_argument('-bd', '--bin_diurn', action=ExtAction, type=int,
ext_content='_to_diurn',
parser=parser,
nargs=0,
help=(
f"Calculate 5-day averages binned by hour from instantaneous "
f"data files\n(i.e., convert 'daily' files into 'diurn' "
f"files.\nMay be used jointly with --bin_average.\n"
f"Requires input file to be in MGCM 'daily' format.\n"
f"{Yellow}Generates a new file ending in ``_to_diurn.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -bd {Blue}(5-sol bin){Green}\n"
f"> MarsFiles 01336.atmos_daily.nc -bd -ba 10 "
f"{Blue}(10-sol bin){Green}\n"
f"> MarsFiles 01336.atmos_daily.nc -bd -ba 1 "
f"{Blue}(no binning, mimics raw Legacy output)"
f"{Nclr}\n\n"
)
)
parser.add_argument('-hpt', '--high_pass_temporal', action=ExtAction,
ext_content='_hpt',
parser=parser,
nargs='+', type=float,
help=(
f"Temporal high-pass filtering: removes low-frequencies \n"
f"Only works with 'daily' or 'average' files. Requires a cutoff "
f"frequency in Sols.\n"
f"Data is detrended before filtering. Use ``-add_trend`` \n"
f"to add the original linear trend to the amplitudes \n"
f"\n{Yellow}Generates a new file ending in ``_hpt.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -hpt 10.\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-lpt', '--low_pass_temporal', action=ExtAction,
ext_content='_lpt',
parser=parser,
nargs='+', type=float,
help=(
f"Temporal low-pass filtering: removes high-frequencies \n"
f"Only works with 'daily' or 'average' files. Requires a cutoff "
f"frequency in Sols.\n"
f"Data is detrended before filtering. Use ``-add_trend`` \n"
f"to add the original linear trend to the amplitudes \n"
f"\n{Yellow}Generates a new file ending in ``_lpt.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -lpt 0.75\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-bpt', '--band_pass_temporal', action=ExtAction,
ext_content='_bpt',
parser=parser,
nargs="+", type=float,
help=(
f"Temporal band-pass filtering"
f"specified by user.\nOnly works with 'daily' or 'average' "
f"files. Requires two cutoff frequencies in Sols.\n"
f"Data is detrended before filtering. Use ``-add_trend`` \n"
f"to add the original linear trend to the amplitudes \n"
f"\n{Yellow}Generates a new file ending in ``bpt.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -bpt 0.75 10.\n"
f"{Nclr}\n\n"
)
)
# Decomposition in zonal harmonics, disabled for initial CAP release:
parser.add_argument('-hps', '--high_pass_spatial', action=ExtAction,
ext_content='_hps',
parser=parser,
nargs='+', type=int,
help=(
f"{Red}"
f"REQUIRES SPECIAL INSTALL:\nSee 'Spectral Analysis "
f"Capabilities' in the installation instructions at \n"
f"https://amescap.readthedocs.io/en/latest/installation.html"
f"{Nclr}\n"
f"Spatial high-pass filtering: removes low-frequency noise. "
f"Only works with 'daily' files.\nRequires a cutoff frequency "
f"in Sols.\n"
f"{Yellow}Generates a new file ending in ``_hps.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -hps 10\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-lps', '--low_pass_spatial', action=ExtAction,
ext_content='_lps',
parser=parser,
nargs='+', type=int,
help=(
f"{Red}"
f"REQUIRES SPECIAL INSTALL:\nSee 'Spectral Analysis "
f"Capabilities' in the installation instructions at \n"
f"https://amescap.readthedocs.io/en/latest/installation.html"
f"{Nclr}\n"
f"Spatial low-pass filtering: removes high-frequency noise "
f"(smoothing).\nOnly works with 'daily' files. Requires a "
f"cutoff frequency in Sols.\n"
f"{Yellow}Generates a new file ending in ``_lps.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -lps 20\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-bps', '--band_pass_spatial', action=ExtAction,
ext_content='_bps',
parser=parser,
nargs='+', type=int,
help=(
f"{Red}"
f"REQUIRES SPECIAL INSTALL:\nSee 'Spectral Analysis "
f"Capabilities' in the installation instructions at \n"
f"https://amescap.readthedocs.io/en/latest/installation.html"
f"{Nclr}\n"
f"Spatial band-pass filtering: filters out frequencies "
f"specified by user.\nOnly works with 'daily' files. Requires a "
f"cutoff frequency in Sols.\nData detrended before filtering.\n"
f"{Yellow}Generates a new file ending in ``_bps.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -bps 10 20\n"
f"{Nclr}\n\n"
)
)
parser.add_argument('-tide', '--tide_decomp', action=ExtAction,
ext_content='_tide_decomp',
parser=parser,
nargs='+', type=int,
help=(
f"{Red}"
f"REQUIRES SPECIAL INSTALL:\nSee 'Spectral Analysis "
f"Capabilities' in the installation instructions at \n"
f"https://amescap.readthedocs.io/en/latest/installation.html"
f"{Nclr}\n"
f"Use fourier decomposition to break down the signal into N "
f"harmonics.\nOnly works with 'diurn' files.\nReturns the phase "
f"and amplitude of the variable.\n"
f"N = 1 diurnal tide, N = 2 semi-diurnal, etc.\n"
f"Works on 'diurn' files only.\n"
f"{Yellow}Generates a new file ending in ``_tide_decomp.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_diurn.nc -tide 2 -incl ps temp\n"
f"{Blue}(extracts semi-diurnal tide component of ps and\ntemp "
f"variables; 2 harmonics)"
f"{Nclr}\n\n"
)
)
parser.add_argument('-regrid', '--regrid_XY_to_match', action=ExtAction,
ext_content='_regrid',
parser=parser,
nargs='+',
help=(
f"Regrid the X and Y dimensions of a target file to match a "
f"user-provided source file.\nBoth files must have the same "
f"vertical dimensions (i.e., should be vertically\ninterpolated "
f"to the same standard grid [zstd, zagl, pstd, etc.].\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Yellow}Generates a new file ending in ``_regrid.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_average_pstd.nc -regrid "
f"01336.atmos_average_pstd_c48.nc\n"
f"{Yellow}NOTE: regridded file name does not matter:\n"
f"{Green}> MarsFiles sim1/01336.atmos_average_pstd.nc -regrid "
f"sim2/01336.atmos_average_pstd.nc"
f"{Nclr}\n\n"
)
)
parser.add_argument('-prop', '--prop_tides', action=ExtAction,
ext_content='_prop_tides',
parser=parser,
nargs=2, type=int,
help=(
f"{Yellow}This function is separate distinct from [-tide "
f"--tide_decomp] and therefore does not return total amplitude \n"
f"and phase nor does it work with [-norm --normalize] or [-recon "
f"--reconstruct].\n"
f"For 'diurn' files only.\n"
f"{Nclr}\n"
f"Use fourier decomposition to break down a variable into `kmx` "
f"longitudinal (spatial) harmonics and `tmx` \n"
f"diurnal (time) harmonics. This returns the normalized phases and "
f"amplitudes (not percent) of the \n"
f"propagating tides for a variable.\n"
f"{Yellow}Generates a new file ending in ``_prop_tides.nc``{Nclr}\n"
f"`kmx = 1` for wavenumber 1, `kmx = 2` for wavenumber 2, etc.\n"
f"`tmx = 1` for diurnal tide, `tmx = 2` for semi-diurnal tide, etc.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_diurn.nc -prop kmx tmx -incl ps temp\n"
f"> MarsFiles 01336.atmos_diurn.nc -prop 2 2 -incl ps temp\n"
f"{Blue}(extracts the eastward and westward tide components of ps and"
f"temp up to semi-diurnal wavenumber 2)"
f"{Nclr}\n\n"
)
)
parser.add_argument('-zavg', '--zonal_average', action=ExtAction,
ext_content='_zavg',
parser=parser,
nargs=0,
help=(
f"Zonally average the entire file over the longitudinal "
f"dimension.\nDoes not work if the longitude dimension has "
f"length <= 1.\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Yellow}Generates a new file ending in ``_zavg.nc``\n"
f"{Green}Example:\n"
"> MarsFiles 01336.atmos_diurn.nc -zavg"
f"{Nclr}\n\n"
)
)
# Secondary arguments: Used with some of the arguments above
parser.add_argument('-dim', '--dim_select', type=str, default=None,
help=(
f"Must be used with [-split --split]. Flag indicates the "
f"dimension on which to trim the file.\nAcceptable values are "
f"'areo', 'lev', 'lat', 'lon'. Default = 'areo'.\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_average.nc --split 0 90 -dim areo\n"
f"> MarsFiles 01336.atmos_average.nc --split -70 -dim lat"
f"{Nclr}\n\n"
)
)
parser.add_argument('-norm', '--normalize', action=ExtAction,
ext_content='_norm',
parser=parser,
nargs=0,
help=(
f"For use with ``-tide``: Returns the result in percent "
f"amplitude.\n"
f"N = 1 diurnal tide, N = 2 semi-diurnal, etc.\n"
f"Works on 'diurn' files only.\n"
f"{Yellow}Generates a new file ending in ``_norm.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_diurn.nc -tide 6 -incl ps "
f"-norm"
f"{Nclr}\n\n"
)
)
parser.add_argument('-add_trend', '--add_trend', action=ExtAction,
ext_content='_trended',
parser=parser,
nargs=0,
help=(
f"Return filtered oscillation amplitudes with the linear trend "
f"added. Works with 'daily' and 'average' files.\n"
f"For use with temporal filtering utilities (``-lpt``, "
f"``-hpt``, ``-bpt``).\n"
f"{Yellow}Generates a new file ending in ``_trended.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -hpt 10. -add_trend\n"
f"> MarsFiles 01336.atmos_daily.nc -lpt 0.75 -add_trend\n"
f"> MarsFiles 01336.atmos_daily.nc -bpt 0.75 10. -add_trend"
f"{Nclr}\n\n"
)
)
parser.add_argument('-recon', '--reconstruct', action=ExtAction,
ext_content='_reconstruct',
parser=parser,
nargs=0,
help=(
f"Reconstructs the first N harmonics.\n"
f"Works on 'diurn' files only.\n"
f"{Yellow}Generates a new file ending in ``_reconstruct.nc``\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_diurn.nc -tide 6 -incl ps temp "
f"-recon"
f"{Nclr}\n\n"
)
)
parser.add_argument('-incl', '--include', nargs='+',
help=(
f"Flag to use only the variables specified in a calculation.\n"
f"All dimensional and 1D variables are ported to the new file "
f"automatically.\n"
f"Works on 'daily', 'diurn', and 'average' files.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_daily.nc -ba -incl ps temp ts"
f"{Nclr}\n\n"
)
)
parser.add_argument('-ext', '--extension', type=str, default=None,
help=(
f"Must be paired with an argument listed above.\nInstead of "
f"overwriting a file to perform a function, ``-ext``\ntells "
f"CAP to create a new file with the extension name specified "
f"here.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_average.nc -c -ext _my_concat\n"
f"{Blue}(Produces 01336.atmos_average_my_concat.nc and "
f"preserves all other files)"
f"{Nclr}\n\n"
)
)
parser.add_argument('--debug', action='store_true',
help=(
f"Use with any other argument to pass all Python errors and\n"
f"status messages to the screen when running CAP.\n"
f"{Green}Example:\n"
f"> MarsFiles 01336.atmos_average.nc -t '3 15' --debug"
f"{Nclr}\n\n"
)
)
args = parser.parse_args()
debug = args.debug
if args.input_file:
for file in args.input_file:
if not (re.search(".nc", file.name) or
re.search("fort.11", file.name)):
parser.error(
f"{Red}{file.name} is not a netCDF or fort.11 file{Nclr}"
)
exit()
if args.dim_select and not args.split:
parser.error(f"{Red}[-dim --dim_select] must be used with [-split "
f"--split]{Nclr}")
exit()
if args.normalize and not args.tide_decomp:
parser.error(f"{Red}[-norm --normalize] must be used with [-tide "
f"--tide_decomp]{Nclr}")
exit()
if args.add_trend and not (args.high_pass_temporal or args.low_pass_temporal
or args.band_pass_temporal):
parser.error(f"{Red}[-add_trend --add_trend] must be used with [-lpt "
f"--low_pass_temporal], [-hpt --high_pass_temporal], or "
f"[-bpt --band_pass_temporal]{Nclr}")
exit()
if args.reconstruct and not args.tide_decomp:
parser.error(f"{Red}[-recon --reconstruct] must be used with [-tide "
f"--tide_decomp]{Nclr}")
exit()
all_args = [args.bin_files, args.concatenate, args.split, args.time_shift,
args.bin_average, args.bin_diurn, args.high_pass_temporal,
args.low_pass_temporal, args.band_pass_temporal,
args.high_pass_spatial, args.low_pass_spatial,
args.band_pass_spatial, args.tide_decomp, args.normalize,
args.regrid_XY_to_match, args.zonal_average, args.prop_tides]
if (all(v is None or v is False for v in all_args)
and args.include is not None):
parser.error(f"{Red}[-incl --include] must be used with another "
f"argument{Nclr}")
exit()
if (all(v is None or v is False for v in all_args) and
args.extension is not None):
parser.error(f"{Red}[-ext --extension] must be used with another "
f"argument{Nclr}")
exit()
# ------------------------------------------------------
# EXTENSION FUNCTION
# ------------------------------------------------------
# Concatenates extensions to append to the file name depending on
# user-provided arguments.
"""
This is the documentation for out_ext
:no-index:
"""
out_ext = (f"{args.time_shift_ext}"
f"{args.bin_average_ext}"
f"{args.bin_diurn_ext}"
f"{args.high_pass_temporal_ext}"
f"{args.low_pass_temporal_ext}"
f"{args.band_pass_temporal_ext}"
f"{args.add_trend_ext}"
f"{args.high_pass_spatial_ext}"
f"{args.low_pass_spatial_ext}"
f"{args.band_pass_spatial_ext}"
f"{args.tide_decomp_ext}"
f"{args.reconstruct_ext}"
f"{args.normalize_ext}"
f"{args.prop_tides_ext}"
f"{args.regrid_XY_to_match_ext}"
f"{args.zonal_average_ext}"
f"{args.concatenate_ext}"
)
if args.extension:
# Append extension, if any:
out_ext = (f"{out_ext}_{args.extension}")
# ------------------------------------------------------
# DEFINITIONS
# ------------------------------------------------------
def concatenate_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
:returns: None
:rtype: None
:raises OSError: If the file cannot be removed.
:raises IOError: If the file cannot be moved.
:raises Exception: If the file cannot be opened.
:raises ValueError: If the file cannot be accessed.
:raises TypeError: If the file is not of the correct type.
:raises IndexError: If the file does not have the correct index.
:raises KeyError: If the file does not have the correct key.
"""
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):
for i in range(1, num_files):
# 1-N files ensures file number 0 is preserved
try:
os.remove(full_file_list[i])
except OSError as e:
print(f"Warning: Could not remove {full_file_list[i]}: {e}")
exit()
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 args.include:
# Exclude variables NOT listed after --include
f = Dataset(file_list[0], "r")
exclude_list = filter_vars(f, args.include, giveExclude = True)
f.close()
else:
exclude_list = []
# Create a temporary file ending in _tmp.nc to work in
base_name = os.path.splitext(full_file_list[0])[0]
tmp_file = os.path.normpath(f"{base_name}_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 concatenate -----
# 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
base_name = os.path.basename(file_list[0])
if base_name.startswith("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:
output_file_name = full_file_list[0]
merged_file = (f"{output_file_name[:-3]}{out_ext}.nc")
# Apply the new name created above
try:
shutil.move(tmp_file, merged_file)
print(f"{Cyan}{merged_file} was created from a merge{Nclr}")
except OSError as e:
print(f"Warning: Could not move {tmp_file} to {merged_file}: {e}")
return
def split_files(file_list, split_dim):
"""
Extracts variables in the file along the specified dimension.
The function creates a new file with the same name as the input
file, but with the specified dimension sliced to the requested
value or range of values. The new file is saved in the same
directory as the input file.
The function also checks the bounds of the requested dimension
against the actual values in the file. If the requested value
is outside the bounds of the dimension, an error message is
printed and the function exits.
The function also checks if the requested dimension is valid
(i.e., time, lev, lat, or lon). If the requested dimension is
invalid, an error message is printed and the function exits.
The function also checks if the requested dimension is a
single dimension (i.e., areo). If the requested dimension is
a single dimension, the function removes all single dimensions
from the areo dimension (i.e., scalar_axis) before performing
the extraction.
:param file_list: list of file names
:type split_dim: dimension along which to perform extraction
:returns: new file with sliced dimensions
:rtype: None
:raises OSError: If the file cannot be removed.
:raises IOError: If the file cannot be moved.
:raises Exception: If the file cannot be opened.
:raises ValueError: If the file cannot be accessed.
:raises TypeError: If the file is not of the correct type.
:raises IndexError: If the file does not have the correct index.
"""
if split_dim not in ['time','areo', 'lev', 'lat', 'lon']:
print(f"{Red}Split dimension must be one of the following:"
f" time, areo, lev, lat, lon{Nclr}")
bounds = np.asarray(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: [bound] to reduce one "
f"dimension to a single value, [lower_bound] [upper_bound] to "
f"reduce one dimension to a range{Nclr}"
)
exit()
# Add path unless full path is provided
if not ("/" in file_list[0]):
input_file_name = os.path.normpath(os.path.join(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, args.include)
# Get file type (diurn, average, daily, etc.)
f_type, interp_type = FV3_file_type(fNcdf)
if split_dim == 'lev':
split_dim = interp_type
if interp_type == 'pstd':
unt_txt = 'Pa'
lnm_txt = 'standard pressure'
elif interp_type == 'zagl':
unt_txt = 'm'
lnm_txt = 'altitude above ground level'
elif interp_type == 'zstd':
unt_txt = 'm'
lnm_txt = 'standard altitude'
else:
unt_txt = 'mb'
lnm_txt = 'ref full pressure level'
# Remove all single dimensions from areo (scalar_axis)
if f_type == 'diurn':
if split_dim == 'areo':
# size areo = (time, tod, scalar_axis)
reducing_dim = np.squeeze(fNcdf.variables['areo'][:, 0, :])
else:
reducing_dim = np.squeeze(fNcdf.variables[split_dim][:, 0])
else:
if split_dim == 'areo':
# size areo = (time, scalar_axis)
reducing_dim = np.squeeze(fNcdf.variables['areo'][:])
else:
reducing_dim = np.squeeze(fNcdf.variables[split_dim][:])
if split_dim == 'areo':
print(f"\n{Yellow}Areo MOD(360):\n{reducing_dim%360.}\n")
print(f"\n{Yellow}All values in dimension:\n{reducing_dim}\n")
dx = np.abs(reducing_dim[1] - reducing_dim[0])
bounds_in = bounds.copy()
if split_dim == 'areo':
while (bounds[0] < (reducing_dim[0] - dx)):
bounds += 360.
if len(np.atleast_1d(bounds)) == 2:
while (bounds[1] < bounds[0]):
bounds[1] += 360.
if len(np.atleast_1d(bounds)) < 2:
check_bounds(bounds[0], reducing_dim[0], reducing_dim[-1], dx)
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:
check_bounds(bounds, reducing_dim[0], reducing_dim[-1], dx)
if ((split_dim == 'lon') & (bounds[1] < bounds[0])):
indices = np.where(
(reducing_dim <= bounds[1]) |
(reducing_dim >= bounds[0])
)[0]
else:
indices = np.where(
(reducing_dim >= bounds[0]) &
(reducing_dim <= bounds[1])
)[0]
dim_out = reducing_dim[indices]
print(
f"Requested range = {bounds_in[0]} - {bounds_in[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_in[0]}, {bounds_in[1]}) ({split_dim} values range "
f"from {reducing_dim[0]:.1f} to {reducing_dim[-1]:.1f})"
)
exit()
fpath = os.path.dirname(input_file_name)
fname = os.path.basename(input_file_name)
if split_dim in ('time', 'areo'):
time_dim = (np.squeeze(fNcdf.variables['time'][:]))[indices]
print(f"time_dim = {time_dim}\n")