-
Notifications
You must be signed in to change notification settings - Fork 4
/
SenseFileOrigin.py
303 lines (249 loc) · 12.7 KB
/
SenseFileOrigin.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
import csv
import openpyxl
from Readers.ReadHanna import *
from CustomErrors import *
import pandas as pd
class SenseFileOrigin():
def isQ(self, filePath, sheetNames):
exl = pd.ExcelFile(filePath)
df = pd.read_excel(exl, sheetNames[-1])
if df.shape[0] < 4:
message = "ERROR: the file " + filePath + " did not contain sufficient information to parse (less than 4 rows (less than 4 rows).\n"
raise Warnings(message, filePath)
hannaReader = ReadHanna(filePath)
# try:
if True:
hannaReader.readDataSheetRow(df,3)
time1 = hannaReader.time
second1 = int(time1.split(":")[-1])
minute1 = int(time1.split(":")[-2])
hour1 = int(time1.split(":")[-3])
# except:
# message = "ERROR: Hanna file missing critical headers.\n"
# raise Warnings(message, filePath)
hannaReader.readDataSheetRow(df,4)
time2 = hannaReader.time
second2 = int(time2.split(":")[-1])
minute2 = int(time2.split(":")[-2])
hour2 = int(time2.split(":")[-3])
if hour2 - hour1 != 0:
minute1 = minute1 + (60 * (hour2 - minute1))
if minute2 - minute1 != 0:
second2 = second2 + (60 * (minute2 - minute1))
interval = second2 - second1
if interval != 0 and interval < 10:
return True
else:
return False
def senseFileOrigin(self, filePath):
# try:
# check file handle:
# if filePath.endswith(".xls"):
# df = pd.ExcelFile(filePath)
# sheetNames = df.sheet_names
# if len(sheetNames) == 2:
# return "field_hanna"
if filePath.endswith(".xlsx") or filePath.endswith(".xls") or filePath.endswith(".XLS"):
exl = pd.ExcelFile(filePath)
sheetNames = exl.sheet_names
df = pd.read_excel(exl, sheetNames[0])
columns = list(df.columns.values)
print(columns)
if "#" == str(columns[0]):
return "sites"
if "Sample ID" in str(columns[0]):
if "Site" in str(columns[1]):
return "water"
if "Sortchem" in str(columns[0]):
return "srp"
if "sortchem" in str(columns[0]):
if "Site" in str(columns[1]):
if ("sample" in str(columns[4])) and ("volume" in str(columns[4])):
return "tss"
if "Operator" in str(columns[0]):
return "aqualog"
if "Sample Identifier" in str(columns[0]):
return "docIsotopes"
if "Chem #" in str(columns[0]):
return "masterScan"
if len(columns) > 3:
if "OVSM" in str(columns[3]):
return "no3"
if "Horizontal Table Report" in str(columns[0]):
return "icp_new"
i = 0
while i < 15 and i < len(list(df.iloc[:,0])): # read through the first row
value = str(df.iloc[i,1]).lower()
if "no" in value:
return "lachat"
if "selected" in value and "peak" in value:
return "ic"
if "lab" in value and "#" in value and "Water" in sheetNames and not 'date' in str(df.iloc[i,0]).lower():
# If any instance of 'icp' exists in the line above "Lab #," return 'icp'. Else, return 'srp_new'
preheader = df.iloc[i-1].values.tolist()
# this checks for hidden/non hidden columns
workbook = openpyxl.load_workbook(filename=filePath)
lookhere = workbook.active.column_dimensions.items()
hidden_cols = []
unhidden_cols = []
# the following code converts Excel column names ('A', 'B', ... 'AB', 'AC', ...) to indices that are used to access the preheaders of df
for column, col_dimension in workbook.active.column_dimensions.items():
if col_dimension.hidden:
letter_list = [ord(x) - 97 for x in column.lower()]
number = (26 * (len(letter_list) - 1)) + letter_list[-1]
try:
hidden_cols.append(df.iloc[i - 1, number])
except:
print(traceback.format_exc())
hidden_cols.append(None)
else:
letter_list = [ord(x) - 97 for x in column.lower()]
number = (26 * (len(letter_list) - 1)) + letter_list[-1]
try:
unhidden_cols.append(df.iloc[i - 1, number])
except:
print(traceback.format_exc())
unhidden_cols.append(None)
if any(['icp' in str(x).lower() for x in unhidden_cols]):
return 'icp'
else:
return "srp_new"
elif "lab" in value and "#" in value and "Water" in sheetNames and 'date' in str(df.iloc[i,0]).lower():
return "icp"
i = i + 1
i = 0
while i < 10 and i < len(list(df.iloc[:,0])): # read through the first row
value = str(df.iloc[i,0]).lower()
if "instrument name" in value:
if len(sheetNames) == 2:
if self.isQ(filePath, sheetNames):
return "q"
else:
return "field_hanna"
if "name" in value:
return "icp"
if "number" in value:
return "ic"
if "inj" in value:
return "ic"
if "project" in value: # if it is a sampleID file that wasn't converted to a .csv
return "excel_sampleID"
i = i + 1
return "ic" # (by default)
elif filePath.endswith(".csv"):
if filePath.endswith("fp.csv"):
return "scan.fp"
if filePath.endswith("log.csv"):
return "ignore"
# open the file and look at the firs
if "ysi" in filePath or "YSI" in filePath:
return "YSI"
with open(filePath) as csvFile:
reader = csv.reader(csvFile, delimiter=",")
try:
firstRow = next(reader)
secondRow = next(reader)
thirdRow = next(reader)
if len(secondRow) == 0:
secondRow = thirdRow
if 'analog0' in secondRow and 'analog1' in secondRow and 'analog2' in secondRow and 'analog3' in secondRow:
return 'smartrock'
if "Inj" in firstRow[0] and "Inj" in firstRow[1] and "Type" in firstRow[2]:
return "ic_new"
if firstRow[0].endswith(".LOG"):
return "field_eureka"
elif "Operator" in firstRow[0]:
return "aqualog"
elif "project" in secondRow[0].lower():
if "device" in secondRow[1].lower():
if "date" in secondRow[2].lower():
return "sampleID"
elif "Eureka" in secondRow[0]:
return "field_eureka"
elif "Plot Title" in firstRow[0] or "Serial Num" in firstRow[0]:
# parse which type of hobo
sRow = ",".join(secondRow)
sRow = sRow.lower()
if "intensity" in sRow:
return "light_hobo"
elif "cm" in sRow and ("range" in sRow or 'conductivity' in sRow):
return "conductivity_hobo"
elif "do" in sRow and "mg" in sRow and "conc" in sRow:
return "dissolved_oxygen_hobo"
else:
return "field_hobo.csv"
elif "stamp" in firstRow[0]:
if filePath.endswith("_log.csv"):
return "unrecognized"
else:
return "scan.par"
elif "sep" in firstRow[0]:
return "elementar"
elif "Eureka" in thirdRow[0]:
return "field_eureka"
elif "Chem #" in str(firstRow[0]):
return 'masterScan'
else:
return "unrecognized"
except:
try:
df = pd.read_csv(filePath, header=None)
firstRow = df.iloc[0].tolist()
secondRow = df.iloc[1].tolist()
thirdRow = df.iloc[2].tolist()
if len(secondRow) == 0:
secondRow = thirdRow
if "Inj" in firstRow[0] and "Inj" in firstRow[1] and "Type" in firstRow[2]:
return "ic_new"
if firstRow[0].endswith(".LOG"):
return "field_eureka"
elif "Operator" in firstRow[0]:
return "aqualog"
elif "project" in secondRow[0].lower():
if "device" in secondRow[1].lower():
if "date" in secondRow[2].lower():
return "sampleID"
elif "Eureka" in secondRow[0]:
return "field_eureka"
elif "Plot Title" in firstRow[0] or "Serial Num" in firstRow[0]:
# parse which type of hobo
sRow = ",".join(secondRow)
sRow = sRow.lower()
if "intensity" in sRow:
return "light_hobo"
elif "cm" in sRow and ("range" in sRow or 'conductivity' in sRow):
return "conductivity_hobo"
elif "do" in sRow and "mg" in sRow and "conc" in sRow:
return "dissolved_oxygen_hobo"
else:
return "field_hobo.csv"
elif "stamp" in firstRow[0]:
if filePath.endswith("_log.csv"):
return "unrecognized"
else:
return "scan.par"
elif "sep" in firstRow[0]:
return "elementar"
elif "Eureka" in thirdRow[0]:
return "field_eureka"
elif "Chem #" in str(firstRow[0]):
return 'masterScan'
else:
return "unrecognized"
except:
# the file was empty (raised an error trying to access it)
print(traceback.format_exc())
return "no_data"
elif filePath.endswith('.hobo'):
return "field_hobo.hobo"
elif filePath.endswith(".sql"):
return "unrecognized"
elif filePath.endswith('.fp'):
return "scan.fp"
elif filePath.endswith(".par"):
return "scan.par"
else:
return "unrecognized"
# except:
# except:
# return "causedException"