Exemple #1
0
def run_uclchem(phase1, phase2, species):

    print("\n Running UCLCHEM..")
    # Check if phase 1 exists (as n is the only important factor here)
    print("\t Running phase 1...")
    uclchem.wrap.run_model_to_file(phase1, species)
    print("\t Phase 1 complete \n")

    print("\t Running phase 2...")
    uclchem.wrap.run_model_to_file(phase2, species)
    print("\t Phase 2 complete \n")

    print("UCLCHEM run complete \n Reading UCLCHEM output...")
    data = plotfunctions.read_uclchem("{0}".format(phase2["outputFile"]))
    times, dens, temp, av, coldens, abundances = list(data["Time"]), list(
        data["Density"]), list(data["gasTemp"]), list(data["av"]), [], []

    for spec in species.split():  # split() required as species is a string
        print("spec={0}".format(spec))
        print("data[spec]={0}".format(data[spec]))
        abundances.append(data[spec])
        coldens.append(
            data[spec] * av * 1.6e21
        )  # See Eq. 2 of https://www.aanda.org/articles/aa/pdf/2014/07/aa23010-13.pdf

    # Determine the H column density through the shock
    # coldens = [phase2["rout"]*(3e18)*n_i for n_i in dens]

    # Read the velocity file
    vels = np.loadtxt(phase2["velocityFile"])

    return {
        "times": times,
        "dens": dens,
        "temp": temp,
        "abundances": abundances,
        "av": av,
        "coldens": coldens,
        "zn": vels[:, 1],
        "vn": vels[:, 2],
        "vi": vels[:, 3]
    }
Exemple #2
0
   #aiming to have 3 panes stacked vertically
   fig,axes=pf.plt.subplots(1,2,figsize=(16,9), sharey=True,num=p,clear=True)
   for j , factor in enumerate(varyfactor):
       #pick species, any number is fine
       #title = ""
       lb=False
       if factor == 1 : 
           collfile = columnpath + "phase1-fullCtrl.dat"
           #title = "Ctrl"
           lb=True
       else: 
           collfile = columnpath + "phase1-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
           #title = "Varying " + e[0]#+str(factor)
           lb=False
 		#call read_uclchem. 
       time,dens,temp,abundances=pf.read_uclchem(collfile,speciesNames)
       for k, s in enumerate(speciesNames):
           specfactor.append(s+"_" + str(factor))
 
     
     		#plot species returns the axis so we can further edit
       #axis.set(xscale='log',ylim=(1e-18,1e-3),xlim=(1e0,6e6))
       #axis.set_title(title)
       #axis.legend(loc='best')
       
       #phase 2 display
       if factor == 1 : 
           collfile = columnpath + "phase2-fullCtrl.dat"
           #title = "Ctrl"
       else: 
           collfile = columnpath + "phase2-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
