def cm_remove_middle(cm,midpoint=0.5,cut_radius=0.2,name="my_cm"):
    #removes the middle of a colormap
    # so that region centered around 0 may have sharper contrast

    cdict = {
        'red': [],
        'green': [],
        'blue': [],
        'alpha': []
    }
    donext=False
    reg_index = np.linspace(0, 1, 100)
    dri=reg_index[1]-reg_index[0]
    slope1=1/(1-2*cut_radius)
    slope2=0.5/(0.5-cut_radius)
    offset=1-slope2
    for ri in reg_index:
        if (ri > midpoint+cut_radius) or (ri < midpoint - cut_radius):
            r, g, b, a = cm(ri)
            if ri < midpoint :
                cdict['red'].append((ri*slope1, r, r))
                cdict['green'].append((ri*slope1, g, g))
                cdict['blue'].append((ri*slope1, b, b))
                cdict['alpha'].append((ri*slope1, a, a))
                #print str(ri) +":" + str(ri*slope1)
            else:
                cdict['red'].append((offset+ri*slope2, r, r))
                cdict['green'].append((offset+ri*slope2, g, g))
                cdict['blue'].append((offset+ri*slope2, b, b))
                cdict['alpha'].append((offset+ri*slope2, a, a))
                #print str(ri) +":" + str(offset+ri*slope2)
        if ri < (midpoint+dri) and ri > (midpoint-dri):
            r2, g2, b2, a2 = cm(midpoint)
            cdict['red'].append((midpoint, r2, r2))
            cdict['green'].append((midpoint, g2, g2))
            cdict['blue'].append((midpoint, b2, b2))
            cdict['alpha'].append((midpoint, a2, a2))
        
    newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict,N=512)
    plt.register_cmap(cmap=newcmap)
    return newcmap
示例#2
0
 def plottingTracks(self, b):
     self.updateModelTitle()
     self.frameNumber.value = 0
     self.refreshDisplay()
     # Setting up color cycle for multiple tracks
     colormap = plt.cm('gist_rainbow')
     color_cycle = ([colormap(i) for i in np.linspace(0, 0.9, len(self.modelList))])
     self.alltimes = []
     # FOR look to create data for tracks and to set color for track
     for i in range(len(self.modelList)):
         self.trackColor = color_cycle[i]
         self.manageData(self.modelList[i])
         self.alltimes += self.time
     
     # Creating an array of times from all selected tracks    
     self.allTimes = sorted(list(set(self.alltimes)))
     self.updateUI()
示例#3
0
def plot_robot(poses, params):
    num_poses = len(poses)
    cm =plt.get_cmap('gist_rainbow')
    
    for i, pose in enumerate(poses):
        col = cm(1.*i/num_poses )
        r = params.sensor_range_m
        # ax = plt.gca()
        axes[0,0].plot([pose[0]-r*np.cos(pose[2]), pose[0]+r*np.cos(pose[2])],
                    [pose[1]-r*np.sin(pose[2]), pose[1]+r*np.sin(pose[2])], '--', color=col)
        axes[0,0].plot([pose[0]-r*np.cos(pose[2]+np.pi/2), pose[0]+r*np.cos(pose[2]+np.pi/2)],
                    [pose[1]-r*np.sin(pose[2]+np.pi/2), pose[1]+r*np.sin(pose[2]+np.pi/2)], '--', color=col)

        axes[0,0].arrow(pose[0], pose[1], 0.05 * np.cos(pose[2]), 0.05 * np.sin(pose[2]),
                    head_length=0.1, head_width=0.1)

        FOV_ANGLE=math.pi/4
        LENGTH = 0.8  # [m]
        WIDTH = 0.5  # [m]
        HALF_LENGTH = LENGTH/2.0  # [m]
        SENSOR_LENGTH = 1.5  # [m]
        WHEEL_LEN = 0.2  # [m]
        WHEEL_WIDTH = 0.2  # [m]

        sensor_outline = np.matrix([[0.0, SENSOR_LENGTH , SENSOR_LENGTH, 0.0],                          #sensor center
                             [0.0,SENSOR_LENGTH*math.tan(FOV_ANGLE),  -SENSOR_LENGTH*math.tan(FOV_ANGLE), 0.0]])

        outline = np.matrix([[-HALF_LENGTH, HALF_LENGTH, HALF_LENGTH, -HALF_LENGTH, -HALF_LENGTH],
                             [WIDTH / 2, WIDTH / 2, - WIDTH / 2, -WIDTH / 2, WIDTH / 2]])
        yaw = pose[2]

        Rot1 = np.matrix([[math.cos(yaw), math.sin(yaw)],
                          [-math.sin(yaw), math.cos(yaw)]])

        outline = (outline.T * Rot1).T
        outline[0, :] += pose[0]
        outline[1, :] += pose[1]

        sensor_outline = (sensor_outline.T * Rot1).T
        sensor_outline[0, :] += pose[0]
        sensor_outline[1, :] += pose[1]
     
        #DRAW an agent_body
        axes[0,0].plot(np.array(outline[0, :]).flatten(),
                 np.array(outline[1, :]).flatten(),color=col)
