Changeset 1660
- Timestamp:
- 02/11/06 09:36:52 (14 years ago)
- Location:
- TI04-geosplat/trunk
- Files:
-
- 6 added
- 18 edited
Legend:
- Unmodified
- Added
- Removed
-
TI04-geosplat/trunk/MANIFEST
r1243 r1660 9 9 pygsc/clientConfig.py 10 10 pygsc/common.py 11 pygsc/jsFunctions.py 11 12 pygsc/localRules.py 12 13 pygsc/version.py -
TI04-geosplat/trunk/cgi/splatui
r1243 r1660 223 223 self.args["targetPage"]="VariableSelectionPage" 224 224 fileURIs=self.args["fileURIList"].split() 225 (optionCategories, options, optionStrings, secureToken)= \ 226 self.server.callServerMethod("provideFileURIs", 227 [self.sessionID, self.secureToken, fileURIs]) 225 resp=self.server.callServerMethod("provideFileURIs", 226 [self.sessionID, self.secureToken, fileURIs]) 227 if zsiv>=2.0: 228 resp=resp[0] 229 (optionCategories, options, optionStrings, secureToken)=apply(self._cleanOptsTuple, resp) 228 230 else: 229 231 pass -
TI04-geosplat/trunk/gss/bin/GSWSInterface.py
r1243 r1660 254 254 controller=GSController(args) 255 255 except Exception, error: 256 print "HHHHHHHHHHHHHHHHHHHHH", str(error) 256 257 return str(error) 257 258 … … 319 320 320 321 exclusions=("callMethod", "secureToken", "optionCategoryRequested", 321 "action", "targetPage" )322 "action", "targetPage", "varDict") 322 323 for key in keylist: 323 324 if req[key]!="" and key not in exclusions: summaryString=summaryString+("%s:\t%s\n" % (key, req[key])) -
TI04-geosplat/trunk/install.conf
r798 r1660 27 27 # "/usr/local/gss" is recommended but you can change it as 28 28 # you wish. 29 BASEDIR="/ home/as56/abstractWebService/gss"29 BASEDIR="/usr/local/test/gss" 30 30 31 31 # OUTPUT_DIR: 32 32 # The full path on the local machine of the output directory. 33 OUTPUT_DIR="/ srv/www/htdocs/gs/output"33 OUTPUT_DIR="/home/as56/apache/htdocs/gs/output" 34 34 35 35 # OUTPUT_DIR_URL: … … 90 90 # "/usr/local/gsc" is recommended but you can change it as 91 91 # you wish. 92 BASEDIR="/ home/as56/abstractWebService/gsc"92 BASEDIR="/usr/local/test/gsc" 93 93 94 94 # STATIC_WEBSERVER_URL_PATH … … 98 98 # STATIC_WEBSERVER_LOCAL_PATH 99 99 # Location on the local machine of the webserver top level directory. 100 STATIC_WEBSERVER_LOCAL_PATH="/ srv/www/htdocs"100 STATIC_WEBSERVER_LOCAL_PATH="/home/as56/apache/htdocs" 101 101 102 102 # WEB_EXTRAS_URL_PATH: … … 118 118 # "/srv/www/cgi-bin/splatui" is likely on a SUSE system but 119 119 # you are free to rename this as you wish. 120 CGI_SCRIPT_LOCAL_PATH="/ srv/www/cgi-bin/splatui"120 CGI_SCRIPT_LOCAL_PATH="/home/as56/apache/cgi-bin/splatui" 121 121 122 122 # OUTPUT_DIR_LOCAL_PATH -
TI04-geosplat/trunk/install.sh
r1210 r1660 1 v="0.3. 0"1 v="0.3.1" 2 2 rm -rR *tar *gz README.txt *conf gs? pygs? pygs?-?.? pygs?-?-?.? cgi web_extras 3 3 -
TI04-geosplat/trunk/pygsc/DisplayManager.py
r798 r1660 18 18 from clientConfig import * 19 19 from common import * 20 import jsFunctions 20 21 21 22 class DisplayManager: … … 64 65 print """<P>Please provide a list of files (by full path on the GeoSPlAT 65 66 server network) that you would like to visualise. Please type each new file 66 a new line in the box below."""67 path on a new line in the box below.""" 67 68 68 69 … … 226 227 227 228 # Second time around display the multi-variable options 228 multiVarLine="""<TR><TD><B>MULTI-VARIABLE OPTIONS:</B>""" 229 multiVarLine="""<TR><TD CLASS="tablestyle"><B><FONT COLOR="black">MULTIPLE VARIABLE OPTIONS:</FONT></B>""" 230 229 231 optCounter=0 230 232 for option in options: … … 274 276 ("<B>Axis ID</B>", "<B>Long name</B>", "<B>Length</B>", "<B>Usage in plots</B>") 275 277 276 278 # Insert javascript functions to check mutually exclusive radio selection 279 nAxes=len(options) 280 indexStringForJavascript=str(range(nAxes)) 281 print jsFunctions.js_animSelectionFunctions % indexStringForJavascript 282 277 283 checkedStrings=[[" CHECKED","",""], [""," CHECKED",""], ["",""," CHECKED"], ["","",""],["","",""],["","",""],["","",""]] 278 284 for i in range(len(options)): 279 285 print """<TR><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s %s %s </TD></TR>""" % \ 280 286 (options[i][0], optionStrings[i][0], options[i][1], 281 """<INPUT TYPE="Radio" NAME="axisLoopForAnimation" VALUE="%s"%s> Loop""" % (options[i][0], checkedStrings[i][0]),282 """<INPUT TYPE="Radio" NAME="axisYForAnimation" VALUE="%s""%s> Y""" % (options[i][0], checkedStrings[i][1]),283 """<INPUT TYPE="Radio" NAME="axisXForAnimation" VALUE="%s""%s> X""" % (options[i][0], checkedStrings[i][2]))287 """<INPUT TYPE="Radio" NAME="axisLoopForAnimation" onclick="return validateAnimSelections('axisLoopForAnimation')" VALUE="%s"%s> Loop""" % (options[i][0], checkedStrings[i][0]), 288 """<INPUT TYPE="Radio" NAME="axisYForAnimation" onclick="return validateAnimSelections('axisYForAnimation')" VALUE="%s""%s> Y""" % (options[i][0], checkedStrings[i][1]), 289 """<INPUT TYPE="Radio" NAME="axisXForAnimation" onclick="return validateAnimSelections('axisXForAnimation')" VALUE="%s""%s> X""" % (options[i][0], checkedStrings[i][2])) 284 290 285 291 print "</TABLE>" -
TI04-geosplat/trunk/pygsc/clientConfig.py
r1243 r1660 115 115 # STATIC_WEBSERVER_LOCAL_PATH 116 116 # Location on the local machine of the webserver top level directory. 117 STATIC_WEBSERVER_LOCAL_PATH="/ srv/www/htdocs"117 STATIC_WEBSERVER_LOCAL_PATH="/home/as56/apache/htdocs" 118 118 119 119 # WEB_EXTRAS_URL_PATH: … … 135 135 # "/srv/www/cgi-bin/splatui" is likely on a SUSE system but 136 136 # you are free to rename this as you wish. 137 CGI_SCRIPT_LOCAL_PATH="/ srv/www/cgi-bin/splatui"137 CGI_SCRIPT_LOCAL_PATH="/home/as56/apache/cgi-bin/splatui" 138 138 139 139 # TOKEN_VALID_LIFETIME: … … 153 153 # "/usr/local/gsc" is recommended but you can change it as 154 154 # you wish. 155 BASEDIR="/ home/as56/abstractWebService/gsc"155 BASEDIR="/usr/local/test/gsc" 156 156 157 157 # OUTPUT_DIR_LOCAL_PATH 158 158 # The full path on the local machine of the output directory. 159 OUTPUT_DIR_LOCAL_PATH=os.path.join(STATIC_WEBSERVER_LOCAL_PATH, " output")159 OUTPUT_DIR_LOCAL_PATH=os.path.join(STATIC_WEBSERVER_LOCAL_PATH, "gs/output") 160 160 161 161 # OUTPUT_DIR_URL_PATH: 162 162 # The URL address of the OUTPUT_DIR_LOCAL_PATH 163 OUTPUT_DIR_URL_PATH=os.path.join(STATIC_WEBSERVER_URL_PATH, " output")163 OUTPUT_DIR_URL_PATH=os.path.join(STATIC_WEBSERVER_URL_PATH, "gs/output") 164 164 165 165 # LOGO_DIR: -
TI04-geosplat/trunk/pygsc/version.py
r1210 r1660 11 11 """ 12 12 13 version="0.3. 0"13 version="0.3.1" -
TI04-geosplat/trunk/pygss/GSController.py
r1210 r1660 136 136 raise Exception, error 137 137 138 try: 139 self._createOutput() 138 try: 139 self._createOutput() 140 140 self.logger=LogManager(self.bag) 141 141 self.bag["status"]="complete" … … 250 250 response to the current request. 251 251 """ 252 252 253 if keyPatternMatch(self.bag, "fileURI")==0: 253 254 print self.bag … … 255 256 return 256 257 257 self.options=OptionHandler(self.bag["userRoles"], self.username, self.bag).options 258 optionHandler=OptionHandler(self.bag["userRoles"], self.username, self.bag) 259 self.options=optionHandler.options 260 if hasattr(optionHandler, "varDict"): 261 self.bag["varDict"]=optionHandler.varDict 262 258 263 return 259 264 … … 310 315 self.bag["outputURLPath"]=outman.URLPath 311 316 317 if __name__=="__main__": 318 print "Trying to plot trajectory over model field...\n" 319 b=GSController({'getOutput':"getOutput", 'status': 'constructing', 'username': 'undefined', 'outputURLPath': 'http://localhost/gs/output/output_20061018074443.gif', 'graphicalOutputType': 'MultipleTrajectoriesOver2DLatLonPlot_1.5-2.1', 'projection': 'standard', 'proceed': 'Proceed', 'fileURIList': ['/data/traj.nc', '/data/var2.nc'], 'userRoles': [], 'fileVariable_1.5': 'temp', 'varDict': {'2.1': {'domain': {'latitude': ['latitude', 'latitude', [-90, 90]], 'grots': [['2DLatLonPlot', "2D Lat-Lon Plot for variable 'var2' from file: '/data/var2.nc'"]], 'ordered_axes': ['time', 'latitude', 'longitude'], 'longitude': ['longitude', 'longitude', [0, 355]], 'time': ['time', 'time', [0, 0]]}, 'id': 'var2'}, '1.1': {'domain': {'grots': [['TrajectoriesOverMap', "Trajectories plotted on map for variable 'lat' from file: '/data/traj.nc'"], ['2DPlot', "2D Plot for variable 'lat' from file: '/data/traj.nc'"]], 'bbox': (67.399993896484375, 22.500001907348633, 42.299999237060547, 126.36080169677734), 'parcel': ['parcel', 'unrecognised', [0.0, 1.0]], 'ordered_axes': ['time', 'parcel'], 'time': ['time', 'time', [0.0, 432000.0]]}, 'id': 'lat'}, '1.5-2.1': {'domain': {'grots': [['MultipleTrajectoriesOver2DLatLonPlot', "Multiple Trajectories for variable 'temp' plotted over 2D Plot for variable 'var2'"]], 'bbox': (90, 0, -90, 355)}}}, 'sessionID': 'session_20061018074431451', 'fileVariable_2.1': 'var2', 'plotType': 'MultipleTrajectoryOverBoxfillLinear', 'mapArea':'surroundingArea', 'outputFilePath': '/home/as56/apache/htdocs/gs/output/output_20061018074443.gif', 'fileFormat': 'gif', 'accessTime': 1161157483.026027, 'imageSize': '800x600'}) 320 321 #({'mapArea':"global", 'outputURLPath': 'http://localhost/gs/output/output_20061004002742.gif', 'graphicalOutputType': 'MultipleTrajectoriesOver2DLatLonPlot_1.1-2.1', 'projection': 'standard', 'getOutput':"getOutput", 'fileURIList': ['/data/traj.nc','/data/var2.nc'], 'fileVariable_1.1': 'temp', 'fileVariable_2.1':'var2', 'sessionID': 'session_20061004002735159', 'plotType': 'MultipleTrajectoryOverBoxfillLinear', 'outputFilePath': '/home/as56/apache/htdocs/gs/output/output_20061004002742.gif', 'fileFormat': 'gif', 'imageSize': '800x600'}) 322 sys.exit() 323 324 325 GSController({'username': 'undefined', 'outputURLPath': 'http://localhost/gs/output/output_20061004002742.gif', 'graphicalOutputType': 'TrajectoriesOverMap_1.1', 'projection': 'standard', 'getOutput':"getOutput", 'fileURIList': ['/data/traj.nc'], 'userRoles': [], 'fileVariable_1.1': 'lat', 'sessionID': 'session_20061004002735159', 'plotType': 'MultipleTrajectory', 'outputFilePath': '/home/as56/apache/htdocs/gs/output/output_20061004002742.gif', 'fileFormat': 'gif', 'accessTime': 1159921662.625607, 'imageSize': '800x600'}) -
TI04-geosplat/trunk/pygss/OptionHandler.py
r1243 r1660 25 25 from GSErrors import * 26 26 from VariableAnalyser import * 27 from CombinedPlotManager import * 27 28 28 29 class OptionHandler: … … 68 69 raise GSSecurityError, "User does not have permission to access file: "+fileURI 69 70 70 print "\n\n\n", self.bag71 #print "\n\n\n", self.bag 71 72 # User is allowed to see data so need work out which options to provide 72 73 if keyPatternMatch(self.bag, "fileVariable_")==0: … … 74 75 75 76 elif keyPatternMatch(self.bag, "graphicalOutputType")==0: 76 self.options=self._analyseChosenVariables() 77 self.options=self._analyseChosenVariables() 77 78 78 79 elif type(self.bag["graphicalOutputType"])==type([1,2]): … … 90 91 else: 91 92 self.options=[[[]],[[]],[[]]] 92 93 93 94 94 95 def _getFileVariableLists(self, fileURIList): … … 157 158 optionStrings=[] 158 159 160 # Will need external caller to access and save varDict so make instance attribute 161 self.varDict={} 162 159 163 # Get list of selected variables 160 161 164 for key in self.bag.keys(): 162 165 match=fvpattern.match(key) … … 185 188 analyser=VariableAnalyser(fileURI, varID) 186 189 plotOpts=analyser.plotOpts 187 188 optionCategories.append("graphicalOutputType_%s.%s" % (fileIndex, varIndex)) 190 domainDict=analyser.domainDict 191 192 suffix="%s.%s" % (fileIndex, varIndex) 193 194 self.varDict[suffix]={"id":varID, 195 "domain":domainDict} 196 197 optionCategories.append("graphicalOutputType_%s" % suffix) 189 198 optsSubList=[] 190 199 optsStringsSubList=[] … … 196 205 options.append(optsSubList[:]) 197 206 optionStrings.append(optsStringsSubList[:]) 198 207 208 # Call combined plot manager to work out what plots can be combined 209 # via overlays or combining parameters 210 cbm=CombinedPlotManager(self.varDict, fileList=self.bag["fileURIList"]) 211 combinedOptions=cbm.combinedPlotOptions 212 if len(combinedOptions)>0: 213 for co in combinedOptions: 214 optionCategories+=[co[0]] 215 options+=[co[1]] 216 optionStrings+=[co[2]] 217 218 #optionCategories.append("graphicalOutputType_1.1-2.1") 219 #options.append(["MultipleTrajectoriesOver2DLatLonPlot"]) 220 #optionStrings.append(["""DONT FORGET TO COMBINE STIRNGS with 'Overlay of' dada on blahblah... Multiple Trajectories for variable 'sdfsd' from file 'dfsd' plotted over 2D Plot for variable 'var2' from file 'sdfdsfsf'"""]) 199 221 return [[optionCategories], [options], [optionStrings]] 200 222 … … 206 228 """ 207 229 # Get items needed for working out which file to open 208 (fileName, varID, graphicalOutputType, suffix)=self._getSelectedItemsForAnalysis() 230 (fileNames, varIDs, graphicalOutputType, suffix)=self._getSelectedItemsForAnalysis() 231 # For animation there can only be one filename and varID 232 fileName=fileNames[0] 233 varID=varIDs[0] 209 234 210 235 if graphicalOutputType!="Animation": 211 raise "Matched animation output type from axes without it being selected!"236 raise GSOptionHandlingError, "Matched animation output type from axes without it being selected!" 212 237 213 238 cdmsfile=cdms.open(fileName) … … 239 264 options=[] 240 265 optionStrings=[] 241 266 242 267 # Get selections for stuff needed here 243 (fileName , varID, graphicalOutputType, suffix)=self._getSelectedItemsForAnalysis()268 (fileNames, varIDs, graphicalOutputType, suffix)=self._getSelectedItemsForAnalysis() 244 269 245 270 if graphicalOutputType=="Animation": … … 252 277 animationAxes=None 253 278 254 255 analyser=VariableAnalyser(fileName, varID, graphicalOutputType, animationAxes) 256 plotDict=analyser.plotConfigurationDict 279 # Get the variable (and domain) dictionary from the session object 280 varDict=self.bag["varDict"] 281 282 """for count in range(len(fileNames)): 283 fileName=fileNames[count] 284 varID=varIDs[count] 285 domainDict=varDict[ """ 286 287 nvars=len(fileNames) 288 289 if nvars>1: 290 cbm=CombinedPlotManager(varDict, required="plotConfigurationDict", graphicalOutputType=graphicalOutputType) 291 plotDict=cbm.plotConfigurationDict 292 else: 293 #analyser=VariableAnalyser(fileNames[0], varIDs[0], graphicalOutputType, animationAxes) 294 varID=varIDs[0] 295 analyser=VariableAnalyser(graphicalOutputType=graphicalOutputType, domainDict=varDict[suffix]["domain"], animationAxes=animationAxes) 296 plotDict=analyser.plotConfigurationDict 257 297 258 298 # Sort keys in useful order … … 264 304 265 305 for key in okeys: 266 optionCategories.append( key+suffix)306 optionCategories.append("%s_%s" % (key, suffix)) 267 307 optsSubList=[] 268 308 optsStringsSubList=[] … … 275 315 optionStrings.append(optsStringsSubList[:]) 276 316 317 """optCategories.append(["jljljljlj","OIIIIIIIIIIII"]) 318 options.append(["jljljljlj","OIIIIIIIIIIII"]) 319 optionStrings.append(["jljljljlj","OIIIIIIIIIIII"]) """ 277 320 return [[optionCategories], [options], [optionStrings]] 278 """279 return [[["plotType_2.1", "fileFormat_2.1", "projection_2.1", "continentsSwitch_2.1", "imageSize_2.1"]],280 [[["boxfill", "isofill"],["gif", "postscript"],["standard","mollweide"],["UNAVAILABLE"],["800x600","400x300"]]],281 [[["Boxfill", "Isofill (filled contours)"], ["GIF", "Postscript"],["Standard", "Mollweide"],["UNAVAILABLE"],282 ["800 x 600","400 x 300"]]], ["securityo"]]"""283 321 284 322 … … 292 330 fileURIs.sort() 293 331 294 gpattern=re.compile(r"(PointValueAndMetadata|YvsXGraph|2DPlot|Animation)_(\d+)\.?(\d+)?-?(\d+)?\.?(\d+)?") 332 gpattern=re.compile(r"(%s)_(\d+)\.?(\d+)?-?(\d+)?\.?(\d+)?" % GRAPHICAL_OUTPUT_TYPES_OR_STRING) 333 334 suffix=self.bag["graphicalOutputType"].split("_")[-1] 295 335 296 336 match=gpattern.match(self.bag["graphicalOutputType"]) … … 300 340 (graphicalOutputType, fileIndex1, varIndex1, fileIndex2, varIndex2)=match.groups() 301 341 302 if fileIndex2: 303 raise GSOptionHandlingError, "Cannot yet handle multiple feature graphical outputs, sorry!" 304 342 fileIndices=[fileIndex1, fileIndex2] 343 varIndices=[varIndex1, varIndex2] 344 345 #if fileIndex2: 346 # raise GSOptionHandlingError, "Cannot yet handle multiple feature graphical outputs, sorry!" 347 348 fileNames=[] 349 varIDs=[] 350 351 for i in range(len(fileIndices)): 352 if fileIndices[i]==None: break 353 findex=int(fileIndices[i]) 354 fileName=fileURIs[findex-1] 355 varIndex=int(varIndices[i]) 356 varID=self.bag["fileVariable_%s.%s" % (findex, varIndex)] 357 fileNames.append(fileName) 358 varIDs.append(varID) 359 360 """ 305 361 fileIndex1=int(fileIndex1) 306 362 fileName=fileURIs[fileIndex1-1] … … 308 364 varID=self.bag["fileVariable_%s.%s" % (fileIndex1, varIndex1)] 309 365 310 suffix="_%s.%s" % (fileIndex1, varIndex1) 311 312 return (fileName, varID, graphicalOutputType, suffix) 313 366 suffix="_%s.%s" % (fileIndex1, varIndex1)""" 367 368 return (fileNames, varIDs, graphicalOutputType, suffix) 369 370 314 371 315 372 if __name__=="__main__": … … 318 375 "graphicalOutputType":"Animation_1.2"}) 319 376 print a.options 320 377 378 print "HERE -1:" 379 b=OptionHandler("jane", ["dset1", "dset2"], {"sessionID":"324242", 380 "fileURIList":["/data/var1.nc","/data/var2.nc"], 381 "fileVariable_1.1":"pqn", 382 "fileVariabel_2.1":"var2"}) 383 print b.options 384 385 386 print "HERE:" 321 387 o=OptionHandler("jane", ["dset1", "dset2"], {"sessionID":"324242", 322 388 "fileURIList":["/data/var1.nc"], "fileVariable_1.2":"pqn", 323 "graphicalOutputType":"2DPlot_1.2"}) 389 "graphicalOutputType":"2DPlot_1.2", 390 "varDict":{"1.2":{"name":"pqn", 391 "domain":{"ordered_axes":["time","latitude","longitude"], 392 "time":["time","time",[0,4]], 393 "latitude":["latitude","latitude",[0,90]], 394 "longitude":["longitude","longitude",[0,359]], 395 "grots":["2DLatLonPlot"]}}}}) 324 396 print o.options 325 397 398 print "HERE 1:" 399 400 o=OptionHandler("jane", ["dset1", "dset2"], {"sessionID":"324242", "fileURIList":["/data/var1.nc", "/data/var2.nc"], "fileVariable_1.1":"pqn", "fileVariable_2.1":"var2", 401 "graphicalOutputType":"MultipleTrajectoriesOver2DLatLonPlot_1.1-2.1", 402 "varDict":{"1.1":{"name":"pqn", 403 "domain":{"ordered_axes":["time","latitude","longitude"], 404 "time":["time","time",[0,4]], 405 "latitude":["latitude","latitude",[0,90]], 406 "longitude":["longitude","longitude",[0,359]], 407 "grots":["2DLatLonPlot"]}}, 408 "2.1":{"name":"var2", 409 "domain":{"ordered_axes":["time","latitude","longitude"], 410 "time":["time","time",[0,4]], 411 "latitude":["latitude","latitude",[0,90]], 412 "longitude":["longitude","longitude",[0,359]], 413 "grots":["2DLatLonPlot"]}}}}) 414 print o.options 415 416 print "HERE 2:" 417 o=OptionHandler("jane", ["dset1", "dset2"], {"sessionID":"324242", 418 "fileURIList":["/data/var1.nc", "/data/var2.nc"], "fileVariable_1.1":"pqn", 419 "fileVariable_2.1":"var2"}) 420 """ "graphicalOutputType":"MultipleTrajectoriesOver2DLatLonPlot_1.1-2.1", 421 "varDict":{"1.1":{"name":"pqn", 422 "domain":{"ordered_axes":["time","latitude","longitude"], 423 "time":["time","time",[0,4]], 424 "latitude":["latitude","latitude",[0,90]], 425 "longitude":["longitude","longitude",[0,359]], 426 "grots":["2DLatLonPlot"]}}, 427 "2.1":{"name":"var2", 428 "domain":{"ordered_axes":["time","latitude","longitude"], 429 "time":["time","time",[0,4]], 430 "latitude":["latitude","latitude",[0,90]], 431 "longitude":["longitude","longitude",[0,359]], 432 "grots":["2DLatLonPlot"]}}}})""" 433 print o.options 434 sys.exit() 326 435 p=OptionHandler("jane", ["dset1", "dset2"], {'continentsSwitch':'on', 'status': 'constructing', 'username': 'jane', 'accessTime': 1142324428.122052, 'projection': 'standard', 'fileVariable_1.2': 'pqn', 'fileURIList': ['/data/var1.nc'], 'userRoles': [], 'sessionID': 'session_20060314082027136', 'plotType': 'boxfill', 'fileFormat': 'GIF', 'getOutput': 'getOutput', 'imageSize': '800x600'}) 327 436 print p.options -
TI04-geosplat/trunk/pygss/OutputManager.py
r1243 r1660 55 55 fileURIs.sort() 56 56 57 gpattern=re.compile(r"( PointValueAndMetadata|YvsXGraph|2DPlot|Animation)_(\d+)\.?(\d+)?-?(\d+)?\.?(\d+)?")57 gpattern=re.compile(r"(%s)_(\d+)\.?(\d+)?-?(\d+)?\.?(\d+)?" % GRAPHICAL_OUTPUT_TYPES_OR_STRING) 58 58 59 59 match=gpattern.match(self.bag["graphicalOutputType"]) … … 63 63 (self.graphicalOutputType, fileIndex1, varIndex1, fileIndex2, varIndex2)=match.groups() 64 64 65 if fileIndex2: 66 raise GSOptionHandlingError, "Cannot yet handle multiple feature graphical outputs, sorry!" 67 68 fileIndex1=int(fileIndex1) 65 """if fileIndex2: 66 raise GSOptionHandlingError, "Cannot yet handle multiple feature graphical outputs, sorry!" """ 67 68 fileIndices=[fileIndex1, fileIndex2] 69 varIndices=[varIndex1, varIndex2] 70 71 varIDs=[] 72 self.infilePaths=[] 73 self.infiles=[] 74 self.vars=[] 75 self.varCodes=[] 76 77 for count in range(len(fileIndices)): 78 varIndex=varIndices[count] 79 if varIndex==None: continue 80 varIndex=int(varIndex) 81 fileIndex=int(fileIndices[count]) 82 varID=self.bag["fileVariable_%s.%s" % (fileIndex, varIndex)] 83 84 varIDs.append(varID) 85 infilePath=fileURIs[fileIndex-1] 86 self.infilePaths.append(infilePath) 87 self.infiles.append(cdms.open(infilePath)) 88 self.vars.append(self.infiles[count](varID)) 89 90 # Set a flag for combined variables so you can get the varIndices 91 self.varCodes.append("%s.%s" % (fileIndex, varIndex)) 92 93 """fileIndex1=int(fileIndex1) 69 94 varIndex1=int(varIndex1) 70 95 varID=self.bag["fileVariable_%s.%s" % (fileIndex1, varIndex1)] 71 96 72 infile=cdms.open(fileURIs[fileIndex1-1]) 73 self.var=infile(varID) 74 75 self.suffix="%s.%s" % (fileIndex1, varIndex1) 97 self.infilePath=fileURIs[fileIndex1-1] 98 infile=cdms.open(self.infilePath) 99 self.infile=infile 100 self.var=self.infile(varID) 101 102 self.suffix="%s.%s" % (fileIndex1, varIndex1)""" 76 103 77 104 if self.graphicalOutputType=="PointValueAndMetadata": 78 self.textOnly=self._createTextOutputString(infile) 79 80 infile.close() 81 82 def _createTextOutputString(self, cdmsFile): 105 self.textOnly=self._createTextOutputString(self.infilePaths[0], varIDs[0]) 106 107 # Close infiles for tidiness 108 for infile in self.infiles: 109 infile.close() 110 111 112 def _createTextOutputString(self, fname, varID): 83 113 """ 84 114 Returns a text string including the variable value and suitable 85 115 metadata. 86 116 """ 117 cdmsFile=cdms.open(fname) 118 var=cdmsFile(varID) 119 87 120 axisinfo="<B>Axis Information:</B>" 88 for ax in self.var.getAxisList():121 for ax in var.getAxisList(): 89 122 axisinfo="""%s 90 123 … … 108 141 <B>Variable units:</B> %s 109 142 110 %s""" % (getBestName( self.var), self.var.flat[0], getattr(self.var, "units", "-"), axisinfo)143 %s""" % (getBestName(var), var.flat[0], getattr(var, "units", "-"), axisinfo) 111 144 112 145 print textOutput … … 140 173 "robinson":"Robinson"} 141 174 142 if plotType in ["YvsXGraph"]: 175 # set bounding box off unless overridden below 176 self.bbox=None 177 178 if plotType in ["YvsXGraph", "MultipleTrajectory"]: 143 179 self.plotClass=plotType 144 180 elif plotType=="isolineAndFill": 145 181 self.plotClass="IsolineAndFill"+projMap[projection] 182 elif plotType=="MultipleTrajectoryOverBoxfillLinear": 183 self.plotClass="MultipleTrajectoryOVERBoxfillLinear" 184 continentsSwitch="on" 185 varCodeString="-".join(self.varCodes) 186 187 if self.bag["mapArea"]=="surroundingArea": 188 self.bbox=self.bag["varDict"][varCodeString]["domain"]["bbox"] 189 elif self.bag["mapArea"]=="global": 190 # bbox lat/lon needed even if global to ensure start 191 # longitude is same for both layers 192 bbox=self.bag["varDict"][varCodeString]["domain"]["bbox"] 193 (lat0, lon0, lat1, lon1)=bbox 194 self.bbox=(-90, lon0, 90, lon1) 146 195 else: 147 196 self.plotClass=plotType.title()+projMap[projection] … … 190 239 proj=self.plotClass[14:] 191 240 plotClassList=["Isofill"+proj, "Isoline"+proj] 241 # Need to patch up here to ensure that correct file and var are used 242 self.vars.append(self.vars[0]) 243 self.infilePaths.append(self.infilePaths[0]) 244 elif self.plotClass.find("OVER")>-1: 245 plotClassList=self.plotClass.split("OVER") 246 # Reverse lists because 'OVER' means display last 247 plotClassList.reverse() 248 self.vars.reverse() 249 self.infilePaths.reverse() 192 250 else: 193 plotClassList=[self.plotClass] 194 195 # Loop through (note only relevant really for isoline and fill 196 for plotClass in plotClassList: 197 plotter=eval("%s(vcsCanvas, self.var(squeeze=1))" % plotClass) 251 plotClassList=[self.plotClass] 252 253 # Loop through for overlays 254 for count in range(len(plotClassList)): 255 thisPlotClass=plotClassList[count] 256 print thisPlotClass 257 infilePath=self.infilePaths[count] 258 var=self.vars[count] 259 260 if thisPlotClass.find("MultipleTrajectory")>-1: 261 area=self.bag.get("mapArea", None) 262 # Need special case for trajectories where whole file is sent 263 print "\n%s(vcsCanvas, infilePath, var.id, area, bbox=self.bbox)" % thisPlotClass 264 plotter=eval("%s(vcsCanvas, infilePath, var.id, area, bbox=self.bbox)" % thisPlotClass) 265 else: 266 print "\n%s(vcsCanvas, var(squeeze=1), bbox=self.bbox)" % thisPlotClass 267 plotter=eval("%s(vcsCanvas, var(squeeze=1), bbox=self.bbox)" % thisPlotClass) 198 268 199 if plotClass in ["YvsXGraph"]:269 if thisPlotClass in ["YvsXGraph", "MultipleTrajectory"]: 200 270 plotter.createPlot() 201 271 else: 202 272 plotter.createPlot(continentsSwitch=self.contSwitch) 203 273 204 274 # Plot appropriate output format 205 275 if self.fileFormat=="gif": … … 219 289 If animation is selected then control it here. 220 290 """ 221 291 self.var=self.vars[0] 222 292 plotter=eval("%s(vcsCanvas, self.var)" % self.plotClass) 223 293 … … 348 418 return (valueList, colourList) 349 419 350 351 352 353 420 354 421 if __name__=="__main__": 355 422 print "Trying to plot trajectory over model field...\n" 423 b=OutputManager({'status': 'complete', 'username': 'undefined', 'outputURLPath': 'http://localhost/gs/output/output_20061101192149.gif', 'graphicalOutputType': 'MultipleTrajectoriesOver2DLatLonPlot_2.2-3.1', 'projection': 'standard', 'proceed': 'Proceed', 'fileURIList': ['/data/trajbadc.nc', '/data/trajcf.nc', '/data/var2.nc'], 'userRoles': [], 'varDict': {'2.2': {'domain': {'grots': [['TrajectoriesOverMap', "Trajectories plotted on map for variable 'o3' from file: '/data/trajcf.nc'"], ['YvsXGraph', "Y-vs-X Graph for variable 'o3' from file: '/data/trajcf.nc'"]], 'time': ['time', 'time', [1.0, 432000.0]], 'ordered_axes': ['time'], 'bbox': (42.299999237060547, 22.5, 67.399986267089844, 126.36080169677734)}, 'id': 'o3'}, '2.2-3.1': {'domain': {'grots': [['MultipleTrajectoriesOver2DLatLonPlot', "Multiple Trajectories for variable 'o3' plotted over 2D Plot for variable 'var2' (files: /data/trajcf.nc, /data/var2.nc)"]], 'bbox': (40.299999237060547, 0, 69.399986267089844, 355)}}, '3.1': {'domain': {'latitude': ['latitude', 'latitude', [-90, 90]], 'grots': [['2DLatLonPlot', "2D Lat-Lon Plot for variable 'var2' from file: '/data/var2.nc'"]], 'ordered_axes': ['time', 'latitude', 'longitude'], 'longitude': ['longitude', 'longitude', [0, 355]], 'time': ['time', 'time', [0, 0]]}, 'id': 'var2'}}, 'fileVariable_2.2': 'o3', 'sessionID': 'session_20061101192119146', 'plotType': 'MultipleTrajectoryOverBoxfillLinear', 'mapArea': 'global', 'fileVariable_3.1': 'var2', 'outputFilePath': '/home/as56/apache/htdocs/gs/output/output_20061101192149.gif', 'fileFormat': 'gif', 'accessTime': 1162408909.777725, 'imageSize': '800x600'}) 424 b.createOutputs() 425 sys.exit() 426 427 b=OutputManager({'status': 'constructing', 'username': 'undefined', 'imageSize': '800x600', 'graphicalOutputType': 'MultipleTrajectoriesOver2DLatLonPlot_1.5-2.1', 'proceed': 'Proceed', 'fileVariable_1.5': 'temp', 'fileURIList': ['/data/traj.nc', '/data/var2.nc'], 'userRoles': [], 'varDict': {'1.5': {'domain': {'grots': [['TrajectoriesOverMap', "Trajectories plotted on map for variable 'temp' from file: '/data/traj.nc'"], ['2DPlot', "2D Plot for variable 'temp' from file: '/data/traj.nc'"]], 'parcel': ['parcel', 'unrecognised', [0.0, 1.0]], 'bbox': (42.299999237060547, 22.500001907348633, 67.399993896484375, 126.36080169677734), 'ordered_axes': ['time', 'parcel'], 'time': ['time', 'time', [0.0, 432000.0]]}, 'id': 'temp'}, '2.1': {'domain': {'latitude': ['latitude', 'latitude', [-90, 90]], 'grots': [['2DLatLonPlot', "2D Lat-Lon Plot for variable 'var2' from file: '/data/var2.nc'"]], 'ordered_axes': ['time', 'latitude', 'longitude'], 'longitude': ['longitude', 'longitude', [0, 355]], 'time': ['time', 'time', [0, 0]]}, 'id': 'var2'}, '1.5-2.1': {'domain': {'grots': [['MultipleTrajectoriesOver2DLatLonPlot', "Multiple Trajectories for variable 'temp' plotted over 2D Plot for variable 'var2'"]], 'bbox': (42.299999237060547, 0, 67.399993896484375, 355)}}}, 'sessionID': 'session_20061101181119418', 'fileVariable_2.1': 'var2', 'plotType': 'MultipleTrajectoryOverBoxfillLinear', 'mapArea': 'global', 'fileFormat': 'gif', 'accessTime': 1162404696.146235, 'projection': 'standard'} 428 ) 429 b.createOutputs() 430 sys.exit() 431 432 b=OutputManager({'mapArea':"global", 'outputURLPath': 'http://localhost/gs/output/output_20061004002742.gif', 'graphicalOutputType': 'TrajectoriesOverMap_1.1', 'projection': 'standard', 'getOutput':"getOutput", 'fileURIList': ['/data/traj.nc'], 'fileVariable_1.1': 'lat', 'sessionID': 'session_20061004002735159', 'plotType': 'MultipleTrajectory', 'outputFilePath': '/home/as56/apache/htdocs/gs/output/output_20061004002742.gif', 'fileFormat': 'gif', 'imageSize': '800x600'}) 433 b.createOutputs() 356 434 b=OutputManager({'fileVariable_1.1':'t', 'status': 'constructing', 'username': 'jane', 'accessTime': 1142557842.2275701, 'fileURIList': ['/data/dx/0d.nc'], 'userRoles': [], 'sessionID': 'session_20060317011041792', 'graphicalOutputType': 'PointValueAndMetadata_1.1', 'getOutput': 'getOutput'}) 357 sys.exit() 358 b=OutputManager({'status': 'constructing', 'username': None, 'outputURLPath': 'http://localhost/output/test.gif', 'fileURIList': ['/ srv/www/htdocs/output/jane/dx_output/output_20060316232539.nc'], 'imageSize': '300x200', 'confirm': 'Confirm', 'accessTime': 1142551623.3794341, 'userRoles': [], 'sessionID': 'session_20060316232622350', 'graphicalOutputType': 'YvsXGraph_1.1', 'plotType': 'YvsXGraph', 'proceed': 'Proceed', 'action': 'createOutput', 'outputFilePath': '/srv/www/htdocs/output/test.gif', 'fileFormat': 'postscript', 'getOutput': 'getOutput', 'fileVariable_1.1': 'var1'})435 436 b=OutputManager({'status': 'constructing', 'username': None, 'outputURLPath': 'http://localhost/output/test.gif', 'fileURIList': ['/data/var2.nc'], 'imageSize': '300x200', 'confirm': 'Confirm', 'accessTime': 1142551623.3794341, 'userRoles': [], 'sessionID': 'session_20060316232622350', 'graphicalOutputType': '2DLatLonPlot_1.1', 'plotType': 'boxfill', 'proceed': 'Proceed', 'action': 'createOutput', 'outputFilePath': '/srv/www/htdocs/output/test.gif', 'fileFormat': 'postscript', 'getOutput': 'getOutput', 'fileVariable_1.1': 'var2'}) 359 437 b.createOutputs() 360 438 sys.exit() -
TI04-geosplat/trunk/pygss/PlotClasses.py
r798 r1660 12 12 13 13 # Import standard libary modules 14 14 import cdms, vcs 15 15 16 16 # Import local modules 17 17 from serverConfig import * 18 from common import * 19 18 20 19 21 class YvsXGraph: … … 108 110 #print dataSlice.shape, dataSlice.getAxisIds() 109 111 #print dataSlice 110 self.canvas.plot(dataSlice, self.template, self.plot_type, continents=continentsSwitch, bg=1, file_comment=fileComment, comment1=SOURCE_NAME) 111 112 113 # elif animationArgs[0]=="time": 114 # self.canvas.plot(self.data(time=slice(animationArgs[1][0],animationArgs[1][1])), self.template, bg=1, continents=continentsSwitch, file_comment=fileComment, comment1=SOURCE_NAME) 115 # elif animationArgs[0]=="level": 116 # self.canvas.plot(self.data(level=slice(animationArgs[1][0],animationArgs[1][1])), self.template, bg=1, continents=continentsSwitch, file_comment=fileComment, comment1=SOURCE_NAME) 112 self.canvas.plot(dataSlice, self.template, self.plot_type, continents=continentsSwitch, bg=1, file_comment=fileComment, comment1=SOURCE_NAME) 117 113 118 114 … … 122 118 """ 123 119 124 def __init__(self, canvas, data ):120 def __init__(self, canvas, data, bbox=None): 125 121 self.canvas=canvas 122 self.bbox=bbox 126 123 try: 127 124 self.plot_type=canvas.createboxfill("new_boxfill","default") … … 149 146 except: 150 147 self.template=self.canvas.gettemplate("AMIP") 148 if self.bbox: # set up lat/lon limits 149 #d=self.template.data 150 #(d.y1,d.x1,d.y2,d.x2)=self.bbox 151 152 pt=self.plot_type 153 pt.datawc_x1=self.bbox[1] 154 pt.datawc_x2=self.bbox[3] 155 pt.datawc_y1=self.bbox[0] 156 pt.datawc_y2=self.bbox[2] 157 151 158 152 159 def createPlot(self, animationArgs=None, continentsSwitch=1): … … 155 162 """ 156 163 # The next line is a bug fix to stop part of the plot being chopped when background plot is set to 1 (on). 157 # self.canvas.open() 164 # self.canvas.open()) 158 165 if hasattr(self.data, "title"): 159 166 fileComment="Dataset: "+self.data.title … … 169 176 self.canvas.plot(dataSlice, self.template, self.plot_type, continents=continentsSwitch, bg=1, file_comment=fileComment, comment1=SOURCE_NAME) 170 177 178 171 179 #elif animationArgs[0]=="time": 172 180 # self.canvas.plot(self.data(time=slice(animationArgs[1][0],animationArgs[1][1])), self.template, self.plot_type, continents=continentsSwitch, bg=1, file_comment=fileComment, comment1=SOURCE_NAME) … … 289 297 290 298 291 299 class MultipleTrajectory: 300 """ 301 Plots multiple trajectories on the selected domain. 302 """ 303 def __init__(self, canvas, filePath, varID, area, bbox=None): 304 """ 305 Takes canvas and file and varID and calls other relevant methods. 306 """ 307 self.canvas=canvas 308 self.area=area 309 self.bbox=bbox 310 self.filePath=filePath 311 self.cdmsFile=cdms.open(filePath) 312 self.varID=varID 313 self._extractData() 314 self.titleTemplate=self._getTemplate("titlet") 315 self.tboxTemplate=self._getTemplate("tboxt") 316 317 def _extractData(self): 318 """ 319 Used to extract the appropriate data object. 320 Returns a dictionary of {"parcelID":[[y,x],[y,x]...]]} 321 """ 322 f=self.cdmsFile 323 self.data={} 324 325 # Get var ids of lat and lon in file 326 [latID, lonID]=identifyLatLonVarIDs(f) 327 if latID==None or lonID==None: 328 raise GSPlottingError, "Could not identify and latitude and longitude variable to plot trajectory." 329 330 # Now sort what needs plotting 331 lat=f[latID] 332 if lat.rank()==1: 333 lats=f(latID)[:].tolist() 334 lons=f(lonID)[:].tolist() 335 data=[[lats[i],lons[i]] for i in range(len(lats))] 336 self.data["single_traj"]=data[:] 337 else: # assume there is a parcel dimension as well 338 for parcel in range(len(lat[1])): 339 lats=f(latID)[:,parcel].tolist() 340 lons=f(lonID)[:,parcel].tolist() 341 data=[[lats[i],lons[i]] for i in range(len(lats))] 342 self.data[parcel]=data[:] 343 344 if hasattr(f[self.varID], "title"): 345 self.title=f[self.varID].title 346 return self.data 347 348 def _getTemplate(self, name): 349 """ 350 Sets up the appropriate template for a plot type. 351 """ 352 try: 353 t=self.canvas.createtemplate(name, VCS_TEMPLATES["no_levels"]) 354 except: 355 try: 356 t=self.canvas.createtemplate(name, "AMIP") 357 except: 358 t=self.canvas.gettemplate(name) 359 """try: 360 t=self.canvas.createtemplate(name, VCS_TEMPLATES["no_levels"]) 361 except: 362 t=self.canvas.gettemplate(name)""" 363 364 """box=t.box1 365 box.x1 = 0.0500000007451 366 box.y1 = 0.259999990463 367 box.x2 = 0.949999988079 368 box.y2 = 0.860000014305""" 369 data=t.data 370 #data.x1 = 0.0500000007451 371 #data.y1 = 0.263999560899 372 #data.x2 = 0.949999988079 373 #data.y2 = 0.856999927733 374 #print t.name,"\n\n\n" 375 if name=="titlet": 376 t.max.priority=0 377 t.min.priority=0 378 t.mean.priority=0 379 t.crdate.priority=0 380 t.units.priority=0 381 t.crtime.priority=0 382 t.dataname.priority=0 383 t.legend.priority=0 384 t.comment1.priority=1 385 386 try: 387 title=self.canvas.createtexttable("title_stuff") 388 except: 389 title=self.canvas.gettexttable("title_stuff") 390 title.font=1 391 t.title.texttable=title 392 try: 393 titleto=self.canvas.createtextorientation("title_textorient") 394 except: 395 titleto=self.canvas.gettextorientation("title_textorient") 396 titleto.height=30 397 print t.title.list() 398 t.title.x=0.13 399 t.title.y=0.99 400 t.title.textorientation=titleto 401 return t 402 403 def _prepareContinents(self, bbox): 404 """ 405 Prepares continents for plot. 406 """ 407 try: 408 c=self.canvas.createcontinents("c1") 409 except: 410 c=self.canvas.getcontinents("c1") 411 412 c.datawc_x1=bbox[1] 413 c.datawc_x2=bbox[3] 414 c.datawc_y1=bbox[0] 415 c.datawc_y2=bbox[2] 416 c.xticlabels1="*" 417 c.xticlabels2="*" 418 c.yticlabels1="*" 419 c.yticlabels2="*" 420 return c 421 422 def _convertWC(self, i, xory, bbox, tbox): 423 """ 424 Converts World Coordinates to pixel coordinates. 425 """ 426 [y1,x1,y2,x2]=bbox 427 [boty,botx,topy,topx]=tbox 428 if xory=="x": 429 return ((i-x1)/(x2-x1)*(topx-botx))+botx 430 elif xory=="y": 431 return ((i-y1)/(y2-y1)*(topy-boty))+boty 432 433 def _getExtent(self, datadict): 434 """ 435 Returns the full extent of all trajectories. 436 """ 437 maxLat=-91; 438 maxLon=-361 439 minLat=91 440 minLon=361 441 for key,data in datadict.items(): 442 for (y,x) in data: 443 if y>maxLat: maxLat=y 444 if y<minLat: minLat=y 445 if x>maxLon: maxLon=x 446 if x<minLon: minLon=x 447 return (minLat,minLon,maxLat,maxLon) 448 449 def createPlot(self): 450 """ 451 Plots the output and saves to a file. 452 """ 453 if hasattr(self, "title"): 454 fileComment="Dataset: "+self.title 455 else: 456 fileComment="" 457 458 datadict=self.data 459 if self.bbox: 460 bbox=self.bbox 461 else: 462 bbox=self._getExtent(datadict) 463 (y1,x1,y2,x2)=bbox 464 465 domain=self.area 466 if domain=="global": 467 bbox=[-90,(x1-20),90,(x1+340)] 468 elif domain=="northernHemisphere": 469 bbox=[0,(x1-20),90,(x1+340)] 470 elif domain=="southernHemisphere": 471 bbox=[-90,(x1-20),0,(x1+340)] 472 else: 473 bbox=[(y1-5),(x1-5),(y2+5),(x2+5)] 474 475 c=self._prepareContinents(bbox) 476 t=self.tboxTemplate 477 d=t.data 478 tbox=(d.y1,d.x1,d.y2,d.x2) 479 480 self.canvas.plot(c, t, bg=1) 481 482 parcels=datadict.keys() 483 parcels.sort() 484 485 colourRange=range(30,180,10)*50 486 count=0 487 488 for p in parcels: 489 data=datadict[p] 490 col=colourRange[count] 491 try: 492 marker=self.canvas.createmarker("markertest%s"%count) 493 except: 494 marker=self.canvas.getmarker("markertest%s"%count) 495 marker.y=[self._convertWC(data[0][0],"y",bbox,tbox)] 496 marker.x=[self._convertWC(data[0][1],"x",bbox,tbox)] 497 marker.size=[4.0] 498 marker.type=["circle"] 499 marker.color=[col] 500 self.canvas.plot(marker,t,bg=1) 501 502 try: 503 line=self.canvas.createline("trajline%s"%count) 504 except: 505 line=self.canvas.getline("trajline%s"%count) 506 507 line.y=[self._convertWC(i[0],"y",bbox,tbox) for i in data] 508 line.x=[self._convertWC(i[1],"x",bbox,tbox) for i in data] 509 line.color=[col] 510 count+=1 511 self.canvas.plot(line, t, bg=1) 512 513 # Now plot a title 514 self.canvas.plot([0,0], self.titleTemplate, bg=1, title="Plot of trajectory data from file: %s" % self.filePath)#, bg=1, file_comment=fileComment, comment1=SOURCE_NAME) 515 516 517 518 if __name__=="__main__": 519 import vcs, cdms 520 vcsCanvas=vcs.init() 521 infile="/data/traj.nc" 522 varid="temp" 523 plotClass="MultipleTrajectory" 524 plotter=eval("%s(vcsCanvas, infile, varid, 'global')" % plotClass) 525 print "done" 526 plotter.createPlot() 527 -
TI04-geosplat/trunk/pygss/VariableAnalyser.py
r798 r1660 26 26 27 27 # Import external modules 28 import cdms 28 import cdms, genutil 29 29 30 30 class VariableAnalyser: … … 33 33 """ 34 34 35 def __init__(self, filename , varID, graphicalOutputType=None, animationAxes=None):35 def __init__(self, filename=None, varID=None, graphicalOutputType=None, animationAxes=None, domainDict=None): 36 36 """ 37 37 Takes a variable and analyses it to return a known Feature type. … … 40 40 self.filename=filename 41 41 self.varID=varID 42 cdmsfile=cdms.open(self.filename) 43 self.var=cdmsfile[varID] 44 self._analyse(graphicalOutputType, animationAxes) 45 cdmsfile.close() 42 self.domainDict=domainDict 43 44 if (self.filename==None and self.varID==None) and self.domainDict==None: 45 raise GSOptionHandlingError, "VariableAnalyser needs either filename/varID or domainDict as valid arguments." 46 47 if self.domainDict: 48 # Call the code to get 49 self._analyse(graphicalOutputType, animationAxes) 50 else: 51 cdmsfile=cdms.open(self.filename) 52 self.var=cdmsfile[varID] 53 self._analyse(graphicalOutputType, animationAxes) 54 cdmsfile.close() 46 55 47 56 … … 51 60 """ 52 61 if graphicalOutputType==None: 53 ft=self._getFeatureType() 54 self.plotOpts=self._getGraphicalOutputTypes(ft) 55 else: 56 print graphicalOutputType*10 62 fts=self._getFeatureTypes() 63 if type(fts)==type("string"): fts=[fts] 64 self.plotOpts=[] 65 for ft in fts: 66 self.plotOpts.append(self._getGraphicalOutputTypes(ft)[0]) 67 # Add graphical output types to domainDict 68 self.domainDict["grots"]=self.plotOpts 69 else: 57 70 self.plotConfigurationDict=self._getPlotConfigurationDetails(graphicalOutputType, animationAxes) 58 71 59 72 60 def _getFeatureType (self):73 def _getFeatureTypes(self): 61 74 """ 62 75 Return Feature Type if can be identified, otherwise returns None. 63 76 """ 64 65 77 axes=self.var.getAxisList() 78 79 # Save axes to self.domainDict for use on next call 80 self.domainDict={} 81 orderedList=[] 82 for axis in axes: 83 id=axis.id 84 if axis.isTime(): 85 known="time" 86 elif axis.isLevel(): 87 known="level" 88 elif axis.isLatitude(): 89 known="latitude" 90 elif axis.isLongitude(): 91 known="longitude" 92 else: 93 known="unrecognised" 94 (low, high)=(axis[0], axis[-1]) 95 self.domainDict[id]=[id, known, [low,high]] 96 orderedList.append(id) 97 98 self.domainDict["ordered_axes"]=orderedList 99 66 100 shape=self.var.shape 67 101 size=self.var.size() … … 76 110 77 111 ndims=len(usefulAxes) 112 78 113 if ndims==1: 79 return "ProfileFeature" 114 trajCheck=self._checkForTrajectoryFeature() 115 if trajCheck: 116 self.domainDict["bbox"]=trajCheck # which is (y1,x1,y2,x2) 117 return ["TrajectoryFeature", "ProfileFeature"] 118 else: 119 return "ProfileFeature" 80 120 elif ndims==2: 81 return "2DGridFeature" 121 trajCheck=self._checkForTrajectoryFeature() 122 if trajCheck: 123 self.domainDict["bbox"]=trajCheck # which is (y1,x1,y2,x2) 124 return ["TrajectoryFeature", "2DGridFeature"] 125 else: 126 if self._testLatLon(axes): 127 return "2DLatLonGridFeature" 128 else: 129 return "2DGridFeature" 82 130 elif ndims>2: 83 131 return "%sDGridFeature" % ndims 84 132 else: 133 raise GSSelectionError, "Could not identify any useful data in this file." 134 85 135 86 136 def _getGraphicalOutputTypes(self, featureType): … … 92 142 93 143 if ft=="PointFeature": 94 return [["PointValue AndMetadata", "Display single value for variable '%s' from file: '%s'" % (self.varID, self.filename)]]144 return [["PointValuetrueAndMetadata", "Display single value for variable '%s' from file: '%s'" % (self.varID, self.filename)]] 95 145 96 146 elif ft=="ProfileFeature": … … 99 149 elif ft=="2DGridFeature": 100 150 return [["2DPlot", "2D Plot for variable '%s' from file: '%s'" % (self.varID, self.filename)]] 151 152 elif ft=="2DLatLonGridFeature": 153 return [["2DLatLonPlot", "2D Lat-Lon Plot for variable '%s' from file: '%s'" % (self.varID, self.filename)]] 154 155 elif ft=="TrajectoryFeature": 156 return [["TrajectoriesOverMap", "Trajectories plotted on map for variable '%s' from file: '%s'" % (self.varID, self.filename)]] 101 157 102 158 else: … … 117 173 118 174 119 elif grot in ("2DPlot", "Animation"): 120 175 elif grot in ("2DPlot", "2DLatLonPlot", "Animation"): 176 177 # Note that domainDict should hold axes as: 178 # id:[id, known_as, [low,high]] 121 179 if animationAxes!=None: 122 180 … … 125 183 126 184 for axID in (loopID, yID, xID): 127 axis=self. var.getAxis(self.var.getAxisIds().index(axID))185 axis=self.domainDict[axID] 128 186 axisList.append(axis) 129 187 130 188 else: 131 189 axisList=[] 132 for axis in self.var.getAxisList(): 133 if len(axis)>1: 190 print self.domainDict 191 orderedList=[self.domainDict[axisID] for axisID in self.domainDict["ordered_axes"]] 192 for axis in orderedList: 193 if len(axis[2])>1: 134 194 axisList.append(axis) 135 195 136 latLonAxesTest=self._testLatLon(axisList[-2:])137 138 if latLonAxesTest:196 if grot in ("2DLatLonPlot",): 197 latLonAxesTest=self._testLatLon(axisList[-2:]) 198 if latLonAxesTest: 139 199 plotConfigDict["continentsSwitch"]=[["on", "Show continents"], ["off", "Do not show continents"]] 140 200 … … 153 213 plotConfigDict["projection"]=projections 154 214 155 if grot =="2DPlot":215 if grot in ("2DPlot", "2DLatLonPlot"): 156 216 plotTypes=[["boxfill", "Boxfill"],["isofill", "Isofill"], 157 217 ["isoline", "Isoline"],["isolineAndFill", "Isoline and Isofill"]] … … 162 222 plotConfigDict["plotType"]=plotTypes 163 223 164 224 elif grot in ("TrajectoriesOverMap",): 225 plotConfigDict["plotType"]=[["MultipleTrajectory", "Multiple Trajectory Plot"]] 226 plotConfigDict["projection"]=[["standard", "Standard"]] 227 plotConfigDict["mapArea"]=[["surroundingArea","Surrounding Area"],["global","Global"]] 228 229 elif grot in ("MultipleTrajectoriesOver2DLatLonPlot",): 230 plotConfigDict["plotType"]=[["MultipleTrajectoryOverBoxfillLinear", "Multiple Trajectory Plot over Boxfill Lat-Lon Plot"]] 231 plotConfigDict["projection"]=[["standard", "Standard"]] 232 plotConfigDict["mapArea"]=[["surroundingArea","Surrounding Area"],["global","Global"]] 233 165 234 # Start with the easy one, image sizes 166 235 imageSizes=["800 x 600", "300 x 200", "600 x 400", "792 x 612", "1000 x 800"] … … 170 239 171 240 # Then file format, also straightforward 241 172 242 if grot=="Animation": 173 243 fileFormats=["GIF"] … … 180 250 181 251 252 #def _getPlotConfigurationDetailsDEPRECATED(self, graphicalOutputType, animationAxes=None): 253 """ 254 Returns plot configuration details in a dictionary of options 255 where each value is a list of lists holding the short name and long name 256 of the available options. 257 """ 258 """plotConfigDict={} 259 grot=graphicalOutputType 260 print grot 261 if grot=="YvsXGraph": 262 plotConfigDict["plotType"]=[["YvsXGraph", "Y-vs-X Graph"]] 263 264 265 elif grot in ("2DPlot", "2DLatLonPlot", "Animation"): 266 267 if animationAxes!=None: 268 269 (loopID, yID, xID)=animationAxes 270 axisList=[] 271 272 for axID in (loopID, yID, xID): 273 axis=self.var.getAxis(self.var.getAxisIds().index(axID)) 274 axisList.append(axis) 275 276 else: 277 axisList=[] 278 for axis in self.var.getAxisList(): 279 if len(axis)>1: 280 axisList.append(axis) 281 282 if grot in ("2DLatLonPlot",): 283 latLonAxesTest=self._testLatLon(axisList[-2:]) 284 if latLonAxesTest: 285 plotConfigDict["continentsSwitch"]=[["on", "Show continents"], ["off", "Do not show continents"]] 286 287 [[south, north], [west, east]]=latLonAxesTest 288 289 projections=[["standard", "Standard"]] 290 if (east-west)>200: # Need 200+ degrees west-east to use projections safely 291 projections.append(["mollweide", "Mollweide"]) 292 projections.append(["robinson", "Robinson"]) 293 294 if north>80 and south<10: 295 projections.append(["northPolar", "Polar (Northern Hemisphere)"]) 296 if north>-10 and south<-80: 297 projections.append(["southPolar", "Polar (Southern Hemisphere)"]) 298 299 plotConfigDict["projection"]=projections 300 301 if grot in ("2DPlot", "2DLatLonPlot"): 302 plotTypes=[["boxfill", "Boxfill"],["isofill", "Isofill"], 303 ["isoline", "Isoline"],["isolineAndFill", "Isoline and Isofill"]] 304 elif grot=="Animation": 305 plotTypes=[["boxfill", "Boxfill"],["isofill", "Isofill"], 306 ["isoline", "Isoline"]] 307 308 plotConfigDict["plotType"]=plotTypes 309 310 elif grot in ("TrajectoriesOverMap",): 311 plotConfigDict["plotType"]=[["MultipleTrajectory", "Multiple Trajectory Plot"]] 312 plotConfigDict["projection"]=[["standard", "Standard"]] 313 plotConfigDict["mapArea"]=[["surroundingArea","Surrounding Area"],["global","Global"]] 314 315 elif grot in ("MultipleTrajectoriesOver2DLatLonPlot",): 316 plotConfigDict["plotType"]=[["MultipleTrajectory", "Multiple Trajectory Plot"]] 317 plotConfigDict["projection"]=[["standard", "Standard"]] 318 plotConfigDict["mapArea"]=[["surroundingArea","Surrounding Area"],["global","Global"]] 319 320 # Start with the easy one, image sizes 321 imageSizes=["800 x 600", "300 x 200", "600 x 400", "792 x 612", "1000 x 800"] 322 imageSizesLists=[[i.replace(" ",""), i] for i in imageSizes] 323 324 plotConfigDict["imageSize"]=imageSizesLists 325 326 # Then file format, also straightforward 327 328 if grot=="Animation": 329 fileFormats=["GIF"] 330 else: 331 fileFormats=["GIF", "Postscript"] 332 fileFormatsLists=[[i.lower(), i] for i in fileFormats] 333 plotConfigDict["fileFormat"]=fileFormatsLists 334 335 return plotConfigDict""" 336 337 338 182 339 def _testLatLon(self, axes): 183 340 """ … … 187 344 latFound=None 188 345 lonFound=None 189 for ax in axes: 190 if len(ax)>1: 191 if ax.isLatitude(): latFound=minmax(ax) 192 if ax.isLongitude(): lonFound=minmax(ax) 346 347 if type(axes[0])==type([1,2]): # set up from domainDict 348 for ax in axes: 349 if len(ax[2])>1: 350 if ax[1]=="latitude": latFound=ax[2] 351 if ax[1]=="longitude": lonFound=ax[2] 352 else: # type is cdms.axis 353 for ax in axes: 354 if len(ax)>1: 355 if ax.isLatitude(): latFound=minmax(ax) 356 if ax.isLongitude(): lonFound=minmax(ax) 357 193 358 if latFound and lonFound: 194 359 return (latFound, lonFound) 195 360 196 361 362 def _checkForTrajectoryFeature(self): 363 """ 364 Returns 1 if it is a trajectory feature. 365 """ 366 axisList=self.var.getAxisList() 367 if not axisList[0].isTime(): 368 return None 369 370 if len(axisList)>1 and axisList[1].id!="parcel": 371 return None 372 373 # If axes look right check that we have lat and lon defined 374 # against time as well 375 fname=self.filename 376 cdmsFile=cdms.open(fname) 377 varNames=[i.lower() for i in cdmsFile.listvariables()] 378 latNames=["latitude","lat","lt"] 379 lonNames=["longitude","lon","lng"] 380 if overlap(varNames, latNames) and overlap(varNames, lonNames): 381 for lnm in latNames: 382 try: 383 lat=cdmsFile(lnm) 384 except: 385 pass 386 for lom in lonNames: 387 try: 388 lon=cdmsFile(lom) 389 except: 390 pass 391 print "Calculating bounding box for traj data..." 392 (y1,y2)=genutil.minmax(lat) # south, north 393 (x1,x2)=genutil.minmax(lon) 394 return (y1,x1,y2,x2) 395 else: 396 return None 397 398 399 197 400 if __name__=="__main__": 198 v=VariableAnalyser("/tmp/tmp.nc", "var1") 401 a=VariableAnalyser("/data/var2.nc", "var2") 402 print a.plotOpts 403 a=VariableAnalyser(graphicalOutputType="2DLatLonPlot", domainDict={"ordered_axes":["time","latitude","longitude"], 404 "time":["time","time",[0,4]], 405 "latitude":["latitude","latitude",[0,90]], 406 "longitude":["longitude","longitude",[0,359]]}) 407 print a.plotConfigurationDict 408 a=VariableAnalyser("/data/traj.nc", "theta") 409 print a.plotOpts 410 a=VariableAnalyser("/data/traj.nc", "theta", "TrajectoriesOverMap") 411 print a.plotConfigurationDict 412 v=VariableAnalyser("/data/var1.nc", "pqn") 413 print v.plotOpts 414 v=VariableAnalyser("/data/var1.nc", "pqn") 199 415 print v.plotOpts 200 a=VariableAnalyser("/tmp/tmp.nc", "var1", "2DPlot") 201 print a.plotConfigurationDict 416 #a=VariableAnalyser("/data/var1.nc", "pqn", "2DPlot") 417 #print a.plotConfigurationDict 418 419 -
TI04-geosplat/trunk/pygss/__init__.py
r798 r1660 64 64 from FeatureTypes import FeatureTypes 65 65 66 # VariableAnalyser analyses single variables 67 from VariableAnalyser import VariableAnalyser 68 69 # CombinedPlotManager works out if any overlays are possible/acceptable 70 from CombinedPlotManager import CombinedPlotManager 71 66 72 # GSErrors holds all the GeoSPlAT error classes 67 73 from GSErrors import * -
TI04-geosplat/trunk/pygss/common.py
r798 r1660 25 25 "resolution", "vertical_units", "vertical_domain", 26 26 "outputFormat") 27 28 GRAPHICAL_OUTPUT_TYPES_OR_STRING="PointValueAndMetadata|YvsXGraph|2DPlot|2DLatLonPlot|Animation|TrajectoriesOverMap|MultipleTrajectoriesOver2DLatLonPlot" 29 GRAPHICAL_OUTPUT_TYPES=GRAPHICAL_OUTPUT_TYPES_OR_STRING.split("|") 27 30 28 31 # Set up common functions … … 66 69 return rtarray 67 70 68 71 def normaliseXCoord(x): 72 """ 73 Converts x values to somewhere in range (0,360) 74 """ 75 if x<0: 76 return x+360 77 return x 78 79 def getSpatialOverlap(bbox1, bbox2): 80 """ 81 If no spatial overlap (i.e. < 2 deg of overlap in lat or lon) 82 then return None. Otherwise return the bounding box that covers 83 both in a way that will be useful to plot. This may shift a global 84 coverage to a new startX, endX. 85 """ 86 threshold=2 # degrees 87 t=threshold # quicker to type 88 (ya,xa,yb,xb)=bbox1 # (south,west,north,east) 89 (yc,xc,yd,xd)=bbox2 90 91 n=normaliseXCoord 92 xa=n(xa) 93 xb=n(xb) 94 xc=n(xc) 95 xd=n(xd) 96 97 if xc>=(xb-t) or xd<=(xa+t): return None 98 if yd<=(ya+t) or yc>=(yb-2): return None 99 100 ybot=max(ya,yc) 101 ytop=min(yb,yd) 102 xbot=min(xa,xc) 103 xtop=max(xb,xd) 104 105 # Now create a slight buffer so not touching edges (unless 90N and 90S) 106 ytop=ytop+t 107 ybot=ybot-t 108 if ytop>90: ytop=90 109 if ybot<-90: ybot=-90 110 111 return (ybot,xbot,ytop,xtop) 112 113 114 def getattrNone(item, attr): 115 """ 116 Returns the attr of item or None. 117 """ 118 if not hasattr(item, attr): 119 return None 120 return getattr(item, attr) 121 122 def identifyLatLonVarIDs(cdmsFile): 123 """ 124 Returns list of latID and lonID in file or cdmsFile object. 125 Any not found are returned as "None" type. 126 """ 127 if type(cdmsFile)==type("filename"): 128 import cdms 129 f=cdms.open(cdmsFile) 130 else: 131 f=cdmsFile 132 varIDs=f.listvariables() 133 latLon=[None, None] 134 135 lonPoss=("longitude", "Longitude", "Lon", "lon", "Lng", "lng") 136 latPoss=("latitude", "Latitude", "Lat", "lat") 137 138 for varID in varIDs: 139 var=f[varID] 140 if getattrNone(var, "standard_name")=="latitude": latLon[0]=varID 141 if getattrNone(var, "standard_name")=="longitude": latLon[1]=varID 142 if getattrNone(var, "long_name") in latPoss: latLon[0]=varID 143 if getattrNone(var, "long_name") in lonPoss: latLon[1]=varID 144 if varID in latPoss: latLon[0]=varID 145 if varID in lonPoss: latLon[1]=varID 146 147 return latLon 148 69 149 def translateURI(uri): 70 150 """ -
TI04-geosplat/trunk/pygss/serverConfig.py
r798 r1660 121 121 # "/usr/local/gss" is recommended but you can change it as 122 122 # you wish. 123 BASEDIR="/ home/as56/abstractWebService/gss"123 BASEDIR="/usr/local/test/gss" 124 124 125 125 # OUTPUT_DIR: 126 126 # The full path on the local machine of the output directory. 127 OUTPUT_DIR="/ srv/www/htdocs/output"127 OUTPUT_DIR="/home/as56/apache/htdocs/gs/output" 128 128 129 129 # OUTPUT_DIR_URL: 130 130 # URL path to output directory. 131 OUTPUT_DIR_URL="http://localhost/ output"131 OUTPUT_DIR_URL="http://localhost/gs/output" 132 132 133 133 # SESSION_OBJECT_DIR: … … 162 162 # OUTPUT_FORMATS: 163 163 # List of available output formats. 164 OUTPUT_FORMATS=[" NetCDF", "NASA Ames"]164 OUTPUT_FORMATS=["GIF", "Postscript", "CGM"] 165 165 166 166 # LOCAL_PYTHONPATH: … … 186 186 # SOURCE_NAME: 187 187 # String to appear on plots. 188 SOURCE_NAME="Source: British Atmospheric Data Centre (http://badc.nerc.ac.uk)"188 SOURCE_NAME="Source: YOUR_ORGANISATION" 189 189 190 190 # CDAT_BIN_PATH: -
TI04-geosplat/trunk/pygss/version.py
r1210 r1660 11 11 """ 12 12 13 version="0.3. 0"13 version="0.3.1" -
TI04-geosplat/trunk/setup.py
r1210 r1660 38 38 import sys, os, shutil, time, re 39 39 from ConfigParser import ConfigParser 40 version="0.3. 0"40 version="0.3.1" 41 41 overwrite="OFF" 42 42 … … 157 157 print "Exiting setup without completing." 158 158 sys.exit() 159 159 160 160 161 if not os.path.isdir(BASEDIR): … … 168 169 target=os.path.join(BASEDIR, item) 169 170 if os.path.exists(target): 171 if item in ("sessionObjects", "logs"): continue 170 172 os.system("rm -fr %s" % target) 171 173
Note: See TracChangeset
for help on using the changeset viewer.