Exemple #3
0
def plotchem(speciesNames):
    p = 0
    speclist = ""
    factorlines = [
        mlines.Line2D([], [], color='w', label="factor", linestyle='None')
    ]
    for j, strfactor in enumerate(varyfactorstr):
        factorlines.append(
            mlines.Line2D([], [],
                          color='k',
                          label=strfactor,
                          linestyle=Linestles[j]))
    for l, s in enumerate(speciesNames):
        speclist += s + " "
    for k, e in enumerate(elements):
        i = 0
        iprev = i
        specfactor = []
        title = "Varying " + e[0]
        #aiming to have 3 panes stacked vertically
        fig, axes = pf.plt.subplots(figsize=imgparams[0], num=p, clear=True)
        if legendoutP1:
            pf.plt.subplots_adjust(right=0.85,
                                   left=None,
                                   bottom=None,
                                   top=None)
        p = p + 1
        #figcombo,axescombo=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        #p=p+1
        #Separate out the phase 2 graph
        #figp2,axesp2=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        phase2startt = 0
        phase2endt = 0
        rtists = []
        for j, factor in enumerate(varyfactor):
            #pick species, any number is fine
            print("plotting: " + speclist + e[0] + " " + str(factor))
            #title = ""
            #phase 1 data extract
            lb = False
            if factor == 1:
                collfile = columnpath + "phase1-fullCtrl.dat"
                #title = "Ctrl"
                lb = True
            else:
                collfile = columnpath + "phase1-full" + e[0] + "-" + str(
                    factor).replace('.', '_') + ".dat"
                #title = "Varying " + e[0]#+str(factor)
                lb = False
    #call read_uclchem.
            time, dens, temp, abundances = pf.read_uclchem(
                collfile, speciesNames)
            for l, s in enumerate(speciesNames):
                specfactor.append(s + "_" + str(factor))

    #plot species and save to test.png, alternatively send dens instead of time.
    #axis,rtist0=pf.plot_species(speciesNames,time,abundances,axes,ls=Linestles[j],lab=lb)#ax=axes[i])
    #axis,rtist1=pf.plot_species(speciesNames,time,abundances,axes[1],ls=Linestles[j],lab=False)#ax=axes[i])

    #phase 2 data notbeing used at mo so leave out
    #     if factor == 1 :
    #         collfile = columnpath + "phase2-fullCtrl.dat"
    #         #lb=True
    #         #title = "Ctrl"
    #     else:
    #         collfile = columnpath + "phase2-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
    #         #lb=False
    #         #title = "Varying " + e[0]#+str(factor)
    # #call read_uclchem.
    #     time2,dens2,temp,abundances2=pf.read_uclchem(collfile,speciesNames)
    #   		#plot species returns the axis so we can further edit
    #     #stitch together the phase1 and phase2 series and plot
    #     timenp = np.asarray(time)
    #     timenp2 = np.asarray(time2)
    #     for l, s in enumerate(speciesNames):
    #         abundances[l].extend(abundances2[l])

    #     tnpp2 = timenp2 + timenp[-1]
    #     t = np.append(timenp,tnpp2)
            axis, rtist0 = pf.plot_species(speciesNames,
                                           time,
                                           abundances,
                                           axes,
                                           ls=Linestles[j],
                                           lab=lb,
                                           lw=imgparams[4],
                                           ncol=6)  #ax=axes[i])
            #axiscombo,rtist0=pf.plot_species(speciesNames,t,abundances,axescombo,ls=Linestles[j],lab=lb)#ax=axes[i])
            rtists.append(
                rtist0
            )  #questionable use as plotspecies doesn't return the list of handles just the last ouneat the moment

            # plot phase2 on its own
            #phase2startt=tnpp2[0]
            #phase2endt=tnpp2[-1]
    #plot species and save to test.png, alternatively send dens instead of time.
    #axisp2,rtist2=pf.plot_species(speciesNames,tnpp2,abundances2,axesp2,ls=Linestles[j],lab=lb)#ax=axes[i])

    #here insert the factor linestyles at the end of the legned under a heading of factor
        if withfactorlegendP1:
            lbls = ["species"]
            hdls = [
                mlines.Line2D([], [],
                              color='w',
                              label="species",
                              linestyle='None')
            ]
            hndls, labls = axes.get_legend_handles_labels()
            lbls.extend(labls)
            lbls.append("factor")
            lbls.extend(varyfactorstr)
            hdls.extend(hndls)
            hdls.extend(factorlines)

        axes.set(xscale=xaslog,
                 yscale='log',
                 ylim=(1e-18, 1e-3),
                 xlim=(1e0, time[-1]))  #timenp[-1]
        axes.set_xlabel('Time / Years', fontsize=imgparams[2])
        if xaslog == 'linear':
            axes.ticklabel_format(axis='x', useMathText=True)
        axes.set_ylabel('X/H', fontsize=imgparams[2])
        axes.set_title(title + " phase1", fontsize=imgparams[3])

        if withfactorlegendP1 and legendoutP1:
            axes.legend(hdls,
                        lbls,
                        loc='upper left',
                        bbox_to_anchor=(1.0, 1.0),
                        fontsize=imgparams[5],
                        handlelength=1.5,
                        borderaxespad=0.0
                        )  #loc='upper left',bbox_to_anchor=(0.0,0.0,1.0,1.0),
        elif withfactorlegendP1:
            axes.legend(hdls, lbls, loc='best', fontsize=imgparams[1])
        else:
            axes.legend(loc='best', fontsize=imgparams[1])

        fig.savefig(plotspath + "/phase1plot" + e[0] + "_" + speciesNames[0] +
                    ".png",
                    dpi=300)

        # axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,6.5e6))#t[-1]))
        # if xaslog == 'linear':
        #     axes.ticklabel_format(axis='x',useMathText=True)
        # axes.set_title(title+" phase1&2",fontsize=imgparams[3])
        # fig.savefig(plotspath+"/comboplot"+e[0]+"_"+speciesNames[0]+".png",dpi=300)

        # axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(phase2startt,phase2startt+0.3e6))
        # if xaslog == 'linear':
        #     axes.ticklabel_format(axis='x',useMathText=True)
        # axes.set_title(title+" phase2",fontsize=imgparams[3])
        # fig.savefig(plotspath+"/phase2plot"+e[0]+"_"+speciesNames[0]+".png",dpi=300)

    p = p + 1
    for k, e in enumerate(elements):
        i = 0
        iprev = i
        specfactor = []
        #aiming to have 3 panes stacked vertically
        fig, axes = pf.plt.subplots(figsize=imgparams[0], num=p, clear=True)
        if legendoutS:
            pf.plt.subplots_adjust(right=0.85,
                                   left=None,
                                   bottom=None,
                                   top=None)
        for j, factor in enumerate(varyfactor):
            print("plotting static: " + speclist + e[0] + " " + str(factor))
            #pick species, any number is fine
            title = ""
            lb = False

            #static model plot
            if factor == 1:
                collfile = columnpath + "static-fullCtrl.dat"
                title = "Ctrl"
                lb = True
            else:
                collfile = columnpath + "static-full" + e[0] + "-" + str(
                    factor).replace('.', '_') + ".dat"
                title = "Varying " + e[0]  #+str(factor)
                lb = False
    #call read_uclchem.
            time3, dens3, temp3, abundances3 = pf.read_uclchem(
                collfile, speciesNames)

            #plot species and save to test.png, alternatively send dens instead of time.
            axis, rtist = pf.plot_species(speciesNames,
                                          time3,
                                          abundances3,
                                          axes,
                                          ls=Linestles[j],
                                          lab=lb,
                                          lw=imgparams[4],
                                          ncol=6)  #ax=axes[i])

            #plot species returns the axis so we can further edit
            if xaslog == 'linear':
                axis.set(xscale=xaslog,
                         yscale='log',
                         ylim=(1e-18, 1e-3),
                         xlim=(1e0, time3[-1]))
                axis.ticklabel_format(axis='x', useMathText=True)
            else:
                axis.set(xscale=xaslog,
                         yscale='log',
                         ylim=(1e-18, 1e-3),
                         xlim=(1e0, time3[-1]))
            axis.set_ylabel('X/H', fontsize=imgparams[2])
            axis.set_xlabel('Time / Years', fontsize=imgparams[2])

            axis.set_title(title + " static cloud", fontsize=imgparams[3])
            #axis.set_title(title)
            #here insert the factor linestyles at the end of the legned under a heading of factor
            if withfactorlegendS:
                lbls = ["species"]
                hdls = [
                    mlines.Line2D([], [],
                                  color='w',
                                  label="species",
                                  linestyle='None')
                ]
                hndls, labls = axes.get_legend_handles_labels()
                lbls.extend(labls)
                lbls.append("factor")
                lbls.extend(varyfactorstr)
                hdls.extend(hndls)
                hdls.extend(factorlines)

            if withfactorlegendS and legendoutS:
                axes.legend(
                    hdls,
                    lbls,
                    loc='upper left',
                    bbox_to_anchor=(1.0, 1.0),
                    fontsize=imgparams[5],
                    handlelength=1.5,
                    borderaxespad=0.0
                )  #loc='upper left',bbox_to_anchor=(0.0,0.0,1.0,1.0),
            elif withfactorlegendS:
                axes.legend(hdls, lbls, loc='best', fontsize=imgparams[1])
            else:
                axes.legend(loc='best', fontsize=imgparams[1])
            i = i + 1

        #axes[0].text(.02,0.98,e[0],horizontalalignment="left",verticalalignment="top",transform=axes[0].transAxes)
        #the single plot per page version


