-
Notifications
You must be signed in to change notification settings - Fork 20
/
flexpart_read.py
1293 lines (1084 loc) · 44.2 KB
/
flexpart_read.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
#### Functions for reading FLEXPART output #####
from __future__ import print_function
import os
import datetime
import re
import numpy as np
from math import pi, sqrt, cos
from collections import OrderedDict
import reflexible.conv2netcdf4
def read_releases(pathname):
"""
Parses release file in `pathname` and return its contents.
"""
signature = open(pathname).read(1)
if signature == "&":
return read_releases_v10(pathname)
else:
# This is mainly a placeholder, but we should worry only about v10
return read_releases_v9(pathname)
def read_releases_v10(pathname):
"""
Parses release file in `pathname` and return a ctable with its contents.
This is only suited for files in Fortran90 namelist format (FP v10).
Parameters
----------
pathname : pathname
Release file name (in Fortran90 namelist format).
Returns
-------
A ctable object from bcolz package.
"""
import bcolz
# Setup the container for the data
dtype = [('IDATE1', np.int32), ('ITIME1', np.int32),
('IDATE2', np.int32), ('ITIME2', np.int32),
('LON1', np.float32), ('LON2', np.float32),
('LAT1', np.float32), ('LAT2', np.float32),
('Z1', np.float32), ('Z2', np.float32),
('ZKIND', np.int8), ('MASS', np.float32),
('PARTS', np.int32), ('COMMENT', 'S32')]
cparams = bcolz.cparams(cname="lz4", clevel=6, shuffle=1)
ctable = bcolz.zeros(0, dtype=dtype, cparams=cparams)
nrecords = ctable['IDATE1'].chunklen
releases = np.zeros(nrecords, dtype=dtype)
# Prepare for reading the input
input_str = open(pathname, 'r').read()
marker = "&RELEASE\n"
len_marker = len(marker)
release_re = r'\S+=\s+[\"|\s](\S+)[,|\"|\w]'
# Loop over all the marker groups
i, n = 0, 0
while True:
i = input_str.find(marker, i)
j = input_str.find(marker, i + 1)
n += 1
group_block = input_str[i + len_marker: j]
i = j
values = tuple(re.findall(release_re, group_block))
try:
releases[(n - 1) % nrecords] = values
except ValueError:
print("Problem at: group: %d, %s" % (n, group_block))
print("values:", values)
raise
if (n % nrecords) == 0:
ctable.append(releases)
if (i == -1) or (j == -1):
break # marker is not found anymore
# Remainder
ctable.append(releases[:n % nrecords])
ctable.flush()
return ctable
def read_releases_v9(path):
"""Read metadata from a RELEASES path and return it as a dict.
Only 'release_point_names' entry returned.
"""
rpnames = []
with open(path) as f:
prev_line = None
for line in f:
if prev_line is not None and "comment" in line:
rpnames.append(prev_line.strip())
prev_line = line
# Return just the release point names for now
return {"release_point_names": np.array(rpnames, dtype="S45")}
def read_releases_old(path, headerrows=11):
"""
Reads a FLEXPART releases file.
.. note::
Assumes releases file has a header of 11 lines. Use
option "headerrows" to override this.
USAGE::
> A = read_releases_v9(path)
where filepath is either a file object or a path.
Returns
a record array with fields:
============ ==========================
fields description
============ ==========================
start_time datetime start
end_time datetime end
lllon lower left longitude
llat lower left latitude
urlon upper right longitude
urlat upper right latitude
altunit 1=magl, 2=masl, 3=hPa
elv1 lower z level
elv2 upper z level
numpart numparticles
mass mass for each spec, so the
array will actually have
fields: mass0, mass1,..
id ID for each release
============ ==========================
"""
def getfile_lines(infile):
""" returns all lines from a file or file string
reverts to beginning of file."""
if isinstance(infile, str):
return open(infile, 'r').readlines()
else:
infile.seek(0)
return infile.readlines()
lines = getfile_lines(path)
lines = [i.strip() for i in lines] # clean line ends
# we know nspec is at line 11
nspec = int(lines[headerrows])
blocklength = headerrows + nspec
spec = []
for i in range(nspec):
spec.append(int(lines[headerrows + 1 + i]))
indx = headerrows + 1 + (i + 2)
blocks = []
for i in range(indx, len(lines), blocklength + 1):
blocks.append(lines[i:i + blocklength])
for b in blocks:
b[0] = datetime.datetime.strptime(b[0], '%Y%m%d %H%M%S')
b[1] = datetime.datetime.strptime(b[1], '%Y%m%d %H%M%S')
b[2:6] = [np.float(i) for i in b[2:6]]
b[6] = int(b[6])
b[7] = float(b[7])
b[8] = float(b[8])
b[9] = int(b[9])
for i in range(nspec):
b[10 + i] = float(b[10 + i])
b = tuple(b)
names = ['start_time', 'end_time', 'lllon', 'lllat', 'urlon', 'urlat',
'altunit', 'elv1', 'elv2', 'numpart']
# formats = [object, object, np.float, np.float, np.float, np.float,\
# int, np.float, np.float, int]
for i in range(nspec):
names.append('mass%s' % i)
# formats.append(np.float)
names.append('id')
# formats.append('S30')
# dtype = {'names':names, 'formats':formats}
# RELEASES = np.rec.array(blocks,dtype=dtype)
return np.rec.fromrecords(blocks, names=names)
def read_command(path, headerrows=7):
with open(path, 'r') as comfile:
if "&COMMAND" in comfile.readline():
command = read_command_v10(path, 1)
return OrderedDict(sorted(command.items(), key=lambda t: t[0]))
for i in range(headerrows - 1):
comfile.readline()
signature = comfile.readline().strip()
if signature[:5] == "1. __":
command = read_command_v9(path, headerrows)
else:
command = read_command_old(path, headerrows)
return OrderedDict(sorted(command.items(), key=lambda t: t[0]))
def read_command_v10(path, headerrows):
lines = open(path, 'r').readlines()
command_vals = [i.strip() for i in lines[headerrows:]] # clean line ends
commands = {}
for command in command_vals:
if '=' not in command:
break # this is the end of commands
key, val = command.split("=")
val = val[:-1] # get rid of the trailing ,
try:
commands[key] = int(val)
except ValueError:
try:
commands[key] = float(val)
except ValueError:
commands[key] = val
return commands
def read_command_v9(path, headerrows):
"""Quick and dirty approach for reading COMMAND file for FP V9"""
COMMAND_KEYS = (
'SIM_DIR',
'SIM_START',
'SIM_END',
'AVG_CNC_INT',
'AVG_CNC_TAVG',
'CNC_SAMP_TIME',
'T_PARTSPLIT',
'SYNC',
'CTL',
'IFINE',
'IOUT',
'IPOUT',
'LSUBGRID',
'LCONVECTION',
'LAGESPECTRA',
'IPIN',
'OUTPUTFOREACHRELEASE',
'IFLUX',
'MDOMAINFILL',
'IND_SOURCE',
'IND_RECEPTOR',
'MQUASILAG',
'NESTED_OUTPUT',
'LINIT_COND')
float_keys = ['CTL']
date_keys = ['SIM_START', 'SIM_END']
COMMAND = {}
ncommand = 0
with open(path, 'r') as comfile:
for i in range(headerrows):
comfile.readline()
while ncommand < len(COMMAND_KEYS):
comfile.readline()
val = comfile.readline().strip().split()
key = COMMAND_KEYS[ncommand]
if key in date_keys:
val = val[:2]
elif key in float_keys:
val = float(val[0])
else:
val = int(val[0])
COMMAND[key] = val
comfile.readline()
comfile.readline()
ncommand += 1
return COMMAND
def read_command_old(path, headerrows):
"""
Reads a FLEXPART COMMAND file.
.. note::
Assumes releases file has a header of 7 lines. Use
option "headerrows" to override this.
USAGE::
> A = read_command(filepath)
where filepath is either a file object or a path.
Returns
a dictionary with the following keys
================ =================================================================
fields description
================ =================================================================
SIM_DIR Simulation direction
SIM_START Text str of YYYYMMDD HHMMSS
SIM_END Text str of YYYYMMDD HHMMSS
AVG_CNC_INT Average concentrations are calculated every SSSSS seconds
AVG_CNC_TAVG The average concentrations are time averages of SSSSS sec
CNC_SAMP_TIME The concentrations are sampled every SSSSS seconds to
calculate the time average concentration.
T_PARTSPLIT Time constant for particle splitting.
SYNC All processes are synchronized with this time interval
CTL --
IFINE IFINE=Reduction factor for time step used for vertical wind
IOUT IOUT determines how the output shall be made: concentration
(ng/m3, Bq/m3), mixing ratio (pptv), or both, or plume
trajectory mode, or concentration + plume trajectory mode.
IPOUT IPOUT determines whether particle positions are outputted
(in addition to the gridded concentrations or mixing ratios)
or not. 0=no output, 1 output every output interval, 2 only
at end of the simulation
LSUBGRID Switch on/off subgridscale terrain parameterization
(increase of mixing heights due to subgridscale orog. var
LCONVECTION Switch on/off the convection parameterization
LAGESPECTRA Switch on/off the calculation of age spectra: if yes, the
file AGECLASSES must be available
IPIN If IPIN=1, a file "partposit_end" from a previous run must
be available in the output directory. Particle positions
are read in and previous simulation is continued. If
IPIN=0, no particles from a previous run are used
IOFR Switch on/off writing out each release.
IFLUX If IFLUX is set to 1, fluxes of each species through each
of the output boxes are calculated. Six fluxes,
corresponding to northward, southward, eastward, westward,
upward and downward are calculated for each grid cell of
the output grid. The control surfaces are placed in the
middle of each output grid cell. If IFLUX is set to 0,
no fluxes are determined.
MDOMAINFILL If MDOMAINFILL is set to 1, the first box specified in file
RELEASES is used as the domain where domain-filling
trajectory calculations are to be done. Particles are
initialized uniformly distributed (according to the air mass
distribution) in that domain at the beginning of the
simulation, and are created at the boundaries throughout
the simulation period
IND_SOURCE IND_SOURCE switches between different units for
concentrations at the source. NOTE that in backward
simulations the release of computational particles takes
place at the "receptor" and the sampling of particles at
the "source". 1=mass units (for bwd-runs = concentration)
2=mass mixing ratio units'''],
IND_RECEPTOR IND_RECEPTOR switches between different units for
concentrations at the receptor 1=mass units (concentrations)
2=mass mixing ratio units
MQUASILAG MQUASILAG indicates whether particles shall be numbered
consecutively (1) or with their release location number (0).
The first option allows tracking of individual particles
using the partposit output files
NESTED_OUTPUT NESTED_OUTPUT decides whether model output shall be made
also for a nested output field (normally with higher resolution)
LINIT_COND For Backward Runs, sets initial conditions:
[0]=No, 1=Mass Unit, 2=Mass Mixing
================ =================================================================
"""
lines = open(path, 'r').readlines()
command_vals = [i.strip() for i in lines[headerrows:]] # clean line ends
COMMAND_KEYS = (
'SIM_DIR',
'SIM_START',
'SIM_END',
'AVG_CNC_INT',
'AVG_CNC_TAVG',
'CNC_SAMP_TIME',
'T_PARTSPLIT',
'SYNC',
'CTL',
'IFINE',
'IOUT',
'IPOUT',
'LSUBGRID',
'LCONVECTION',
'LAGESPECTRA',
'IPIN',
'OUTPUTFOREACHRELEASE',
'IFLUX',
'MDOMAINFILL',
'IND_SOURCE',
'IND_RECEPTOR',
'MQUASILAG',
'NESTED_OUTPUT',
'LINIT_COND')
float_keys = ['CTL']
date_keys = ['SIM_START', 'SIM_END']
COMMAND = {}
for i, key in enumerate(COMMAND_KEYS):
val = command_vals[i].split()
if key in date_keys:
val = val[:2]
elif key in float_keys:
val = float(val[0])
else:
val = int(val[0])
COMMAND[key] = val
return COMMAND
def read_trajectories(H, trajfile='trajectories.txt',
ncluster=5,
ageclasses=20):
"""
Reads the trajectories.txt file in a FLEXPART run output directory.
Based on output from plumetraj.f::
********************************************************************************
* *
* Determines a plume centroid trajectory for each release site, and manages *
* clustering of particle locations. Certain parameters (average PV, *
* tropopause height, etc., are provided along the plume trajectories. *
* At the end, output is written to file 'trajectories.txt'. *
* *
* Author: A. Stohl *
* *
* 24 January 2002 *
* *
* Variables: *
* fclust fraction of particles belonging to each cluster *
* hmixcenter mean mixing height for all particles *
* ncluster number of clusters to be used *
* pvcenter mean PV for all particles *
* pvfract fraction of particles with PV<2pvu *
* rms total horizontal rms distance after clustering *
* rmsdist total horizontal rms distance before clustering *
* rmsclust horizontal rms distance for each individual cluster *
* topocenter mean topography underlying all particles *
* tropocenter mean tropopause height at the positions of particles *
* tropofract fraction of particles within the troposphere *
* zrms total vertical rms distance after clustering *
* zrmsdist total vertical rms distance before clustering *
* xclust,yclust, Cluster centroid positions *
* zclust *
* *
********************************************************************************
USAGE::
> T = read_trajectories(H_OR_path_to_directory, **kwargs)
.. note::
The first argument is either a path to a trajectory file, or simply a :class:`Header`
instance.
Returns a dictionary of the trajectories for each release.
.. tabularcolumns:: |l|L|
============= ========================================
Keys Description
============= ========================================
Trajectories array_of_floats(j,it1,xi,yi,zi,topoi,hmixi,tropoi,pvi,
rmsdisti,rmsi,zrmsdisti,zrmsi,hfri,pvfri,trfri,
(xclusti(k),yclusti(k),zclusti(k),fclusti(k),rmsclusti(k),k=1,5))
RELEASE_ID 1array(i1,i2,xp1,yp1,xp2,yp2,zp1,zp2,k,npart)
numpspec number of species
numageclass number of ageclasses
============= ========================================
Arguments
.. tabularcolumns:: |l|L|
============= ========================================
keyword Description [default]
============= ========================================
trajfile over the name of the input
file ['trajectories.txt']
ncluster number of clusters [5]
ageclasses number of ageclasses [20]
============= ========================================
"""
if isinstance(H, str):
try:
alltraj = open(H, 'r').readlines()
except:
raise IOError('Could not open file: %s' % H)
else:
path = H.path
alltraj = open(os.path.join(path, trajfile), 'r').readlines()
try:
ibdate, ibtime, model, version = alltraj[0].strip().split()[:4]
except:
ibdate, ibtime = alltraj[0].strip().split()[:2]
model = 'Flexpart'
version = 'V.x'
dt = datetime.datetime.strptime(ibdate + ibtime.zfill(6),
'%Y%m%d%H%M%S')
numpoint = int(alltraj[2].strip())
# Fill a dictionary with the Release points and information keyed by name
# RelTraj['RelTraj_ID'] = (i1,i2,xp1,yp1,xp2,yp2,zp1,zp2,k,npart)
RelTraj = reflexible.conv2netcdf4.Structure()
Trajectories = []
for i in range(3, 3 + (numpoint * 2), 2):
i1, i2, xp1, yp1, xp2, yp2, zp1, zp2, k, npart, = \
tuple([float(j) for j in alltraj[i].strip().split()])
itimerel1 = dt + datetime.timedelta(seconds=i1)
itimerel2 = dt + datetime.timedelta(seconds=i2)
Xp = (xp1 + xp2) / 2
Yp = (yp1 + yp2) / 2
Zp = (zp1 + zp2) / 2
RelTraj[
alltraj[
i +
1].strip()] = np.array(
(itimerel1,
itimerel2,
Xp,
Yp,
Zp,
k,
npart))
for i in range(3 + (numpoint * 2), len(alltraj)):
raw = alltraj[i]
FMT = [0, 5, 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 6, 6, 6] + \
ncluster * [8, 8, 7, 6, 8]
data = [raw[sum(FMT[:ii]):sum(FMT[:ii + 1])]
for ii in range(1, len(FMT) - 1)] + [raw[sum(FMT[:-1]):]]
### FIX ###
# To get rid of '******' that is now in trajectories.txt
data = [float(r.replace('********', 'NaN')) for r in data]
Trajectories.append(data)
data = np.array(Trajectories)
RelTraj['version'] = model + ' ' + version
RelTraj['date'] = dt
RelTraj['Trajectories'] = data
RelTraj['labels'] = \
['release number', 'seconds prior to release', 'lon', 'lat', 'height',
'mean topography', 'mean mixing height', 'mean tropopause height',
'mean PV index', 'rms distance', 'rms', 'zrms distance', 'zrms',
'fraction height??', 'fraction PV<2pvu',
'fraction in troposphere'] + ncluster * [
'xcluster', 'ycluster', 'zcluster', 'fcluster', 'rmscluster']
RelTraj['info'] = """
Returns a dictionary:
R['Trajectories'] = array_of_floats(
releasenum, it1, xi, yi, zi, topoi, hmixi, tropoi, pvi,
rmsdisti, rmsi, zrmsdisti, zrmsi, hfri, pvfri, trfri,
(xclusti(k), yclusti(k), zclusti(k), fclusti(k), rmsclusti(k),
k=1,5))
R['RELEASE_ID'] = (dt_i1, dt_i2, xp1, yp1, xp2, yp2, zp1, zp2, k, npart)
R['info'] = this message
To plot a trajectory timeseries:
RT = read_trajectories(H)
T = RT['Trajectories']
rel = 1
t = T[np.where(T[:,0]==rel),:][0]
plt.plot(t[:,1],t[:,14])
plt.savefig('trajectories.png')
"""
return RelTraj
def read_agespectrum(filename, part=False, ndays=20):
"""
Reads the spectrum.txt files generated from the "make_webpages" scripts.
.. note::
This functionality depends on having run the make_webpages scripts
in-house. It is not supported in the public API.
USAGE::
> A = read_agespectrum(filename)
Returns a dictionary containing ageclass information
.. tabularcolumns:: |l|L|
============= ========================================
Keys Description
============= ========================================
agespectrum 2d-array
(dt, lat, lon, alt, tracer[:numageclass]
for each release)
ageclasses 1d-array(ageclass ages)
numpspec number of species
numageclass number of ageclassesA
part if it is from make webpages without the
header information.
ndays The number of ageclasses
============= ========================================
"""
f = open(filename, 'r').readlines()
line1 = f[0].strip().split()
if part:
numageclass = ndays
ageclasses = np.arange(1, ndays * 1) * 60 * 60 * 24
numspec = 1
else:
numageclass = int(line1[0])
ageclasses = np.array([int(i) for i in line1[1:]])
numspec = int(f[1].strip().split()[0])
A = reflexible.conv2netcdf4.Structure()
D = []
for line in f[2:]:
line = line.strip().split()
# convert ibdate, ibtime to datetime
dt = datetime.datetime.strptime(
line[0] +
line[1].zfill(6),
'%Y%m%d%H%M%S')
data = [float(i) for i in line[2:]]
# reordering the array, dt object will be '0'
data = [data[1]] + [data[0]] + data[2:]
D.append([dt] + data)
D = np.array(D)
A['agespectrum'] = D
A['numageclass'] = numageclass
A['ageclasses'] = ageclasses
A['numspec'] = numspec
A['filename'] = filename
A['info'] = \
"""
A dictionary containing ageclass information:
keys:
agespectrum = 2d-array(dt, lon, lat, alt, tracer[:numageclass] for each release)
ageclasses = 1d-array(ageclass ages)
numpspec = number of species
numageclass = number of ageclasses
info = this message
"""
return A
def save_spectrum(outf, H, agespectra, spectype='agespec',
header='## AGECLASS File'):
""" Save an ageclass or continents spectrum to an outfile. """
if spectype == 'agespec':
# ftype = 'AGECLASS'
try:
T = H.releasetimes
spectrum = agespectra
nClasses = spectrum.shape[1]
except:
# assume H is a list or None
if H:
nClasses = H[0]
T = H[1]
spectrum = agespectra
else:
T = agespectra[:, 0]
nClasses = agespectra.shape[1] - 1
spectrum = agespectra[:, 1:]
elif spectype == 'contspec':
# assume H is a list or None
# ftype = 'SPECTRUM'
try:
T = H.releasetimes
spectrum = agespectra
nClasses = spectrum.shape[1]
header = '## Continental Spectrum File'
except:
# assume H is a list or None
if H:
nClasses = H[0]
T = H[1]
spectrum = agespectra
else:
T = agespectra[:, 0]
nClasses = agespectra.shape[1] - 1
spectrum = agespectra[:, 1:]
T = np.array(T)
T = np.reshape(T, (len(T), 1))
xout = np.hstack((T, spectrum))
fmt = '%s ' + nClasses * '%10.5f '
outf.write("%s \n" % (header))
np.savetxt(outf, xout, fmt=fmt)
outf.close()
def gridarea(H):
"""returns an array of area corresponding to each nx,ny,nz
Usage::
> area = gridarea(H)
Returns
OUT = array area corresponding to nx,ny,nz
Arguments
H = :class:`Header` object from readheader function.
"""
pih = pi / 180.
r_earth = 6.371e6
cosfunc = lambda y: cos(y * pih) * r_earth
nx = H['numxgrid']
ny = H['numygrid']
outlat0 = H['outlat0']
dyout = H['dyout']
dxout = H['dxout']
area = np.zeros((nx, ny))
for iy in range(ny):
# NEED TO Check this, iy since arrays are 0-index
ylata = outlat0 + (float(iy) + 0.5) * dyout
ylatp = ylata + 0.5 * dyout
ylatm = ylata - 0.5 * dyout
if ylatm < 0 and ylatp > 0:
hzone = dyout * r_earth * pih
else:
# cosfact = cosfunc(ylata)
cosfactp = cosfunc(ylatp)
cosfactm = cosfunc(ylatm)
if cosfactp < cosfactm:
hzone = sqrt(r_earth ** 2 - cosfactp ** 2) - \
sqrt(r_earth ** 2 - cosfactm ** 2)
else:
hzone = sqrt(r_earth ** 2 - cosfactm ** 2) - \
sqrt(r_earth ** 2 - cosfactp ** 2)
gridarea = 2. * pi * r_earth * hzone * dxout / 360.
for ix in range(nx):
area[ix, iy] = gridarea
return area
def _get_header_version(bf):
"""
Open and read the binary file (bf) header only to the point of
the Flexpart version string, return the string, seek to the
start of the file.
"""
try:
bf = reflexible.conv2netcdf4.BinaryFile(bf)
except:
bf = bf
ret = bf.tell()
bf.seek(12) # start of version string
version = bf.read('13S').decode()
# Somewhere in version 9.2 beta, the version length changed to 29
# However, one *must* check which is the final size for this
if '9.2 b' in version or '10' in version:
bf.seek(12)
version = bf.read('29S').decode()
bf.seek(ret)
return version
def read_header(pathname, **kwargs):
"""
The readheader function returns a special class (Structure) which behaves
like a dictionary. It contains all the metadata from the simulation which
is contained in the "header" or "header_nest" binary files from the model
output.
.. warning::
It is recommended to use the :class:`Header` class: H = Header(path)
This version is using the BinaryFile class rather than FortFlex.
Usage::
> H = read_header(pathname) #Don't include header filename
Returns a dictionary
H = dictionary like object with all the run metadata.
Arguments
.. tabularcolumns:: |l|L|
============= ========================================
keyword Description [default]
============= ========================================
pathname FLEXPART run output directory
readp read release points 0=no, [1]=y
nested nested output [False] or True
headerfile provide custom name for header file
datefile provide a custom name for the date file
verbose print information while loading header
============= ========================================
.. note::
**This function is in development**
Please report any bugs found.
.. TODO::
probably a lot of things, among which ...
[] choose skip/getbin or direct seek/read
[] define output keys in docstring
.. note::
The user is no longer required to indicate which version of FLEXPART
the header is from. Checks are made, and the header is read accordingly.
Please report any problems...
"""
h = reflexible.conv2netcdf4.Structure()
h.options = OPS = reflexible.conv2netcdf4.Structure()
OPS.readp = True
OPS.nested = False
OPS.ltopo = 1 # 1 for AGL, 0 for ASL
OPS.verbose = False
OPS.headerfile = None
OPS.datefile = None
# add keyword overides and options to header
for k in kwargs.keys():
if k not in OPS.keys():
print("WARNING: {0} not a valid input option.".format(k))
# BW compat fixes
if 'nest' in kwargs.keys():
raise IOError(
"nest is no longer a valid keyword, see docs. \n "
"Now use nested=True or nested=False")
if 'nested' in kwargs.keys():
# Force the use of true boolean values
kwargs['nested'] = bool(kwargs['nested'])
OPS.update(kwargs)
if OPS.verbose:
print("Reading Header with:\n")
for o in OPS:
print("%s ==> %s" % (o, OPS[o]))
# Define utility functions for reading binary file
skip = lambda n = 8: bf.seek(n, 1)
getbin = lambda dtype, n = 1: bf.read(dtype, (n,))
if OPS.headerfile:
filename = os.path.join(pathname, OPS.headerfile)
elif OPS.nested is True:
filename = os.path.join(pathname, 'header_nest')
h['nested'] = True
else:
filename = os.path.join(pathname, 'header')
h['nested'] = False
# Open header file in binary format
if not os.path.exists(filename):
raise IOError("No such file: {0}".format(filename))
else:
try:
bf = reflexible.conv2netcdf4.BinaryFile(filename, order="fortran")
except:
raise IOError(
"Error opening: {0} with BinaryFile class".format(filename))
# Get available_dates from dates file in same directory as header
if OPS.datefile:
datefile = os.path.join(pathname, OPS.datefile)
else:
datefile = os.path.join(pathname, 'dates')
if not os.path.exists(datefile):
raise IOError("No DATEFILE: {0}".format(datefile))
else:
try:
fd = open(datefile, 'r').readlines()
except:
raise IOError("Could not read datefile: {0}".format(datefile))
# get rid of any duplicate dates (a fix for the forecast system)
fd = sorted(list(set(fd)))
h['available_dates'] = [d.strip('\n') for d in fd]
# which version format is header file:
version = _get_header_version(bf)
lenver = len(version)
# required containers
junk = [] # for catching unused output
h['nz_list'] = []
h['species'] = []
h['wetdep'] = []
h['drydep'] = []
h['ireleasestart'] = []
h['ireleaseend'] = []
h['compoint'] = []
# Define Header format and create Dictionary Keys
I = {0: '_0', 1: 'ibdate', 2: 'ibtime', 3: 'flexpart',
4: '_1', 5: 'loutstep', 6: 'loutaver', 7: 'loutsample',
8: '_2', 9: 'outlon0', 10: 'outlat0', 11: 'numxgrid',
12: 'numygrid', 13: 'dxout', 14: 'dyout', 15: '_3', 16: 'numzgrid',
}
# format for binary reading first part of the header file
Dfmt = ['i', 'i', 'i', '%dS'%lenver, '2i', 'i', 'i', 'i', '2i', 'f', 'f', 'i', 'i', 'f', 'f', '2i', 'i']
if bf:
a = [bf.read(fmt) for fmt in Dfmt]
for j in range(len(a)):
h[I[j]] = a[j]
h['outheight'] = np.array([bf.read('f') for i in range(h['numzgrid'])])
junk.append(bf.read('2i'))
h['jjjjmmdd'] = bf.read('i')
h['hhmmss'] = bf.read('i')
junk.append(bf.read('2i'))
h['nspec'] = bf.read('i') // 3 # why!?
h['numpointspec'] = bf.read('i')
junk.append(bf.read('2i'))
# Read in the species names and levels for each nspec
# temp dictionaries
for i in range(h['nspec']):
if 'V6' in version:
h['wetdep'].append(
''.join([bf.read('c') for i in range(10)]).strip())
junk.append(bf.read('2i'))
junk.append(bf.read('i'))
h['drydep'].append(
''.join([bf.read('c') for i in range(10)]).strip())
junk.append(bf.read('2i'))
h['nz_list'].append(getbin('i'))
h['species'].append(
''.join([getbin('c') for i in range(10)]).strip())
else:
junk.append(bf.read('i'))
h['wetdep'].append(
''.join([bf.read('c').decode() for i in range(10)]).strip())
junk.append(bf.read('2i'))
junk.append(bf.read('i'))
h['drydep'].append(
''.join([bf.read('c').decode() for i in range(10)]).strip())
junk.append(bf.read('2i'))
h['nz_list'].append(bf.read('i'))
h['species'].append(
''.join([bf.read('c').decode() for i in range(10)]).strip())
junk.append(bf.read('2i'))
if 'V6' in version:
bf.seek(8, 1)
# pdb.set_trace()
h['numpoint'] = bf.read('i')
# read release info if requested
# if OPS.readp pass has changed, we cycle through once,
# then break the loop if OPS.readp is false. This is done
# in order to get some of the information into the header.
before_readp = bf.tell()
# initialise release fields
I = {2: 'kindz', 3: 'xp1', 4: 'yp1', 5: 'xp2',
6: 'yp2', 7: 'zpoint1', 8: 'zpoint2', 9: 'npart', 10: 'mpart'}
for k, v in I.items():
# create zero-filled lists in H dict
h[v] = np.zeros(h['numpoint'])
h['xmass'] = np.zeros((h['numpoint'], h['nspec']))
if 'V6' in version:
skip()
_readV6(bf, h)
else:
junk.append(bf.read('i'))
for i in range(h['numpoint']):
junk.append(bf.read('i'))