-
Notifications
You must be signed in to change notification settings - Fork 122
/
ExportVulcanSampleLogs.py
291 lines (218 loc) · 7.68 KB
/
ExportVulcanSampleLogs.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
"""*WIKI*
== Assumption ==
1. All logs specified by user should be synchronized.
== File format ==
* Column 0:
* Column 1:
* Column 2 to 2 + n:
*WIKI*"""
import mantid.simpleapi as api
from mantid.api import *
from mantid.kernel import *
import os
class ExportVulcanSampleLogs(PythonAlgorithm):
""" Python algorithm to export sample logs to spread sheet file
for VULCAN
"""
def category(self):
""" Category
"""
return "Utilities;PythonAlgorithms"
def name(self):
""" Algorithm name
"""
return "ExportVulcanSampleLogs"
def PyInit(self):
""" Declare properties
"""
# Input workspace
self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),
"Name of data workspace containing sample logs to be exported. ")
# Output file name
self.declareProperty(FileProperty("OutputFilename", "", FileAction.Save, [".txt"]),
"Name of the output sample environment log file name.")
# Sample log names
self.declareProperty(StringArrayProperty("SampleLogNames", values=[], validator=arrvalidator,
direction=Direction.Input), "Names of sample logs to be exported in a same file.")
# Header
self.declareProperty("WriteHeaderFile", False, "Flag to generate a sample log header file.")
self.declareProperty("Header", "", "String in the header file.")
# Time zone
timezones = ["America/New_York"]
self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones))
return
def PyExec(self):
""" Main executor
"""
# Read inputs
self._getProperties()
# Read in logs
logtimesdict, logvaluesdict, loglength = self._readSampleLogs()
# Local time difference
localtimediff = self._calLocalTimeDiff(logtimesdict)
# Write log file
self._writeLogFile(logtimesdict, logvaluedict, loglength, localtimediff)
# Write header file
if self._writeheader is True:
testdatetime = self._wksp.getRun().getProperty("run_start").value
description = "Type your description here"
self._writeHeaderFile(testdatetime, description)
return
def _getProperties(self):
""" Get and process properties
"""
self._wksp = self.getProperty("InputWorkspace").value
self._outputfilename = self.getProperty("OutputFilename").value
filedir = os.path.split(self._outputfilename)[0]
if os.path.exists(filedir) is False:
raise NotImplementedError("Directory %s does not exist. File cannot be written." % (filedir))
self._sampleloglist = self.getProperty("SampleLogNames").value
if len(self._sampleloglist) == 0:
raise NotImplementedError("Sample logs names cannot be empty.")
self._writeheader = self.getProperty("WriteHeaderFile").value
self._headercontent = self.getProperty("Header").value
if self._writeheader is True and len(self._headercontent.strip()) == 0:
self.log().warning("Header is empty. Thus WriteHeaderFile is forced to be False.")
self._writeheader = False
self._timezone = self.getProperty("TimeZon").value
return
def _calLocalTimeDiff(self, logtimesdict):
""" Calcualte the time difference between local time and UTC in seconds
"""
# Find out local time
if loglength > 0:
# Locate time0
for key in logtimesdict.keys():
times = logtimesdict[key]
if times is not None:
time0 = logtimesdict[key][0]
break
# Local time difference
localtimediff = getLocalTimeShiftInSecond(time0)
else:
localtimediff = 0
return localtimediff
def _writeLogFile(self, logtimesdict, logvaluedict, loglength, localtimediff):
""" Write the logs to file
"""
wbuf = ""
# Init time
if loglength > 0:
for log in logtimesdict.keys():
if logtimesdict[log] is not None:
time0 = logtimesdict[log][0]
abstime_init = time0.totalNanoseconds() * 1.E-9 - localtimediff
times = logtimesdict[log]
break
# Loop
for i in xrange(loglength):
abstime = times[i].totalNanoseconds() * 1.E-9 - localtimediff
reltime = abstime - abstime_init
# Write absoute time and relative time
wbuf += "%.6f\t %.6f\t " % (abstime, reltime)
# Write each log value
for samplelog in lognames:
if logvaluedict[samplelog] is not None:
logvalue = logvaluedict[samplelog][i]
else:
logvalue = 0.
wbuf += "%.6f\t " % (logvalue)
wbuf += "\n"
# ENDFOR
try:
ofile = open(self._outputfilename, "w")
ofile.write(wbuf)
ofile.close()
except IOError as err:
print err
raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)
return
def _readSampleLogs(self):
""" Read sample logs
"""
# Get all properties' times and value and check whether all the logs are in workspaces
samplerun = wksp.getRun()
logtimesdict = {}
logvaluedict = {}
for samplename in lognames:
# Check existence
logexist = samplerun.hasProperty(samplename)
if logexist is True:
# Get hold of sample values
p = samplerun.getProperty(samplename)
logtimesdict[samplename] = p.times
logvaluedict[samplename] = p.value
else:
# Add None
self.log().warning("Sample log %s does not exist. " % (samplename))
logtimesdict[samplename] = None
logvaluedict[samplename] = None
# ENDIF
# ENDFOR
# Check properties' size
loglength = sys.maxint
for i in xrange(len(lognames)):
if logtimesdict[lognames[i]] is not None:
tmplength = len(logtimesdict[lognames[i]])
if loglength != tmplength:
if loglength != sys.maxint:
self.log().warning("Log %s has different length from previous ones. " % (lognames[i]))
loglength = min(loglength, tmplength)
# ENDIF
# ENDIF
# ENDFOR
if loglength == sys.maxint:
self.log().warning("None of given log names is found in workspace. ")
loglength = 0
else:
self.log().information("Final Log length = %d" % (loglength))
return (logtimesdict, logvaluedict, loglength)
def _writeHeaderFile(self, testdatetime, description):
""" Write the header file for a LoadFrame
"""
# Construct 3 lines of the header file
line0 = "Test date: %s" % (str(testdatetime))
line1 = "Test description: %s" % (description)
line2 = self._headercontent
# Write file
wbuf = line0 + "\n" + line1 + "\n" + line2 + "\n"
headerfilename = self._outputfilename.split(".")[0] + "_header.txt"
self.log().information("Writing header file %s ... " % (headerfilename))
try:
ofile = open(headerfilename, "w")
ofile.write(wbuf)
ofile.close()
except OSError as err:
self.log().error(str(err))
return
def getLocalTimeShiftInSecond(utctime):
""" Calculate the difference between UTC time and local time of given
DataAndTime
"""
from datetime import datetime
from dateutil import tz
print "Input UTC time = %s" % (str(utctime))
from_zone = tz.gettz('UTC')
to_zone = tz.gettz(LOCAL_TIME_ZONE)
t1str = (str(utctime)).split('.')[0]
utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
sns = utc.astimezone(to_zone)
shift_in_hr = utc.hour - sns.hour
shift_in_sec = shift_in_hr * 3600.
return shift_in_sec
def convertToLocalTime(utctimestr):
""" Convert UTC time in string to local time
"""
from datetime import datetime
from dateutil import tz
print "Input UTC time = %s" % (utctimestr)
from_zone = tz.gettz('UTC')
to_zone = tz.gettz(LOCAL_TIME_ZONE)
t1str = (utctimestr).split('.')[0]
utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
sns = utc.astimezone(to_zone)
return str(sns)
# Register algorithm with Mantid
AlgorithmFactory.subscribe(ExportVulcanSampleLogs)