#        axes.text(.02,0.98,e[0],horizontalalignment="left",verticalalignment="top",transform=axes.transAxes)

#axes[3].text(.02,0.98,"Your Row",horizontalalignment="left",verticalalignment="top",transform=axes[3].transAxes)
        fig.savefig(plotspath + "/staticplot" + e[0] + "_" + speciesNames[0] +
                    ".png",
                    dpi=300)
        pf.plt.clf()
Exemple #4
0
def plotchem(speciesGroup):
    #speciesGroup=speciesNameLists[0]#use this to just do one element for a test
    speciesNames = speciesGroup[1]
    speciesDisplay = speciesGroup[2]
    groupname = speciesGroup[0]
    p=0
    for k, e in enumerate(elements):
        i=0
        iprev = i
        specfactor = []
        time = []
        abundances = []
        species = []
        abundscale = []
        varying=[]#willl be a different plot "varying" may be able to put in a grid of plots
        model = []
        timelim = 5.4e6
        title = modelname + " Varying " + e[0]
        #aiming to have 3 panes stacked vertically
        fig,axes=plt.subplots(figsize=imgparams[0], num=p,clear=True)
        plt.rcParams["axes.labelsize"]=imgparams[5]
        plt.rcParams["axes.titlesize"]="large"
        plt.rcParams["axes.formatter.use_mathtext"]=True
        plt.rcParams["font.size"]=8.0
        plt.rcParams["legend.fontsize"]="small"
        plt.rcParams["legend.borderaxespad"]=0.0
        plt.rcParams["legend.handletextpad"]=0.1
        #plt.rcParams["figure.autolayout"]=True

        p=p+1
        #figcombo,axescombo=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        #p=p+1
    #Separate out the phase 2 graph
        #figp2,axesp2=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        
        
        timeadded = False
    #        phase2startt=0
    #        phase2endt=0
        #iterate over all the multipliers held in varyfactor
        for j , factor in enumerate(varyfactor):
            #pick species, any number is fine
            #title = ""
            lb=False
            
            #phase 1 plot
            if factor == 1 : 
                collfile = columnpath + "phase1-fullCtrl.dat"
                #title = "Ctrl"
                lb=True
            else: 
                collfile = columnpath + "phase1-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
                #title = "Varying " + e[0]#+str(factor)
                lb=False
      		#call read_uclchem. 
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            if t[-1] > timelim:
                timelim = t[-1]
            for l, s in enumerate(speciesDisplay):
                if len(abund[l]) != len(t):
                    print("Species "+s+"no values a=" +str(len(abund))+" t="+str(len(t)))
                    continue
                abundances.extend(abund[l])
                time.extend(t)
                species.extend([s]*len(t)) #.replace('ice','*')
                abundscale.extend([str(factor)]*len(t))
                varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                model.extend(["collapse"]*len(t))
            
            #static model plot
            if factor == 1 : 
                collfile = columnpath + "static-fullCtrl.dat"
                title = "Ctrl"
                lb = True
            else: 
                collfile = columnpath + "static-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
                title = modelname + "Varying " + e[0]#+str(factor)
                lb = False
      		#call read_uclchem. 
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            
            for l, s in enumerate(speciesDisplay):
                if len(abund[l]) != len(t):
                    print("Species "+s+"no values a=" +str(len(abund))+" t="+str(len(t)))
                    continue
                abundances.extend(abund[l])
                time.extend(t)
                species.extend([s]*len(t)) #.replace('ice','*')
                abundscale.extend([str(factor)]*len(t))
                varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                model.extend(["static"]*len(t))
            # timenp = np.asarray(time)
            # if not timeadded:
            #     p1df["time"] = time
            #     timeadded = True
            # for l, s in enumerate(speciesNames):
            #     colname=s+str(factor)
            #     colname = s.replace('#','ice')
                
            #     specfactor.append(colname)
                
            #     p1df = pd.concat([p1df,pd.DataFrame({colname:abundances[l]})],axis=1)#column for each species with 
            
            #
      		#plot species and save to test.png, alternatively send dens instead of time.
            #axis,rtist0=pf.plot_species(speciesNames,time,abundances,axes,ls=Linestles[j],lab=lb)#ax=axes[i])
            #axis,rtist1=pf.plot_species(speciesNames,time,abundances,axes[1],ls=Linestles[j],lab=False)#ax=axes[i])
        #p1 = p1df.transpose()
        p1df = pd.DataFrame({"time":time,"abundances":abundances,"species":species,"factor":abundscale,"varying":varying,"model":model})
        
        g = sns.FacetGrid(p1df,col="model",row="varying",aspect = 1.0)#,legend_out=True)
        
        
        g.map_dataframe(sns.lineplot, x="time",y="abundances",hue="species",style="factor",dashes=Linestyles,linewidth=imgparams[4],ci=None) #data=p1df,legend="brief",ax=axes,
        g.set(xscale=xaslog,yscale='log',ylim=(1e-18,5e-3),xlim=(1e0,timelim)) 
        g.set_axis_labels('Time years','X/H')
        g.add_legend(fontsize=imgparams[5])#,loc='upper left',bbox_to_anchor=(1.0,1.0))
        g.fig.suptitle("Abundances "+modelname, fontsize=8)
        g.fig.subplots_adjust(top=0.9,left=0.1,right=0.9)

        #axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,t[-1]))
        #axes.set_xlabel('Time / Years',fontsize=imgparams[2])
        #if xaslog == 'linear':
        #    axes.ticklabel_format(axis='x',useMathText=True)
       # axes.set_ylabel('X/H',fontsize=imgparams[2])
        #axes.set_title(title+" static cloud",fontsize=imgparams[3])
        #axes.legend(loc='best',fontsize=imgparams[1])
        plt.savefig(plotspath+"/facetplot"+e[0]+"_"+groupname+".png",dpi=300)  
