Beispiel #1
0
def demo_fixed_size_axes():
    fig1 = plt.figure(1, (6, 6))
    h = [Size.Fixed(1.0), Size.Fixed(4.5)]
    v = [Size.Fixed(0.7), Size.Fixed(5.)]
    divider = Divider(fig1, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    ax = LocatableAxes(fig1, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
    fig1.add_axes(ax)
    ax.plot([1,2,3])
Beispiel #2
0
def demo_fixed_pad_axes():
    fig = plt.figure(2, (6, 6))
    h = [Size.Fixed(1.0), Size.Scaled(1.), Size.Fixed(.2),]
    v = [Size.Fixed(0.7), Size.Scaled(1.), Size.Fixed(.5),]
    divider = Divider(fig, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    ax = LocatableAxes(fig, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))
    fig.add_axes(ax)
    ax.plot([1,2,3])
def demo_fixed_size_axes():

    fig1 = plt.figure(1, (6, 6))

    # The first items are for padding and the second items are for the axes.
    # sizes are in inch.
    h = [Size.Fixed(1.0), Size.Fixed(4.5)]
    v = [Size.Fixed(0.7), Size.Fixed(5.)]

    divider = Divider(fig1, (0.0, 0.0, 1., 1.), h, v, aspect=False)
    # the width and height of the rectangle is ignored.

    ax = LocatableAxes(fig1, divider.get_position())
    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    fig1.add_axes(ax)

    ax.plot([1,2,3])
 def subplot_array( self, hsize, vsize=(1.0,), figsize=(10,10)):
     """ Use the axes_divider module to make a single row of plots
     hsize : list of floats
         horizontal spacing: alternates Scaled for plot, Fixed for between plots
     vsize : list of floats
         vertical spacing
         
     ref:   http://matplotlib.org/mpl_toolkits/axes_grid/users/axes_divider.html
     """
     nx = (len(hsize)+1)/2
     ny = (len(vsize)+1)/2
     fig, axx = plt.subplots(ny,nx,squeeze=False, figsize=figsize) # just to make the axes, will move them
     sizer = lambda x,i: axes_size.Scaled(x) if i%2==0 else axes_size.Fixed(x)
     horiz = [ sizer(h,i) for i,h in enumerate(hsize) ]
     vert  = [ sizer(v,i) for i,v in enumerate(vsize) ]
     divider = Divider(fig, (0.1, 0.1, 0.8, 0.8), horiz, vert, aspect=False)
     for i,ax in enumerate(axx.flatten()):
         iy = i//nx; ix = i%nx
         ax.set_axes_locator(divider.new_locator(nx=2*ix, ny=2*iy))
     return fig, axx
Beispiel #5
0
 def subplot_array(self, hsize, vsize=(1.0, ), figsize=(10, 10)):
     """ Use the axes_divider module to make a single row of plots
     hsize : list of floats
         horizontal spacing: alternates Scaled for plot, Fixed for between plots
     vsize : list of floats
         vertical spacing
         
     ref:   http://matplotlib.org/mpl_toolkits/axes_grid/users/axes_divider.html
     """
     nx = (len(hsize) + 1) / 2
     ny = (len(vsize) + 1) / 2
     fig, axx = plt.subplots(
         ny, nx, squeeze=False,
         figsize=figsize)  # just to make the axes, will move them
     sizer = lambda x, i: axes_size.Scaled(
         x) if i % 2 == 0 else axes_size.Fixed(x)
     horiz = [sizer(h, i) for i, h in enumerate(hsize)]
     vert = [sizer(v, i) for i, v in enumerate(vsize)]
     divider = Divider(fig, (0.1, 0.1, 0.8, 0.8), horiz, vert, aspect=False)
     for i, ax in enumerate(axx.flatten()):
         iy = i // nx
         ix = i % nx
         ax.set_axes_locator(divider.new_locator(nx=2 * ix, ny=2 * iy))
     return fig, axx
import mpl_toolkits.axes_grid.axes_size as Size
from mpl_toolkits.axes_grid import Divider
import matplotlib.pyplot as plt

fig1 = plt.figure(1, (5.5, 4.))

# the rect parameter will be ignore as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig1.add_axes(rect, label="%d"%i) for i in range(4)]

horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.),
         Size.Scaled(.5)]

vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]

# divide the axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig1, rect, horiz, vert, aspect=False)

ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))
ax[1].set_axes_locator(divider.new_locator(nx=0, ny=2))
ax[2].set_axes_locator(divider.new_locator(nx=2, ny=2))
ax[3].set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))

for ax1 in ax:
    plt.setp(ax1.get_xticklabels()+ax1.get_yticklabels(),
             visible=False)

plt.draw()
plt.show()
import mpl_toolkits.axes_grid.axes_size as Size
from mpl_toolkits.axes_grid import Divider
import matplotlib.pyplot as plt

fig1 = plt.figure(1, (5.5, 4.))

# the rect parameter will be ignore as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig1.add_axes(rect, label="%d" % i) for i in range(4)]

horiz = [Size.Scaled(1.5), Size.Fixed(.5), Size.Scaled(1.), Size.Scaled(.5)]

vert = [Size.Scaled(1.), Size.Fixed(.5), Size.Scaled(1.5)]

# divide the axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig1, rect, horiz, vert, aspect=False)

ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))
ax[1].set_axes_locator(divider.new_locator(nx=0, ny=2))
ax[2].set_axes_locator(divider.new_locator(nx=2, ny=2))
ax[3].set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))

for ax1 in ax:
    plt.setp(ax1.get_xticklabels() + ax1.get_yticklabels(), visible=False)

plt.draw()
plt.show()
from mpl_toolkits.axes_grid import Divider
import matplotlib.pyplot as plt


fig1 = plt.figure(1, (5.5, 4))

# the rect parameter will be ignore as we will set axes_locator
rect = (0.1, 0.1, 0.8, 0.8)
ax = [fig1.add_axes(rect, label="%d"%i) for i in range(4)]


horiz = [Size.AxesX(ax[0]), Size.Fixed(.5), Size.AxesX(ax[1])]
vert = [Size.AxesY(ax[0]), Size.Fixed(.5), Size.AxesY(ax[2])]

# divide the axes rectangle into grid whose size is specified by horiz * vert
divider = Divider(fig1, rect, horiz, vert, aspect=False)


ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0))
ax[1].set_axes_locator(divider.new_locator(nx=2, ny=0))
ax[2].set_axes_locator(divider.new_locator(nx=0, ny=2))
ax[3].set_axes_locator(divider.new_locator(nx=2, ny=2))

ax[0].set_xlim(0, 2)
ax[1].set_xlim(0, 1)

ax[0].set_ylim(0, 1)
ax[2].set_ylim(0, 2)