示例#4
0
    'ytick.labelsize': 17,
    'text.usetex': True,
    'figure.figsize': fig_size
}
plt.rcParams.update(params)

# read data
filename = 'plot.out'
data = np.loadtxt(filename)
ql = pd.DataFrame(data, columns=["x", "y"])
cm = ListedColormap([
    'cornflowerblue', 'cornflowerblue', 'cornflowerblue', 'cornflowerblue',
    'cornflowerblue', 'cornflowerblue', 'cornflowerblue', 'cornflowerblue',
    'cornflowerblue'
])
my_cmap = cm(np.arange(cm.N))
my_cmap[:, -1] = np.linspace(0, 1, cm.N)
my_cmap = ListedColormap(my_cmap)

#plot data
g = sns.JointGrid(x="x",
                  y="y",
                  data=ql,
                  space=0.2,
                  xlim=(1.0, 1.7),
                  ylim=(0, 640))
g = g.plot_joint(sns.kdeplot,
                 cmap=my_cmap,
                 shade=True,
                 shade_lowest=False,
                 kernel='gau')
示例#5
0
def perfect_2d_plot(dirlist,attribs,xattr="psi",yattr="theta",normname="norms.namelist",speciesname="species",psiN_to_psiname="psiAHat.h5",cm=cm.rainbow,lg=True,xlims=[90,100],ylims=[0,2],species=True,sort_species=True,first=["D","He"],last=["e"],generic_labels=True,label_dict={"D":"i","He":"z","N":"z","e":"e"},vlines=None,hlines=None,share_scale=[],skip_species = [],simulList=None):
    #dirlist: list of simulation directories
    #attribs: list of fields to plot from simulation
    #speciesname: species filename in the simuldir
    #normname: norm filename in the simuldir
    #lg: controls whether to interpret nearby simulations as being paired
    
    if type(attribs) is not list:
        attribs=[attribs]

    if simulList == None:
        normlist=[x + "/" + normname for x in dirlist]
        specieslist=[x + "/" + speciesname for x in dirlist]
        psiN_to_psiList=[x + "/" + psiN_to_psiname for x in dirlist]
        simulList=perfect_simulations_from_dirs(dirlist,normlist,specieslist,psiN_to_psiList)
    else:
        "p_2d_plot: simulList specified externally, ignoring dirlist, etc."
    

    #if we translate species labels to generic ion and impurity labels
    #we still need to use original species for sorting preferences
    if generic_labels:
        for simul in simulList:
            simul.species_list=generic_species_labels(simul.species_list,label_dict)
            first=generic_species_labels(first,label_dict)
            last=generic_species_labels(last,label_dict)
            
        
    #get the total list of species found in each simulation
    species_set=set([])
    for simul in simulList:
        # exclude species that are in the skip list
        #nonexcluded = set(simul.species).difference(skip_species)
        nonexcluded = [s for s in simul.species if s not in skip_species]
        
        simul.species_list = nonexcluded
        # add nonexcluded species to total species set
        species_set = species_set | set(simul.species)
        
    # sort species according to preferences
    if sort_species:
        species_set=sort_species_list(list(species_set),first,last)
    print species_set
        
    
    for attrib in attribs:
        psp_list=[] #list of perfect subplot objects
        attrib_sp_dep = is_attribute_species_dependent(simulList,attrib)
        #we will assign data to the following attribute related groups
        attrib_groupname=attrib
        if attrib_sp_dep and species:
            species_attrib_groupname="species_dependent"
            this_species_set=species_set
            gridspec=[len(simulList),len(species_set)]
        else:
            species_attrib_groupname="species_independent"
            this_species_set=set([''])
            gridspec=[len(simulList),1]
        for i,simul in enumerate(simulList):
            data0=getattr(simul,attrib) #need to split this into species data
            #i_s will be coordinate of plot
            for i_s,s in enumerate(this_species_set):
                if attrib_sp_dep:
                    index=[i2 for i2,s2 in enumerate(simul.species) if s2 == s]
                    if len(index)==0:
                        #no data for this species in this simulation. Set data to zeros
                        data=numpy.zeros(data0[:,:,0].shape)
                    elif len(index)==1:
                        data=data0[:,:,index[0]]
                    else:
                        print "perfect_2d_plot: warning: more than one of the same species in the simulation. Will add contributions, but this is untested."
                        data=numpy.sum(data0[:,:,index],axis=2)
                else:
                    data=data0
                subplot_coordinates=(i,i_s)
                #print subplot_coordinates 
                if i == 0:
                    show_zaxis_ticklabel=True
                    show_xaxis_ticklabel=False
                    title=s
                else:
                    show_zaxis_ticklabel=False
                    title=''
                    if i == len(simulList)-1:
                        show_xaxis_ticklabel=True
                    else:
                        show_xaxis_ticklabel=False
                if i_s == 0:
                    show_yaxis_ticklabel=True
                else:
                    show_yaxis_ticklabel=False
                #print simul.local
                if simul.local:
                    gl_grp="local"
                else:
                    gl_grp="global"

                if (yattr == "theta") or (yattr == "theta_shifted"):
                    y_scale = 1/numpy.pi
                else:
                    y_scale=1
                    
                if (xattr == "theta") or (xattr == "theta_shifted"):
                    x_scale = 1/numpy.pi
                elif (xattr == "psi") or (xattr == "actual_psiN"):
                    x_scale=100
                else:
                    x_scale=1
                if xattr is not "psio":
                    x = getattr(simul,xattr)*x_scale
                else:
                    print "WARNING: orbit width uses hardcoded index for deuterium and pedestal start and stop values!"
                    vlines2 = [0.94927395957025573,0.97463697978512787]
                    
                    iD = 0
                    ped_start_index=get_index_range(simul.actual_psiN,[vlines2[0],vlines2[0]])[1]
                    ped_stop_index=get_index_range(simul.actual_psiN,[vlines2[1],vlines2[1]])[1]
                    ow_start=simul.orbit_width[ped_start_index,iD]
                    ow_stop=simul.orbit_width[ped_stop_index,iD]
                    x = (simul.actual_psiN-vlines2[1])/simul.orbit_width[:,iD]
                    vlines=[(vlines2[0]-vlines2[1])/ow_start,(vlines2[1]-vlines2[1])/ow_stop]
                y = getattr(simul,yattr)*y_scale
                psp_list.append(perfect_subplot(data,x=x,y=y,subplot_coordinates=subplot_coordinates,show_zaxis_ticklabel=show_zaxis_ticklabel,show_yaxis_ticklabel=show_yaxis_ticklabel,show_xaxis_ticklabel=show_xaxis_ticklabel,title=title,groups=[s,"sim"+str(i),gl_grp,"pair"+str(i/2),species_attrib_groupname],dimensions=2))
        #end simulList loop
        for psp in psp_list:
            print psp.groups
        species_groups=[perfect_subplot_group(psp_list,groups=[s,"species_dependent"],logic="and") for s in species_set if len(perfect_subplot_group(psp_list,groups=[s,"species_dependent"],logic="and").p_subplot_list)>0]
        nospecies_group=perfect_subplot_group(psp_list,groups=["species_independent"])

        sim_groups = [perfect_subplot_group(psp_list,groups=["sim"+str(i)]) for i in range(len(simulList))]
        pair_groups = [perfect_subplot_group(psp_list,groups=["pair"+str(i)]) for i in range(len(simulList)/2)]
        local_group = perfect_subplot_group(psp_list,groups=["local"])
        global_group = perfect_subplot_group(psp_list,groups=["global"])
        all_group=perfect_subplot_group(psp_list,groups='',get_all=True)
        share_scale_group=perfect_subplot_group(psp_list,groups=share_scale,logic="or")
        
        
        if lg==False:
            color=iter(cm(numpy.linspace(0,1,len(simulList))))
            for sim_group in sim_groups:
                c=next(color)
                sim_group.setattrs("border_color",c)
        else:
            color=iter(cm(numpy.linspace(0,1,len(pair_groups))))
            for pair_group in pair_groups:
                c=next(color)
                pair_group.setattrs("border_color",c)

        local_group.setattrs("border_linestyle","dashed")
        
        all_group.setattrs("xlims",xlims)
        #all_group.setattrs("ylims",[all_group.get_min("y",xlim=False,ylim=False),all_group.get_max("y",xlim=False,ylim=False)])
        all_group.setattrs("ylims",ylims)
        all_group.setattrs("vlines",vlines)
        all_group.setattrs("hlines",hlines)
        
        for species_group in species_groups:
            species_group.setattrs("zlims",[species_group.get_min("data"),species_group.get_max("data")])
            print [species_group.get_min("data"),species_group.get_max("data")]
            
        if len(share_scale_group.p_subplot_list)>0:
            share_scale_group.setattrs("zlims",[share_scale_group.get_min("data"),share_scale_group.get_max("data")])

        if len(nospecies_group.p_subplot_list)>0:
            nospecies_group.setattrs("zlims",[nospecies_group.get_min("data"),nospecies_group.get_max("data")])
            
        for i,sim_group in enumerate(sim_groups):
            if i != 0:
                sim_group.setattrs("show_zaxis",False)
        if xattr is not "psio":
            global_xlabel=r"$100\psi_N$"
        else:
            global_xlabel=r"$\psi^\mathrm{o}$"
        perfect_visualizer(psp_list,gridspec,global_xlabel=global_xlabel,dimensions=2,global_ylabel=r"$\theta/\pi$")

        plt.savefig(attrib+'.pdf')