def plotchem(speciesGroup):
    #speciesGroup=speciesNameLists[0]#use this to just do one element for a test
    speciesNames = speciesGroup[1]
    speciesDisplay = speciesGroup[2]
    groupname = speciesGroup[0]
    if bulk is False:
        print(speciesNames)
    p=0
    for k, e in enumerate(elements):
        i=0
        iprev = i
        specfactor = []
        time = []
        abundances = []
        species = []
        abundscale = []
        varying=[]#willl be a different plot "varying" may be able to put in a grid of plots
        model = []
        timelim = 5.4e6
        title = "Varying " + e[0]
        #aiming to have 3 panes stacked vertically
        fig,axes=plt.subplots(figsize=imgparams[0], num=p,clear=True)
        p=p+1
        #figcombo,axescombo=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        #p=p+1
    #Separate out the phase 2 graph
        #figp2,axesp2=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        
        
        timeadded = False
    #        phase2startt=0
    #        phase2endt=0
        collfilepf1 = columnpath + "phase1-fullCtrl.dat"
        tpf1,denspf1,temppf1,abundpf1=pf.read_uclchem(collfilepf1,speciesNames)
        collfilesf1 = columnpath + "static-fullCtrl.dat"
        tsf1,denssf1,tempsf1,abundsf1=pf.read_uclchem(collfilesf1,speciesNames)
        #iterate over all the multipliers held in varyfactor
        for j , factor in enumerate(varyfactor):
            #pick species, any number is fine
            #title = ""
            lb=False
            
            #phase 1 plot
            if factor == 1 : #we have the abundances for factor 1 the base level
                continue

            lb=True
            collfile = columnpath + "phase1-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
            #title = "Varying " + e[0]#+str(factor)
            lb=False
      		#call read_uclchem. Fetches a list of abundances for each species requested.
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            if t[-1] > timelim:
                timelim = t[-1]
            for l, s in enumerate(speciesDisplay):
                if (len(abund[l]) != len(t)) | (len(abundpf1[l]) != len(tpf1)):
                    print("Collapse Species "+s+"no values a=" +str(len(abund[l]))+" t="+str(len(t)) + "a1=" +str(len(abundpf1[l]))+" t1="+str(len(tpf1)))
                else:
                    #extract the abundance and subtract the base factor 1 level first get the lists the same length as for factor 1
                    if len(t) > len(tpf1):
                        aabundf = np.asarray(abund[l][:len(tpf1)])
                        aabpf = np.asarray(abundpf1[l][:len(tpf1)])
                        aab = aabundf - aabpf
                        abundances.extend(aab.tolist())
                        time.extend(tpf1)
                        species.extend([s.replace('#','ice')]*len(tpf1)) 
                        abundscale.extend([str(factor)]*len(tpf1))
                        varying.extend([e[0]]*len(tpf1))#varying element means we could construct a page of plots
                        model.extend(["collapse"]*len(tpf1))
                        #calculate the parallel track for the current factor
                        
                        #This should be a function to insert a track of abundance and time
                        # npx = aabundf * (factor - 1.0)#rebase so factor 1 is teh new zero
                        # abundances.extend(npx.tolist())
                        # time.extend(tpf1)
                        # species.extend([s.replace('#','ice')+"pll"]*len(tpf1)) 
                        # abundscale.extend([str(factor)]*len(tpf1))
                        # varying.extend([e[0]]*len(tpf1))#varying element means we could construct a page of plots
                        # model.extend(["collapse"]*len(tpf1))
                    else:
                        aabundf = np.asarray(abund[l][:len(t)])
                        aabpf = np.asarray(abundpf1[l][:len(t)])
                        aab = aabundf - aabpf
                        abundances.extend(aab.tolist())
                        time.extend(t)
                        species.extend([s.replace('#','ice')]*len(t)) 
                        abundscale.extend([str(factor)]*len(t))
                        varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                        model.extend(["collapse"]*len(t))
                        #calculate the parallel track for the current factor
                        
                        # npx = aabundf * (factor - 1.0)
                        # abundances.extend(npx.tolist())
                        # time.extend(t)
                        # species.extend([s.replace('#','ice')+"pll"]*len(t)) 
                        # abundscale.extend([str(factor)]*len(t))
                        # varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                        # model.extend(["collapse"]*len(t))
                    #print("time "+str(len(time))+" abundances ",str(len(abundances))+" species "+str(len(species))+" factor "+str(len(abundscale))+" varying "+str(len(varying))+" model "+str(len(model)))
            #static model plot
            title = "Ctrl"
            lb = True
            collfile = columnpath + "static-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
            title = "Varying " + e[0]#+str(factor)
            lb = False
      		#call read_uclchem. 
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            
            #note this time pf1 replaced by sf1
            for l, s in enumerate(speciesDisplay):
                if (len(abund[l]) != len(t)) | (len(abundsf1[l]) != len(tsf1)):
                    print("Static Species "+s+" no values a=" +str(len(abund[l]))+" t="+str(len(t)) + " a1=" +str(len(abundsf1[l]))+" t1="+str(len(tsf1)))
                else:
                    #extract the abundance and subtract the base factor 1 level first get the lists the same length as for factor 1
                    if len(t) > len(tsf1):
                        aabundf = np.asarray(abund[l][:len(tsf1)])
                        aabpf = np.asarray(abundsf1[l][:len(tsf1)])
                        aab = aabundf - aabpf
                        abundances.extend(aab.tolist())
                        time.extend(tsf1)
                        species.extend([s.replace('#','ice')]*len(tsf1)) 
                        abundscale.extend([str(factor)]*len(tsf1))
                        varying.extend([e[0]]*len(tsf1))#varying element means we could construct a page of plots
                        model.extend(["static"]*len(tsf1))
                        #calculate the parallel track for the current factor
                        
                        # npx = aabundf * (factor - 1.0)#rebase so factor 1 is teh new zero
                        # abundances.extend(npx.tolist())
                        # time.extend(tsf1)
                        # species.extend([s.replace('#','ice')+"pll"]*len(tsf1)) 
                        # abundscale.extend([str(factor)]*len(tsf1))
                        # varying.extend([e[0]]*len(tsf1))#varying element means we could construct a page of plots
                        # model.extend(["static"]*len(tsf1))
                    else:
                        aabundf = np.asarray(abund[l][:len(t)])
                        aabpf = np.asarray(abundsf1[l][:len(t)])
                        aab = aabundf - aabpf
                        abundances.extend(aab.tolist())
                        time.extend(t)
                        species.extend([s.replace('#','ice')]*len(t)) 
                        abundscale.extend([str(factor)]*len(t))
                        varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                        model.extend(["static"]*len(t))
                        #calculate the parallel track for the current factor
                        
                        # npx = aabundf * (factor - 1.0)
                        # abundances.extend(npx.tolist())
                        # time.extend(t)
                        # species.extend([s.replace('#','ice')+"pll"]*len(t)) 
                        # abundscale.extend([str(factor)]*len(t))
                        # varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                        # model.extend(["static"]*len(t))
                    #print("time "+str(len(time))+" abundances ",str(len(abundances))+" species "+str(len(species))+" factor "+str(len(abundscale))+" varying "+str(len(varying))+" model "+str(len(model)))
            # timenp = np.asarray(time)
            # if not timeadded:
            #     p1df["time"] = time
            #     timeadded = True
            # for l, s in enumerate(speciesNames):
            #     colname=s+str(factor)
            #     colname = s.replace('#','ice')
                
            #     specfactor.append(colname)
                
            #     p1df = pd.concat([p1df,pd.DataFrame({colname:abundances[l]})],axis=1)#column for each species with 
            
            #
      		#plot species and save to test.png, alternatively send dens instead of time.
            #axis,rtist0=pf.plot_species(speciesNames,time,abundances,axes,ls=Linestles[j],lab=lb)#ax=axes[i])
            #axis,rtist1=pf.plot_species(speciesNames,time,abundances,axes[1],ls=Linestles[j],lab=False)#ax=axes[i])
        #p1 = p1df.transpose()
        if bulk is False:
            print("time "+str(len(time))+" abundances ",str(len(abundances))+" species "+str(len(species))+" factor "+str(len(abundscale))+" varying "+str(len(varying))+" model "+str(len(model)))
        p1df = pd.DataFrame({"time":time,"abundances":abundances,"species":species,"factor":abundscale,"varying":varying,"model":model})
        
        g = sns.FacetGrid(p1df,col="model",row="varying")
        
        
        g.map_dataframe(sns.lineplot, x="time",y="abundances",hue="species",style="factor",dashes=Linestyles,linewidth=imgparams[4],ci=None) #data=p1df,legend="brief",ax=axes,
        g.set(xscale=xaslog,yscale='linear',xlim=(1e0,timelim)) #,ylim=(-1e-6,1e-6)
        g.set_axis_labels('Time / Years','X/H')
        g.add_legend()
        
        #axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,t[-1]))
        #axes.set_xlabel('Time / Years',fontsize=imgparams[2])
        #if xaslog == 'linear':
        #    axes.ticklabel_format(axis='x',useMathText=True)
       # axes.set_ylabel('X/H',fontsize=imgparams[2])
        #axes.set_title(title+" static cloud",fontsize=imgparams[3])
        #axes.legend(loc='best',fontsize=imgparams[1])
        plt.savefig(plotspath+"/facetplot"+e[0]+"_"+groupname+".png",dpi=300)  