divider.set_aspect(1.)
def create_multipanel_plot(size, dpi, shape, layout, var_info, cmap, lims):
        fig = plt.figure(figsize=size, dpi=dpi)
        rings = []

        # the rect parameter will be ignore as we will set axes_locator
        rect = (0.08, 0.08, 0.9, 0.9)
        nrow,ncol = shape

        # divide the axes rectangle into grid whose size is specified
        # by horiz * vert
        horiz = [Scaled(1.)]
        for i in range(ncol - 1):
            horiz.extend([Fixed(.2), Scaled(1.)])

        vert = [Scaled(.1), Fixed(.35), Scaled(1.)]
        for i in range(nrow - 1):
            vert.extend([Fixed(.1), Scaled(1.)])

        divider = Divider(fig, rect, horiz, vert, aspect=False)

#        ax0 = fig.add_axes(rect, label="0")
#        ax0.set_aspect('equal', 'datalim')
#        ax = [ax0] + [fig.add_axes(rect, label="%d"%i, sharex=ax0, sharey=ax0)
#            for i in range(1,6)]
        ax = [fig.add_axes(rect, label="%d"%i) for i in range(len(layout))]
        cax = [fig.add_axes(rect, label='cb%d'%i) for i in range(ncol)]

        for i,a in enumerate(ax):
