-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgaia.py
1115 lines (922 loc) · 44.2 KB
/
gaia.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
#! /usr/bin/env python
# $Id: gaia.py,v 1.6 2014/05/19 11:35:08 stbrown Exp $ #
# Copyright 2009, Pittsburgh Supercomputing Center (PSC).
# See the file 'COPYRIGHT.txt' for any restrictions.
import string,sys,os
import httplib
import math
class GAIA:
def __init__(self,plot_info_,conf_info_=None):
assert(isinstance(plot_info_,PlotInfo))
if conf_info_ is not None:
assert(isinstance(conf_info_,ConfInfo))
self.plotInfo = plot_info_
if conf_info_ is None:
self.confInfo = ConfInfo()
else:
self.confInfo = conf_info_
def call(self):
with open("log.txt","a") as f:
try:
xmlMessage = self.plotInfo.printXMLMessage()
print "Done Parsing XML Message"
except Exception as e:
f.write("XMLFAIL: %s\n"%str(e))
try:
httpConn = httplib.HTTPConnection(self.confInfo.serverURL,self.confInfo.serverPort,True)
if self.confInfo.debug:
httpConn.set_debuglevel(2)
httpConn.connect()
except Exception as e:
f.write("HTTPCONN FAILED: %s\n"%str(e))
#xmlMessage = self.plotInfo.printXMLMessage()
#with open("out.xml","wb") as f:
# f.write(xmlMessage)
try:
headers = { Constants.MIME_CONTENT_TYPE: Constants.MIME_TEXT_XML,
Constants.MIME_CONTENT_LENGTH: '%d; %s="%s"'%(len(xmlMessage),Constants.MIME_CHARSET,Constants.MIME_ISO_8859_1)}
httpConn.request("GET",self.confInfo.serverURL,"%s"%xmlMessage,headers)
print "Parsed Headers"
except Exception as e:
f.write("HEADERS FAILED: %s\n"%str(e))
try:
response = httpConn.getresponse()
except Exception as e:
f.write("RESPONSE FAILED: %s\n"%str(e))
### determine the file we are returning
try:
print "Getting the Response"
responseFileType = response.getheader(Constants.MIME_CONTENT_TYPE)
responseLength = response.getheader(Constants.MIME_CONTENT_LENGTH)
if responseLength == 0:
raise RuntimeError("GAIA Server returned an empty visuzalization")
except Exception as e:
f.write("RESPONSE 2 FAILED: %s\n"%str(s))
try:
responseFileExt = ""
if responseFileType in Constants.fileExtensions.keys():
responseFileExt = Constants.fileExtensions[responseFileType]
else:
print 'WARNING: Unrecognized File Type returned from GAIA Server\n'\
'File Statistics:\n'\
'\tFile Type:%s\n'\
'\tFile Size:%s\n'\
'\tSaving to:%s'\
%(responseFileType,str(responseLength),self.plotInfo.output_filename+".gaia")
responseFileExt = ".gaia"
print "Getting File"
except Exception as e:
f.write("RESPONSE 3 FAILED: %s\n"%str(e))
try:
responseOutFile = self.plotInfo.output_filename + responseFileExt
with open(responseOutFile,"wb") as f:
f.write("%s"%response.read())
if httpConn.sock:
httpConn.sock.shutdown()
httpConn.close()
print "Close that Bitch"
except Exception as e:
f.write("CLOSING FAILED: %s\n"%str(e))
class Constants:
maximum_ABGR_value = int(255)
minimum_ABGR_value = int(0)
kNormalizedGeometry = float(1000.0)
supportedOutputFormats = ['gif','png']
supportedBundleFormats = ['tar','ogg','mpg','mov','mp4']
supportedWrapperTypes = {'fips':5,'hasc':5,'usfips':5,'lonlat':6,'lonlat-label':7,'lonlat-path':-1,
'lonlat-poly':-1}
GAIA_DEFAULT_STYLE = 0
GAIA_DEFAULT_TIME_SEQ = -1
WRAPPER_TYPE_VARIABLE = -1
WRAPPER_RAW_ELEMENT_DELIMITER = ':'
WRAPPER_VALUE_STYLE_DELIMITER = ':'
GAIA_CLIENT_VERSION_NUMBER='0.1'
WRAPPER_BUFFER_SIZE = 8192
GAIA_INPUT_COMMENT_FLAG = "#"
MIME_CONTENT_LENGTH = "Content-Length"
MIME_CONTENT_ENCODING = "Content-Encoding"
MIME_CONTENT_TYPE = "Content-Type"
MIME_TEXT_XML = "text/xml"
MIME_TEXT_PLAIN = "text/plain"
MIME_IMAGE_GIF = "image/gif"
MIME_IMAGE_PNG = "image/png"
MIME_VIDEO_MPG = "video/mpeg"
MIME_VIDEO_MOV = "video/quicktime"
MIME_VIDEO_MP4 = "video/mp4"
MIME_VIDEO_OGG = "video/ogg"
MIME_APP_TAR = "application/x-tar"
MIME_APP_GZIP = "application/x-gzip"
MIME_APP_OCT_STREAM = "application/octet-stream"
MIME_BINARY = MIME_APP_OCT_STREAM
MIME_CHARSET = "charset"
MIME_ISO_8859_1 = "ISO-8859-1"
MIME_CONTENT_TYPE_TEXT ="text/"
fileExtensions = {MIME_IMAGE_GIF:'.gif',
MIME_IMAGE_PNG:'.png',
MIME_VIDEO_MPG:'.mpg',
MIME_VIDEO_MOV:'.mov',
MIME_VIDEO_MP4:'.mp4',
MIME_VIDEO_OGG:'.ogg',
MIME_APP_TAR:'.tgz',
MIME_APP_GZIP:'.gz'}
class aBGR:
def __init__(self,alpha_=None, blue_=None, green_=None, red_=None, value=None):
### Alpha, blue, green, red values will override value
if value is not None:
if alpha_ is not None:
raise RuntimeError("Cannot specify individual aBGR values and a string" \
" value in the same instance of aBGR")
try:
value_list = value.split(".")
if len(value_list) == 4 :
alpha_ = int(value_list[0])
blue_ = int(value_list[1])
green_ = int(value_list[2])
red_ = int(value_list[3])
else:
raise aBGRError
except:
raise RuntimeError("Format of String %s not suitable for an aBGR value"%value)
if alpha_ is not None:
try:
self.alpha = int(alpha_)
if self.alpha < Constants.minimum_ABGR_value or self.alpha > Constants.maximum_ABGR_value:
raise aBGRError
except:
raise RuntimeError("Alpha value of %s invalid for an aBGR value"%alpha_)
try:
self.blue = int(blue_)
if self.blue < Constants.minimum_ABGR_value or self.blue > Constants.maximum_ABGR_value:
raise aBGRError
except:
raise RuntimeError("Blue value of %s invalid for an aBGR value"%blue_)
try:
self.green = int(green_)
if self.green < Constants.minimum_ABGR_value or self.green > Constants.maximum_ABGR_value:
raise aBGRError
except:
raise RuntimeError("Green value of %s invalid for an aBGR value"%green_)
try:
self.red = int(red_)
if self.red < Constants.minimum_ABGR_value or self.red > Constants.maximum_ABGR_value:
raise aBGRError
except:
raise RuntimeError("Red value of %s invalid for an aBGR value"%red_)
else:
raise RuntimeError("Arguments to aBGR instance do not make sense")
def __str__(self):
return "%d.%d.%d.%d"%(self.alpha,self.blue,self.green,self.red)
def __repr__(self):
return 'aBGR values:\n\talpha:%10d\n\tblue:%11d\n\tgreen:%10d\n\tred:%12d'%(self.alpha,
self.blue,
self.green,
self.red)
def __sub__(self,otherColor):
assert(isinstance(otherColor,aBGR))
return (self.alpha - otherColor.alpha,
self.blue - otherColor.blue,
self.green - otherColor.green,
self.red - otherColor.red)
class PlotInfo:
def __init__(self,
input_filename_ = None,
output_filename_ = None,
styles_filenames_ = None,
wsdl_request_=False,
output_format_ ="png",
bundle_format_ = None,
start_color_ = None,
end_color_ = None,
start_radius_ = -1.0,
end_radius_ = -1.0,
num_gradients_ = 0,
max_resolution_ = Constants.kNormalizedGeometry,
project_image_ = False,
font_ = None,
font_size_ = 24.0,
legend_font_size_ = 16.0,
background_color_ = None,
fill_color_ = None,
stroke_width_ = 1.0,
title_ = None,
legend_ = None):
self.input_filename = input_filename_
if output_filename_ is None:
self.output_filename = os.path.splitext(self.input_filename)[0]
else:
self.output_filename = output_filename_
self.styles_filenames = styles_filenames_
self.wsdl_request = False
if wsdl_request_ is not None and wsdl_request_ is not False:
self.wsdl_request = True
self.output_format = output_format_
self.bundle_format = bundle_format_
self.start_color = None
if start_color_ is not None:
self.start_color = aBGR(value=start_color_)
print "pI: " +str(self.start_color)
self.end_color = None
if end_color_ is not None:
self.end_color = aBGR(value=end_color_)
self.start_radius = float(start_radius_)
self.end_radius = float(end_radius_)
self.num_gradients = int(num_gradients_)
self.max_resolution = float(max_resolution_)
self.project_image = False
if project_image_ is not None and project_image_ is not False:
self.project_image = True
self.font = font_
self.font_size = float(font_size_)
self.legend_font_size = float(legend_font_size_)
self.background_color = None
if background_color_ is not None:
self.background_color = aBGR(value=background_color_)
self.fill_color = None
if fill_color_ is not None:
self.fill_color = aBGR(value=fill_color_)
self.stroke_width = float(stroke_width_)
self.title = title_
self.legend = legend_
if self.input_filename is not None:
self.wrappers = self.parseWrappers()
else:
self.wrappers = []
self.styles = []
if styles_filenames_ is not None:
for styleFilename in styles_filenames_:
self.styles.append(self.parseStyles(styleFilename))
def parseWrappers(self):
wrappers_tmp = []
lonLatPathRecs = {}
lonLatPolyRecs = {}
with open(self.input_filename,"rb") as f:
for line in f:
elements = line.split()
if elements[0][0]== Constants.GAIA_INPUT_COMMENT_FLAG:
continue
elemType = elements[0].lower()
element = None
if elemType == "lonlat":
element = LonLat()
element.parseRec(line[len('lonlat '):])
elif elemType == "usfips":
element = USFips()
element.parseRec(line[len('usfips '):])
elif elemType[:2] == "us":
element = USApolloCode()
element.parseRec(line[len('US'):])
elif elemType == "hasc":
element = HASC()
element.parseRec(line[len('hasc '):])
elif elemType == "lonlat-label":
element = LonLatLabel()
element.parseRec(line[len('lonlat-label '):])
elif elemType == "lonlat-path":
elemID = int(elements[1])
if not lonLatPathRecs.has_key(elemID):
lonLatPathRecs[elemID] = []
elemStr = ""
for elem in elements[1:]:
elemStr += str(elem) + " "
lonLatPathRecs[elemID].append(elemStr)
elif elemType == "lonlat-poly":
elemID = int(elements[1])
if not lonLatPolyRecs.has_key(elemID):
lonLatPolyRecs[elemID] = []
elemStr = ""
for elem in elements[1:]:
elemStr += str(elem) + " "
lonLatPolyRecs[elemID].append(elemStr)
else:
raise RuntimeError("ERROR: Unsupported GAIA Element Type of %s in input"%elemType)
if element is not None:
wrappers_tmp.append(element)
### Parse out the LonLatPaths
if len(lonLatPathRecs) > 0:
for lonLatID in lonLatPathRecs.keys():
element = LonLatPath()
element.parseRec(lonLatPathRecs[lonLatID])
wrappers_tmp.append(element)
### Parse out the LonLatPolys
if len(lonLatPolyRecs) > 0:
for lonLatID in lonLatPolyRecs.keys():
element = LonLatPoly()
element.parseRec(lonLatPolyRecs[lonLatID])
wrappers_tmp.append(element)
return wrappers_tmp
def parseStyles(self,styleFilename):
styles_tmp = {}
styles_tmp['elements'] = []
styleID = 0
legendSupport = 0
with open(styleFilename,"rb") as f:
lineList = f.readlines()
for line in lineList:
elements = line.split()
if elements[0][0:2] == "id":
styleID = int(elements[0].split("=")[1])
elif elements[0][0:14] == "legend-support":
legendSupport = int(elements[0].split("=")[1])
else:
styles_tmp['elements'].append({'color':aBGR(value=elements[0]),
'radius':float(elements[1]),
'lower_bound':float(elements[2]),
'upper_bound':float(elements[3])})
styles_tmp['styleID'] = int(styleID)
styles_tmp['legend-support'] = int(legendSupport)
return styles_tmp
def printXMLMessage(self):
xmlString = '<?xml version="1.0" encoding="UTF-8" standalone="no" ?><gaia>'
xmlString+= '<output-format>%s</output-format>'%(self.output_format)
if self.bundle_format is not None:
xmlString+= '<bundle-format>%s</bundle-format>'%(self.bundle_format)
if self.num_gradients > 0:
xmlString+= '<num-gradients>%d</num-gradients>'%(self.num_gradients)
if self.max_resolution > 0:
xmlString+= '<max-resolution>%#g</max-resolution>'%(self.max_resolution)
if self.start_color is not None:
xmlString+= '<start-color>%s</start-color>'%(str(self.start_color))
if self.end_color is not None:
xmlString+= '<end-color>%s</end-color>'%(str(self.end_color))
if self.start_radius > -1:
xmlString+= '<start-radius>%g</start-radius>'%(self.start_radius)
if self.end_radius > -1:
xmlString+= '<end-radius>%g</end-radius>'%(self.end_radius)
if self.font is not None:
xmlString+= '<font-type>%s</font-type>'%(self.font)
if self.font_size > -1:
xmlString+= '<font-size>%g</font-size>'%(self.font_size)
if self.legend_font_size > -1:
xmlString+= '<legend-font-size>%g</legend-font-size>'%(self.legend_font_size)
if self.background_color is not None:
xmlString+= '<background-color>%s</background-color>'%(self.background_color)
if self.stroke_width > -1:
xmlString+= '<stroke-width>%g</stroke-width>'%(self.stroke_width)
if self.project_image is True:
xmlString+= '<project-image>1</project-image>'
if self.title is not None:
xmlString+= '<title>%s</title>'%self.title
if self.legend is not None:
xmlString+= '<legend-text>%s</legend-text>'%self.legend
### Now write the styles
if len(self.styles) > 0:
for styleDict in self.styles:
xmlString+= '<style-range-list style-id="%d" legend-support="%d">'\
%(styleDict['styleID'],styleDict['legend-support'])
for style in styleDict['elements']:
xmlString += '<color>%s</color><radius>%f</radius>'\
'<lower-bound>%f</lower-bound>'\
'<upper-bound>%f</upper-bound>'\
%(str(style['color']),
style['radius'],
style['lower_bound'],
style['upper_bound'])
xmlString+= '</style-range-list>'
xmlString += '<wrapper-raw>'
wrapperCount = 0
for wrapper in self.wrappers:
elementStr = str(wrapper) + Constants.WRAPPER_RAW_ELEMENT_DELIMITER
wrapperCount += len(elementStr)
if wrapperCount > Constants.WRAPPER_BUFFER_SIZE:
xmlString += '</wrapper-raw><wrapper-raw>'
wrapperCount = len(elementStr)
xmlString += elementStr
xmlString = xmlString[:-1] + '</wrapper-raw>'
xmlString += '</gaia>'
return xmlString
class ConfInfo:
def __init__(self,serverURL_="gaia.pha.psc.edu",serverPort_="13500",logInfo_=None,debug_=False):
self.serverURL = serverURL_
self.serverPort = serverPort_
self.logInfo = logInfo_
self.debug = debug_
def __str__(self):
return "(%s,%d,%s)"%(self.serverURL,self.serverPort,self.logInfo)
def __repr__(self):
return "Configuration Information:\n\tServer:\t%s\n\tPort:\t%d\n\tLog:\t%s\n"\
%(self.serverURL,self.serverPort,self.logInfo)
class Wrapper:
def __init__(self,type_,
time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
self.type = type_.lower()
self.time = time_
self.styleID = styleID_
if type_ not in Constants.supportedWrapperTypes.keys():
raise RuntimeError("ERROR: Trying to create a Wrapper that is of an"\
"unsupported type %s in GAIA"%type_)
self.info = {}
def __str__(self):
raise RuntimeError("Printing from the abstract Wrapper Class is not appropriate,"\
"please use a proper concrete class")
def parseRec(self,rec):
raise RuntimeError("Cannot parse record from abstract class Wrapper")
class LonLat(Wrapper):
def __init__(self,longitude_=0.0,latitude_=0.0,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"lonlat",time_,styleID_)
self.latitude = float(latitude_)
self.longitude = float(longitude_)
self.value = float(value_)
def parseRec(self,rec):
## split by space
recSplit = rec.split()
if len(recSplit) <3 or len(recSplit) > 4:
raise RuntimeError("ERROR: lonlat element input has the incorrect number of fields")
## First look for a styleID parameter
self.latitude = float(recSplit.pop(0).strip('"').strip("'").strip())
self.longitude = float(recSplit.pop(0).strip('"').strip("'").strip())
### can have multiple values associated with styles
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of LonLat Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
self.styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
self.value = float(recSplit.pop(0).strip('"').strip("'").strip())
### is there a time sequence value
if len(recSplit) > 0:
self.time = float(recSplit.pop(0).strip('"').strip("'").strip())
def __str__(self):
return 'lonlat %f %f %g %d %g'%(self.longitude,self.latitude,\
self.value,self.styleID,self.time)
class USFips(Wrapper):
def __init__(self,fipsString_=None,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"usfips",time_,styleID_)
self.fipsString = fipsString_
self.value = float(value_)
def parseRec(self,rec):
## split by space
recSplit = rec.split()
if len(recSplit) < 2 or len(recSplit) > 3:
raise RuntimeError("ERROR: usfips element input has the incorrect number of fields")
self.fipsString = recSplit.pop(0).strip('"').strip("'").strip()
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of USFips Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
self.styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
self.value = float(recSplit.pop(0).strip('"').strip("'").strip("\n"))
### is there a time sequence value
if len(recSplit) > 0:
self.time = float(recSplit.pop(0).strip('"').strip("'").strip("\n"))
def __str__(self):
return "usfips %s %g %d %g"%(self.fipsString,self.value,self.styleID,self.time)
class USApolloCode(Wrapper):
def __init__(self,fipsString_=None,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"usfips",time_,styleID_)
self.fipsString = fipsString_
self.value = float(value_)
def parseRec(self,rec):
## split by space
recSplit = rec.split()
#print str(recSplit)
if len(recSplit) < 2 or len(recSplit) > 3:
raise RuntimeError("ERROR: usfips element input has the incorrect number of fields")
self.fipsString = self.convertFIPSToGaiaFips(recSplit.pop(0).strip('"').strip("'").strip())
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of USFipsApolloCode Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
self.styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
val = recSplit.pop(0).strip('"').strip("'").strip("\n")
self.value = float(val)
### is there a time sequence value
if len(recSplit) > 0:
tim = recSplit.pop(0)
self.time = float(tim.strip('"').strip("'").strip("\n"))
def convertFIPSToGaiaFips(self,fips_):
fipsWOAsterix = fips_.strip('*')
astCount = fips_.count('*')
if astCount > 4:
raise RuntimeError("ERROR: USApolloCode::convertFipsToGaiaFips %s has %d asterices, can only have 4"%(str(fips_),astCount))
if len(fipsWOAsterix) < 2:
raise RuntimeError("ERROR: USApolloCode::convertFipsToGaiaFips is less than 2 in length")
if len(fipsWOAsterix) != 2 and len(fipsWOAsterix) != 5 and len(fipsWOAsterix) != 9 and len(fipsWOAsterix) != 11 and len(fipsWOAsterix) < 12:
raise RuntimeError("ERROR: USApolloCode::convertFipsToGaiaFips %s, %d is not an standard length"%(str(fipsWOAsterix),len(fipsWOAsterix)))
if len(fipsWOAsterix) == 0:
returnString = self.asterixToCode("all",astCount)
else:
returnString = "st%s"%fipsWOAsterix[0:2]
if len(fipsWOAsterix) == 2:
returnString += self.asterixToCode("st",astCount)
if len(fipsWOAsterix) > 2:
returnString += ".ct%s"%fips_[2:5]
if len(fipsWOAsterix) == 5:
returnString += self.asterixToCode("ct",astCount)
if len(fipsWOAsterix) > 5:
fips_tr = fipsWOAsterix[5:11]
if fips_tr[-2:] == "00":
fips_tr = fipsWOAsterix[5:9]
returnString += ".tr%s"%fips_tr
if len(fipsWOAsterix) == 9 or len(fipsWOAsterix) == 11:
returnString += self.asterixToCode("tr",astCount)
if len(fipsWOAsterix) == 10 or len(fipsWOAsterix) == 12:
returnString += ".bl%s"%fipsWOAsterix[11:]
if returnString.count('ct') > 1 or returnString.count('st') > 1 or returnString.count('tr') > 1 or returnString.count('bl') > 1:
raise RuntimeError("ERROR: USApolloCode::convetFipsToGaiaFips %s has and incorrect format in parsing asterices"%(returnString))
return returnString
def asterixToCode(self,level,astCount):
if level not in ["all","st","ct","tr"]:
raise RuntimeError("ERROR: USApolloCode::asterixToCode: invalid level %s"%str(level))
print "Level: %s count %d"%(level,astCount)
if level == "all":
if astCount > 4:
astCount = 4
if astCount == 4:
return "st*.ct*.tr*.bl*"
elif astCount == 3:
return "st*.ct*.tr*"
elif astCount == 2:
return "st*.ct*"
elif astCount == 1:
return "st*"
elif level == "st":
if astCount > 3:
astCount = 3
if astCount == 3:
return ".ct*.tr*.bl*"
elif astCount == 2:
return ".ct*.tr*"
elif astCount == 1:
return ".ct*"
elif level == "ct":
if astCount > 2:
astCount = 2
if astCount == 2:
return ".tr*.bl*"
if astCount ==1:
return ".tr*"
elif level == "tr":
if astCount > 1:
astCount = 1
if astCount == 1:
return ".bl*"
return ""
def __str__(self):
return "usfips %s %g %d %g"%(self.fipsString,self.value,self.styleID,self.time)
class HASC(Wrapper):
def __init__(self,fipsString_=None,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"hasc",time_,styleID_)
self.fipsString = fipsString_
self.value = float(value_)
def parseRec(self,rec):
## split by space
recSplit = rec.split()
if len(recSplit) < 2 or len(recSplit) > 3:
raise RuntimeError("ERROR: hasc element input has the incorrect number of fields")
self.fipsString = recSplit.pop(0).strip('"').strip("'").strip()
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of LonLat Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
self.styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
self.value = float(recSplit.pop(0).strip('"').strip("'").strip())
### is there a time sequence value
if len(recSplit) > 0:
self.time = float(recSplit.pop(0).strip('"').strip("'").strip())
def __str__(self):
return "hasc %s %g %d %g"%(self.fipsString,self.value,self.styleID,self.time)
class LonLatLabel(Wrapper):
def __init__(self,longitude_=0.0,latitude_=0.0,label_="Label",value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"lonlat-label",time_,styleID_)
self.longitude = float(longitude_)
self.latitude = float(latitude_)
self.value = float(value_)
self.label = str(label_)
def parseRec(self,rec):
### first we need to parse out the label between quotes
if rec.find('"') == -1:
raise RuntimeError("ERROR: lonlat-label element has no label in it")
start = rec.index('"') + len('"')
end = rec.index('"',start)
self.label = rec[start:end]
### eliminate the label from the record and move on
rec = rec[end+1:]
## split by space
recSplit = rec.split()
if len(recSplit) < 3 or len(recSplit) > 4:
raise RuntimeError("ERROR: lonlat-label element input has the incorrect number of fields")
self.latitude = float(recSplit.pop(0).strip('"').strip("'").strip())
self.longitude = float(recSplit.pop(0).strip('"').strip("'").strip())
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of LonLat Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
self.styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
self.value = float(recSplit.pop(0).strip('"').strip("'").strip())
if len(recSplit) > 0:
self.time = float(recSplit.pop(0).strip('"').strip("'").strip())
def __str__(self):
return 'lonlat-label %f %f "%s" %g %d %g'%(self.longitude,self.latitude,self.label,\
self.value,self.styleID,self.time)
class LonLatPath(Wrapper):
def __init__(self,coordinates_=None,pathID_=0,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"lonlat-path",time_,styleID_)
if coordinates_ is None:
self.coordinates = []
else:
self.coordinates = coordinates_
self.value = float(value_)
self.pathID = int(pathID_)
### This is a special element, as it needs to be defined on more than one record
def parseRec(self,recs):
assert(isinstance(recs,list))
if len(recs) < 2:
raise RuntimeError("ERROR: Must Define more than one lonlat point for a LonLatPath")
second_pass = False
for rec in recs:
## split by space
recSplit = rec.split()
pathID = int(recSplit.pop(0).strip('"').strip("'").strip())
latitude = float(recSplit.pop(0).strip('"').strip("'").strip())
longitude = float(recSplit.pop(0).strip('"').strip("'").strip())
styleID = Constants.GAIA_DEFAULT_STYLE
time = Constants.GAIA_DEFAULT_TIME_SEQ
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of LonLat Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
value = float(recSplit.pop(0).strip('"').strip("'").strip())
if len(recSplit) > 0:
time = float(recSplit.pop(0).strip('"').strip("'").strip())
if second_pass:
# If this is the second entry or greater... just error check
if self.pathID != pathID or self.value != value or self.time != time:
raise RuntimeError("ERROR: Inconsistent Records in LonLatPath records")
else:
# If this is the first entry, set the values
self.pathID = pathID
self.value = value
self.time = time
self.styleID = styleID
self.coordinates.append((longitude,latitude))
def __str__(self):
returnString = "lonlat-path %d "%(self.pathID)
for coords in self.coordinates:
returnString += "%f %f, "%(coords[0],coords[1])
return returnString[:-2] + " %g %d %g"%(self.value,self.styleID,self.time)
class LonLatPoly(Wrapper):
def __init__(self,coordinates_=None,polyID_=0,value_=0.0,time_=Constants.GAIA_DEFAULT_TIME_SEQ,
styleID_=Constants.GAIA_DEFAULT_STYLE):
Wrapper.__init__(self,"lonlat-path",time_,styleID_)
if coordinates_ is None:
self.coordinates = []
else:
self.coordinates = coordinates_
self.value = float(value_)
self.polyID = int(polyID_)
### This is a special element, as it needs to be defined on more than one record
def parseRec(self,recs):
assert(isinstance(recs,list))
if len(recs) < 2:
raise RuntimeError("ERROR: Must Define more than one lonlat point for a LonLatPoly")
second_pass = False
for rec in recs:
## split by space
recSplit = rec.split()
polyID = int(recSplit.pop(0).strip('"').strip("'").strip())
latitude = float(recSplit.pop(0).strip('"').strip("'").strip())
longitude = float(recSplit.pop(0).strip('"').strip("'").strip())
styleID = Constants.GAIA_DEFAULT_STYLE
time = Constants.GAIA_DEFAULT_TIME_SEQ
foundFlag = False
for record in recSplit:
if Constants.WRAPPER_VALUE_STYLE_DELIMITER in record:
if foundFlag:
raise RuntimeError("ERROR: Format of LonLat Wrapper has more than one Style parameter specified")
foundFlag = True
styleSplit = record.split(Constants.WRAPPER_VALUE_STYLE_DELIMITER)
styleID = int(styleSplit[1])
### eliminate this from the record
recSplit[recSplit.index(record)] = str(styleSplit[0])
value = float(recSplit.pop(0).strip('"').strip("'").strip())
if len(recSplit) > 0:
time = float(recSplit.pop(0).strip('"').strip("'").strip())
if second_pass:
# If this is the second entry or greater... just error check
if self.polyID != polyID or self.value != value or self.time != time:
raise RuntimeError("ERROR: Inconsistent Records in LonLatPoly records")
else:
# If this is the first entry, set the values
self.polyID = polyID
self.value = value
self.time = time
self.styleID = styleID
self.coordinates.append((longitude,latitude))
def __str__(self):
returnString = "lonlat-poly %d "%(self.polyID)
for coords in self.coordinates:
returnString += "%f %f, "%(coords[0],coords[1])
return returnString[:-2] + " %g %d %g"%(self.value,self.styleID,self.time)
### Static Utility functions
def compressList(chunkList):
for i in range(0,len(chunkList)-1):
#print "Start " + str(chunkList[i])
#print "End " + str(chunkList[i+1])
if len(chunkList[i])==0:
continue
endValue = chunkList[i][len(chunkList[i])-1]
begValue = chunkList[i+1][0]
#print "start beg,end: " + str(begValue) + " " + str(endValue)
while int(begValue) == int(endValue) and len(chunkList[i+1]) != 0:
del chunkList[i+1][0]
chunkList[i].append(begValue)
# print "Alter Start " + str(chunkList[i])
# print "Alter End " + str(chunkList[i+1])
if len(chunkList[i+1]) == 0:
continue
begValue = chunkList[i+1][0]
# print "new begValue: " + str(begValue)
for i in range(len(chunkList)-1,0,-1):
if len(chunkList[i]) == 0:
del chunkList[i]
return len(chunkList)
def chunkUpList(valueList,numOfBins):
## If the number of unique values in this list is too small, adjust
valueUnique = set(valueList)
if numOfBins > len(valueUnique): numOfBins = len(valueUnique)
minimumValue = min(valueList)
maximumValue = max(valueList)
numberOfValues = len(valueList)
#Compute Initial Value for ideal chunk size
idealChunk = int(round(float(numberOfValues)/float((numOfBins))))
## Create initial chunks
chunkList = [valueList[i:i+idealChunk] for i in range(0,len(valueList),idealChunk)]
## If this produces more chunks than needed, adjust the chunks
if len(chunkList) > numOfBins:
appendList = chunkList.pop()
for value in appendList:
chunkList[len(chunkList)-1].append(value)
## Put like values in the same chunks
beforeNumChunks = len(chunkList)
afterNumChunks = 0
while beforeNumChunks != afterNumChunks:
beforeNumChunks = len(chunkList)
afterNumChunks = compressList(chunkList)
## Return this tuple so that we can adjust our expectations
return (numOfBins,chunkList)
def computeBoundaries(valueList,numOfBins):
valueListSorted = sorted(valueList)
### Initial Chunks
(orgNumBins,chunkList) = chunkUpList(valueListSorted,numOfBins)
### Iterate until we get to the proper number of bins
while orgNumBins != len(chunkList):
reducedNumBins = orgNumBins - 1
newValueList = []
for chunk in chunkList[1:]:
for value in chunk:
newValueList.append(value)
(newNumBins,newChunkList) = chunkUpList(newValueList,reducedNumBins)
if newNumBins+1 < orgNumBins: orgNumBins = newNumBins + 1
chunkList = [chunkList[0]]
for chunk in newChunkList:
chunkList.append(chunk)
# Create and Return Boundaries (Joel would not approve of the fact that this is multple lines :))
boundaryList = []
boundaryList.append((chunkList[0][0],chunkList[0][len(chunkList[0])-1]))
for i in range(1,len(chunkList)):
boundaryList.append((chunkList[i-1][len(chunkList[i-1])-1]+1,chunkList[i][len(chunkList[i])-1]))
return boundaryList
def computeColors(colorStart,colorEnd,numberOfColors):
if isinstance(colorStart,str):
colorStart = aBGR(value=colorStart)
if isinstance(colorEnd,str):
colorEnd = aBGR(value=colorEnd)
colors = [colorStart]
colorDiff = colorEnd - colorStart
for i in range(1,numberOfColors-1):
alpha = colorStart.alpha + i*int(math.ceil(colorDiff[0]/(numberOfColors-1)))
blue = colorStart.blue + i*int(math.ceil(colorDiff[1]/(numberOfColors-1)))
green = colorStart.green + i*int(math.ceil(colorDiff[2]/(numberOfColors-1)))
red = colorStart.red + i*int(math.ceil(colorDiff[3]/(numberOfColors-1)))
if alpha < 0: alpha = 0
if blue < 0: blue = 0
if green < 0: green = 0
if red < 0: red = 0
colors.append(aBGR(alpha,blue,green,red))