示例#6
0
def perfect_1d_plot(dirlist,attribs,xattr="psi",normname="norms.namelist",speciesname="species",psiN_to_psiname="psiAHat.h5",global_term_multiplier_name="globalTermMultiplier.h5",cm=cm.rainbow,lg=True,markers=None,linestyles=None,xlims=None,same_plot=False,outputname="default",ylabels=None,label_all=False,global_ylabel="",sort_species=True,first=["D","He"],last=["e"],generic_labels=True,label_dict={"D":"i","He":"z","N":"z","e":"e"},vlines=None,hlines=None,share_scale=[],interactive=False):
    #dirlist: list of simulation directories
    #attribs: list of fields to plot from simulation
    #speciesname: species filename in the simuldir
    #normname: norm filename in the simuldir
    #lg: controls whether to interpret nearby simulations as being paired
    
    if type(attribs) is not list:
        attribs=[attribs]
    if ylabels is not None:
        if type(ylabels) is not list:
            ylabels=[ylabels]*len(attribs)
        else:
            if len(ylabels) != len(attribs):
                print "p_1d_plot: error: ylabels not the same size as attribs"
                exit(1)
    else:
        ylabels=['']*len(attribs)
                
    
    normlist=[x + "/" + normname for x in dirlist]
    specieslist=[x + "/" + speciesname for x in dirlist]
    psiN_to_psiList=[x + "/" + psiN_to_psiname for x in dirlist]
    global_term_multiplierList=[x + "/" + global_term_multiplier_name for x in dirlist]
    simulList=perfect_simulations_from_dirs(dirlist,normlist,specieslist,psiN_to_psiList,global_term_multiplierList)
    if markers == None:
        markers=['']*len(simulList)

    #some logic to differentiate between species independent
    #and species quantities further down will fail if there are simulations
    #one species (which you really shouldn't do due to quasi-neutrality!!)
    num_species_array=numpy.array([len(simul.species) for simul in simulList])
    one_species_list=numpy.where(num_species_array<=1)
    if len(num_species_array[one_species_list])>0:
        print "p_1d_plot: warning: there are simulations with one (or) less species! Logic to determine whether attribute is a species property will not work."
        
    
    if generic_labels:
        for simul in simulList:
            simul.species_list=generic_species_labels(simul.species_list,label_dict)
            first=generic_species_labels(first,label_dict)
            last=generic_species_labels(last,label_dict)
    species_set=set([])
    for simul in simulList:
        species_set = species_set | set(simul.species)
    
    #print gridspec
    

    i=-1
    psp_lists=[] #list of lists of perfect subplot object
    gridspec_list=[]
    
    colors=cm(numpy.linspace(0,1,len(simulList)))
    #assign colors to simulations
    all_linecolors=[]
    color_index=0

    local=[simul.local for simul in simulList]
    noddpsi=[simul.no_ddpsi for simul in simulList]
    
    if lg:
        colors=cm(numpy.linspace(0,1,len(simulList)-sum(local)-sum(noddpsi)))
        if sum(local)>0:
            #if we have local simulations, increment color after them
            for loc in local:
                all_linecolors.append(colors[color_index])
                if loc == True:
                    color_index=color_index+1
        elif sum(noddpsi)>0:
            #otherwise, increment color after noddpsi simulation
            for nd in noddpsi:
                all_linecolors.append(colors[color_index])
                if nd == True:
                    color_index=color_index+1
        else:
            #else, always increment
            all_linecolors=cm(numpy.linspace(0,1,len(simulList)))
    else:
        # force always increment behavior
        all_linecolors=cm(numpy.linspace(0,1,len(simulList)))

    if linestyles == None:
        linestyles=[] #linestyles generated from local or global
        for n,l in zip(noddpsi,local):
            # local overrides noddpsi in code as well
            if l:
                linestyles=linestyles+["dashed"]
            elif n:
                linestyles=linestyles+["dashdot"]
            else:
                linestyles=linestyles+["solid"]
    
    for i_a,attrib in enumerate(attribs):
        psp_list=[]
        #check whether attribute is species dependent
        #it will be assumed to be if the lenght along the 1 axis
        #is equal to the number of species in a simulation for all simulations
        #at least as long as there is more than one species in the simulation.
        attrib_sp_dep = is_attribute_species_dependent(simulList,attrib)
        #we will assign data to the following attribute related groups
        attrib_groupname=attrib
        if attrib_sp_dep:
            species_attrib_groupname="species_dependent"
        else:
            species_attrib_groupname="species_independent"
        if same_plot:
            if i_a == len(attribs)-1:
                perhaps_last=True
            else:
                perhaps_last=False
        else:
            perhaps_last=True
        if sort_species:
            species_set=sort_species_list(list(species_set),first,last)
        if attrib_sp_dep:
            for i_sp,s in enumerate(species_set):
                i=i+1
                #data is taken for a given species for all simulations
                #index of species in simulation given by index to index
                index=[[ind for ind,spec in enumerate(simul.species) if spec==s] for simul in simulList]
                
                if all(len(ind)<=1 for ind in index):
                    data=[getattr(simul,attrib)[:,index[i_si][0]] for i_si,simul in enumerate(simulList) if s in simul.species]
                else:
                    print "p_1d_plot: warning: more than one of the same species in the simulation. Will add contributions."
                    data=[numpy.sum(getattr(simul,attrib)[:,index[i_si]],axis=1) for i_si,simul in enumerate(simulList) if s in simul.species]

                if xattr=="theta":
                    x_scale=1/numpy.pi
                else:
                    x_scale=1
                if xattr != None:
                    x=[getattr(simul,xattr)*x_scale for simul in simulList if s in simul.species]
                else:
                    # If xattrib is None, we plot against the index of the data
                    # This probably will not work if we are not plotting against
                    # the first index of data
                    x=[numpy.array(range(len(getattr(simul,attrib)))) for simul in simulList if s in simul.species]
                if xlims == None:
                    # min to max among all the simulations
                    xlims = [numpy.min(x),numpy.max(x)]
                    
                linecolors=[all_linecolors[i_si] for i_si,simul in enumerate(simulList) if s in simul.species]
                coordinates=(i,0)
                if perhaps_last and (i_sp == len(species_set) - 1):
                    last_groupname="last"
                    gridspec_list.append([i+1,1])
                else:
                    last_groupname="not_last"

                psp_list.append(perfect_subplot(data,x,subplot_coordinates=coordinates,groups=[s,attrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers)) #yaxis_label=ylabels[i_a]
                

        else:
            i=i+1
            if perhaps_last:
                last_groupname="last"
                gridspec_list.append([i+1,1])
            else:
                last_groupname="not_last"
            #species independent plot
            data=[getattr(simul,attrib) for simul in simulList]
            x=[getattr(simul,xattr) for simul in simulList]
            linecolors=all_linecolors
            coordinates=(i,0)
            psp_list.append(perfect_subplot(data,x,subplot_coordinates=coordinates,groups=[attrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers)) #yaxis_label=ylabels[i_a]
            
        
        psp_lists.append(psp_list)
        if not same_plot:
            i=-1

    #merge the psp_lists if everything is supposed to go in the same plot
    if same_plot:
        final_psp_lists=[]
        for psp_list in psp_lists:
            final_psp_lists = final_psp_lists + psp_list
        psp_lists=[final_psp_lists]
        
            
    for i_li,psp_list in enumerate(psp_lists):
        for psp in psp_list:
            print psp.groups
            psp.xlims=xlims
            psp.data=psp.data_inrange()
            psp.x=psp.x_inrange()
        if same_plot:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in attribs]
            for ylabel,attrib_group in zip(ylabels,attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
        else:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in [attribs[i_li]]]
            for ylabel,attrib_group in zip([ylabels[i_li]],attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
                if len(share_scale)>0:
                    share_scale_group=perfect_subplot_group(psp_list,groups=share_scale,logic="or")
                    share_scale_group.setattrs("ylims",[share_scale_group.get_min("data",margin=0.1),share_scale_group.get_max("data",margin=0.1)])
                    

                    
        
        species_groups=[perfect_subplot_group(psp_list,groups=[s]) for s in species_set]
        species_indep_groups=perfect_subplot_group(psp_list,groups=["species_independent"])
        local_group = perfect_subplot_group(psp_list,groups=["local"])
        global_group = perfect_subplot_group(psp_list,groups=["global"])
        last_group = perfect_subplot_group(psp_list,groups=["last"])
        all_group=perfect_subplot_group(psp_list,groups='',get_all=True)
        
        for species_group,s in zip(species_groups,species_set):
            species_group.setattrs("title",s)

        

        for attrib_group in attrib_groups:
            this_species_groups=[perfect_subplot_group(attrib_group.p_subplot_list,groups=[s]) for s in species_set]
            for this_species_group in this_species_groups:
                if len(this_species_group.p_subplot_list)>0:
                    this_species_group.setattrs("ylims",[this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)])
                    #print [this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)]
            this_species_indep_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=["species_independent"])
            if len(this_species_indep_group.p_subplot_list)>0:
                this_species_indep_group.setattrs("ylims",[this_species_indep_group.get_min("data",margin=0.1),this_species_indep_group.get_max("data",margin=0.1)])
            this_share_scale_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=share_scale,logic="or")
            if len(this_share_scale_group.p_subplot_list)>0:
                this_share_scale_group.setattrs("ylims",[this_share_scale_group.get_min("data",margin=0.1),this_share_scale_group.get_max("data",margin=0.1)])
            
            
        
            
        all_group.setattrs("show_yaxis_ticklabel",True)
        all_group.setattrs("vlines",vlines)
        all_group.setattrs("hlines",hlines)
        last_group.setattrs("show_xaxis_ticklabel",True)
        #print gridspec_list[i_li]
        if xattr=="psi":
            global_xlabel=r"$\psi_N$"
        elif xattr=="theta":
            global_xlabel=r"$\theta/\pi$"
        elif xattr=="sqrtpsi":
            global_xlabel=r"$\sqrt{\psi_N}$"
        elif xattr=="psiOverOrbitWidth":
            global_xlabel=r"$\sqrt{\psi_N}$"
        elif xattr=="actual_psi":
            global_xlabel=r"$\hat{\psi}$"
        elif xattr=="actual_psiN":
            global_xlabel=r"$\psi_N$"
        elif xattr=="psi_index":
            global_xlabel=r"$i_\psi$"
        elif xattr==None:
            global_xlabel=r"$i$"
        perfect_visualizer(psp_list,gridspec_list[i_li],global_xlabel=global_xlabel,dimensions=1,global_ylabel=global_ylabel)
        if same_plot:
            plt.savefig(outputname+".pdf")
        else:
            plt.savefig(attribs[i_li]+".pdf")
        if interactive:
            #dangerous, since it will (for some reason) be executed after all 1d_plot calls and show everything plotted in the given script.
            datacursor(display='multiple', draggable=True)
            plt.show()