#            a.set_axes_locator(divider.new_locator(nx=(i // nrow) * 2,
#                ny=((i%nrow) + 1) * 2))
            a.set_axes_locator(divider.new_locator(nx=(i % ncol) * 2,
                ny=(nrow - (i // ncol)) * 2))
            a.set_aspect('equal', 'datalim')

        for i,a in enumerate(cax):
            a.set_axes_locator(divider.new_locator(nx=2 * i, ny=0))

        for num,(a,(data, label, var)) in enumerate(zip(ax, layout)):
            norm,ticks,units = var_info[var]
            ppi_plot(init_data.xlocs, init_data.ylocs, data, norm=norm,
                cmap=cmap, ax=a, rings=rings)
#            a.set_title('%s (%s)' % (moment, units))

            if num >= ncol:
                a.set_xlabel('X Distance (km)')
                cbar = ColorbarBase(ax=cax[num%ncol], norm=norm, cmap=cmap,
                    orientation='horizontal')
                cbar.set_label('%s (%s)' % (label, units))
                cbar.set_ticks(ticks)
            else:
                a.xaxis.set_major_formatter(plt.NullFormatter())

            if num % ncol == 0:
                a.set_ylabel('Y Distance (km)')
            else:
                a.yaxis.set_major_formatter(plt.NullFormatter())

            if lims:
                a.xaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.yaxis.set_major_locator(plt.MultipleLocator(lims[0]))
                a.set_xlim(*lims[1:3])
                a.set_ylim(*lims[3:])

            # loc = 2 is upper left. TODO: Should patch matplotlib to use
            # same strings as legend
            at = AnchoredText("%s)" % chr(97 + num), loc=2, prop=dict(size='large'),
                frameon=True)
#            at.patch.set_boxstyle("round, pad=0., rounding_size=0.2")
            a.add_artist(at)

        return fig
Beispiel #10
0
    def redraw(self):
        if len(self.input) == 0:
            self.warning("Empty input")
            return
        fast_redraw = self.name in self.pp.get_figlabels()
        fig = self.pp.figure(self.name)
        axes = fig.add_subplot(111)

        if not fast_redraw:
            self.draw_grid(axes)
        else:
            while len(axes.texts):
                axes.texts[0].remove()

        # Draw the inner hexagons with text
        all_patches = [list() for _ in range(len(self.fitness_by_label))]
        hits_max = numpy.max(self.input)
        if hits_max == 0:
            hits_max = 1
        reversed_result = {}
        for label, neurons in enumerate(self.result):
            for neuron in neurons:
                reversed_result[neuron] = label
        # Add hexagons one by one
        for y in range(self.height):
            for x in range(self.width):
                neuron = y * self.width + x
                fitness = self.fitness_by_neuron[neuron]
                number = self.input[y * self.width + x]
                if numpy.sqrt(number / hits_max) <= \
                   KohonenHits.SIZE_TEXT_THRESHOLD:
                    fitness = 0
                try:
                    label = reversed_result[neuron]
                except KeyError:
                    continue
                patches = all_patches[label]
                self._add_hexagon(axes, patches, x, y, fitness)
        if fast_redraw:
            axes.collections = [axes.collections[-1]]
        else:
            legend_patches = []
        cmap = getattr(self.cm, self.cmap)
        for index, patches in enumerate(all_patches):
            if len(patches) == 0:
                continue
            facecolor = cmap(index * cmap.N // len(all_patches))
            col = self.matplotlib.collections.PatchCollection(
                patches, edgecolors='none', facecolors=facecolor)
            axes.add_collection(col)
            if not fast_redraw:
                legend_patches.append(
                    self.matplotlib.patches.Patch(
                        color=facecolor,
                        label="%d - %.2f" %
                        (index, self.fitness_by_label[index])))
        # Make the grid to be drawn last
        axes.collections = axes.collections[1:] + [axes.collections[0]]

        if not fast_redraw:
            legend = axes.legend(handles=legend_patches,
                                 loc='upper left',
                                 bbox_to_anchor=(1.05, 1),
                                 borderaxespad=0.0,
                                 title="Fitness: %.2f" % self.fitness)
            fig.tight_layout()
            # The legend becomes truncated, but it should not
            # Measure the legend width to fix buggy matplotlib layout
            # Without drawing, window extent equals to 1
            if legend is not None:
                legend.draw(fig.canvas.get_renderer())
                bbox = legend.get_window_extent()
                bbox = bbox.transformed(fig.dpi_scale_trans.inverted())

                from mpl_toolkits.axes_grid import Divider
                from mpl_toolkits.axes_grid.axes_size import Fixed, Scaled
                divider = Divider(
                    fig, (0.05, 0.05, 0.9, 0.9),
                    (Scaled(1.0), Fixed(bbox.width), Scaled(0.05)),
                    (Scaled(1), Fixed(0)))
                axes.set_axes_locator(divider.new_locator(0, 0))
        else:
            # Modify legend title and labels
            legend = axes.get_legend()
            if legend is not None:
                legend.set_title("Fitness: %.2f" % self.fitness)
                for index, text in enumerate(legend.get_texts()):
                    text.set_text("%d - %.2f" %
                                  (index, self.fitness_by_label[index]))
        self.show_figure(fig)
        fig.canvas.draw()
        return fig
Beispiel #11
0
from mpl_toolkits.axes_grid import Size, Divider
import matplotlib.pyplot as plt
fig1 = plt.figure(1, (6, 6))
horiz = [Size.Fixed(1.), Size.Fixed(.5), Size.Fixed(1.5),
         Size.Fixed(.5)] 
vert = [Size.Fixed(1.5), Size.Fixed(.5), Size.Fixed(1.)]
rect = (0.1, 0.1, 0.8, 0.8)
divider = Divider(fig1, rect, horiz, vert, aspect=False)
ax1 = fig1.add_axes(rect, label="1")
ax2 = fig1.add_axes(rect, label="2")
ax3 = fig1.add_axes(rect, label="3")
ax4 = fig1.add_axes(rect, label="4")
ax1.set_axes_locator(divider.new_locator(nx=0, ny=0))
ax2.set_axes_locator(divider.new_locator(nx=0, ny=2))
ax3.set_axes_locator(divider.new_locator(nx=2, ny=2))
ax4.set_axes_locator(divider.new_locator(nx=2, nx1=4, ny=0))
plt.draw()
plt.show()
def main(path):
    adsdata = ads_data.AdsData(path)

    all_structs = adsdata.get_all_structs()
    print(all_structs)
    
    all_temps = adsdata.get_all_temps()
    print(all_temps)

    all_num_comps = adsdata.get_all_num_comps()
    print(all_num_comps)

    all_comps = adsdata.get_all_comps()
    print(all_comps)

    all_possible_ratios = adsdata.get_all_possible_ratios()
    print(all_possible_ratios)

    num_grids = len(all_temps)

    # dubug grid indexing
    #num_grids = 6 
    with PdfPages(os.getcwd() + "/delH_asfcn_n.pdf") as pdf:
    #print(adsdata.master_dict[all_structs[-1]][all_temps[-1]][all_num_comps[-1]][all_comps[-1]])
        curr_fig = 0

        # Max num of columns of grid is 2
        if(num_grids == 1):
            colnum = 1
        else:
            colnum = 2 

        # all the rest of the grids get stacked in the rows underneath
        rownum = int(math.ceil(float(num_grids)/colnum))

        # one special object is buffered in the first row to the right of the two grids
        special_obj_buffer = 2.6

        grid_x = 3.5
        grid_y = 2.9

        if(rownum == 1):
            figsize = (colnum*grid_x+special_obj_buffer, rownum*grid_y)
        else:
            figsize = (colnum*grid_x+special_obj_buffer, rownum*grid_y+1.2)


        fig = plt.figure(curr_fig, figsize=figsize)

        # the location of the axes in each grid
        #rect = (0.1,0.1,0.8,0.8)
        rect = (0.06,0.16,0.2,0.2)
        #rect = (0.0,0.0,0.2,0.2)
        #ax = [fig.add_axes(rect, label="%d"%i) for i in range((colnum+1)*rownum)]
        ax = [fig.add_axes(rect, label="%d"%i) for i in range(num_grids+1)]

        horiz = []
        vert = []
        all_rect = []
    
        #for i in range(colnum):
        #    horiz += [Size.Fixed(3.5)]
        #for j in range(rownum):
        #    vert += [Size.Fixed(2.8)]
        #    all_rect.append(rect)
        #print(Size.Scaled(1).get_size())
        for i in range(colnum):
            horiz += [Size.Fixed(2.9), Size.Fixed(0.6)]
        for j in range(rownum):
            vert += [Size.Fixed(2.2), Size.Fixed(0.6)]

        horiz.pop()
        horiz += [Size.Fixed(0.2)]
        vert.pop()
        horiz += [Size.Fixed(special_obj_buffer - 1.0),Size.Fixed(0.2)]


        divider = Divider(fig, rect, horiz, vert, aspect=False)
        this_rect = divider.get_position()
        print('num_grids' + str(num_grids))
        print('num_rows' + str(rownum))
        print('num_rows' + str(colnum))
        # set all access, i counts across rows and wraps to the next row after reaching max of columns
        for i in range(num_grids):
            print(rownum)
            print(int(np.floor(i/colnum)))
            if(num_grids <= colnum):
                row_ind = 0
            else:
                row_ind = 2*((rownum-1) - int(np.floor(i/colnum)))
            col_ind = 2*(np.mod(i,colnum))
            print(str(i) + ": " + " nx: " + str(col_ind) + " ny: " + str(row_ind))
            ax[i].set_axes_locator(divider.new_locator(nx = col_ind, ny = row_ind))


        # set special object access to last column in first row
        special_col_ind = 2*(colnum)
        special_row_ind = 2*(rownum-1)
        print(str("s") + ": " + " nx: " + str(special_col_ind) + " ny: " + str(special_row_ind))
        ax[num_grids].set_axes_locator(divider.new_locator(nx = special_col_ind, ny=0, ny1 = special_row_ind+1))

        #plt.show()

    

        # for keeping track of the 95% drop
        summary1 = []
        summary2 = []

        ax_iter = -1 
        plot_max_max = -1
        for this_temp in all_temps: 
            ax_iter += 1
            print("\n\nPREPARING TEMP = " + str(this_temp) + " K\n----------------------------------")
            temp = this_temp
            temp_ind = all_temps.index(temp)
            xkey = "water"
            plot_xs = []
            plot_ys = []
            plot_ys_err = []

            percentage_drop = []
            labels = []
            colors = []
            markers = []
            linestyles = []
            facecolors = []
            edgecolors = []
            mfcs = []



            plot_max = 0.0
            for i in range(len(all_structs)):
                for j in range(len(all_num_comps)):
                    comp = all_comps[j]
                    if(all_structs[i] == "0_all_conf_0_0_full_symm"):
                        this_struct = "Mg$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        labels.append(this_struct + ": " + comp)
                        linestyles += ["--" for k in range(int(all_num_comps[j]))]
                        mfcs.append('white')
                        facecolors.append('white')
                        edgecolors.append('blue')
                        colors.append('blue')
                        print(markers)
                    elif(all_structs[i] == "1000_all_conf_0_0_full_symm"):
                        this_struct = "Mg$_2$(DHFUMA)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('blue')
                        facecolors.append('blue')
                        edgecolors.append('blue')
                        colors.append('blue')
                        print(markers)
                    elif(all_structs[i] == "Fe_dobdc"):
                        this_struct = "Fe$_2$(DOBDC)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["--" for k in range(int(all_num_comps[j]))]
                        mfcs.append('white')
                        facecolors.append('white')
                        edgecolors.append('firebrick')
                        colors.append('firebrick')
                        print(markers)
                    elif(all_structs[i] == "Fe_dhfuma"):
                        this_struct = "Fe$_2$(DHFUMA)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('firebrick')
                        facecolors.append('firebrick')
                        edgecolors.append('firebrick')
                        colors.append('firebrick')
                        print(markers)
                    elif(all_structs[i] == "Co_dobdc"):
                        this_struct = "Co$_2$(DOBDC)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["--" for k in range(int(all_num_comps[j]))]
                        mfcs.append('white')
                        facecolors.append('white')
                        edgecolors.append('dimgray')
                        colors.append('dimgray')
                        print(markers)
                    elif(all_structs[i] == "Co_dhfuma"):
                        this_struct = "Co$_2$(DHFUMA)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('dimgray')
                        facecolors.append('dimgray')
                        edgecolors.append('dimgray')
                        colors.append('dimgray')
                        print(markers)
                    elif(all_structs[i] == "Ni_dobdc"):
                        this_struct = "Ni$_2$(DOBDC)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["--" for k in range(int(all_num_comps[j]))]
                        mfcs.append('white')
                        facecolors.append('white')
                        edgecolors.append('gold')
                        colors.append('gold')
                        print(markers)
                    elif(all_structs[i] == "Ni_dhfuma"):
                        this_struct = "Ni$_2$(DHFUMA)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('gold')
                        facecolors.append('gold')
                        edgecolors.append('gold')
                        colors.append('gold')
                        print(markers)
                    elif(all_structs[i] == "Zn_dobdc"):
                        this_struct = "Zn$_2$(DOBDC)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["--" for k in range(int(all_num_comps[j]))]
                        mfcs.append('white')
                        facecolors.append('white')
                        edgecolors.append('green')
                        colors.append('green')
                        print(markers)
                    elif(all_structs[i] == "Zn_dhfuma"):
                        this_struct = "Zn$_2$(DHFUMA)"
                        labels.append(this_struct + ": " + comp)
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('green')
                        facecolors.append('green')
                        edgecolors.append('green')
                        colors.append('green')
                        print(markers)
                    elif(all_structs[i] == "1001_all_conf_0_0_full_symm"):
                        this_struct = "MW_INV"
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('black')
                        facecolors.append('black')
                        edgecolors.append('black')
                        colors.append('black')
                    else:
                        this_struct = all_structs[i]
                        labels.append(this_struct + ": " + comp)
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        mfcs.append('black')
                        facecolors.append('black')
                        edgecolors.append('black')
                        colors.append('black')


                    # NOTE all keys
                    #temp        comp  partial_p          partial_f          fugacity_coeff  avg_load[molec/unit_cell]  avg_err[molec/unit_ce    ll]  avg_load[mol/kg]  avg_err[mol/kg]  avg_load[mg/g]  avg_err[mg/g]  exs_load[molec/unit_cell]  exs_err[molec/unit_cell]  exs_load    [mol/kg]  exs_err[mol/kg]  exs_load[mg/g]  exc_err[mg/g]  heat_of_des[K]  heat_of_des_err[K]  heat_of_des[kJ/mol]  heat_of_des_err[k    J/mol]

                    # Some structs/temps may have different ratio_keys
                    x, y = adsdata.extract_data(all_structs[i], all_temps[temp_ind],"1", comp, len(all_possible_ratios), yheader = "heat_of_des[kJ/mol]")
                    x_err, y_err = adsdata.extract_data(all_structs[i], all_temps[temp_ind],"1", comp, len(all_possible_ratios), yheader = "heat_of_des_err[kJ/mol]")
                    x = np.array(x)/100000
                    y = np.array(y)
                    y_err = np.array(y_err)

                    perm = x.argsort()
                    x = x[perm]
                    y = y[perm]
                    y_err = y_err[perm]
                    # Print debug info to terminal
                    print(this_struct + ": " + comp)
                    print("x: " + str(x))
                    print("y: " + str(y))

                    plot_xs.append(x)
                    plot_ys.append(y)
                    plot_ys_err.append(y_err)
                    try:
                        if(max(y) > plot_max):
                            plot_max = max(y)
                    except:
                        plot_max = plot_max
                    

        


            if(plot_max > plot_max_max):
                plot_max_max = float(plot_max)

            print("Data max:" + str(plot_max))
            print("Overall max:" + str(plot_max_max))
            #fig = plt.figure(curr_fig, figsize = (7,5.6))
            #ax = fig.add_subplot(1, 1, 1)
            ax[ax_iter].set_xlabel(r'CO$_2$ Pressure [bar]')
            ax[ax_iter].set_ylabel(r'Avg. Heat of Des. [kJ/mol]')
            ax[ax_iter].set_xscale('log')
            #ax[ax_iter].set_xlim((0, 1))
            ax[ax_iter].set_ylim(0,plot_max_max*1.2)

            label = this_temp
            ax[ax_iter].legend(label, title='T=' + str(this_temp) + ' K', loc='upper left', frameon = False, framealpha=1.0, prop={'size':10})


            #axtwin = ax[ax_iter].twinx()
            #axtwin.set_ylabel(r'% CO$_2$ Capacity Lost')
            #axtwin.set_ylim(0,100)


            merge_legends = []
         
            #for i in range(len(all_structs)*int(all_num_comps[0]) + int(all_num_comps[0])): 
            #    if((i+1)%(int(all_num_comps[0])+1)==0):
            #        print("twin axis: " + str(i))
            #        #merge_legends += axtwin.plot(plot_xs[i], plot_ys[i], label=labels[i], color = colors[i], marker = markers[i], linestyle = linestyles[i], fillstyle='none')
            #    else:
            for i in range(len(markers)):
                merge_legends += ax[ax_iter].plot(plot_xs[i], plot_ys[i], label=labels[i], ms = 3, marker = markers[i], linestyle = linestyles[i], color = colors[i], mfc = mfcs[i], mec = edgecolors[i], markeredgewidth = 1)
                #ax[ax_iter].errorbar(plot_xs[i], plot_ys[i], yerr = plot_ys_err[i], label=labels[i], marker = markers[i], linestyle = linestyles[i],color = colors[i], mfc = mfcs[i], mec = edgecolors[i], markeredgewidth = 1)
                ax[ax_iter].scatter(plot_xs[i], plot_ys[i], label=labels[i], marker = markers[i], s = 3, facecolors = facecolors[i], edgecolors = edgecolors[i], linestyle = linestyles[i])


            print(type(merge_legends))
            merge_labels = [l.get_label() for l in merge_legends]
           
            #merge_legends = np.array(merge_legends) 
            #merge_labels = np.array(merge_labels) 

            #perm = merge_labels.argsort(key=lambda x:x[0])
            #merge_legends = merge_legends[perm]
            lab_leg = zip(merge_labels, merge_legends)
            lab_leg.sort(key=lambda x:x[0:6][0])
       
            merge_labels = [lab_leg[i][0] for i in range(len(lab_leg))] 
            merge_legends = [lab_leg[i][1] for i in range(len(lab_leg))] 
            #merge_labels, merge_legends
            #merge_labels.sort(key=lambda x:x[0])

        # ax num_grids is the axis allocated for the legend
        ax[num_grids].legend(merge_legends, merge_labels, loc='center left', prop={'size':12})
        ax[num_grids].get_xaxis().set_visible(False)
        ax[num_grids].get_yaxis().set_visible(False)
        ax[num_grids].set_frame_on(False)
        #ax.legend(merge_legends, merge_labels, loc='best', prop={'size':12})
        #plt.tight_layout()

        #pdf.savefig(fig)
        fig.savefig(os.getcwd() + "/" + all_comps[0] + "_heat_of_des_ALL_T.png", dpi = 300)

            #curr_fig += 1
        print("Summary1:")
        for i in range(len(summary1)):
            print(summary1[i])
        print("Summary2:")
        for i in range(len(summary2)):
            print(summary2[i])
Beispiel #13
0
def static_plot_grid_hist_selections(lst_det_left, lst_det_right, selection,
                                     fname_det):
    """

    :param lst_det_left:
    :param lst_det_right:
    :param selection:
    :param fname_det:
    """
    # Plot starts here:
    cms = matplotlib.cm
    color_map_left = cms.Blues
    color_map_right = cms.RdPu

    if fname_det:
        f1 = plt.figure(1, (23, 13), dpi=1200)
    else:
        f1 = plt.figure(1, (15, 8))

    vel_range = range(-90, 70)

    f1.clf()
    # the rect parameter is ignored as we set the axes_locator
    rect = (0.05, 0.07, 0.9, 0.87)
    f1ax = [f1.add_axes(rect, label="%d" % i) for i in range(7)]
    horiz = [
        Size.Scaled(5.),
        Size.Fixed(1.0),
        Size.Scaled(1.5),
        Size.Fixed(1.0),
        Size.Scaled(2.)
    ]
    vert = [
        Size.Scaled(1.),
        Size.Fixed(0.5),
        Size.Scaled(1.),
        Size.Fixed(0.5),
        Size.Scaled(1.),
        Size.Fixed(0.5),
        Size.Scaled(1.)
    ]

    # divide the axes rectangle into grid whose size is specified by horiz * vert
    divider = Divider(f1, rect, horiz, vert, aspect=False)
    f1ax[0].set_axes_locator(divider.new_locator(nx=0, ny=0, ny1=7))
    f1ax[1].set_axes_locator(divider.new_locator(nx=2, ny=0))
    f1ax[2].set_axes_locator(divider.new_locator(nx=2, ny=2))
    f1ax[3].set_axes_locator(divider.new_locator(nx=2, ny=4))
    f1ax[4].set_axes_locator(divider.new_locator(nx=2, ny=6))
    f1ax[5].set_axes_locator(divider.new_locator(nx=4, ny=0, ny1=3))
    f1ax[6].set_axes_locator(divider.new_locator(nx=4, ny=4, ny1=7))

    f1ax[0].axis([-40, 100, -80, 80])
    f1ax[5].axis([-140, 140, 0, 100])
    f1ax[6].axis([-140, 140, -100, 80])

    f1ax[0].grid(True)
    f1ax[1].grid(True)
    f1ax[2].grid(True)
    f1ax[3].grid(True)
    f1ax[4].grid(True)
    f1ax[5].grid(True)
    f1ax[6].grid(True)

    number_of_dets_left = 0
    number_of_dets_left_processed = 0
    number_of_dets_right = 0
    number_of_dets_right_processed = 0

    # Left radar plot
    if lst_det_left:
        LR_data = lst_det_left.get_array_detections_selected(
            selection=selection)
        if LR_data["mcc"].any():
            LR_data_exists = True
            f1ax[2].hist(LR_data["rvelocity"],
                         vel_range,
                         color=color_map_left(0.4),
                         normed=1)
            number_of_dets_left = np.size(LR_data["mcc"])

            if selection["beam_tp"].count(0):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [0]
                LR0_data = lst_det_left.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[1].hist(LR0_data["rvelocity"],
                             vel_range,
                             color=color_map_left(0.2),
                             normed=1,
                             label='beam 0')
                f1ax[0].plot(LR0_data["x"],
                             LR0_data["y"],
                             color=color_map_left(0.2),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 0')
                f1ax[6].plot(-180 * LR0_data["razimuth"] / np.pi,
                             LR0_data["rvelocity"],
                             color=color_map_left(0.2),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 0')
                f1ax[5].plot(-180 * LR0_data["razimuth"] / np.pi,
                             LR0_data["range"],
                             color=color_map_left(0.2),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 0')
                number_of_dets_left_processed += np.size(LR0_data["mcc"])

            if selection["beam_tp"].count(1):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [1]
                LR1_data = lst_det_left.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[1].hist(LR1_data["rvelocity"],
                             vel_range,
                             color=color_map_left(0.4),
                             normed=1,
                             label='beam 1')
                f1ax[0].plot(LR1_data["x"],
                             LR1_data["y"],
                             color=color_map_left(0.4),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 1')
                f1ax[6].plot(-180 * LR1_data["razimuth"] / np.pi,
                             LR1_data["rvelocity"],
                             color=color_map_left(0.4),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 1')
                f1ax[5].plot(-180 * LR1_data["razimuth"] / np.pi,
                             LR1_data["range"],
                             color=color_map_left(0.4),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 1')
                number_of_dets_left_processed += np.size(LR1_data["mcc"])

            if selection["beam_tp"].count(2):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [2]
                LR2_data = lst_det_left.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[1].hist(LR2_data["velocity"],
                             vel_range,
                             color=color_map_left(0.6),
                             normed=1,
                             label='beam 2')
                f1ax[0].plot(LR2_data["x"],
                             LR2_data["y"],
                             color=color_map_left(0.6),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 2')
                f1ax[6].plot(-180 * LR2_data["azimuth"] / np.pi,
                             LR2_data["velocity"],
                             color=color_map_left(0.6),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 2')
                f1ax[5].plot(-180 * LR2_data["azimuth"] / np.pi,
                             LR2_data["range"],
                             color=color_map_left(0.6),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 2')
                number_of_dets_left_processed += np.size(LR2_data["mcc"])

            if selection["beam_tp"].count(3):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [3]
                LR3_data = lst_det_left.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[1].hist(LR3_data["rvelocity"],
                             vel_range,
                             color=color_map_left(0.8),
                             normed=1,
                             label='beam 3')
                f1ax[0].plot(LR3_data["x"],
                             LR3_data["y"],
                             color=color_map_left(0.8),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 3')
                f1ax[6].plot(-180 * LR3_data["razimuth"] / np.pi,
                             LR3_data["rvelocity"],
                             color=color_map_left(0.8),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 3')
                f1ax[5].plot(-180 * LR3_data["razimuth"] / np.pi,
                             LR3_data["range"],
                             color=color_map_left(0.8),
                             marker='o',
                             ls='None',
                             label='Left RDR, beam 3')
                number_of_dets_left_processed += np.size(LR3_data["mcc"])

            plt.draw()
        else:
            LR_data_exists = False

    # Right radar plot
    if lst_det_right:
        RR_data = lst_det_right.get_array_detections_selected(
            mcc=selection['mcc_tp'])
        if RR_data["mcc"].any():
            RR_data_exists = True
            f1ax[4].hist(RR_data["velocity"],
                         vel_range,
                         color=color_map_left(0.4),
                         normed=1)
            number_of_dets_right = np.size(RR_data["mcc"])

            if selection["beam_tp"].count(0):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [0]
                RR0_data = lst_det_right.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[3].hist(RR0_data["velocity"],
                             vel_range,
                             color=color_map_right(0.2),
                             normed=1,
                             label='beam 0')
                f1ax[0].plot(RR0_data["x"],
                             RR0_data["y"],
                             color=color_map_right(0.2),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 0')
                f1ax[6].plot(-180 * RR0_data["azimuth"] / np.pi,
                             RR0_data["velocity"],
                             color=color_map_right(0.2),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 0')
                f1ax[5].plot(-180 * RR0_data["azimuth"] / np.pi,
                             RR0_data["range"],
                             color=color_map_right(0.2),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 0')
                number_of_dets_right_processed += np.size(RR0_data["mcc"])

            if selection["beam_tp"].count(1):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [1]
                RR1_data = lst_det_right.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[3].hist(RR1_data["velocity"],
                             vel_range,
                             color=color_map_right(0.4),
                             normed=1,
                             label='beam 1')
                f1ax[0].plot(RR1_data["x"],
                             RR1_data["y"],
                             color=color_map_right(0.4),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 1')
                f1ax[6].plot(-180 * RR1_data["azimuth"] / np.pi,
                             RR1_data["velocity"],
                             color=color_map_right(0.4),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 1')
                f1ax[5].plot(-180 * RR1_data["azimuth"] / np.pi,
                             RR1_data["range"],
                             color=color_map_right(0.4),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 1')
                number_of_dets_right_processed += np.size(RR1_data["mcc"])

            if selection["beam_tp"].count(2):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [2]
                RR2_data = lst_det_right.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[3].hist(RR2_data["velocity"],
                             vel_range,
                             color=color_map_right(0.6),
                             normed=1,
                             label='beam 2')
                f1ax[0].plot(RR2_data["x"],
                             RR2_data["y"],
                             color=color_map_right(0.6),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 2')
                f1ax[6].plot(-180 * RR2_data["azimuth"] / np.pi,
                             RR2_data["velocity"],
                             color=color_map_right(0.6),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 2')
                f1ax[5].plot(-180 * RR2_data["azimuth"] / np.pi,
                             RR2_data["range"],
                             color=color_map_right(0.6),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 2')
                number_of_dets_right_processed += np.size(RR2_data["mcc"])

            if selection["beam_tp"].count(3):
                selection_tp = copy.deepcopy(selection)
                selection_tp["beam_tp"] = [3]
                RR3_data = lst_det_right.get_array_detections_selected(
                    selection=selection_tp)
                f1ax[3].hist(RR3_data["velocity"],
                             vel_range,
                             color=color_map_right(0.8),
                             normed=1,
                             label='beam 3')
                f1ax[0].plot(RR3_data["x"],
                             RR3_data["y"],
                             color=color_map_right(0.8),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 3')
                f1ax[6].plot(-180 * RR3_data["azimuth"] / np.pi,
                             RR3_data["velocity"],
                             color=color_map_right(0.8),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 3')
                f1ax[5].plot(-180 * RR3_data["azimuth"] / np.pi,
                             RR3_data["range"],
                             color=color_map_right(0.8),
                             marker='o',
                             ls='None',
                             label='Right RDR, beam 3')
                number_of_dets_right_processed += np.size(RR3_data["mcc"])

            plt.draw()
        else:
            RR_data_exists = False
    if LR_data_exists and RR_data_exists:
        lgd2 = f1ax[0].legend(loc='upper right', bbox_to_anchor=(1.0, 1.0))

        f1ax[0].set_xlabel('x [meters]')
        f1ax[0].set_ylabel('y [meters]')
        f1ax[1].set_ylabel('Left RDR, separate')
        f1ax[1].set_xlabel('Velocity $v(mcc)$ [m/s]')
        f1ax[2].set_ylabel('Left RDR, all')
        f1ax[3].set_ylabel('Right RDR, separate')
        f1ax[4].set_ylabel('Right RDR, all')
        f1ax[5].set_xlabel('Azimuth [deg]')
        f1ax[5].set_ylabel('Range [meters]')
        f1ax[6].set_ylabel('Velocity [km h$^{-1}$]')

        tit = "MCC: %08d Num of Det: L=%d R=%d In Selected Beams: L=%d R=%d" % (
            selection["mcc_tp"][0], number_of_dets_left, number_of_dets_right,
            number_of_dets_left_processed, number_of_dets_right_processed)
        f1.suptitle(tit, fontsize=14, fontweight='bold')

        if fname_det:
            f1.savefig(fname_det, format='eps', dpi=1200)
        else:
            plt.show()
    else:
        print("Nothing to plot for MCC:", selection["mcc_tp"])
def main(path):
    adsdata = AdsData(path)

    all_structs = adsdata.get_all_structs()
    print(all_structs)
    
    all_temps = adsdata.get_all_temps()
    print(all_temps)

    all_num_comps = adsdata.get_all_num_comps()
    print(all_num_comps)

    all_comps = adsdata.get_all_comps()
    print(all_comps)

    all_possible_ratios = adsdata.get_all_possible_ratios()
    print(all_possible_ratios)

    num_grids = len(all_temps)

    # dubug grid indexing
    #num_grids = 6 
    with PdfPages(os.getcwd() + "/H20_CO2_reduction.pdf") as pdf:
    #print(adsdata.master_dict[all_structs[-1]][all_temps[-1]][all_num_comps[-1]][all_comps[-1]])
        curr_fig = 0

        # Max num of columns of grid is 2
        if(num_grids == 1):
            colnum = 1
        else:
            colnum = 2 

        # all the rest of the grids get stacked in the rows underneath
        rownum = int(math.ceil(float(num_grids)/colnum))

        # one special object is buffered in the first row to the right of the two grids
        special_obj_buffer = 2.6

        grid_x = 3.5
        grid_y = 2.8

        if(rownum == 1):
            figsize = (colnum*3.5+special_obj_buffer, rownum*2.8)
        else:
            figsize = (colnum*3.5+special_obj_buffer, rownum*2.8+1.2)


        fig = plt.figure(curr_fig, figsize=figsize)

        # the location of the axes in each grid
        #rect = (0.1,0.1,0.8,0.8)
        rect = (0.06,0.16,0.2,0.2)
        #rect = (0.0,0.0,0.2,0.2)
        #ax = [fig.add_axes(rect, label="%d"%i) for i in range((colnum+1)*rownum)]
        ax = [fig.add_axes(rect, label="%d"%i) for i in range(num_grids+1)]

        horiz = []
        vert = []
        all_rect = []
    
        #for i in range(colnum):
        #    horiz += [Size.Fixed(3.5)]
        #for j in range(rownum):
        #    vert += [Size.Fixed(2.8)]
        #    all_rect.append(rect)
        #print(Size.Scaled(1).get_size())
        for i in range(colnum):
            horiz += [Size.Fixed(2.9), Size.Fixed(0.6)]
        for j in range(rownum):
            vert += [Size.Fixed(2.2), Size.Fixed(0.6)]

        horiz.pop()
        horiz += [Size.Fixed(0.2)]
        vert.pop()
        horiz += [Size.Fixed(special_obj_buffer - 1.0),Size.Fixed(0.2)]


        divider = Divider(fig, rect, horiz, vert, aspect=False)
        this_rect = divider.get_position()
        print('num_grids' + str(num_grids))
        print('num_rows' + str(rownum))
        print('num_rows' + str(colnum))
        # set all access, i counts across rows and wraps to the next row after reaching max of columns
        for i in range(num_grids):
            print(rownum)
            print(int(np.floor(i/colnum)))
            if(num_grids <= colnum):
                row_ind = 0
            else:
                row_ind = 2*((rownum-1) - int(np.floor(i/colnum)))
            col_ind = 2*(np.mod(i,colnum))
            print(str(i) + ": " + " nx: " + str(col_ind) + " ny: " + str(row_ind))
            ax[i].set_axes_locator(divider.new_locator(nx = col_ind, ny = row_ind))


        # set special object access to last column in first row
        special_col_ind = 2*(colnum)
        special_row_ind = 2*(rownum-1)
        print(str("s") + ": " + " nx: " + str(special_col_ind) + " ny: " + str(special_row_ind))
        ax[num_grids].set_axes_locator(divider.new_locator(nx = special_col_ind, ny=0, ny1 = special_row_ind+1))

        #plt.show()

    

        # for keeping track of the 95% drop
        summary1 = []
        summary2 = []

        ax_iter = -1 
        plot_max_max = -1
        for this_temp in all_temps: 
            ax_iter += 1
            print("\n\nPREPARING TEMP = " + str(this_temp) + " K\n----------------------------------")
            temp = this_temp
            temp_ind = all_temps.index(temp)
            xkey = "water"
            plot_xs = []
            plot_ys = []

            percentage_drop = []
            labels = []
            colors = []
            markers = []
            linestyles = []



            plot_max = 0.0
            for i in range(len(all_structs)):
                for j in range(len(all_num_comps)):
                    comp = all_comps[0]
                    if(all_structs[i] == "0_all_conf_0_0_full_symm"):
                        this_struct = "Mg$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "1000_all_conf_0_0_full_symm"):
                        this_struct = "Mg$_2$(DHFUMA)"
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Fe_dobdc"):
                        this_struct = "Fe$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Fe_dhfuma"):
                        this_struct = "Fe$_2$(DHFUMA)"
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Co_dobdc"):
                        this_struct = "Co$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Co_dhfuma"):
                        this_struct = "Co$_2$(DHFUMA)"
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Ni_dobdc"):
                        this_struct = "Ni$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Ni_dhfuma"):
                        this_struct = "Ni$_2$(DHFUMA)"
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Zn_dobdc"):
                        this_struct = "Zn$_2$(DOBDC)"
                        markers += ["o" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "Zn_dhfuma"):
                        this_struct = "Zn$_2$(DHFUMA)"
                        markers += ["^" for k in range(int(all_num_comps[j]))]
                        linestyles += ["-" for k in range(int(all_num_comps[j]))]
                        print(markers)
                    elif(all_structs[i] == "1001_all_conf_0_0_full_symm"):
                        this_struct = "MW_INV"
                    else:
                        this_struct = all_structs[i]

                    labels.append(this_struct + ": " + comp)

                    # Some structs/temps may have different ratio_keys
                    ratio_keys = adsdata.master_dict[all_structs[i]][all_temps[temp_ind]]["2"][comp].keys()
                    x, y = adsdata.extract_data(all_structs[i], all_temps[temp_ind],"2", comp, len(ratio_keys), xkey = "water")

                    # Print debug info to terminal
                    print(this_struct + ": " + comp)
                    print("x: " + str(x))
                    print("y: " + str(y))

                    plot_xs.append(x)
                    plot_ys.append(y)
                    try:
                        if(max(y) > plot_max):
                            plot_max = max(y)
                    except:
                        plot_max = plot_max
                    
                    colors.append("black")

                    comp = all_comps[1]
                    labels.append(this_struct + ": " + comp)
        
                    # Some structures may have diff ratio keys
                    ratio_keys = adsdata.master_dict[all_structs[i]][all_temps[temp_ind]]["2"][comp].keys()
                    x1, y1 = adsdata.extract_data(all_structs[i], all_temps[temp_ind], "2", comp, len(ratio_keys), xkey = "water")

                    # Print debug info to terminal
                    print(this_struct + ": " + comp)
                    print("x1: " + str(x1))
                    print("y1: " + str(y1))

                    plot_xs.append(x1)
                    plot_ys.append(y1)
                    colors.append("red")

                    #try:
                    #    if(max(y1) > plot_max):
                    #        plot_max = max(y1)
                    #except:
                    #    plot_max = plot_max
                    
                    # NOTE for now kind of irrelevant to calculate % loss, it's easily determined visually
                    percent = []
                    for k in range(len(x)):
                        percent.append((y[0] - y[k])/y[0]*100)
                    print(this_struct + " percent")
                    print("x: " + str(x))
                    print("y: " + str(percent))
                    #plot_xs.append(x)    
                    #plot_ys.append(percent)    
                    #colors.append("black")
                    #labels.append(this_struct + ": % loss")

                    # Calculate critical water fraction
                    compile_summary = False
                    for k in range(len(percent)):
                        if(k != len(percent)-1):
                            if(10.0 > percent[k] and 10.0 < percent[k+1]):
                                ind1 = int(k)
                                ind2 = int(k+1)
                                h2Omolfrac=(x[k+1]-x[k])/(percent[k+1]-percent[k]) + x[k]
                                compile_summary = True
                        else:   
                            break
                    
                    # Calculate CO2 capacity at that point
                    # For now we know x,y contains CO2 stats and x1,y1 contains water
                    if(compile_summary):
                        CO290percent = y[ind1] + (y[ind2]-y[ind1])/(x[ind2]-x[ind1])*(h2Omolfrac-x[ind1])
                        print("<H2Omolfrac> <90%CO2capacity> <temp>") 
                        print(str(h2Omolfrac) + " " + str(CO290percent) + " " + str(this_temp))
                    else:   
                        print("Not a high enough H20 fraction to see 90% CO2 capacity")

                    if(i==0):
                        summary1 += [str(h2Omolfrac) + " " + str(CO290percent) + " " + str(this_temp)]
                    elif(i==1):
                        summary2 += [str(h2Omolfrac) + " " + str(CO290percent) + " " + str(this_temp)]


            if(plot_max > plot_max_max):
                plot_max_max = float(plot_max)

            print("Data max:" + str(plot_max))
            print("Overall max:" + str(plot_max_max))
            #fig = plt.figure(curr_fig, figsize = (7,5.6))
            #ax = fig.add_subplot(1, 1, 1)
            ax[ax_iter].set_xlabel(r'H$_2$O Mol Fraction')
            ax[ax_iter].set_ylabel(r'Avg. Loading [mol/kg]')
            ax[ax_iter].set_xscale('log')
            ax[ax_iter].set_xlim((1e-5, 1))
            ax[ax_iter].set_ylim(0,plot_max_max*1.2)

            label = this_temp
            ax[ax_iter].legend(label, title='T=' + str(this_temp) + ' K', loc='upper left', frameon = False, framealpha=1.0, prop={'size':10})


            #axtwin = ax[ax_iter].twinx()
            #axtwin.set_ylabel(r'% CO$_2$ Capacity Lost')
            #axtwin.set_ylim(0,100)


            merge_legends = []
         
            #for i in range(len(all_structs)*int(all_num_comps[0]) + int(all_num_comps[0])): 
            #    if((i+1)%(int(all_num_comps[0])+1)==0):
            #        print("twin axis: " + str(i))
            #        #merge_legends += axtwin.plot(plot_xs[i], plot_ys[i], label=labels[i], color = colors[i], marker = markers[i], linestyle = linestyles[i], fillstyle='none')
            #    else:
            for i in range(len(markers)):
                merge_legends += ax[ax_iter].plot(plot_xs[i], plot_ys[i], label=labels[i], color = colors[i], marker = markers[i], linestyle = linestyles[i])



            merge_labels = [l.get_label() for l in merge_legends]

        ax[num_grids].legend(merge_legends, merge_labels, loc='center left', prop={'size':12})
        ax[num_grids].get_xaxis().set_visible(False)
        ax[num_grids].get_yaxis().set_visible(False)
        ax[num_grids].set_frame_on(False)
        #ax.legend(merge_legends, merge_labels, loc='best', prop={'size':12})
        #plt.tight_layout()

        #pdf.savefig(fig)
        fig.savefig(os.getcwd() + "/H2O_CO2_reduction_ALL_T.png", dpi = 300)

            #curr_fig += 1
        print("Summary1:")
        for i in range(len(summary1)):
            print(summary1[i])
        print("Summary2:")
        for i in range(len(summary2)):
            print(summary2[i])
    def redraw(self):
        if len(self.input) == 0:
            self.warning("Empty input")
            return
        fast_redraw = self.name in self.pp.get_figlabels()
        fig = self.pp.figure(self.name)
        axes = fig.add_subplot(111)

        if not fast_redraw:
            self.draw_grid(axes)
        else:
            while len(axes.texts):
                axes.texts[0].remove()

        # Draw the inner hexagons with text
        all_patches = [list() for _ in range(len(self.fitness_by_label))]
        hits_max = numpy.max(self.input)
        if hits_max == 0:
            hits_max = 1
        reversed_result = {}
        for label, neurons in enumerate(self.result):
            for neuron in neurons:
                reversed_result[neuron] = label
        # Add hexagons one by one
        for y in range(self.height):
            for x in range(self.width):
                neuron = y * self.width + x
                fitness = self.fitness_by_neuron[neuron]
                number = self.input[y * self.width + x]
                if numpy.sqrt(number / hits_max) <= \
                   KohonenHits.SIZE_TEXT_THRESHOLD:
                    fitness = 0
                try:
                    label = reversed_result[neuron]
                except KeyError:
                    continue
                patches = all_patches[label]
                self._add_hexagon(axes, patches, x, y, fitness)
        if fast_redraw:
            axes.collections = [axes.collections[-1]]
        else:
            legend_patches = []
        cmap = getattr(self.cm, self.cmap)
        for index, patches in enumerate(all_patches):
            if len(patches) == 0:
                continue
            facecolor = cmap(index * cmap.N // len(all_patches))
            col = self.matplotlib.collections.PatchCollection(
                patches, edgecolors='none',
                facecolors=facecolor)
            axes.add_collection(col)
            if not fast_redraw:
                legend_patches.append(self.matplotlib.patches.Patch(
                    color=facecolor,
                    label="%d - %.2f" % (index, self.fitness_by_label[index])))
        # Make the grid to be drawn last
        axes.collections = axes.collections[1:] + [axes.collections[0]]

        if not fast_redraw:
            legend = axes.legend(handles=legend_patches, loc='upper left',
                                 bbox_to_anchor=(1.05, 1), borderaxespad=0.0,
                                 title="Fitness: %.2f" % self.fitness)
            fig.tight_layout()
            # The legend becomes truncated, but it should not
            # Measure the legend width to fix buggy matplotlib layout
            # Without drawing, window extent equals to 1
            if legend is not None:
                legend.draw(fig.canvas.get_renderer())
                bbox = legend.get_window_extent()
                bbox = bbox.transformed(fig.dpi_scale_trans.inverted())

                from mpl_toolkits.axes_grid import Divider
                from mpl_toolkits.axes_grid.axes_size import Fixed, Scaled
                divider = Divider(fig, (0.05, 0.05, 0.9, 0.9),
                                  (Scaled(1.0), Fixed(bbox.width),
                                   Scaled(0.05)), (Scaled(1), Fixed(0)))
                axes.set_axes_locator(divider.new_locator(0, 0))
        else:
            # Modify legend title and labels
            legend = axes.get_legend()
            if legend is not None:
                legend.set_title("Fitness: %.2f" % self.fitness)
                for index, text in enumerate(legend.get_texts()):
                    text.set_text("%d - %.2f" %
                                  (index, self.fitness_by_label[index]))
        self.show_figure(fig)
        fig.canvas.draw()
        return fig