Exemple #6
0
def plotchem(speciesGroup):
    #speciesNames=speciesNameLists[0]#use this to just do one element for a test
    speciesNames = speciesGroup[1]
    speciesDisplay = speciesGroup[2]
    groupname = speciesGroup[0]
    p=0
    for k, e in enumerate(elements):
        i=0
        iprev = i
        specfactor = []
        time = []
        abundances = []
        species = []
        abundscale = []
        varying=[]#willl be a different plot "varying" may be able to put in a grid of plots
        
        title = "Varying " + e[0]
        #aiming to have 3 panes stacked vertically
        fig,axes=plt.subplots(figsize=imgparams[0], num=p,clear=True)
        p=p+1
        #figcombo,axescombo=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        #p=p+1
    #Separate out the phase 2 graph
        #figp2,axesp2=pf.plt.subplots(figsize=(16,9), sharey=True,num=p,clear=True)
        
        
        timeadded = False
    #        phase2startt=0
    #        phase2endt=0
        #iterate over all the multipliers held in varyfactor
        for j , factor in enumerate(varyfactor):
            #pick species, any number is fine
            #title = ""
            lb=False
            if factor == 1 : 
                collfile = columnpath + "phase1-fullCtrl.dat"
                #title = "Ctrl"
                lb=True
            else: 
                collfile = columnpath + "phase1-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
                #title = "Varying " + e[0]#+str(factor)
                lb=False
      		#call read_uclchem. 
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            
            for l, s in enumerate(speciesDisplay):
                if len(abund[l]) != len(t):
                    print("Species "+s+"no values a=" +str(len(abund))+" t="+str(len(t)))
                    continue
                abundances.extend(abund[l])
                time.extend(t)
                species.extend([s.replace('#','ice')]*len(t)) 
                abundscale.extend([str(factor)]*len(t))
                varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                if factor == 1:
                    npabund = np.asarray(abund[l])
                    for q, f in enumerate(varyfactor):
                        if f == 1:
                            continue#just the outliier tracks
                        npx = npabund * f
                        abundances.extend(npx.tolist())
                        time.extend(t)
                        species.extend([s.replace('#','ice')+"pll"]*len(t)) 
                        abundscale.extend([str(f)]*len(t))
                        varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                        
            # timenp = np.asarray(time)
            # if not timeadded:
            #     p1df["time"] = time
            #     timeadded = True
            # for l, s in enumerate(speciesNames):
            #     colname=s+str(factor)
            #     colname = s.replace('#','ice')
                
            #     specfactor.append(colname)
                
            #     p1df = pd.concat([p1df,pd.DataFrame({colname:abundances[l]})],axis=1)#column for each species with 
            
            #
      		#plot species and save to test.png, alternatively send dens instead of time.
            #axis,rtist0=pf.plot_species(speciesNames,time,abundances,axes,ls=Linestles[j],lab=lb)#ax=axes[i])
            #axis,rtist1=pf.plot_species(speciesNames,time,abundances,axes[1],ls=Linestles[j],lab=False)#ax=axes[i])
        #p1 = p1df.transpose()
        p1df = pd.DataFrame({"time":time,"abundances":abundances,"species":species,"factor":abundscale,"varying":varying})
        sns.lineplot(x="time",y="abundances",hue="species",style="factor",dashes=Linestyles,data=p1df,legend="brief",ax=axes,linewidth=imgparams[4]) 
            
        axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,t[-1]))
        axes.set_xlabel('Time / Years',fontsize=imgparams[2])
        if xaslog == 'linear':
            axes.ticklabel_format(axis='x',useMathText=True)
        axes.set_ylabel('X/H',fontsize=imgparams[2])
        axes.set_title(title+" phase1",fontsize=imgparams[3])
        axes.legend(loc='best',fontsize=imgparams[1])
        plt.savefig(plotspath+"/phase1plot"+e[0]+"_"+groupname+".png",dpi=300)  
    #plt.show()