示例#7
0
def perfect_0d_plot(dirlist,yattribs,xattribs,normname="norms.namelist",speciesname="species",psiN_to_psiname="psiAHat.h5",cm=cm.rainbow,lg=True,markers=None,linestyles=None,same_plot=False,outputname="default",xlabels=None,ylabels=None,label_all=False,global_xlabel="",global_ylabel="",sort_species=True,first=["D","He"],last=["e"],generic_labels=True,label_dict={"D":"i","He":"z","N":"z","e":"e"},vlines=None,hlines=None,share_scale=[],interactive=False):
    #dirlist: list of simulation directories
    #attribs: list of fields to plot from simulation
    #speciesname: species filename in the simuldir
    #normname: norm filename in the simuldir
    #lg: controls whether to interpret nearby simulations as being paired
    
    if type(yattribs) is not list:
        yattribs=[yattribs]
    if type(xattribs) is not list:
        xattribs=[xattribs]
        
    if ylabels is not None:
        if type(ylabels) is not list:
            ylabels=[ylabels]*len(yattribs)
        else:
            if len(ylabels) != len(yattribs):
                print "p_0d_plot: error: ylabels not the same size as attribs"
                exit(1)
    else:
        ylabels=['']*len(yattribs)
        
    if xlabels is not None:
        if type(xlabels) is not list:
            xlabels=[xlabels]*len(xattribs)
        else:
            if len(xlabels) != len(xattribs):
                print "p_0d_plot: error: ylabels not the same size as attribs"
                exit(1)
    else:
        xlabels=['']*len(xattribs)
                
    
    normlist=[x + "/" + normname for x in dirlist]
    specieslist=[x + "/" + speciesname for x in dirlist]
    psiN_to_psiList=[x + "/" + psiN_to_psiname for x in dirlist]
    simulList=perfect_simulations_from_dirs(dirlist,normlist,specieslist,psiN_to_psiList)
    if markers == None:
        markers=['']*len(simulList)

    num_species_array=numpy.array([len(simul.species) for simul in simulList])
    one_species_list=numpy.where(num_species_array<=1)
    if len(num_species_array[one_species_list])>0:
        print "p_0d_plot: warning: there are simulations with one (or) less species! Logic to determine whether attribute is a species property will not work."
        
    if generic_labels:
        for simul in simulList:
            simul.species_list=generic_species_labels(simul.species_list,label_dict)
            first=generic_species_labels(first,label_dict)
            last=generic_species_labels(last,label_dict)
    species_set=set([])
    for simul in simulList:
        species_set = species_set | set(simul.species)
    
    #print gridspec
    
    i=-1
    psp_lists=[] #list of lists of perfect subplot object
    gridspec_list=[]
    
    colors=cm(numpy.linspace(0,1,len(simulList)))
    #assign colors to simulations
    all_linecolors=[]
    color_index=0

    local=[simul.local for simul in simulList]
    noddpsi=[simul.no_ddpsi for simul in simulList]
    
    if lg:
        colors=cm(numpy.linspace(0,1,len(simulList)-sum(local)-sum(noddpsi)))
        if sum(local)>0:
            #if we have local simulations, increment color after them
            for loc in local:
                all_linecolors.append(colors[color_index])
                if loc == True:
                    color_index=color_index+1
        elif sum(noddpsi)>0:
            #otherwise, increment color after noddpsi simulation
            for nd in noddpsi:
                all_linecolors.append(colors[color_index])
                if nd == True:
                    color_index=color_index+1
        else:
            #else, always increment
            all_linecolors=cm(numpy.linspace(0,1,len(simulList)))
    else:
        # force always increment behavior
        all_linecolors=cm(numpy.linspace(0,1,len(simulList)))

    if linestyles == None:
        linestyles=[] #linestyles generated from local or global
        for n,l in zip(noddpsi,local):
            # local overrides noddpsi in code as well
            if l:
                linestyles=linestyles+["dashed"]
            elif n:
                linestyles=linestyles+["dashdot"]
            else:
                linestyles=linestyles+["solid"]
    
    for i_a,(xattrib,yattrib) in enumerate(zip(xattribs,yattribs)):
        psp_list=[]
        yattrib_sp_dep = is_attribute_species_dependent(simulList,yattrib)
        #we will assign data to the following attribute related groups
        yattrib_groupname=yattrib
        if yattrib_sp_dep:
            species_attrib_groupname="species_dependent"
        else:
            species_attrib_groupname="species_independent"
        if same_plot:
            if i_a == len(yattribs)-1:
                perhaps_last=True
            else:
                perhaps_last=False
        else:
            perhaps_last=True
        if sort_species:
            species_set=sort_species_list(list(species_set),first,last)
        if yattrib_sp_dep:
            for i_sp,s in enumerate(species_set):
                i=i+1
                #data is taken for a given species for all simulations
                #index of species in simulation given by index to index
                index=[[ind for ind,spec in enumerate(simul.species) if spec==s] for simul in simulList]
                
                if all(len(ind)<=1 for ind in index):
                    ydata=[getattr(simul,yattrib)[index[i_si][0]] for i_si,simul in enumerate(simulList) if s in simul.species]
                else:
                    print "p_0d_plot: warning: more than one of the same species in the simulation. Will add contributions."
                    ydata=[numpy.sum(getattr(simul,yattrib)[index[i_si]],axis=1) for i_si,simul in enumerate(simulList) if s in simul.species]
                ydata = numpy.array(ydata)

                xdata=[getattr(simul,xattrib) for simul in simulList if s in simul.species]
                xdata = numpy.array(xdata)
                print repr(xdata)
                print repr(ydata)
                
                linecolors=[all_linecolors[i_si] for i_si,simul in enumerate(simulList) if s in simul.species]
                coordinates=(i,0)
                if perhaps_last and (i_sp == len(species_set) - 1):
                    last_groupname="last"
                    gridspec_list.append([i+1,1])
                else:
                    last_groupname="not_last"

                psp_list.append(perfect_subplot(ydata,xdata,subplot_coordinates=coordinates,groups=[s,yattrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers))
                

        else:
            i=i+1
            if perhaps_last:
                last_groupname="last"
                gridspec_list.append([i+1,1])
            else:
                last_groupname="not_last"
            #species independent plot
            ydata=numpy.array([getattr(simul,yattrib) for simul in simulList])
            xdata=numpy.array([getattr(simul,xattrib) for simul in simulList])
            linecolors=all_linecolors
            coordinates=(i,0)
            
            psp_list.append(perfect_subplot(ydata,xdata,subplot_coordinates=coordinates,groups=[yattrib_groupname,species_attrib_groupname,last_groupname],linestyles=linestyles,colors=linecolors,markers=markers,dimensions=1))
            
        
        psp_lists.append(psp_list)
        if not same_plot:
            i=-1

    #merge the psp_lists if everything is supposed to go in the same plot
    if same_plot:
        final_psp_lists=[]
        for psp_list in psp_lists:
            final_psp_lists = final_psp_lists + psp_list
        psp_lists=[final_psp_lists]
        
            
    for i_li,psp_list in enumerate(psp_lists):
        for psp in psp_list:
            print psp.groups
            xlims = [numpy.min(xdata),numpy.max(xdata)]
            psp.xlims=xlims
            psp.data=psp.data_inrange()
            psp.x=psp.x_inrange()
        if same_plot:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in yattribs]
            for ylabel,attrib_group in zip(ylabels,attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
        else:
            attrib_groups=[perfect_subplot_group(psp_list,groups=[a]) for a in [attribs[i_li]]]
            for ylabel,attrib_group in zip([ylabels[i_li]],attrib_groups):
                if label_all:
                    attrib_group.setattrs("yaxis_label",ylabel)
                else:
                    attrib_group.set_middle_ylabel(ylabel)
                if len(share_scale)>0:
                    share_scale_group=perfect_subplot_group(psp_list,groups=share_scale,logic="or")
                    share_scale_group.setattrs("ylims",[share_scale_group.get_min("data",margin=0.1),share_scale_group.get_max("data",margin=0.1)])
                    

                    
        
        species_groups=[perfect_subplot_group(psp_list,groups=[s]) for s in species_set]
        species_indep_groups=perfect_subplot_group(psp_list,groups=["species_independent"])
        local_group = perfect_subplot_group(psp_list,groups=["local"])
        global_group = perfect_subplot_group(psp_list,groups=["global"])
        last_group = perfect_subplot_group(psp_list,groups=["last"])
        all_group=perfect_subplot_group(psp_list,groups='',get_all=True)
        
        for species_group,s in zip(species_groups,species_set):
            species_group.setattrs("title",s)

        

        for attrib_group in attrib_groups:
            this_species_groups=[perfect_subplot_group(attrib_group.p_subplot_list,groups=[s]) for s in species_set]
            for this_species_group in this_species_groups:
                if len(this_species_group.p_subplot_list)>0:
                    this_species_group.setattrs("ylims",[this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)])
                    #print [this_species_group.get_min("data",margin=0.1),this_species_group.get_max("data",margin=0.1)]
            this_species_indep_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=["species_independent"])
            if len(this_species_indep_group.p_subplot_list)>0:
                this_species_indep_group.setattrs("ylims",[this_species_indep_group.get_min("data",margin=0.1),this_species_indep_group.get_max("data",margin=0.1)])
            this_share_scale_group=perfect_subplot_group(attrib_group.p_subplot_list,groups=share_scale,logic="or")
            if len(this_share_scale_group.p_subplot_list)>0:
                this_share_scale_group.setattrs("ylims",[this_share_scale_group.get_min("data",margin=0.1),this_share_scale_group.get_max("data",margin=0.1)])
            
            
        
            
        all_group.setattrs("show_yaxis_ticklabel",True)
        all_group.setattrs("vlines",vlines)
        all_group.setattrs("hlines",hlines)
        last_group.setattrs("show_xaxis_ticklabel",True)
        
        perfect_visualizer(psp_list,gridspec_list[i_li],global_xlabel=global_xlabel,dimensions=1,global_ylabel=global_ylabel)
        if same_plot:
            plt.savefig(outputname+".pdf")
        else:
            plt.savefig(attribs[i_li]+".pdf")
        if interactive:
            #dangerous, since it will (for some reason) be executed after all 0d_plot calls and show everything plotted in the given script.
            datacursor(display='multiple', draggable=True)
            plt.show()
