-
Notifications
You must be signed in to change notification settings - Fork 11
/
AQUARIUSDataExtractionToolManager.py
1643 lines (1337 loc) · 67.2 KB
/
AQUARIUSDataExtractionToolManager.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
# All works in this code have been curated by ECCC and licensed under the GNU General Public License v3.0.
# Read more: https://www.gnu.org/licenses/gpl-3.0.en.html
from AQUARIUSDataExtractionToolFrame import *
import subprocess
import os
import io
import sys
from suds.client import Client
from base64 import b64encode
from base64 import b64decode
import datetime
import io
import csv
import requests
import re
import json
import heapq
from suds.xsd.doctor import Import, ImportDoctor
from operator import itemgetter
# Aquarius Python Wrapper created by Doug Schmidt
from timeseries_client import timeseries_client
from requests.exceptions import HTTPError
from xml.etree import ElementTree
try:
to_unicode = str
except NameError:
to_unicode = str
class AQUARIUSDataExtractionToolManager(object):
def __init__(self, mode, scriptLoc, gui, EHSNGui):
self.gui = gui
self.config_path = None
if self.gui is not None:
self.gui.manager = self
if self.gui.GetParent() is not None:
self.config_path = self.gui.GetParent().config_path
self.timeZones = {'-8' : 'PST',
'-7' : 'MST',
'-6' : 'CST',
'-5' : 'EST',
'-4' : 'AST',
'-3.5' : 'NST',
'-0' : 'UTC'}
self.scriptLoc = scriptLoc
self.EHSNGui = EHSNGui
self.mode = mode
# if hasattr(sys, '_MEIPASS'):
# self.config_path = os.path.join(sys._MEIPASS, self.config_path)
# else:
# self.config_path = os.getcwd() + "\\" + self.config_path
# print self.config_path
if self.config_path is not None:
self.configFile = ElementTree.parse(self.config_path).getroot().find('AQUARIUSDataExtractionToolManager')
self.rctUser = self.configFile.find('rctUser').text
self.rctPassword = self.configFile.find('rctPassword').text
def RunScript(self, path):
# counter = 0
# while True:
# Check authentication
Login = self.gui.GetUsername()
Password = self.gui.GetPassword()
Server = self.gui.GetURL()
if Login == "":
self.gui.CreateErrorDialog("Username field cannot be left blank. Please use your AQUARIUS username.")
return
elif Password == "":
self.gui.CreateErrorDialog("Password field cannot be left blank. Please use your AQUARIUS password.")
return
elif self.gui.StationListIsEmpty():
self.gui.CreateErrorDialog("Station ID list field cannot be left blank. Please enter the station ID that you are uploading.")
return
try:
aq = Client(Server + '/aquarius/AQAcquisitionService.svc?wsdl')
aq.set_options(headers={'AQAuthToken':aq.service.GetAuthToken(Login, Password)})
authcode = aq.service.GetAuthToken(Login, Password)
except:
self.gui.CreateErrorDialog("User Login Failed, please use your AQUARIUS username and password.")
return -1
# # Check if stations exist
# locations = self.GetStationList()
# for station in locations:
# # Check if real station
# locid = aq.service.GetLocationId(station)
# print locid
# # is not a real station
# if locid == 0:
# self.gui.CreateErrorDialog("Station ID: " + station + " appears to be invalid")
# return -2
# if the export file path does not exist, create a new folder
if not os.path.exists(path):
os.makedirs(path)
# Lists of stations that go wrong per method
failedStnInfo = []
failedLvlInfo = []
failedRatingInfo = []
failedHistMmts = []
# Check checkboxes for which items to retrieve
# if StationInfo checked
if self.gui.StnIsChecked():
self.gui.CreateProgressDialog('Extraction In Progress...', 'Collecting data for Station Information (stations.txt)')
res = self.GetStationInfo(aq, path, failedStnInfo)
self.CheckReturn(res)
if res == -1 or res == -2:
pass
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Unable to write to file. Please make sure the file stations.txt is closed")
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Something went wrong while collecting Levelling Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n "+\
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n"+\
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n"+\
"If you're still having problems after this hint, please file a bug report.")
# if LevelsInfo checked
if self.gui.LvlIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting data for Levels Information (levels.txt)')
else:
self.gui.CreateProgressDialog('Extraction In Progress', 'Collecting data for Levels Information (levels.txt)')
res = self.GetLevelsInfo(aq, path, failedLvlInfo)
self.CheckReturn(res)
if res == -1 or res == -2:
pass
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Something went wrong while collecting Levelling Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n "+\
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n"+\
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n"+\
"If you're still having problems after this hint, please file a bug report.")
# if GetRatingInfo checked
if self.gui.RCIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting Rating Curve Information (StationID_ratingcurves.xml)')
else:
self.gui.CreateProgressDialog('Extraction In Progress...', 'Collecting Rating Curve Information (StationID_ratingcurves.xml)')
res = self.GetRatingInfo(path, failedRatingInfo)
self.CheckReturn(res)
if res == -1 or res == -2:
pass
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Something went wrong while collecting Rating Curve Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n "+\
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n"+\
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n"+\
"If you're still having problems after this hint, please file a bug report.")
# if GetHistField checked
if self.gui.DataPeriodIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting Historical Field Mmts (StationID_FieldVisits.csv)')
else:
self.gui.CreateProgressDialog('Extraction In Progress...', 'Collecting Historical Field Mmts (StationID_FieldVisits.csv)')
if self.gui.IncludeMinMaxIsChecked():
numMinMax = self.gui.GetNumOfMinMax()
else:
numMinMax = None
res = self.GetFieldVisit(path, failedHistMmts, numMinMax)
self.CheckReturn(res)
if res == -1 or res == -2:
pass
elif res != 0:
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Getting Field Visit from AQUARIUS Failed")
if self.gui.ProgressDialogIsOpen():
self.gui.DeleteProgressDialog()
# counter += 1
# print "*****************************" + str(counter) + "********************************"
report = self.ReportOnFailedStations(failedStnInfo, failedLvlInfo, failedRatingInfo, failedHistMmts, path)
def RunScriptNg(self, path):
# counter = 0
# while True:
# Check authentication
#print "here"
Login = self.gui.GetUsername()
Password = self.gui.GetPassword()
if Login == "":
self.gui.CreateErrorDialog("Username field cannot be left blank. Please use your AQUARIUS username.")
return
elif Password == "":
self.gui.CreateErrorDialog("Password field cannot be left blank. Please use your AQUARIUS password.")
return
elif self.gui.StationListIsEmpty():
self.gui.CreateErrorDialog(
"Station ID list field cannot be left blank. Please enter the station ID that you are uploading.")
return
# Login
try:
# Using Aquarius Python Wrapper created by Doug Schmidt
aq = timeseries_client('https://wsc.aquaticinformatics.net', Login, Password)
except HTTPError as e:
if e.response.status_code == 401:
result = "The username or the password is incorrect."
error = wx.MessageDialog(None, result, 'Error', wx.OK | wx.ICON_ERROR)
error.ShowModal()
return "The username or the password is incorrect."
else:
self.gui.deleteProgressDialog()
return "Failed to login."
print("login")
if not os.path.exists(path):
os.makedirs(path)
# Remove previous error report if it exists
if os.path.exists(os.path.join(path, 'ExtractionErrorReport.txt')):
os.remove(os.path.join(path, 'ExtractionErrorReport.txt'))
# Remove all previously created rating curve json files and field visit csv files
extracted_data_files = os.listdir(path)
for file in extracted_data_files:
if file.endswith(".json") or file.endswith(".csv"):
os.remove(os.path.join(path, file))
# Lists of stations that go wrong per method
failedStnInfo = []
failedLvlInfo = []
failedRatingInfo = []
failedHistMmts = []
# Check checkboxes for which items to retrieve
# if StationInfo checked
if self.gui.StnIsChecked():
self.gui.CreateProgressDialog('Extraction In Progress...',
'Collecting data for Station Information (stations.txt)')
res = self.GetStationInfoNg(aq, path, failedStnInfo)
if res == -1 or res == -2:
pass
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Unable to write to file. Please make sure the file stations.txt is closed")
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog(
"Something went wrong while collecting Levelling Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n " + \
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n" + \
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n" + \
"If you're still having problems after this hint, please file a bug report.")
# if LevelsInfo checked
if self.gui.LvlIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting data for Levels Information (levels.txt)')
else:
self.gui.CreateProgressDialog('Extraction In Progress',
'Collecting data for Levels Information (levels.txt)')
res = self.GetLevelsInfoNg(aq, path, failedLvlInfo)
if res == -1 or res == -2:
pass
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog(
"Something went wrong while collecting Levelling Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n " + \
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n" + \
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n" + \
"If you're still having problems after this hint, please file a bug report.")
# if GetRatingInfo checked
if self.gui.RCIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting Rating Curve Information (StationID_ratingcurves.xml)')
else:
self.gui.CreateProgressDialog('Extraction In Progress...',
'Collecting Rating Curve Information (StationID_ratingcurves.xml)')
res = self.GetRatingInfoNg(aq, path, failedRatingInfo)
if res == -1 or res == -2:
pass
elif res != 0:
# unplanned response
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog(
"Something went wrong while collecting Rating Curve Information A few trouble shooting tips: \n" + \
"\t1. Try reducing the list of stations you're extracting data for and try again.\n " + \
"\t2. ometimes naming conventions within AQUARIUS are incorrect. Ensure that your naming conventions are correct.\n" + \
"\t3. Sometimes I try and extract data that doesn't exist (e.g., a rating curve for a stage only station). This can mess me up. Make sure what you're asking me to extract exisits.\n" + \
"If you're still having problems after this hint, please file a bug report.")
# if GetHistField checked
if self.gui.DataPeriodIsChecked():
if self.gui.ProgressDialogIsOpen():
self.gui.UpdateProgressDialog('Collecting Historical Field Mmts (StationID_FieldVisits.csv)')
else:
self.gui.CreateProgressDialog('Extraction In Progress...',
'Collecting Historical Field Mmts (StationID_FieldVisits.csv)')
if self.gui.IncludeMinMaxIsChecked():
numMinMax = self.gui.GetNumOfMinMax()
else:
numMinMax = None
res = self.GetFieldVisitNg(aq, path, failedHistMmts, numMinMax)
if res == -1 or res == -2:
pass
elif res != 0:
self.gui.DeleteProgressDialog()
self.gui.CreateErrorDialog("Getting Field Visit from AQUARIUS Failed")
if self.gui.ProgressDialogIsOpen():
self.gui.DeleteProgressDialog()
# counter += 1
# print "*****************************" + str(counter) + "********************************"
report = self.ReportOnFailedStations(failedStnInfo, failedLvlInfo, failedRatingInfo, failedHistMmts, path)
def GetStationInfo(self, aq, path, failedStations):
# SOAP Acquisition API
# Check Auth
print("Get Station Info")
Login = self.gui.GetUsername()
Password = self.gui.GetPassword()
Server = self.gui.GetURL()
authcode = None
stationsList = []
# login
try:
aq2 = Client(Server+'/AQUARIUS/Publish/AquariusPublishService.svc?wsdl')
authcode = aq2.service.GetAuthToken(Login, Password)
except:
return -1
# print authcode
# Rest Authentication
ServerCall = Server + r"/aquarius/Publish/AquariusPublishRestService.svc/"
command = ServerCall + r"GetAuthToken?user="
command += Login + r"&encPwd=" + Password
r = requests.get(command)
MyAuthCode = r.text
# print MyAuthCode
# For each station in the stationlist
locations = self.GetStationList()
for station in locations:
# Check if real station
locid = aq.service.GetLocationId(station)
# print locid
if locid == 0:
failedStations.append(station)
continue
# new line in the csv
newStationLine = []
# GetLocations for station name
# stationID
newStationLine.append(station)
command = ServerCall + "GetLocations?token=" + MyAuthCode + "&filter=Identifier=" + station
# print "Sending command: " + command
r = requests.get(command)
f = io.StringIO(str(r.text).encode("utf8"))
reader = csv.reader(f, delimiter=',')
next(reader)
locationName = None
line = next(reader)
# print line
locationName = line[3]
status = line[16]
if status.lower() != "active":
failedStations.append(station)
continue
# station name
newStationLine.append(locationName)
# Check row count
row_count = sum(1 for row in reader)
# print row_count
# reset position in file
f.seek(0)
reader = csv.reader(f, delimiter=',')
offsetVal = None
if row_count > 1:
next(reader)
line = next(reader)
# # if station does not have any Data Sets (like meteorology stations)
# if not line:
# failedStations.append(station)
# continue
# # print line
# offset = str(line[7]).split('.')
# # print offset
# offset = offset[-1][-6:]
# offset = offset.split(':')[-2]
# # print "offset: ", offset
# # print self.timeZones[offset]
# offsetVal = self.timeZones[offset]
# offset for station
newStationLine.append(self.timeZones[line[12]])
stationsList.append(newStationLine)
# Maybe check if the file can be written to
fileExists = None
exportFile = None
while True:
try:
if os.path.isfile(path + '\\stations.txt'):
fileExists = True
exportFile = open(path + '\\stations.txt', 'a+')
else:
exportFile = open(path + '\\stations.txt', "w")
break
except IOError:
print("Could not open file! Please close Excel!")
self.gui.DeleteProgressDialog()
res = self.gui.CreateTryAgainDialog("Unable to write to file. Please close the file: stations.txt.\nTry again?")
if res == 0:
self.gui.CreateProgressDialog('In Progress', 'Collecting data for Station Information (stations.txt)')
else:
failedStations = locations
return
if exportFile is not None:
if not fileExists:
exportFile.write("STATION ID,STATION NAME,TIMEZONE")
else:
# if file exists, read the file
# reader = csv.reader(exportFile, delimiter='\n')
readList = []
with open(path + '\\stations.txt', 'a+') as f:
reader = csv.reader(f, delimiter=",")
for i, line in enumerate(reader):
if i > 0:
readList.append(line[0])
# print "-----------------"
# for j in readList:
# print j
# print "-----------------"
removeIndices = []
for i, line in enumerate(stationsList):
if len(line) > 2:
for row in readList:
if line[0] == row:
print(line[0] + " is in file")
removeIndices.append(i)
break
# exportFile.seek(0)
# reader = csv.reader(exportFile, delimiter=',')
removeIndices.reverse()
for i in removeIndices:
stationsList.remove(stationsList[i])
writeList = []
for line in stationsList:
if len(line) > 2:
stationid = line[0]
stationName = line[1]
timezone = line[2]
outputLine = stationid + "," + str(stationName) + "," + timezone
writeList.append(outputLine)
exportFile.close()
exportFile = open(path + '\\stations.txt', 'a+')
for line in writeList:
exportFile.write("\n")
exportFile.write(line)
exportFile.close()
return 0
def GetStationInfoNg(self, aq, path, failedStations):
print("Get Station Info")
authcode = None
stationsList = []
# For each station in the stationlist
locations = self.GetStationList()
# print locations
writeList = []
for station in locations:
# Check if real station
try:
parameters = {'LocationIdentifier': station}
locid = aq.publish.get('/GetLocationData', params=parameters)
# print locid
if 'ResponseStatus' in locid:
print(locid['ResponseStatus']['Message'])
failedStations.append(station)
continue
except:
failedStations.append(station)
continue
# new line in the csv
newStationLine = []
# GetLocations for station name
# stationID
newStationLine.append(station)
# command = ServerCall + "GetLocations?token=" + MyAuthCode + "&filter=Identifier=" + station
# # print "Sending command: " + command
# r = requests.get(command)
# f = StringIO.StringIO(unicode(r.text).encode("utf8"))
stId = station
stName = locid['LocationName']
stUtc = self.timeZones[str(locid['UtcOffset'])]
stIf = [stId, stName, stUtc]
writeList.append(stIf)
# print writeList
# Maybe check if the file can be written to
fileExists = None
exportFile = None
while True:
try:
exportFile = open(path + '\\stations.txt', "w")
break
except IOError:
print("Could not open file! Please close Excel!")
self.gui.DeleteProgressDialog()
res = self.gui.CreateTryAgainDialog(
"Unable to write to file. Please close the file: stations.txt.\nTry again?")
if res == 0:
self.gui.CreateProgressDialog('In Progress',
'Collecting data for Station Information (stations.txt)')
else:
failedStations = locations
return
if exportFile is not None:
exportFile.write("STATION ID,STATION NAME,TIMEZONE")
for line in writeList:
exportFile.write("\n")
lineData = line[0] + ',' + line[1] + ',' + line[2]
exportFile.write(lineData)
exportFile.close()
return 0
# Taken from http://stackoverflow.com/questions/904041/reading-a-utf8-csv-file-with-python
def unicode_csv_reader(self, utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, skipinitialspace=True, **kwargs)
for row in csv_reader:
row_data = []
for cell in row:
if isinstance(cell, str):
cell = cell.decode('utf8')
row_data.append(str(cell))
yield row_data
# yield cell_data
def GetLevelsInfo(self, aq, path, failedStations):
print("Level Info Checked")
Login = self.gui.GetUsername()
Password = self.gui.GetPassword()
Server = self.gui.GetURL()
totalBenchmarkList = []
extractedBenchmarkList = []
inactiveBMList = []
# login
imp1 = Import('http://www.w3.org/2001/XMLSchema')
doctor = ImportDoctor(imp1)
try:
# aq2 = Client(Server + '/AQUARIUS/AquariusDataService.svc?wsdl')
aq2 = Client(Server + '/AQUARIUS/AquariusDataService.svc?wsdl', doctor=doctor)
except:
print("Client(Server + '/AQUARIUS/AquariusDataService.svc?wsdl', doctor=doctor)")
return
# for each station
locations = self.GetStationList()
for station in locations:
benchmarkList = []
# Check if real station
locid = aq.service.GetLocationId(station)
# print locid
# is not a real station
if locid == 0:
failedStations.append(station)
continue
# GetLocationBenchmarks
benchmarks = aq2.service.GetLocationBenchmarks(locid)
try:
# list of benchmarks
benchmarks = benchmarks[0]
except IndexError:
# has no benchmarks not active?
failedStations.append(station)
continue
for bm in benchmarks:
line = []
addedBM = False
bmName = str(bm.Name)
desc = bm.LongName
if isinstance(desc, str):
desc = desc.decode('utf8')
desc = str(desc)
latestBM = None
if bm.History is not None:
history = bm.History[0]
for i, hist in enumerate(history):
if i == 0:
latestBM = hist
else:
if hist.StartDate > latestBM.StartDate:
latestBM = hist
if latestBM is not None:
if "inactive" not in latestBM.Status.lower():
# add it to the master list of benchmarks
# Add info to line
# print str(bmName), "***"
if "primary" in latestBM.Status.lower():
bmName = "**" + str(bmName)
line.append(station)
line.append(bmName)
line.append(latestBM.AcceptedElevation)
line.append(desc)
benchmarkList.append(line)
addedBM = True
if not addedBM:
line.append(station)
line.append(bmName)
line.append("")
line.append("")
inactiveBMList.append(line)
# sort the list by benchmark names
benchmarkList = sorted(benchmarkList, key=lambda bm: bm[1])
extractedBenchmarkList.extend(benchmarkList)
# print benchmarkList
# print "============"
# Maybe check if file can be written to
fileExists = None
exportFile = None
while True:
try:
if os.path.isfile(path + '\\levels.txt'):
fileExists = True
exportFile = open(path + '\\levels.txt', 'rU')
else:
exportFile = open(path + '\\levels.txt', "wb")
break
except IOError:
print("Could not open file! Please close Excel!")
self.gui.DeleteProgressDialog()
res = self.gui.CreateTryAgainDialog("Unable to write to file. Please close the file: levels.txt.\nTry again?")
if res == 0:
self.gui.CreateProgressDialog('Extraction In Progress...', 'Collecting data for Levels Information (levels.txt)')
else:
failedStations = locations
return
if exportFile is not None:
if fileExists:
# if file exists, read the file
# import file (if exists) by parsing as csv
# reader = csv.reader(exportFile, delimiter=',')
reader = self.unicode_csv_reader(exportFile)
fileBMList = []
for row in reader:
fileBMList.append(row)
fileBMList = fileBMList[1:]
removeIndices = []
# update lists
for bm in fileBMList:
for ebm in extractedBenchmarkList:
if bm[0] == ebm[0] and bm[1] == ebm[1]:
bm[2] = ebm[2]
bm[3] = ebm[3]
break
# combine lists
for ebm in extractedBenchmarkList:
bmFound = False
for bm in fileBMList:
if bm[0] == ebm[0] and bm[1] == ebm[1]:
bmFound = True
break
if not bmFound:
fileBMList.append(ebm)
# remove inactive bms
for rbm in inactiveBMList:
for i, bm in enumerate(fileBMList):
if bm[0] == rbm[0] and bm[1] == rbm[1]:
removeIndices.append(i)
removeIndices.sort()
removeIndices.reverse()
for i in removeIndices:
fileBMList.remove(fileBMList[i])
exportFile.close()
exportFile = open(path + '\\levels.txt', "wb")
totalBenchmarkList = sorted(fileBMList, key=itemgetter(0, 1))
else:
totalBenchmarkList = extractedBenchmarkList
writeList = []
for bm in totalBenchmarkList:
stationid = bm[0]
reference = bm[1]
elevation = bm[2]
desc = bm[3]
desc = desc.replace("\"", "\"\"")
outputLine = str(stationid) + "," + str(reference) + "," + str(elevation) + ",\"" + str(desc) + "\""
writeList.append(outputLine)
# print stationid + ", " + reference + ", " + elevation + ", " + desc
# Write to file
exportFile.write("STATION,REFERENCE,ELEVATION,DESCRIPTION\n")
for line in writeList:
# print line.encode("utf8")
line += '\n'
exportFile.write(line)
exportFile.close()
return 0
def GetLevelsInfoNg(self, aq, path, failedStations):
print("Level Info Checked")
totalBenchmarkList = []
extractedBenchmarkList = []
inactiveBMList = []
# for each station
locations = self.GetStationList()
for station in locations:
try:
parameters = {'LocationIdentifier': station}
req = aq.publish.get('/GetLocationData', params=parameters)
staInfo = req['ReferencePoints']
except:
failedStations.append(station)
continue
# print staInfo
for benchMark in staInfo:
benchMarkInfo = []
decommissioned = False
try:
decom = benchMark['DecommissionedDate']
decommissioned = True
except:
decommissioned = False
if not decommissioned:
try:
staRef = benchMark['Name']
staRef.replace('\n', ' ')
except:
staRef = ''
print("The reference is empty.")
try:
pmyRef = benchMark['PrimarySinceDate']
staRef = "**" + staRef
except:
pmyRef = ''
try:
refPoint = benchMark['ReferencePointPeriods']
# Get the most recent reference point elevation
staElevation = refPoint[len(refPoint) - 1]['Elevation']
# If the elevation has a precision of more than 5 decimal places
# then it should be rounded to 3 decimal places
if "." in str(staElevation):
if len(str(staElevation).split(".")[1]) > 5:
staElevation = round(staElevation, 3)
except:
refPoint = ''
print("The elevation is empty.")
try:
staDescription = benchMark['Description']
staDescription.replace('\n', ' ')
except:
staDescription = ''
print("The description is empty.")
benchMarkInfo.append(station)
benchMarkInfo.append(str(staRef))
benchMarkInfo.append(str(staElevation))
benchMarkInfo.append(str(staDescription))
totalBenchmarkList.append(benchMarkInfo)
# print totalBenchmarkList
# Maybe check if file can be written to
fileExists = None
exportFile = None
extractedBenchmarkList = totalBenchmarkList
while True:
try:
if os.path.isfile(path + '\\levels.txt'):
fileExists = True
exportFile = open(path + '\\levels.txt', 'rU')
else:
exportFile = open(path + '\\levels.txt', "wb")
break
except IOError:
print("Could not open file! Please close Excel!")
self.gui.DeleteProgressDialog()
res = self.gui.CreateTryAgainDialog(
"Unable to write to file. Please close the file: levels.txt.\nTry again?")
if res == 0:
self.gui.CreateProgressDialog('Extraction In Progress...',
'Collecting data for Levels Information (levels.txt)')
else:
failedStations = locations
return
if exportFile is not None:
'''
if fileExists:
# if file exists, read the file
# import file (if exists) by parsing as csv
# reader = csv.reader(exportFile, delimiter=',')
reader = self.unicode_csv_reader(exportFile)
# print reader
fileBMList = []
for row in reader:
fileBMList.append(row)
# print fileBMList
fileBMList = fileBMList[1:]
removeIndices = []
# update lists
for bm in fileBMList:
for ebm in extractedBenchmarkList:
if bm[0] == ebm[0] and bm[1] == ebm[1]:
bm[2] = ebm[2]
bm[3] = ebm[3]
break
# combine lists
for ebm in extractedBenchmarkList:
bmFound = False
for bm in fileBMList:
if bm[0] == ebm[0] and bm[1] == ebm[1]:
bmFound = True
break
if not bmFound:
fileBMList.append(ebm)
# totalBenchmarkList = sorted(fileBMList, key=itemgetter(0, 1))
'''
# Write to file
exportFile = open(path + '\\levels.txt', "w+")
exportFile.write("STATION,REFERENCE,ELEVATION,DESCRIPTION")
for line in totalBenchmarkList:
# print line
exportFile.write("\n")
lineData = line[0] + ',' + line[1] + ',' + line[2] + ',' + line[3]
# print lineData
exportFile.write(lineData)
exportFile.close()
return 0
def GetRatingInfo(self, path, failedStations):
if self.mode == "DEBUG":
print("Manager Run Script")
FNULL = open(os.devnull, 'w') #use this if you want to suppress output to stdout from the subprocess
stationList = self.GetStationList()
url = self.gui.GetURL()
path = self.gui.GetPath()
base_arg = "\"" + self.scriptLoc + "\""
base_arg += " /username:" + self.rctUser + " /password:" + self.rctPassword + " /path:\"" + path + "\""
# print base_arg
# # if folder does not exist, make folder (folder should always exist since they're selecting it!
# if not os.path.exists(path):
# os.makedirs(path)
for station in stationList: