# ============================================================================ # ============================================================================ ''' carboKML_*.py Takes the dumps from carboLOT and makes interesting KML displays ''' # ========================= 2 2 2 2 2 2 2 2 2 2 2 2 ========================== # ============================================================================ import time,os,glob import sys import numpy as NPY import matplotlib as MPL import matplotlib.pyplot as PLT import matplotlib.path as PATH import matplotlib.patches as PATCHES import matplotlib.colors as COL from matplotlib.transforms import Affine2D # ============================================================================ # ============================================================================ def getSetUp(): loudQ=False #Determines whether run screen is verbose #(Not a global: different each module)iCr,kbWdHabittA #Read the author-edited setup file ... # and assign the values to variables in the program setUpF=open(dirS+"_"+prjS+"_SETUP.txt","r") setUpS=setUpF.read() #All in one gulp setUpS=setUpS+"\n" setUpF.close() setUpDataA=[] paramsA=['prjA','lolaA','modlSZa','modlRESN','showA','sectnA',\ 'tStart','tStop','tStep','tRept','tCompute','tBurstLen',\ 'sStart'] formatsA=['textA','floatA','intA','float','intA','intA',\ 'int','int','int','int','int','int',\ 'text'] valuesA=[] setUpLinesA=setUpS.split("\n") for setUpLine in setUpLinesA: if setUpLine.strip()<>"": setUpDataS=setUpLine.split("\t")[0] if setUpDataS.strip()[0]<>"#": setUpDataS=setUpDataS.strip()\ .replace("[","").replace("]","")\ .replace('"',"") setUpValuA=setUpDataS.split("=") print "setUpValuA=|",setUpValuA,"|",setUpValuA[:][0] try: datIdx=paramsA.index(setUpValuA[0]) except: print "Revise the startup - parameter ",setUpValuA[0] raw_input (" not expected !") if formatsA[datIdx]=="float": setUpValuA[1]=float(setUpValuA[1]) elif formatsA[datIdx]=="int": setUpValuA[1]=int(setUpValuA[1]) elif formatsA[datIdx]=="intA": setUpValuA[1]=map(int,setUpValuA[1].split(",")) elif formatsA[datIdx]=="floatA": setUpValuA[1]=map(float,setUpValuA[1].split(",")) elif formatsA[datIdx]=="textA": setUpValuA[1]=setUpValuA[1].split(",") elif formatsA[datIdx]=="text": pass #Unchanged valuesA.append(setUpValuA[1]) #print "datIdx,paramsA[],formatsA[],valuesA=",\ # datIdx,paramsA[datIdx],formatsA[datIdx],valuesA[datIdx] print "paramsA,formatsA,valuesA=",\ paramsA,formatsA,valuesA print "<'] kmlOutF.write("\n".join(outA)+"\n") elif stageQ=="area": #Make a transparent map rectangle... outA=['','',\ ''+'carboLOT modelBox'+'',\ '1',\ ''] kmlOutF.write("\n".join(outA)+"\n") outA=['',\ ''+prjS+":"+runS+'',\ '#modelBox',\ '',\ ' '+str(lolaA[0])+'',\ ' '+str(lolaA[1])+'',\ ' 000',\ ' 60',\ ' 36000',\ ' relativeToSeaFloor',\ ''] kmlOutF.write("\n".join(outA)+"\n") ulA=[llA[0]+0., llA[1]+float(modlSZy)*modlRESN] urA=[llA[0]+float(modlSZx)*modlRESN,llA[1]+float(modlSZy)*modlRESN] lrA=[llA[0]+float(modlSZx)*modlRESN,llA[1]+0.] outA=['',\ '1',\ '1',\ 'absolute ',\ '',\ ' ',\ ' ',\ ' '+",".join(map(str,llA)),\ ' '+",".join(map(str,ulA)),\ ' '+",".join(map(str,urA)),\ ' '+",".join(map(str,lrA)),\ ' '+",".join(map(str,llA)),\ ' ',\ ' ',\ '',\ '',\ '',\ ''] kmlOutF.write("\n".join(outA)+"\n") elif stageQ=="points": #Write all the modelling points ... # (Withdrawn in favour of the boxes) ''' outA=['','',\ ''+'carboLOT modelPoints'+'',\ '0'] kmlOutF.write("\n".join(outA)+"\n") for xcell in range(modlSZx): for ycell in range(modlSZy): lolawdPntA=[llA[0]+(float(xcell)+0.5)*modlRESN,\ llA[1]+(float(xcell)+0.5)*modlRESN,0.] pointCodeS=str(xcell)+":"+str(ycell) outA=['',\ '',\ '1',\ 'absolute',\ '',\ ' '+",".join(map(str,lolawdPntA)),\ '',\ '',\ ''] kmlOutF.write("\n".join(outA)+"\n") outA=[''] kmlOutF.write("\n".join(outA)+"\n") ''' pass elif stageQ=="columns": #Write all the modelling boxes ... outA=['','',\ ''+'carboLOT modelColumns'+'',\ '0'] kmlOutF.write("\n".join(outA)+"\n") columnSidesA=[[0.,0.],[0.,1.],[1.,1.],[1.,0.]] #Will multiply by cellSZ/5 for xcell in range(modlSZx): for ycell in range(modlSZy): lolawdPntA=[llA[0]+(float(xcell)+0.5)*modlRESN,\ llA[1]+(float(ycell)+0.5)*modlRESN,0.] pointCodeS=str(xcell)+":"+str(ycell) columnX=[];columnY=[] for colX in columnSidesA: columnX.append(lolawdPntA[0]+colX[0]*modlRESN/5.) for colY in columnSidesA: columnY.append(lolawdPntA[1]+colY[1]*modlRESN/5.) columnZ=[100]*len(columnY) #print "columnX=",columnX #print "columnY=",columnY columnXYZ=zip(columnX,columnY,columnZ) columnXYZ.append(columnXYZ[0]) #Closes the rings #print "columnXYZ=",columnXYZ,len(columnXYZ) columnS="\n".join(map(str,columnXYZ)) columnS=columnS.replace("(","").replace(")","") while " " in columnS: columnS=columnS.replace(" ","") outA=['',\ '',\ '',\ ' 0',\ ' 1',\ ' 1',\ ' relativeToSeaFloor',\ ' ',\ ' '+columnS,\ '',\ '',\ '',\ ''] '''Now spare... '',\ '',\ ' '+",".join(map(str,lolawdPntA)),\ '',\ '',\ ''' kmlOutF.write("\n".join(outA)+"\n") outA=[''] kmlOutF.write("\n".join(outA)+"\n") elif stageQ=="end": outA=[''] kmlOutF.write("\n".join(outA)+"\n") kmlOutF.close() else: raw_input("Bad stageQ option ! |"+stageQ+"|") return # ============================================================================ def drawPie(lablsA,frxnsA): print;print ">>drawPie:" #Draws a unit pie diagram from a set of percentages/fractions # like [34,2,6,23,35][a,b,c,d,e] #Any unknown will be drawn dark grey #Add the unknown... frxnsA=map(int,frxnsA) frxnsA.append(100-sum(frxnsA)) lablsA.append("unspec") #Plotting (after... #"http://stackoverflow.com/questions/3816809/how-to-plot-a-pie-chart-with-the-first-wedge-on-top-in-python-matplotlib" plt.figure() #plt.suptitle("Things I narrowly missed while learning to drive") wedges, labels = plt.pie(frxnsA, labels=lablsA) plt.axis('equal') print "wedges=",wedges starting_angle = 90 rotation = Affine2D().rotate(np.radians(starting_angle)) for wedge, label in zip(wedges, labels): label.set_position(rotation.transform(label.get_position())) if label._frxnsA > 0: label.set_horizontalalignment('left') else: label.set_horizontalalignment('right') wedge._path = wedge._path.transformed(rotation) plt.show() return # ============================================================================ def stockPanel(): import random as RND #Gets the statistics from eg: "_StockDumps/_live_0_0.txt" # and feeds them to pie or random to draw images for putting intoKML stockTypeS="_dead_" #"_live_" panelDirS=runDirS+"_KmlPanels/" for xcell in range(modlSZx): for ycell in range(modlSZy): dataF=open(runDirS+"_StockDumps/"+\ stockTypeS+str(xcell)+"_"+str(ycell)+".txt","r") while dataF: dataS=dataF.readline() if dataS=="": break #EOF dataA=dataS.strip().split(";") if dataA=="": pass else: if "[" in dataA: print "dataA=",dataA evalQ=False stockVa=[] #0. cell string; 1. time; 2. stocks time=int(dataA[1].replace("T=","")) stockS=dataA[2].replace("Stocks=","")\ .replace("Dead=","") stockA=[dS for dS in stockS.split(",")] for stock in stockA: if "e" in stock: stock=stock.split("e") #print "for eval: ",stock[0]+'*10.**('+stock[1]+")" evalQ=True stockV=eval(stock[0]+'*10.**'+stock[1]) else: try: stockV=float(stock) except: print dataS stockVa.append(stockV) print "stockVa=",stockVa #if evalQ: raw_input("eval !") #Now make the random plot image #a. Distribute the values according to frequency sumVa=sum(stockVa) if sumVa<>0: stockVa=[int(sVa/sumVa*10) for sVa in stockVa] print "norm-10: stockVa=",stockVa freqVa=[];nVa=-1 for sVa in stockVa: nVa+=1 freqVa.extend([float(nVa) for fVa in range(sVa)]) while len(freqVa)<10: freqVa.extend([-1.]) RND.shuffle(freqVa) freqVa=[freqVa] print "freqVa=",freqVa else: #grey panel... freqVa=[[-1.]*10] #b. freqVa=NPY.array(freqVa) print "freqVa=",freqVa fig = PLT.figure(num=None, figsize=(10.,1.)) PLT.pcolor(freqVa, axes=None) for ax in fig.axes: ax.grid(False) PLT.savefig(\ panelDirS+str(xcell)+"_"+str(ycell)+"_"+str(time)+".png", \ edgecolor=None, format="png") fig.show() raw_input("!") dataF.close() return # ============================================================================ #myMAIN: global dirS,runDirS global prjA,lolaA,modlSZa,modlRESN global modlSZx,modlSZy global LoLfHtWdA,llA #Set the work addresses ------------------------------- kyS="" while kyS=="": kyS=raw_input("Name the existing project...") if kyS.lower() in ["chag","midw","agin"]: prjS=kyS else: kyS="" dirS="_"+prjS+"/" print kyS,prjS,dirS #Pickup the reference to the last run lastRunF=open(dirS+"_lastRun.txt","r") lastRunS=lastRunF.read().strip() lastRunF.close() kyS="" while kyS=="": kyS=raw_input("Use the last run ? (y./else name another)") if kyS.lower().replace("y","")=="": runS=lastRunS runDirS=dirS+runS+"/" print "Will use the last" else: kyS="" print "Working on project-run at: ",prjS,dirS,runDirS #Start the KML with project geography ----------- valuesA=getSetUp() prjA,lolaA,modlSZa,modlRESN,showA,sectnA,\ tStart,tStop,tStep,tRept,tCompute,tBurstLen,\ sStart=valuesA modlSZx,modlSZy=modlSZa LoLfHtWdA=[lolaA[0]-float(modlSZx)*modlRESN/2,\ lolaA[1]-float(modlSZy)*modlRESN/2,\ float(modlSZx)*modlRESN,\ float(modlSZy)*modlRESN] llA=LoLfHtWdA[:2] #Start the KML and with a map area rectangle... foo=writeKML("ini") foo=writeKML("area") foo=writeKML("points") foo=stockPanel() foo=writeKML("columns") foo=writeKML("end") print "End of processing" # ============================================================================