示例#8
0
from cycler import cycler

cm=plt.get_cmap('gist_rainbow')
NUM_COLORS=9

script_dir=os.path.dirname(__file__)
rel_path_o="Output_data/"
abs_path_o=os.path.join(script_dir,rel_path_o)

# plt.rc('axes', prop_cycle=(cycler('linestyle', ['-', '--', ':', '-.'])))

fig, ax = plt.subplots(1, 1,figsize=(12,9))

ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.set_prop_cycle(cycler('color',[cm(1.*i/9) for i in range(9)])*cycler('linestyle',['-', '--', ':']))

handle_list=[]

for item in glob.glob(abs_path_o+'Gradient_attack_SVM_PCA_*.txt'):
    curr_array=np.genfromtxt(item,skip_header=1,delimiter=',')
    handle_list.append(plt.plot(curr_array[:,1],curr_array[:,2],label=int(curr_array[0,0])))

curr_array=np.genfromtxt(abs_path_o+'Gradient_attack_SVM_no_PCA_.txt',
skip_header=1,delimiter=',')
plt.plot(curr_array[:,1],curr_array[:,2],label='noPCA')

plt.xlabel(r'Adversarial perturbation $\epsilon$')
plt.ylabel('Misclassification percentage')
plt.title('Adversarial example success vs. perturbation magnitude \n'
            ' for various reduced dimensions using the '