#     axes.legend(loc='best',fontsize=imgparams[1])
# #        fig.savefig(plotspath+"/phase1plot"+e[0]+"_"+speciesNames[0]+".png",dpi=300)
    
#     axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,6.5e6))#t[-1]))
#     if xaslog == 'linear':
#         axes.ticklabel_format(axis='x',useMathText=True)
#     axes.set_title(title+" phase1&2",fontsize=imgparams[3])
#        fig.savefig(plotspath+"/comboplot"+e[0]+"_"+speciesNames[0]+".png",dpi=300)

#        axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(phase2startt,phase2startt+0.3e6))
#        if xaslog == 'linear':
#            axes.ticklabel_format(axis='x',useMathText=True)
#        axes.set_title(title+" phase2",fontsize=imgparams[3])
#        fig.savefig(plotspath+"/phase2plot"+e[0]+"_"+speciesNames[0]+".png",dpi=300)

        

    p=p+1
    for k, e in enumerate(elements):
        i=0
        iprev = i
        specfactor = []
        time = []
        abundances = []
        species = []
        abundscale = []
        varying=[]#willl be a different plot "varying" may be able to put in a grid of plots
        #aiming to have 3 panes stacked vertically
        fig,axes=plt.subplots(figsize=imgparams[0],num=p,clear=True)
        for j , factor in enumerate(varyfactor):
            #pick species, any number is fine
            title = ""
            lb=False
            
            #static model plot
            if factor == 1 : 
                collfile = columnpath + "static-fullCtrl.dat"
                title = "Ctrl"
                lb = True
            else: 
                collfile = columnpath + "static-full"+e[0]+ "-" + str(factor).replace('.','_')+".dat"
                title = "Varying " + e[0]#+str(factor)
                lb = False
      		#call read_uclchem. 
            t,dens,temp,abund=pf.read_uclchem(collfile,speciesNames)
            
            for l, s in enumerate(speciesDisplay):
                if len(abund[l]) != len(t):
                    print("Species "+s+"no values a=" +str(len(abund))+" t="+str(len(t)))
                    continue
                abundances.extend(abund[l])
                time.extend(t)
                species.extend([s.replace('#','ice')]*len(t)) 
                abundscale.extend([str(factor)]*len(t))
                varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                if factor == 1:#produce parralell tracks and label as a related species
                    npabund = np.asarray(abund[l])
                    for q, f in enumerate(varyfactor):
                        if f == 1:
                            continue#just the outliier tracks
                        npx = npabund * f
                        abundances.extend(npx.tolist())
                        time.extend(t)
                        species.extend([s.replace('#','ice')+"pll"]*len(t)) 
                        abundscale.extend([str(f)]*len(t))
                        varying.extend([e[0]]*len(t))#varying element means we could construct a page of plots
                
            # timenp = np.asarray(time)
            # if not timeadded:
            #     p1df["time"] = time
            #     timeadded = True
            # for l, s in enumerate(speciesNames):
            #     colname=s+str(factor)
            #     colname = s.replace('#','ice')
                
            #     specfactor.append(colname)
                
            #     p1df = pd.concat([p1df,pd.DataFrame({colname:abundances[l]})],axis=1)#column for each species with 
            
            #
      		#plot species and save to test.png, alternatively send dens instead of time.
            #axis,rtist0=pf.plot_species(speciesNames,time,abundances,axes,ls=Linestles[j],lab=lb)#ax=axes[i])
            #axis,rtist1=pf.plot_species(speciesNames,time,abundances,axes[1],ls=Linestles[j],lab=False)#ax=axes[i])
        #p1 = p1df.transpose()
        p1df = pd.DataFrame({"time":time,"abundances":abundances,"species":species,"factor":abundscale,"varying":varying})
        sns.lineplot(x="time",y="abundances",hue="species",style="factor",dashes=Linestyles,data=p1df,legend="brief",ax=axes,linewidth=imgparams[4]) 
          
        axes.set(xscale=xaslog,yscale='log',ylim=(1e-18,1e-3),xlim=(1e0,t[-1]))
        axes.set_xlabel('Time / Years',fontsize=imgparams[2])
        if xaslog == 'linear':
            axes.ticklabel_format(axis='x',useMathText=True)
        axes.set_ylabel('X/H',fontsize=imgparams[2])
        axes.set_title(title+" static cloud",fontsize=imgparams[3])
        axes.legend(loc='best',fontsize=imgparams[1])
        plt.savefig(plotspath+"/staticplot"+e[0]+"_"+groupname+".png",dpi=300)