-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxagg.py
executable file
·217 lines (182 loc) · 6.38 KB
/
xagg.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Stephen Po-Chedley 9 May 2019
This is a wrapper for runing xagg software. It makes use of:
runSettings.py - runtime variables for software
fx.py - functions called by this wrapper
There are a number of command line options. These can be viewed using:
./xagg.py --help
The environment was created / implemented using:
conda create -n cdat81 -c cdat/label/v81 -c conda-forge cdat scandir joblib
conda activate cdat81
@author: pochedls
"""
import fx
import time
import os
from runSettings import *
import numpy as np
import argparse
try:
__IPYTHON__
except NameError:
INIPYTHON = False
else:
INIPYTHON = True
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
if INIPYTHON is False: # Look for cmd line arguments if we are NOT in Ipython
parser = argparse.ArgumentParser()
# Optional arguments
parser.add_argument('-p', '--updatePaths', type=str2bool,
default=True,
help="Flag (TRUE/FALSE) to update SQL database" +
" (default is TRUE)")
parser.add_argument('-s', '--updateScans', type=str2bool,
default=True,
help="Flag (TRUE/FALSE) to run cdscan" +
" (default is TRUE)")
parser.add_argument('-out', '--outputDirectory', type=str,
default='/p/user_pub/xclim/',
help="Base output directory for xml files" +
" (default /p/user_pub/xclim/)")
parser.add_argument('-n', '--numProcessors', type=int,
default=20,
help="Number of processors for creating xml files" +
" (default 20)")
parser.add_argument('-c', '--countStats', type=str2bool,
default=True,
help="Boolean to record statistics on xml database")
parser.add_argument('-e', '--experiment', type=str,
default='',
help="Comma separated list of experiments" +
" (e.g., piControl,abrupt4xCO2,rcp85)")
parser.add_argument('-f', '--frequency', type=str,
default='',
help="Comma separated list of frequencies" +
" (e.g., mon,day,3hr)")
parser.add_argument('-v', '--variable', type=str,
default='',
help="Comma separated list of variables" +
" (e.g., tas,ts,ps)")
args = parser.parse_args()
updatePaths = args.updatePaths
updateScans = args.updateScans
outputDirectory = args.outputDirectory
numProcessors = args.numProcessors
countStats = args.countStats
experimentIn = args.experiment
variableIn = args.variable
frequencyIn = args.frequency
else:
updatePaths = True
updateScans = True
outputDirectory = '/p/user_pub/xclim/'
numProcessors = 20
countStats = True
experimentIn = ''
variableIn = ''
frequencyIn = ''
print('Starting job')
print(time.ctime())
print()
# Ensure there isn't a concurrent run or unresolved error
# If there is no lock, place a lock and continue
if fx.runLock('check'):
raise ValueError('Lock is on. xagg is running or encountered an error.')
else:
fx.runLock('on')
# override default variables with user inputs
if experimentIn != '':
experiments = experimentIn.split(',')
if frequencyIn != '':
frequencies = frequencyIn.split(',')
if variableIn != '':
variables = variableIn.split(',')
# ensure database is initialized
if not os.path.exists(sqlDB):
print('Initializing database')
print(time.ctime())
print()
fx.initializeDB(sqlDB)
# get all paths
if updatePaths:
print('Checking disk paths')
print(time.ctime())
print()
diskStat = fx.parallelFindData(data_directories, split=split_directories,
rmDir=rm_directories)
diskPaths = diskStat.keys()
# ensure there is a cmip metadata file
if not os.path.exists(cmipMetaFile):
print('Initializing CMIP Meta File')
print(time.ctime())
print()
fx.createLookupDictionary(diskPaths, outfile=cmipMetaFile)
# get paths in database
print()
print('Get existing xml metadata')
print(time.ctime())
print()
db = fx.getDBPaths(sqlDB)
dbPaths = db.keys()
invalidPaths = fx.getInvalidDBPaths(sqlDB)
retiredPaths = fx.getRetiredDBPaths(sqlDB)
# compare paths on disk to those in database
if updatePaths:
print('Comparing disk paths with database')
print(time.ctime())
print()
fx.updateDatabaseHoldings(sqlDB, diskPaths, diskStat, dbPaths, db,
invalidPaths, retiredPaths)
del diskStat, diskPaths
del db, invalidPaths, retiredPaths, dbPaths
# get paths to scan
if updateScans:
print('Getting paths to scan')
print(time.ctime())
print()
db = fx.getDBPaths(sqlDB) # get updated database
scanList = fx.getScanList(sqlDB, db, variables, experiments, frequencies)
del db
print('Start scans')
print(time.ctime())
print()
nChunks = int(np.ceil(len(scanList)/chunkSize))
nTotal = 0
for i in range(nChunks):
# get a chunk of the scanList
Idx = np.arange(i * chunkSize, i*chunkSize + chunkSize)
if Idx[-1] > len(scanList):
Idx = np.arange(i * chunkSize, len(scanList))
inList = [scanList[i] for i in Idx]
nTotal += len(inList)
print(time.ctime() + ': ' + str(nTotal) + '/' + str(len(scanList)) +
' (' + str(np.round(nTotal/len(scanList)*100, 1)) + '%) ',
end='')
# scan chunk
s = time.time()
results = fx.scanChunk(inList, numProcessors, outputDirectory)
e = time.time()
print('- ' + str(int(e-s)) + 's ', end='')
# write results to database
s = time.time()
fx.writeScanResults(sqlDB, results)
e = time.time()
print('- ' + str(int(e-s)) + 's ')
if countStats:
print()
print('Write statistics to database')
print(time.ctime())
print()
fx.writeStats(sqlDB)
fx.runLock('off') # remove run lock
print('Finished run')
print(time.ctime())
print()