Example #1
0
def run():
	# Create a list of contact models to analyze
	models = [sim.models.SpringDashpot, sim.models.HertzMindlin]

	# Set particle radius to 1 mm
	steel['radius'] = 1e-3

	# Compute the force-displacement curve
	for model in models:
		model = model(material=steel, limitForce=True)

		time, delta, force = model.displacement()
		plt.plot(delta[:,0] * 1e6, force * 1e3)

		if hasattr(model, 'displacementAnalytical'):
			time, delta, force = model.displacementAnalytical()
			plt.plot(delta[:,0] * 1e6, force * 1e3, ':o')

	plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
	plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
	plt.legend(['SpringDashpot (numerical)', 'SpringDashpot (analytical)', 'HertzMindlin'], loc='best')
	plt.xlabel(r'$\delta$ $(\mu m)$')
	plt.ylabel('Force (mN)')
	plt.grid(linestyle=':')
	plt.show()
Example #2
0
def run():
    # Create a list of contact models to analyze
    models = [sim.models.SpringDashpot, sim.models.HertzMindlin]

    # Set particle radius to 1 mm
    steel['radius'] = 1e-3

    # Compute the force-displacement curve
    for model in models:
        model = model(material=steel, limitForce=True)

        time, delta, force = model.displacement()
        plt.plot(delta[:, 0] * 1e6, force * 1e3)

        if hasattr(model, 'displacementAnalytical'):
            time, delta, force = model.displacementAnalytical()
            plt.plot(delta[:, 0] * 1e6, force * 1e3, ':o')

    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plt.legend([
        'SpringDashpot (numerical)', 'SpringDashpot (analytical)',
        'HertzMindlin'
    ],
               loc='best')
    plt.xlabel(r'$\delta$ $(\mu m)$')
    plt.ylabel('Force (mN)')
    plt.grid(linestyle=':')
    plt.show()
Example #3
0
def run():
    # Create a list of contact models to analyze
    models = [sim.models.SpringDashpot, sim.models.HertzMindlin]

    # Set particle radius to 1 mm
    steel["radius"] = 1e-3

    # Compute the force-displacement curve
    for model in models:
        model = model(material=steel, limitForce=True)

        time, delta, force = model.displacement()
        plt.plot(delta[:, 0] * 1e6, force * 1e3)

        if hasattr(model, "displacementAnalytical"):
            time, delta, force = model.displacementAnalytical()
            plt.plot(delta[:, 0] * 1e6, force * 1e3, ":o")

    plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
    plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
    plt.legend(
        [
            "SpringDashpot (numerical)", "SpringDashpot (analytical)",
            "HertzMindlin"
        ],
        loc="best",
    )
    plt.xlabel(r"$\delta$ $(\mu m)$")
    plt.ylabel("Force (mN)")
    plt.grid(linestyle=":")
    plt.show()
Example #4
0
def show_results(res1, res2, res3, res4, param):

    fig, axes = plt.subplots()
    x2 = [i for i in range(1000)]
    #axes.plot(x2, res1, 'gold', label="20x20")
    #axes.plot(x2, res2, 'orange', label="40x40")
    #axes.plot(x2, res3, 'r', label="80x80")
    axes.plot(x2, res4, 'k', label=r"$\ell = 3 \; (160\times160)$")
    if param != None:
        plt.axhline(
            y=param[0],
            linestyle='--',
            color='k',
            label=
            r"$\mathrm{\mathbb{E}} \left[\Vert u\Vert^2_{L^2} \right]_{MLMC}$")
    #axes.hist(solutions, bins = 40, color = 'blue', edgecolor = 'black')
    plt.style.use('classic')
    axes.legend(loc="best", prop={'size': 13})

    axes.set_ylabel(
        r'$\mathrm{\mathbb{E}} \left[\Vert u \Vert^2_{L^2} \right]$',
        fontsize=14)
    axes.set_xlabel(r'Repetitions, $N$', fontsize=13)

    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    axes.tick_params(axis="y", direction='in', which='both')
    axes.tick_params(axis="x", direction='in', which='both')

    plt.tight_layout()
    plt.show()
Example #5
0
def last_two():
    P = data.load_file()
    params = {
        "epochs": 4000,
        "neurons": 1024,
        "learn_method": 'classic'
    }

    # generate weight matrix
    W = np.random.randn(params['neurons'], params['neurons'])
    W = (W + W.T) / 2
    W = W - np.diag(W.diagonal())
    p = np.random.randint(-1, 1, params['neurons']).reshape(1,-1)
    p = (p*2) + 1
    Hop = HopfieldNet(p)
    Hop.W = W
    recalled_set, energy = Hop.sequential_recall_shuffle(p, epochs=4000)
    plt.imshow(recalled_set.reshape(32,32))
    plt.show()
    plt.plot(range(len(energy[0])), energy[0])
    plt.xlabel('Epoch', fontsize=16)
    plt.ylabel('Energy', fontsize=16)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plt.savefig('Energy_sym.png')
    plt.show()
def plithist(im, nbins=256):
    f = plt.figure(figsize=(6, 6))
    plt.hist(im.ravel(), bins=nbins, histtype='step', color='black')
    img_cdf, bins = exposure.cumulative_distribution(im, nbins)
    plt.plot(bins, img_cdf, 'r')
    plt.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))
    plt.xlabel('Pixel intensity')
    plt.xlim(0, 1)
    plt.yticks([])
Example #7
0
    def plot_autocorrs(self, axis=0, n_rows=4, n_cols=8):
        """ Plot autocorrelations for all antennas
        """
        self.current_plot = 'multi'
        self.ax_zoomed = False
        
        bls = self.uv.d_uv_data['BASELINE']

        # Extract the relevant baselines using a truth array
        # bls = bls.tolist()
        bl_ids = set([256*i + i for i in range(1, n_rows * n_cols + 1)])
        bl_truths = np.array([(b in bl_ids) for b in bls])
        
        #print self.uv.d_uv_data['DATA'].shape
        #x_data    = self.d_uv_data['DATA'][bl_truths,0,0,:,0,axis]  # Baselines, freq and stokes
        #x_cplx    = x_data[:,:,0] + 1j * x_data[:,:,1]

        x_cplx  = self.stokes[axis][bl_truths]


        
        # Plot the figure
        #print self.uv.n_ant
        fig = self.sp_fig
        figtitle = '%s %s: %s -- %s'%(self.uv.telescope, self.uv.instrument, self.uv.source, self.uv.date_obs)
        for i in range(n_rows):
            for j in range(n_cols):
                ax = fig.add_subplot(n_rows, n_cols, i*n_cols + j +1)
                ax.set_title(self.uv.d_array_geometry['ANNAME'][i*n_cols + j], fontsize=10)
                #ax.set_title("%s %s"%(i, j))
                
                x = x_cplx[i*n_cols+j::self.uv.n_ant]
                
                if self.scale_select.currentIndex() == 0 or self.scale_select.currentIndex() == 1:
                    if x.shape[0] == self.uv.n_ant:
                        self.plot_spectrum(ax, x, label_axes=False)
                    else:
                        self.plot_spectrum(ax, x, stat='max', label_axes=False)
                        self.plot_spectrum(ax, x, stat='med', label_axes=False)
                        self.plot_spectrum(ax, x, stat='min', label_axes=False)
                else:
                    self.plot_spectrum(ax, x, label_axes=False)
                self.updateFreqAxis(ax)
                
                if i == n_rows-1:
                    ax.set_xlabel('Freq')
                if j == 0:
                    ax.set_ylabel('Amplitude')
                
                plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
                plt.tick_params(axis='both', which='major', labelsize=10)
                plt.tick_params(axis='both', which='minor', labelsize=8)
                plt.xticks(rotation=30)
        
        plt.subplots_adjust(left=0.05, right=0.98, top=0.95, bottom=0.1, wspace=0.3, hspace=0.45)
        return fig, ax
Example #8
0
def show_cavity_step(title):
    plt.title(title, fontsize=40, y=1.02)
    plt.xlabel('Time [s]', fontsize=30)
    plt.ylabel(r'$| \vec V_{\rm acc}|$ [V]', fontsize=30)

    plt.ticklabel_format(style='sci', axis='y', scilimits=(1, 0))

    plt.rc('font', **{'size': 20})
    plt.legend(loc='upper right')
    plt.show()
    def plotdata(self, xdata, ydata):
        
        self.subplot = self.plot.add_subplot(1, 1, 1) ;

        self.subplot.xaxis.grid(True, which = 'both') ;
        plt.ticklabel_format(style = 'sci', axis = 'x', scilimits = (0,0)) ;
        self.subplot.xaxis.set_minor_locator(self.minorLocator) ;
        
        self.subplot.plot(xdata, ydata, 'k') ;
        print (xdata)
        print (ydata)
def unit_SSA(showplots=True, TOL=1.0e-14):
    """
    Unit test for Solid-State Amplifier funtion.
    Performs the step response of the SSA (which included a low-pass filter + Saturation) and plots the results.
    This is not a PASS/FAIL test and just intended to provide qualitative evidence, but it could potentially be compared
    with the real SSA in use.
    """

    # Import JSON parser module
    from get_configuration import Get_SWIG_RF_Station

    # Configuration file for specific test configuration
    # (to be appended to standard test cavity configuration)
    test_file = [
        "source/configfiles/unit_tests/LCLS-II_accelerator.json",
        "source/configfiles/unit_tests/SSA_test.json"
    ]

    # Get SWIG-wrapped C handles for RF Station
    rf_station, Tstep, fund_mode_dict = Get_SWIG_RF_Station(test_file,
                                                            Verbose=False)

    # Simulation duration
    Tmax = 1e-6

    # Create time vector
    trang = np.arange(0, Tmax, Tstep)

    # Number of points
    nt = len(trang)

    # Initialize vectors for test
    sout = np.zeros(nt,
                    dtype=np.complex)  # Overall cavity accelerating voltage

    # Set drive signal to 60% of full power
    drive = rf_station.C_Pointer.PAscale * 0.6

    # Run numerical simulation
    for i in xrange(1, nt):
        sout[i] = acc.SSA_Step(rf_station.C_Pointer, drive, rf_station.State)

    # Format plot
    plt.plot(trang, np.abs(sout), '-', label='SSA output', linewidth=3)
    plt.ticklabel_format(style='sci', axis='x', scilimits=(1, 0))
    plt.title('SSA Test', fontsize=40, y=1.01)
    plt.xlabel('Time [s]', fontsize=30)
    plt.ylabel('Amplitude ' + r'[$\sqrt{W}$]', fontsize=30)
    plt.legend(loc='upper right')

    plt.ylim([0, 50])

    plt.show()
Example #11
0
    def plot_autocorrs(self, axis=0, n_rows=4, n_cols=8):
        """ Plot autocorrelations for all antennas
        """
        self.current_plot = 'multi'
        self.ax_zoomed = False
        
        bls = self.uv.d_uv_data['BASELINE']

        # Extract the relevant baselines using a truth array
        # bls = bls.tolist()
        bl_ids = [256*i + i for i in range(1,self.uv.n_ant+1)]
        bl_truths = np.array([(b in bl_ids) for b in bls])
        
        #print self.uv.d_uv_data['DATA'].shape
        #x_data    = self.d_uv_data['DATA'][bl_truths,0,0,:,0,axis]  # Baselines, freq and stokes
        #x_cplx    = x_data[:,:,0] + 1j * x_data[:,:,1]

        x_cplx  = self.stokes[axis][bl_truths]

        #print x_cplx.shape
        
        # Plot the figure
        #print self.uv.n_ant
        fig = self.sp_fig
        figtitle = '%s %s: %s -- %s'%(self.uv.telescope, self.uv.instrument, self.uv.source, self.uv.date_obs)
        for i in range(n_rows):
            for j in range(n_cols):
                ax = fig.add_subplot(n_rows, n_cols, i*n_cols + j +1)
                ax.set_title(self.uv.d_array_geometry['ANNAME'][i*n_cols + j], fontsize=10)
                #ax.set_title("%s %s"%(i, j))
                
                x = x_cplx[i*n_cols+j::self.uv.n_ant]
                
                if self.scale_select.currentIndex() == 0 or self.scale_select.currentIndex() == 1:
                    self.plot_spectrum(ax, x, stat='max', label_axes=False)
                    self.plot_spectrum(ax, x, stat='med', label_axes=False)
                    self.plot_spectrum(ax, x, stat='min', label_axes=False)
                else:
                    self.plot_spectrum(ax, x, label_axes=False)
                self.updateFreqAxis(ax)
                
                if i == n_rows-1:
                    ax.set_xlabel('Freq')
                if j == 0:
                    ax.set_ylabel('Amplitude')
                
                plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
                plt.tick_params(axis='both', which='major', labelsize=10)
                plt.tick_params(axis='both', which='minor', labelsize=8)
                plt.xticks(rotation=30)
        
        plt.subplots_adjust(left=0.05, right=0.98, top=0.95, bottom=0.1, wspace=0.3, hspace=0.45)
        return fig, ax
def violin_plot(ax, values_list, measure_name, group_names, fontsize, color='blue',  ttest=False):
    '''
    This is a little wrapper around the statsmodels violinplot code
    so that it looks nice :)    
    '''    
    
    # IMPORTS
    import matplotlib.pylab as plt
    import statsmodels.api as sm
    import numpy as np
    
    # Make your violin plot from the values_list
    # Don't show the box plot because it looks a mess to be honest
    # we're going to overlay a boxplot on top afterwards
    plt.sca(ax)
    
    # Adjust the font size
    font = { 'size'   : fontsize}
    plt.rc('font', **font)

    max_value = np.max(np.concatenate(values_list))
    min_value = np.min(np.concatenate(values_list))
    
    vp = sm.graphics.violinplot(values_list,
                            ax = ax,
                            labels = group_names,
                            show_boxplot=False,
                            plot_opts = { 'violin_fc':color ,
                                          'cutoff': True,
                                          'cutoff_val': max_value,
                                          'cutoff_type': 'abs'})
    
    # Now plot the boxplot on top
    bp = plt.boxplot(values_list, sym='x')
    
    for key in bp.keys():
        plt.setp(bp[key], color='black', lw=fontsize/10)
        
    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    ax.yaxis.major.formatter.set_powerlimits((-3,3))
    plt.tick_params(axis='both', which='major', labelsize=fontsize)

    # Add the y label
    plt.ylabel(measure_name, fontsize=fontsize)
    
    # And now turn off the major ticks on the y-axis
    for t in ax.yaxis.get_major_ticks(): 
        t.tick1On = False 
        t.tick2On = False

    return ax
Example #13
0
def histograms(det,sec):
    '''
    :param det: det-data-product of an uswipha instance
    :param sec: sec-data-product of an uswipha instance
    :return: simple histograms of the det- and sec-distribution in the given data
    '''
    fig, (ax1,ax2) = pylab.subplots(1,2)
    ax1.hist(det, bins = [0,1,2,3,4])
    ax1.set_xticks(np.arange(0.5,4.5,1))
    ax1.set_xticklabels(np.arange(0,4,1))
    ax1.set_title('det')
    ax2.hist(sec, bins = np.arange(0,8,1))
    ax2.set_title('sec')
    pylab.ticklabel_format(style='sci', axis='y')
Example #14
0
def run():

    # Setup matplotlib params
    mpl.rc("text", usetex=True)
    plt.rcParams.update({"font.size": 18})

    cModel = sim.models.ThorntonNing

    COR, yieldVel = [], []

    # Create a yield pressure array to study
    pressure = arange(1, 6, 0.1) * cohesionless["youngsModulus"] * 0.01

    # Set particle radius to 100 microns
    cohesionless["radius"] = 1e-4

    for yieldPress in pressure:

        cohesionless["yieldPress"] = yieldPress
        model = cModel(material=cohesionless)

        time, disp, force = model.displacement()

        deltav = disp[:, 1]

        COR.append(fabs(deltav[-1] / cohesionless["characteristicVelocity"]))
        yieldVel.append(model.yieldVel /
                        cohesionless["characteristicVelocity"])

    ratio = array(yieldVel)
    ratio[ratio > 1] = 1

    COR_anal = (sqrt(6.0 * sqrt(3.0) / 5.0) * sqrt(1.0 - (1.0 / 6.0) *
                                                   (ratio)**2) *
                (ratio / (ratio + 2 * sqrt(6.0 / 5.0 -
                                           (1.0 / 5.0) * ratio**2)))**(0.25))

    fig = plt.figure()

    plt.plot(pressure, COR, "-o")
    plt.plot(pressure, COR_anal)

    plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
    plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 0))
    plt.xlabel("Yield Pressure (MPa)")
    plt.ylabel("Coefficient of Restitution")
    plt.grid(linestyle=":")
    plt.legend(["Numerical", "Analytical"])
    plt.show()
Example #15
0
	def collect(self):

		for topic, msg, t in self.bag.read_messages(topics="/nav/fix"):
			if topic == "/nav/fix":

				self.gnss_data_dict[msg.status.status].append( np.array([msg.longitude, msg.latitude]) )

		status_num = [0]*8
		for key_name in self.gnss_data_dict.keys():
			status_len = len(self.gnss_data_dict[key_name])
			if status_len == 0:
				continue
			elif status_len == 1:
				self.gnss_data_dict[key_name] = np.array(self.gnss_data_dict[key_name])
			else:
				self.gnss_data_dict[key_name] = np.vstack( self.gnss_data_dict[key_name])
				status_num[key_name] += status_len

		bar_edge = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5]
		plt.figure()
		plt.subplot(121)
		plt.xlabel("GNSS status")
		plt.ylabel("Points")
		plt.title("Total points: %d"%sum(status_num))
		plt.bar(bar_edge, status_num)
		for i, v in enumerate(status_num):
		    plt.text(bar_edge[i], v, str(v))

		self.color_lst = ['k', 'w', 'm', 'c', 'r', 'o', 'y', 'b']
		handle_lst = []
		plt.subplot(122)
		plt.axis('equal')
		plt.xlabel("Longitude")
		plt.ylabel("Latitude")
		plt.ticklabel_format(useOffset=False)

		for i in range(8):
			if status_num[i] == 0:
				continue
			if i != 7:
				plt_handle, = plt.plot(self.gnss_data_dict[i][:,0], self.gnss_data_dict[i][:,1], \
					"*"+self.color_lst[i],label="status="+str(i), markersize=10)
			else:
				plt_handle, = plt.plot(self.gnss_data_dict[i][:,0], self.gnss_data_dict[i][:,1], \
					"."+self.color_lst[i],label="status="+str(i), markersize=2)
			handle_lst.append(plt_handle)

		plt.legend(handles=handle_lst, loc=2)
		plt.show()  
def create_bar_plots(bins,
                     freq_list,
                     height,
                     group_names,
                     colors,
                     xlabel,
                     ylabel,
                     legend=True):
    import matplotlib.pylab as plt
    import numpy as np
    from matplotlib.ticker import MaxNLocator

    fig = plt.figure(figsize=(height * 1.5, height))
    ax = fig.add_subplot(111)

    font = {'size': 22 * height / 8}

    plt.rc('font', **font)

    range = np.max(bins) - np.min(bins)
    w = range / ((len(bins) - 1) * len(group_names))

    for i, group in enumerate(group_names):

        bar = plt.bar(bins + w * i,
                      freq_list[i],
                      width=w,
                      label=group,
                      color=colors[i],
                      edgecolor='none')

        # Adjust the power limits so that you use scientific notation on the y axis
        plt.ticklabel_format(style='sci', axis='y')
        ax.yaxis.major.formatter.set_powerlimits((-3, 3))

        for t in ax.yaxis.get_major_ticks():
            t.tick1On = False
            t.tick2On = False

    if legend:
        plt.legend(loc=0)

    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    # Make sure the layout looks good :)
    fig.tight_layout()

    return fig
    def OpenPlot(self):

        def getspec(self):

            global x
            global y

            ftypes = [('Data files', '*.dat'), ('All files', '*')] 
            dlg = tkFileDialog.Open(self, filetypes = ftypes)

            fl = dlg.show()

            if fl != '':
                f = open(fl)
                data = np.loadtxt(f)

            x = data[:,0]
            y = data[:,1]

        getspec(self)

        minorLocator = AutoMinorLocator()
        golden = (plt.sqrt(5) + 1.)/2.
        figprops = dict(figsize = (6., 6./golden), dpi = 128)
        adjustprops = dict(left = 0.15, bottom = 0.20, right = 0.90, top = 0.93, wspace = 0.2, hspace = 0.2)

        MyPlot = plt.figure(1, **figprops)
        MyPlot.subplots_adjust(**adjustprops)
        plt.clf()

        MySubplot = MyPlot.add_subplot(1, 1, 1)
        
        MySubplot.plot(x,y)

        plt.xlabel('$\lambda$ ($\AA$)', fontsize = 18) 
        plt.ylabel('$F_\lambda$ ($10^{-17}$ erg/$cm^2$/s/$\AA$)', fontsize = 18)

        axes = plt.gca()

        plt.tick_params(which = 'both', width = 2) 
        plt.tick_params(which = 'major', length = 4) 
        plt.tick_params(which = 'minor', length = 4, color = 'r')

        MySubplot.xaxis.grid(True, which = "both")
        plt.ticklabel_format(style = 'sci', axis = 'x', scilimits = (0,0))
        MySubplot.xaxis.set_minor_locator(minorLocator)

        print("Done!")
Example #18
0
def run():

    # Setup matplotlib params
    mpl.rc('text', usetex=True)
    plt.rcParams.update({'font.size': 18})

    cModel = sim.models.ThorntonNing

    COR, yieldVel = [], []

    # Create a yield pressure array to study
    pressure = arange(1, 6, 0.1) * cohesionless['youngsModulus'] * 0.01

    # Set particle radius to 100 microns
    cohesionless['radius'] = 1e-4

    for yieldPress in pressure:

        cohesionless['yieldPress'] = yieldPress
        model = cModel(material=cohesionless)

        time, disp, force = model.displacement()

        deltav = disp[:, 1]

        COR.append(fabs(deltav[-1] / cohesionless['characteristicVelocity']))
        yieldVel.append(model.yieldVel /
                        cohesionless['characteristicVelocity'])

    ratio = array(yieldVel)
    ratio[ratio > 1] = 1

    COR_anal = sqrt(6. * sqrt(3.0) / 5.0) * sqrt(1.0 - (1.0/6.0) * (ratio)**2) * \
        (ratio / (ratio + 2 * sqrt( 6.0/5.0 - (1.0/5.0) * ratio**2 ) ) )**(0.25)

    fig = plt.figure()

    plt.plot(pressure, COR, '-o')
    plt.plot(pressure, COR_anal)

    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plt.xlabel('Yield Pressure (MPa)')
    plt.ylabel('Coefficient of Restitution')
    plt.grid(linestyle=':')
    plt.legend(['Numerical', 'Analytical'])
    plt.show()
def create_bar_plots(bins, freq_list, height, group_names, colors, xlabel, ylabel, legend=True):
    import matplotlib.pylab as plt
    import numpy as np
    from matplotlib.ticker import MaxNLocator
    
    fig = plt.figure(figsize=(height*1.5, height))
    ax = fig.add_subplot(111)
    
    font = { 'size'   : 22 * height/8}

    plt.rc('font', **font)
    
    range = np.max(bins) - np.min(bins)
    w = range/((len(bins)-1) * len(group_names))

    for i, group in enumerate(group_names):
        
        bar = plt.bar(bins + w*i, freq_list[i],
                                width=w, label = group,
                                color=colors[i],
                                edgecolor='none')
        
        # Adjust the power limits so that you use scientific notation on the y axis
        plt.ticklabel_format(style='sci', axis='y')
        ax.yaxis.major.formatter.set_powerlimits((-3,3))

        for t in ax.yaxis.get_major_ticks(): 
            t.tick1On = False 
            t.tick2On = False 

    if legend:
        plt.legend(loc=0)
    
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    # Make sure the layout looks good :)        
    fig.tight_layout()
    
    return fig
Example #20
0
 def Plot_Resumen_estrategia(cls,
                             df: DataFrame,
                             title: str = None,
                             plot_rounds: bool = False,
                             plot_cumulative: bool = True,
                             figsize: tuple = (17, 7),
                             column_position: str = "Position",
                             column_cumulative: str = "Cumulative",
                             color_round: str = "rebeccapurple",
                             color_cumulative: str = "royalblue"):
     if plot_rounds and plot_cumulative:
         fig = plt.figure(figsize=(25, 10))
         plt.subplot(121)
         df[column_position].plot(figsize=figsize, color=color_round)
         plt.ticklabel_format(axis="y",
                              style="sci",
                              scilimits=(4, 4),
                              useMathText=True)
         plt.xlabel("Dates")
         plt.ylabel("USD")
         plt.subplot(122)
         df[column_cumulative].plot(figsize=figsize, color=color_cumulative)
         plt.ticklabel_format(axis="y",
                              style="sci",
                              scilimits=(4, 4),
                              useMathText=True)
         plt.xlabel("Dates")
         plt.ylabel("USD")
     elif plot_rounds and not plot_cumulative:
         df[column_position].plot(figsize=figsize,
                                  color=color_round,
                                  title=title)
         plt.ticklabel_format(axis="y",
                              style="sci",
                              scilimits=(4, 4),
                              useMathText=True)
         plt.xlabel("Dates")
         plt.ylabel("USD")
     elif plot_cumulative and not plot_rounds:
         df[column_cumulative].plot(figsize=figsize,
                                    color=color_cumulative,
                                    title=title)
         plt.ticklabel_format(axis="y",
                              style="sci",
                              scilimits=(4, 4),
                              useMathText=True)
         plt.xlabel("Dates")
         plt.ylabel("USD")
Example #21
0
    def plotTrajectory(self, sample_type='o-'):

        handle_lst = []
        plt.axis('equal')
        plt.xlabel("time sample")
        plt.ylabel("value")
        plt.ticklabel_format(useOffset=False)

        plt_handle0, = plt.plot(self.sub_data0,
                                sample_type +
                                self.color_list[self.color_choice[0]],
                                label="/trajectory0",
                                markersize=5)
        plt_handle1, = plt.plot(self.sub_data1,
                                sample_type +
                                self.color_list[self.color_choice[1]],
                                label="/trajectory1",
                                markersize=5)
        handle_lst.append(plt_handle0)
        handle_lst.append(plt_handle1)

        plt.legend(handles=handle_lst, loc=2)
        plt.pause(0.5 / self.update_rate)
Example #22
0
def main():
    one = np.array([0.8656, 0.8683, 0.8716, 0.8698])
    e1 = np.array([0.0007, 0.0006, 0.0006, 0.0006])

    two = np.array([0.8748, 0.8781, 0.8808, 0.8798])
    e2 = np.array([0.0010, 0.0007, 0.0006, 0.0006])

    three = np.array([0.8778, 0.8822, 0.8848, 0.8864])
    e3 = np.array([0.0011, 0.0008, 0.0006, 0.0007])

    p1 = np.array([795010, 1590010, 3180010, 6360010])
    p2 = np.array([798360, 1570335, 3173685, 6314185])
    p3 = np.array([792505, 1580320, 3187627, 6355475])

    plt.errorbar(p1, one, e1, marker="o", color='red', label='One')
    plt.errorbar(p2, two, e2, marker='s', color='blue', label='Two')
    plt.errorbar(p3, three, e3, marker='^', color='green', label='Three')
    plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 0))
    plt.xlabel("Parameters")
    plt.ylabel("Score")
    plt.legend(loc='lower right')
    plt.tight_layout()
    plt.savefig("relu_layers.pdf", format="pdf", dpi=600)
    plt.show()
Example #23
0
# period
T = 1.0 / dt
length = samp * dt
# number of coefficients (initial value: 100)
N = 100
# weighting factors for coefficients (selected randomly)
a0 = np.random.rand(1)
a = np.random.randint(1, high=11, size=N)
b = np.random.randint(1, high=11, size=N)

t = np.linspace(0, length, samp)             # time axis
sig = series_real_coeff(a0, a, b, t, T)

# plotting
plt.plot(t, sig, 'r', label='arbitrary, periodic, discrete, finite signal')
plt.ticklabel_format(axis='y', style='sci', scilimits=(-1,1))
plt.xlabel('time [sec]')
plt.ylabel('amplitude')
plt.legend()
plt.show()
# -

# ---  
# Now, we can play with the signal and see what happens when we try to reconstruct it with a limited number of coefficients.  
# 2) Run the cells 4 and 5. What do you observe?  
# 3) Increase the number of coefficients $n$ step by step and re-run cells 4 and 5. What do you observe now? Can you explain?   
# 4) In cell 5 uncomment the lines to make a plot which is not normalized (and comment the other two) and re-run the cell. What do you see now and can you explain it?

# Cell 4: determine the first 'n' coefficients of the function using the code function of cell 1
T = 1        # period
n = 5        # number of coeffs to reconstruct
def scatter_interaction(ax, x, y, groups, colors, ms=5, labels=None, title=None, legend=False, formula='y ~ x', legend_loc='best'):
    
    # Here are the imports
    import numpy as np
    import matplotlib.pylab as plt
    import pandas as pd
    from scipy.stats import pearsonr
    from statsmodels.sandbox.regression.predstd import wls_prediction_std
    from statsmodels.formula.api import ols
    from statsmodels.stats.outliers_influence import summary_table

    # If you haven't already been given an axis on which to plot, then
    # create a new figure
        
    if not ax:
        fig = plt.figure(figsize = (5,4))
        
        ax = fig.add_subplot(111)
    
    marker_styles = [ 'o', '^', 'D', 's', '*' ] * len(groups)
    line_styles = ['--', '-', '-.', ':'] * len(groups)
    
    # Loop through all the groups
    for i, x_i, y_i, c_i, g_i, m_i, l_i in zip(range(len(groups)), x, y, colors, groups, marker_styles, line_styles):

        # Scatter each with the appropriate colors
        ax.scatter(x_i, y_i, c=c_i, edgecolor=c_i, alpha=0.8, s=ms, marker=m_i, zorder=7*i)
        
        # Now calculate the linear correlation between x and y
        # for each group
        # Heavily stolen from:
        # http://www.students.ncl.ac.uk/tom.holderness/software/pythonlinearfit
        #z = np.polyfit(x_i,y_i,1)
        #p = np.poly1d(z)
        #fit = p(x_i)
        #c_x = [np.min(x_i),np.max(x_i)]
        #c_y = [p(np.min(x_i)), p(np.max(x_i))]

        df2 = pd.DataFrame({ 'x' : x_i, 'y' : y_i })
        df2.sort('x', inplace=True)
        lm = ols(formula, df2).fit()
        ps = [ '{:2.4f}'.format(p) for p in lm.pvalues[1:] ]
        print '    {}, r2 = {}, p(s) = {}'.format(g_i, lm.rsquared, ', '.join(ps))
        prstd, iv_l, iv_u = wls_prediction_std(lm)
        iv_l = np.array(iv_l)
        iv_u = np.array(iv_u)
        fit_y = np.array(lm.fittedvalues)
        st, data, ss2 = summary_table(lm, alpha=0.05)

        predict_mean_ci_low, predict_mean_ci_upp = data[:,4:6].T

        #pl.plot(x, y, 'k-')
        #pl.plot(x, fit_y, 'r--')
        #pl.fill_between(x, iv_l, iv_u, alpha=0.2)
        
        # Get the r and p values
        #r, p = pearsonr(x_i, y_i)
        #label = '{} r: {: .2g} p: {: .2g}'.format(g_i, r, p)
        # Now plot
        ax.plot(df2.x.values, fit_y, c=c_i, linestyle = '-', linewidth = ms/25.0, zorder=6*i, label=g_i)
        ax.plot(df2.x.values, predict_mean_ci_low, c=c_i, linestyle = '-', linewidth = ms/50.0, zorder=3*i)
        ax.plot(df2.x.values, predict_mean_ci_upp, c=c_i, linestyle = '-', linewidth = ms/50.0, zorder=2*i)
        ax.fill_between(df2.x.values, predict_mean_ci_upp, predict_mean_ci_low, alpha=0.3, facecolor=c_i, interpolate=True, zorder=1*i)
        
    if legend:
        # Add the legend
        leg = ax.legend(loc=legend_loc, fancybox=True, fontsize=ms/2.)
        leg.get_frame().set_alpha(0)

    # Set the y limits
    # This is to deal with very small numbers (the MaxNLocator gets all turned around!)
    # Concatenate all the y data:
    y_all = y[0]
    if len(y) > 1:
        for k in range(1,len(y)):
            y_all = np.concatenate([y_all, y[k]])
    max_y = np.max(y_all)
    min_y = np.min(y_all)
    buffer = ( max_y - min_y ) / 10
    upper = max_y + buffer
    lower = min_y - buffer
    ax.set_ybound(upper, lower)
    
    # Set the axis labels    
    ax.set_ylabel(labels[1], fontsize=ms/2.0)
    ax.set_xlabel(labels[0], fontsize=ms/2.0)
    
    for item in (ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize(ms/2.0)
    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    ax.yaxis.major.formatter.set_powerlimits((-3,3))
    
    plt.rc('font', **{'size':ms/2.0})
    
    if title:
        # Set the overall title
        ax.set_title(title)

    plt.tight_layout()
    
    return ax
Example #25
0
def plot_swe(run_id, met_inp, which_model, hydro_years_to_take, catchment,
             output_dem, origin, model_swe_sc_threshold, mask_file,
             dsc_snow_output_folder, plot_folder):

    bounding = 'moving'
    lats = np.linspace(
        48e5, 50e5, 365
    )  # asssume plot is 5e5 high, 4e5 wide    lats = np.linspace(47e5, 52e5, 365) # asssume plot is 5e5 high, 4e5 wide
    lons = np.linspace(11e5, 12e5,
                       365)  #    lons = np.linspace(10e5, 15e5, 365)
    camera_motion = [lats, lons]

    plt.rcParams.update({'font.size': 14})
    plt.rcParams.update({'axes.titlesize': 14})

    # bin_edges = [-0.001, 30, 60, 90, 120, 180, 270, 360]  # use small negative number to include 0 in the interpolation

    for i, year_to_take in enumerate(hydro_years_to_take):
        modis_mask = np.load(mask_file)
        fig1 = plt.figure(figsize=[8, 6])
        print('loading data for year {}'.format(year_to_take))
        nc_file = nc.Dataset(
            model_output_folder + '/snow_out_{}_{}_{}_{}_{}_{}.nc'.format(
                met_inp, which_model, catchment, output_dem, run_id,
                year_to_take), 'r')
        nztm_dem = nc_file.variables['elevation'][:]
        x_centres = nc_file.variables['easting'][:]
        y_centres = nc_file.variables['northing'][:-116]
        out_dt = nc.num2date(
            nc_file.variables['time'][:], nc_file.variables['time'].units
        )  #, only_use_cftime_datetimes=False,                             only_use_python_datetimes=True
        for i in range(nc_file.variables['swe'].shape[0]):

            swe = np.log(nc_file.variables['swe'][i, :-116, :])
            swe[np.isinf(swe)] = 0  # take for NZ
            swe[modis_mask == False] = np.nan

            CS1 = plt.pcolormesh(x_centres,
                                 y_centres,
                                 swe,
                                 cmap=copy.copy(plt.cm.get_cmap('viridis')),
                                 vmin=1.61,
                                 vmax=8.52)  #levels=bin_edges, extend='max'
            #CS1.cmap.set_bad('grey')
            #CS1.cmap.set_under('grey')
            #CS1.cmap.set_under('grey')
            plt.gca().set_aspect('equal')
            # plt.imshow(modis_scd, origin=0, interpolation='none', vmin=0, vmax=365, cmap='magma_r')
            plt.xticks([])
            plt.yticks([])
            cbar = plt.colorbar(CS1, ticks=np.log([5, 50, 500, 5000]))
            cbar.set_ticklabels([5, 50, 500, 5000])
            cbar.set_label('Snow water equivalent (mm w.e.)', rotation=90)
            plt.xticks(np.arange(12e5, 21e5, 2e5))
            plt.yticks(np.arange(48e5, 63e5, 2e5))
            if bounding == 'moving':
                plt.ylim((camera_motion[0][i], camera_motion[0][i] + 4e5))
                plt.xlim((camera_motion[1][i], camera_motion[1][i] + 5e5))
            plt.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
            plt.ylabel('NZTM northing')
            plt.xlabel('NZTM easting')
            plt.title('SWE {}'.format(out_dt[i]))
            plt.tight_layout()

            plt.savefig(
                plot_folder + '/SWE model {} thres{} {} {} {} {}.png'.format(
                    year_to_take, model_swe_sc_threshold, run_id, met_inp,
                    which_model, i),
                dpi=150)
            # plt.show()
            plt.clf()
        return new_vector
  

    ax = plt.subplot(111)
    box = ax.get_position()
    ax.set_position([box.x0+0.08, box.y0, box.width*0.95, box.height]) 
    #r = scipy.zeros(10)  
    rlist= np.array([0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1])
   # rlist= [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 1.1]
    bias_sq_rlist = scipy.zeros(len(rlist))    
    for r_i in range(0, len(rlist)):
      #  bias_sq_rlist[r_inv-1] =  norm(resize( np.loadtxt('Jv_dx=e-2_r_inv=%d.out' %r_inv)  , bins) - Jv_sde )**2  Jv_dx=e-2_r=%d.out
        bias_sq_rlist[r_i] =  norm(resize( np.loadtxt('Jv_dx=e-2_r=%.3f.out' %rlist[r_i])  , bins) - Jv_sde )**2
    rlist =rlist/10000
      #  r[r_inv-1]= 1.0/r_inv
    plt.plot( rlist, bias_sq_rlist /bins, label ='$\Delta x = 10^{-2} $', linewidth=2  ) 
    plt.xlabel('$\Delta t$', fontsize = 14)
    plt.ylabel(r'$\left(\hat{\mathbf{Bias}}(\mathbf{\hat{Jv}} , \mathbf{Jv}_{FP} \right))^2$'  , fontsize = 15)
   # plt.xscale(log_flag)
   # plt.yscale(log_flag)
   # plt.ticklabel_format(style='sci',  scilimits=(0,10))
  #  plt.ticklabel_format(style='sci') 
    plt.ticklabel_format(useOffset=False, axis='y') 
    plt.savefig('plots/ftcs_checkup_linear_in_delta_t.pdf')
    plt.show()

    
 
    

Example #27
0
    Y.append(np.mean(D[i]))
    X.append(i)
    Y_err.append(np.std(D[i]))
    yy.append(np.sum(D[i]))

X = np.array(X)
Y = np.array(Y)
Y_err = np.array(Y_err)
# los datos estan el microsegundo, entonces lo pasamos a mili multiplicando por 10^-3
plt.figure(figsize=(8, 4))
plt.errorbar(X, Y, Y_err, color="firebrick")
plt.scatter(X, Y, color="navy")
# plt.plot(X,Y)
plt.title("Tiempo del algoritmo en funcion de la particion")
plt.xlabel("Particion")
plt.ylabel("Tiempo de computo")
plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 3))
plt.tight_layout()
plt.savefig("Grafica_tiempo.pdf")
plt.close()
plt.figure(figsize=(8, 4))
plt.plot(X, yy, color="slateblue")
plt.scatter(X, yy, color="firebrick")
plt.title("Tiempo total del algoritmo en funcion de la particion")
plt.xlabel("Particion")
plt.ylabel("Tiempo total de computo")
plt.ticklabel_format(style="sci", axis="y", scilimits=(0, 3))
plt.tight_layout()
plt.savefig("Graf_tiempo_total.pdf")
plt.close()
Example #28
0
plt.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)
colors = ['mediumpurple', 'gold', 'limegreen']

for i in range(len(data_1)):
    for j in range(1, len(data_1[0])):
        if (i == 0):
            ax1.bar(10 * ind[i] + width * j,
                    data_1[idx[i], j],
                    width,
                    color=colors[j - 1],
                    label=algos_name[j - 1])
        else:
            ax1.bar(10 * ind[i] + width * j,
                    data_1[idx[i], j],
                    width,
                    color=colors[j - 1])
ax1.legend(loc='best', fontsize=26)
ax1.set_xlabel("Number of points computed", fontsize=25)
ax1.set_ylabel("Running time (ms)", fontsize=25)
ax1.set_title("Performances Comparisons of Point in Polygon algorithms",
              fontsize=26)
ax1.set_xlim(-5 + width, len(data_1) + 90 + width)
ax1.set_xticks(ind + width)
plt.ticklabel_format(useOffset=True, style='sci', axis='y')
plt.xticks(np.linspace(0, 90, num=10) + 4.1,
           np.linspace(2500, 25000, num=10).astype(int),
           rotation=0,
           fontsize=20)
plt.yticks(rotation=0, fontsize=20)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 1))
fig.savefig("Grafico_belloWI_CN.png")
plot_data = []
plot_data.append(np.array(sir).flatten())
for step in range(365):
    #print(infected)          
    contact = contact_rate(int(sir[0]),int(sir[1]),step )
    P = transition_probability(contact,sir)
    #print (P)
    result = sir * P
    sir = result.tolist()[0]
    print(step,sir)
    plot_data.append(np.array(result).flatten())
    #print(sir[1] - infected_earlier)
 # Convert the data format
plot_data = np.array(plot_data)

# Create the plot
#plt.plot(plot_data[:, 0], label='S(t)')
plt.plot(plot_data[:, 1], label='I(t)')
plt.plot(plot_data[:, 2], label='D(t)')
plt.plot(plot_data[:, 3], label='R(t)')

plt.legend()

plt.xlabel('T')
plt.ylabel('N')

# use scientific notation
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))

plt.show()
Example #30
0
def plot_by_locs(data, output_name, colors, shapes, sub_ids, loc_ids, locs, roi_name, figsize=(15,5)):
    """
    Plot_by_locs takes a data rec_array and loops through three measures:
        fa, md, and vol_vox and plots each on separate plots with the
        x-axis representing the different locations
    
    Required:   data rec_array (eg: data)
                output_name (eg: results_dir/'plot_by_subs.png')
                colors (eg: colors)
                shapes (eg: shapes)
                sub_ids (eg: sub_ids)
                loc_ids (eg: loc_ids)
                locs (eg: locs)

    Optional:   figsize (default 15 x 5)

    Example usage:
        plot_by_locs(data=data, output_name=results_dir/'plot_by_subs.png',
                        colors=colors, shapes=shapes, sub_ids=sub_ids,
                        loc_ids=loc_ids, locs=locs, figsize=(15,5))

    """
    #==========================================================================
    import numpy as np
    import matplotlib.pylab as plt
    from matplotlib.ticker import MaxNLocator
    #==========================================================================
    
    # Set up the figure
    fig = plt.figure(figsize=(15,5))
    ax1 = plt.subplot(131)  # FA axis
    ax2 = plt.subplot(132)  # MD axis
    ax3 = plt.subplot(133)  # volume axis
    ax = [ax1, ax2, ax3]
    
    # Loop through the three measures (FA, MD, VOL_VOX)
    for count, measure in enumerate(['fa', 'md', 'vol_vox']):

        # Now loop through the subjects
        for i, sub in enumerate(sub_ids):

            # First things first, we want to set up a new numpy array
            # that will hold the mean values for each location so we
            # can plot a line through them at the end
            
            mean_array = np.zeros(3)
            
            for j, loc in enumerate(loc_ids):

                # Assign the correct color and shape for the marker
                c=colors[j,i]
                m=shapes[j]

                # Mask the data so you only have this sub at this loc's numbers
                mask = ( data['sub'] == sub ) & ( data['loc_id']== loc )

                # Find the number of data points you have for this sub at this location
                n = np.sum(mask)

                if n > 1:
                    # If you have more than one data point then we're going to plot
                    # the individual points (kinda small and a little transparent)
                    ax[count].scatter(np.ones(n)*loc, data[measure][mask],
                                            c=c, edgecolor=c,
                                            marker=m, s=20, alpha=0.5 )
                    
                    # ... connect them with a line ...
                    #ax[count].plot(np.ones(n)*loc, data[measure][mask], c=c)
                
                # And for everyone we'll plot the average
                # (which is just the data if you only have one point)
                mean = np.average(data[measure][mask])
                mean_array[j] = mean # Update the mean_array for plotting later!
                ax[count].scatter(loc, mean,
                                    c=c, edgecolor=c,
                                    marker=m, s=50 )
                
            # Now that we've filled up the mean_array let's plot it :)
            c=colors[3,i]
            ax[count].plot(loc_ids, mean_array, c=c, zorder=0)
            
            # Set the y limits
            # This is to deal with very small numbers (the MaxNLocator gets all turned around!)
            buffer = ( np.max(data[measure]) - np.min(data[measure]) ) / 10
            upper = np.max(data[measure]) + buffer
            lower = np.min(data[measure]) - buffer
            ax[count].set_ybound(upper, lower)  
            
        # Set the axis labels    
        ax[count].set_ylabel('{}'.format(measure.upper()))
        ax[count].set_xlabel('Scanner Location')
        
        # And label the x axis with the scanner locations
        ax[count].set_xticklabels(locs)

    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    [ a.yaxis.major.formatter.set_powerlimits((-3,3)) for a in ax ] 
    
    # Adjust the y axis ticks so that there are 6 at sensible places
    [ a.yaxis.set_major_locator(MaxNLocator(6)) for a in ax ]
    
    # Set the x axis ticks to be at the loc_ids
    [ a.set_xticks(loc_ids) for a in ax ]

    # Set the overall title
    fig.suptitle('Region of interest: {}'.format(roi_name), fontsize=20)
    plt.subplots_adjust(top=0.85)
    
    # And now save it!
    plt.savefig(output_name, bbox_inches=0, facecolor='w', edgecolor='w', transparent=True)
fig, ax = plt.subplots(1)
#ax.yaxis.set_label_position("right")
for dsys in ['linux_tuned_joule', 'linux_tuned_tail']:
    ddf = ddfs[dsys][0]
    ddfn = ddfs[dsys][1]
    ddfn = ddfn[(ddfn['instructions_diff'] > 0)
                & (ddfn['instructions_diff'] < 250000000)]
    plt.plot(ddfn['timestamp_non0'],
             ddfn['instructions_diff'],
             HATCHS[dsys],
             label=LABELS[dsys],
             c=COLORS[dsys],
             alpha=0.5)
plt.xlabel("Time (secs)")
plt.ylabel("Instructions")
plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
plt.legend(markerscale=3, loc='upper right')
plt.grid()
plt.tight_layout()
#plt.savefig(f'mcd_linux_{QPS}_instructions_timeline.png')

#### bar plot
metric_labels = [
    'CPI', 'Instructions', 'Cycles', 'RxBytes', 'TxBytes', 'Interrupts'
]
N_metrics = len(metric_labels)  #number of clusters
N_systems = 3  #number of plot loops
fig, ax = plt.subplots(1)
idx = np.arange(N_metrics)  #one group per metric
width = 0.2
data_dict = {}
Example #32
0
# In[3]:

np.random.seed(1234)  #Set random seed for reproducibility

N_rand = N * (1 + np.random.normal(scale=0.1, size=len(N))
              )  #Add some error to data

# Here's what the data look like:

# In[4]:

plt.plot(t, N_rand, 'r+', markersize=15, markeredgewidth=2, label='Data')
plt.xlabel('t', fontsize=20)
plt.ylabel(r'$N$', fontsize=20)
plt.ticklabel_format(style='scientific', scilimits=[0, 3])
plt.yscale('log')

# ## Fitting a Linear model to the data

# Lets start with the simplest case; a linear model.
#
# \begin{equation*}\label{eq:linear_model}
#     N_t = at^3 + bt^2 + ct + d
# \end{equation*}
#
# where $a$, $b$, $c$ and $d$, are phenomenological parameters.

# ### Using NLLS

# In[5]:
        vv[timestamps[i]] += 1

    fs = 1e6
    L = vv.shape[0]
    vv = vv - np.sum(vv)/L
    NFFT = int(2**np.ceil(np.log2(L)))
    ff = np.fft.fft(vv, NFFT)/L
    f = fs/2*(np.arange(NFFT/2)/float(NFFT/2))

    f_draw = f
    ff_draw = 2*np.abs(ff[:NFFT/2])

    plt.figure(figsize=(50, 45))
    plt.xlim([0, 100])
    plt.plot(f_draw, ff_draw, 'b', linewidth=10)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plt.xticks(np.arange(0, 100+1, 20))
    plt.yticks(np.arange(0, 1.8e-1+0.3e-1, 0.3e-1))
    plt.xlabel("Frequency [Hz]", fontsize=150)
    plt.savefig(vot_save_path, format="eps", dpi=1200,
                bbox_inches='tight', pad_inches=0.5)
    print("[MESSAGE] Amplitude Spectrum is saved at %s" % (vot_save_path))
elif option == "tracking-as":
    tracking_fn = "INI_TrackingDataset_30fps_20160424.hdf5"
    tracking_path = os.path.join(data_path, tracking_fn)
    tracking_db = h5py.File(tracking_path, mode="r")
    tracking_stats_path = os.path.join(stats_path, "tracking_stats.pkl")
    tracking_save_path = os.path.join(data_path, "tracking_as.eps")

    f = file(tracking_stats_path, mode="r")
    tracking_stats = pickle.load(f)
Example #34
0
def run_RF_trip_experiment(Tmax, test_file):

    # Import JSON parser module
    from get_configuration import Get_SWIG_Cryomodule

    cryo_object, Tstep, fund_mode_dicts = Get_SWIG_Cryomodule(test_file,
                                                              Verbose=False)

    # Create time vector
    trang = np.arange(0, Tmax, Tstep)

    # Number of points
    nt = len(trang)

    # Initialize vectors for test
    cav_v = np.zeros(nt,
                     dtype=np.complex)  # Overall cavity accelerating voltage
    E_reverse = np.zeros(nt, dtype=np.complex)
    Kg = np.zeros(nt, dtype=np.complex)

    delta_omega = np.zeros(nt, dtype=np.double)

    # Manually set the controller set-point
    # FPGA controller will be operating in open-loop mode,
    # which is equivalent to driving the cavity with the set-point value
    # cryo_object.station_list[0].C_Pointer.fpga.set_point = 30.0
    # cryo_object.station_list[0].State.fpga_state.openloop = 1

    # Get a C pointer to the Electrical Mode State to record its detune frequency
    elecMode_state = acc.ElecMode_State_Get(
        cryo_object.station_list[0].State.cav_state, 0)

    # Run Numerical Simulation
    for i in xrange(1, nt):
        # Run Cryomodule Step function
        acc.Cryomodule_Step(cryo_object.C_Pointer, cryo_object.State, 0.0, 0.0)

        # Record some waveforms
        # Cavity state
        cav_v[i] = cryo_object.station_list[0].State.cav_state.V
        E_reverse[i] = cryo_object.station_list[0].State.cav_state.E_reverse
        Kg[i] = cryo_object.station_list[0].State.cav_state.Kg

        # pi-mode's detune frequency [rad/s]
        delta_omega[i] = elecMode_state.delta_omega

    # Make some calculations for plots
    # Mode's bandwidth
    omega_f = fund_mode_dicts[0]['bw']
    # Derivative of the cavity field
    cav_v_der = np.diff(cav_v, 1) / Tstep
    factor = 1 - 1j * delta_omega / omega_f
    # Calculate waveforms with corresponding factors to equate units in order to plot together
    x2 = cav_v_der / omega_f
    x3 = np.multiply(cav_v, factor)

    # Plot cavity signals
    plt.plot(trang * 1e6,
             np.abs(Kg),
             '-',
             label=r'Forward ($\vec K_{\rm g}$)',
             linewidth=2)
    plt.plot(trang * 1e6,
             np.abs(cav_v) * 1e-4,
             '-',
             label=r'Cavity ($\vec V_{\pi}\times \, 10^{-4}$)',
             linewidth=2)
    plt.plot(trang * 1e6,
             np.abs(E_reverse),
             '-',
             label=r'Reverse ($\vec E_{\rm reverse}$)',
             linewidth=2)

    plt.title('Cryomodule Test', fontsize=40, y=1.01)
    plt.xlabel(r'Time [$\rm \mu s$]', fontsize=30)
    plt.ylim(0, 60)
    plt.ylabel('Amplitude [V]', fontsize=30)
    plt.legend(loc='upper right')
    plt.rc('font', **{'size': 25})

    plt.show()
    plt.figure()

    # Plot detune frequency vs time
    plt.title('Detune Frequency', fontsize=40, y=1.01)
    plt.plot(trang * 1e6,
             1.9e-7 * np.square(np.abs(cav_v)) / 2.0 / np.pi,
             '-',
             label=r'$k_{\rm L}|\vec V_{\pi}|^{\rm 2}$',
             linewidth=2)
    plt.plot(trang * 1e6,
             -delta_omega / 2.0 / np.pi,
             '-',
             label=r'$-\Delta f_{\pi}$',
             linewidth=2)
    plt.ylabel('Frequency [Hz]', fontsize=30)
    plt.xlabel(r'Time [$\rm \mu s$]', fontsize=30)
    plt.legend(loc='upper right')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plt.ylim(0, 8e3)
    plt.show()

    # Plot cavity signals in complex plane
    dpi = 100
    f = plt.figure(figsize=(1400 / dpi, 1350 / dpi), dpi=dpi)
    x = f.gca()
    x.set_aspect("equal")

    plt.title(r'$\pi$-mode in Volts', fontsize=40, y=1.01)

    x.plot(np.real(cav_v),
           np.imag(cav_v),
           '-',
           label=r'Cavity ($\vec V_{\pi}$)',
           linewidth=2)
    x.plot(np.real(x2),
           np.imag(x2),
           '-',
           label=r'$\omega_{\rm f}\times \, \frac{d\vec V_{\pi}}{dt}$',
           linewidth=2)
    x.plot(
        np.real(x3),
        np.imag(x3),
        '-',
        label=r'$\left( 1-j\omega_{\rm d}/\omega_{\rm f}\right) \vec V_{\pi}$',
        linewidth=2)
    x.set_ylabel(r'$\Im$ [V]', fontsize=30)
    x.set_xlabel(r'$\Re$ [V]', fontsize=30)
    x.set_xlim(-7e5, 7e5)
    x.set_ylim(-7e5, 7e5)
    x.ticklabel_format(style='sci', axis='both', scilimits=(0, 0))
    x.legend(loc='upper right')

    plt.show()
    plt.figure()
Example #35
0
def plot_by_locs(data,
                 output_name,
                 colors,
                 shapes,
                 sub_ids,
                 loc_ids,
                 locs,
                 roi_name,
                 figsize=(15, 5)):
    """
    Plot_by_locs takes a data rec_array and loops through three measures:
        fa, md, and vol_vox and plots each on separate plots with the
        x-axis representing the different locations
    
    Required:   data rec_array (eg: data)
                output_name (eg: results_dir/'plot_by_subs.png')
                colors (eg: colors)
                shapes (eg: shapes)
                sub_ids (eg: sub_ids)
                loc_ids (eg: loc_ids)
                locs (eg: locs)

    Optional:   figsize (default 15 x 5)

    Example usage:
        plot_by_locs(data=data, output_name=results_dir/'plot_by_subs.png',
                        colors=colors, shapes=shapes, sub_ids=sub_ids,
                        loc_ids=loc_ids, locs=locs, figsize=(15,5))

    """
    #==========================================================================
    import numpy as np
    import matplotlib.pylab as plt
    from matplotlib.ticker import MaxNLocator
    #==========================================================================

    # Set up the figure
    fig = plt.figure(figsize=(15, 5))
    ax1 = plt.subplot(131)  # FA axis
    ax2 = plt.subplot(132)  # MD axis
    ax3 = plt.subplot(133)  # volume axis
    ax = [ax1, ax2, ax3]

    # Loop through the three measures (FA, MD, VOL_VOX)
    for count, measure in enumerate(['fa', 'md', 'vol_vox']):

        # Now loop through the subjects
        for i, sub in enumerate(sub_ids):

            # First things first, we want to set up a new numpy array
            # that will hold the mean values for each location so we
            # can plot a line through them at the end

            mean_array = np.zeros(3)

            for j, loc in enumerate(loc_ids):

                # Assign the correct color and shape for the marker
                c = colors[j, i]
                m = shapes[j]

                # Mask the data so you only have this sub at this loc's numbers
                mask = (data['sub'] == sub) & (data['loc_id'] == loc)

                # Find the number of data points you have for this sub at this location
                n = np.sum(mask)

                if n > 1:
                    # If you have more than one data point then we're going to plot
                    # the individual points (kinda small and a little transparent)
                    ax[count].scatter(np.ones(n) * loc,
                                      data[measure][mask],
                                      c=c,
                                      edgecolor=c,
                                      marker=m,
                                      s=20,
                                      alpha=0.5)

                    # ... connect them with a line ...
                    #ax[count].plot(np.ones(n)*loc, data[measure][mask], c=c)

                # And for everyone we'll plot the average
                # (which is just the data if you only have one point)
                mean = np.average(data[measure][mask])
                mean_array[
                    j] = mean  # Update the mean_array for plotting later!
                ax[count].scatter(loc, mean, c=c, edgecolor=c, marker=m, s=50)

            # Now that we've filled up the mean_array let's plot it :)
            c = colors[3, i]
            ax[count].plot(loc_ids, mean_array, c=c, zorder=0)

            # Set the y limits
            # This is to deal with very small numbers (the MaxNLocator gets all turned around!)
            buffer = (np.max(data[measure]) - np.min(data[measure])) / 10
            upper = np.max(data[measure]) + buffer
            lower = np.min(data[measure]) - buffer
            ax[count].set_ybound(upper, lower)

        # Set the axis labels
        ax[count].set_ylabel('{}'.format(measure.upper()))
        ax[count].set_xlabel('Scanner Location')

        # And label the x axis with the scanner locations
        ax[count].set_xticklabels(locs)

    # Adjust the power limits so that you use scientific notation on the y axis
    plt.ticklabel_format(style='sci', axis='y')
    [a.yaxis.major.formatter.set_powerlimits((-3, 3)) for a in ax]

    # Adjust the y axis ticks so that there are 6 at sensible places
    [a.yaxis.set_major_locator(MaxNLocator(6)) for a in ax]

    # Set the x axis ticks to be at the loc_ids
    [a.set_xticks(loc_ids) for a in ax]

    # Set the overall title
    fig.suptitle('Region of interest: {}'.format(roi_name), fontsize=20)
    plt.subplots_adjust(top=0.85)

    # And now save it!
    plt.savefig(output_name,
                bbox_inches=0,
                facecolor='w',
                edgecolor='w',
                transparent=True)
    model_scd = model_scd[:, 20:]
    model_scd[nztm_dem == 0] = np.nan
    CS1 = plt.contourf(x_centres,
                       y_centres,
                       model_scd,
                       levels=bin_edges,
                       cmap=copy.copy(plt.cm.get_cmap('magma_r')),
                       extend='max')
    # CS1.cmap.set_bad('grey')
    CS1.cmap.set_over([0.47, 0.72, 0.77])
    # CS1.cmap.set_under('none')
    plt.gca().set_aspect('equal')
    # plt.imshow(modis_scd, origin=0, interpolation='none', vmin=0, vmax=365, cmap='magma_r')
    plt.xticks([])
    plt.yticks([])
    cbar = plt.colorbar()
    cbar.set_label('Snow cover duration (days)', rotation=90)
    plt.xticks(np.arange(12e5, 17e5, 2e5))
    plt.yticks(np.arange(50e5, 55e5, 2e5))
    plt.ticklabel_format(axis='both', style='sci', scilimits=(0, 0))
    plt.ylabel('NZTM northing')
    plt.xlabel('NZTM easting')
    plt.title('Snow cover duration {}'.format(year_to_take))
    plt.tight_layout()

    plt.savefig(plot_folder + '/SCD model {} thres{} {} {} {}.png'.format(
        year_to_take, model_swe_sc_threshold, run_id, met_inp, which_model),
                dpi=300)
    plt.show()
    plt.close()
Example #37
0
def plot_data(directory='./data/',
              data_type="bsf",
              nbytes=4,
              average=False,
              ax=None):
    """
    Plots either the Best-so-far (BSF) fitness or the average fitness per
    population.

    Args:
        directory (string): The full path to the directory the data are stored
        data_type (string): bsf-for best-so-far fitness or average_fitness for
                            the average fitness per population
        nbytes (int):       Number of bytes of the encoding. Default is 4 (int
                            or float). Use 8 for double or long int.
        average (bool):     If enabled (True) averages the fitness records over
                            all individuals.
        ax (obj):           A subplot object in case one would like to use
                            subplots or grids.

    Returns:
    """
    if os.path.isdir(directory) is not True:
        print("Directory does not exist!")
        sys.exit(-1)

    fnames = glob.glob(directory+'/*.dat')

    i = 0
    data = []
    for name in fnames:
        if data_type in name:
            with open(name, 'rb') as f:
                c = f.read()
            if nbytes == 4:
                tmp = np.array(unpack('f'*(len(c)//4), c), 'f')
            elif nbytes == 8:
                tmp = np.array(unpack('d'*(len(c)//8), c), 'd')
            else:
                print("Number of bytes is not valid!")
                sys.exit(-1)
            data.append(tmp)
    data = np.array(data)
    if average:
        average_fit = data.mean(axis=0)

    if ax is None:
        fig = plt.figure(figsize=(9, 5))
        fig.subplots_adjust(bottom=0.2, left=0.2)
        ax = fig.add_subplot(111)
    if average:
        ax.plot(average_fit, lw=2)
    else:
        for i in range(len(data)):
            ax.plot(data[i], lw=2)
            plt.ticklabel_format(axis="y", style='sci')
    # ax.set_ylim([data.min(), 0])
    ax.set_xlabel("Generations", fontsize=16, weight='bold')
    if data_type == "bsf":
        ax.set_ylabel("BSF", fontsize=16, weight='bold')
    else:
        ax.set_ylabel("Average fitness", fontsize=16, weight='bold')
    ticks = ax.get_xticks().astype('i')
    ax.set_xticklabels(ticks, fontsize=16, weight='bold')
    ticks = np.round(ax.get_yticks(), 6)
    ax.set_yticklabels(ticks, fontsize=16, weight='bold')
Example #38
0

ax.plot3D(x, y, z, 'c' , label ='Orbita')
plt.plot( [0,0], [0,Atmosfera], '-', c='k')
plt.plot( [0,0], [0,-Atmosfera], '-', c='k')
plt.plot( [0,Atmosfera], [0,0], '-', c='k')
plt.plot( [0,-Atmosfera], [0,0], '-', c='k')
ax.plot3D(cx, cy, cz, 'peru' , alpha = 0.2, label = 'Tierra')  
plt.plot( cx2 , cy2 , c = 'salmon' , label = 'Atmosfera')      #Atmosfera
  
plt.grid() 

plt.ylabel ('Y (m)' , fontweight = 'bold')
plt.xlabel ('X (m)',  fontweight = 'bold' )
plt.title("Satelite A", fontweight = 'bold') 
plt.ticklabel_format(useOffset = False, style = 'plain')

plt.tight_layout()  
plt.legend()
plt.savefig('Satelite 3D' ,dpi = 300)
plt.show()


# ----------Grafico 2D Tierra, Orbita y Atmosfera -----------


fig = plt.figure(2)
Atmosfera = Rt + 80*km


# Hago la Tierra en 2D
Example #39
0
    def print_plybook(self,
                      filename='plybook',
                      vmode='stack',
                      include_materials=False,
                      slim=[],
                      add_filename=False,
                      add_page=False):
        ''' Prints a PDF file for layup visualization.

        :param filename: name of the PDF
        :param vmode: 'stack' or 'explode' visualization of layup
        :param include_materials: True if materials should be included (runs only
                when check_consistency() is OK)
        :param slim: [slim_lower, slim_upper] limits the x axis of the plots
        :param add_filename: if True filename is added to each plot 
        :param add_page: if True page number of plybook is added to each plot 

        '''

        import matplotlib.pylab as plt
        import matplotlib.patches as patches
        from matplotlib.backends.backend_pdf import PdfPages

        pb = PdfPages(filename + '.pdf')

        cm = plt.get_cmap('jet')

        # create material color dict (necessary for the case that materials list
        # is longer than 7)
        start = 0.2
        stop = 1.0
        number_of_lines = len(self.materials)
        mat_colors = [cm(x) for x in np.linspace(start, stop, number_of_lines)]
        cm_dict = {}
        for i, m in enumerate(self.materials.iterkeys()):
            cm_dict[m] = mat_colors[i]

        page_pos_x = 0.98
        page_pos_y = 0.02
        filename_pos_x = 0.02
        filename_pos_y = 0.02
        if include_materials:
            # material properties
            fig, _ = plt.subplots()
            plt.title('MATPROPS')
            N = 10
            ind = np.arange(N)  # the x locations for the groups
            # the width of the bars: can also be len(x) sequence
            width = 1.0 / N
            for i, mat_name in enumerate(self.materials.iterkeys()):
                plt.bar(ind + i * width,
                        self.materials[mat_name].matprops()[0],
                        width,
                        color=cm_dict[mat_name],
                        label=mat_name,
                        log=1)
                if i == 1:
                    matprops_labels = self.materials[mat_name].matprops()[1]

            plt.xticks(ind + .5, matprops_labels)
            plt.legend(loc='best', prop={'size': 10}, framealpha=0.5)
            # add page number and filename to figure
            if add_page:
                fig.text(page_pos_x,
                         page_pos_y,
                         str(pb.get_pagecount() + 1),
                         ha='left',
                         fontsize=8)
            if add_filename:
                fig.text(filename_pos_x,
                         filename_pos_y,
                         str(filename),
                         ha='left',
                         fontsize=8)
            pb.savefig()  # save fig to plybook

            # failmat_stress
            fig, _ = plt.subplots()
            plt.title('FAILMAT_STRESS')
            N = 9
            ind = np.arange(N)  # the x locations for the groups
            # the width of the bars: can also be len(x) sequence
            width = 1.0 / N
            for i, mat_name in enumerate(self.materials.iterkeys()):
                plt.bar(ind + i * width,
                        self.materials[mat_name].failmat()[0][:N],
                        width,
                        color=cm_dict[mat_name],
                        label=mat_name,
                        log=1)
                if i == 1:
                    matprops_labels = self.materials[mat_name].failmat()[1]

            plt.xticks(ind + .5, matprops_labels[:N])
            plt.legend(loc='best', prop={'size': 10}, framealpha=0.5)
            # add page number and filename to figure
            if add_page:
                fig.text(page_pos_x,
                         page_pos_y,
                         str(pb.get_pagecount() + 1),
                         ha='left',
                         fontsize=8)
            if add_filename:
                fig.text(filename_pos_x,
                         filename_pos_y,
                         str(filename),
                         ha='left',
                         fontsize=8)
            pb.savefig()  # save fig to plybook

            # failmat_strain
            fig, _ = plt.subplots()
            plt.title('FAILMAT_STRAIN')
            N = 9
            ind = np.arange(N)  # the x locations for the groups
            # the width of the bars: can also be len(x) sequence
            width = 1.0 / N
            for i, mat_name in enumerate(self.materials.iterkeys()):
                plt.bar(ind + i * width,
                        self.materials[mat_name].failmat()[0][N:2 * N],
                        width,
                        color=cm_dict[mat_name],
                        label=mat_name)
                if i == 1:
                    matprops_labels = self.materials[mat_name].failmat()[1]

            plt.xticks(ind + .5, matprops_labels[N:2 * N])
            plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
            plt.legend(loc='best', prop={'size': 10}, framealpha=0.5)
            # add page number and filename to figure
            if add_page:
                fig.text(page_pos_x,
                         page_pos_y,
                         str(pb.get_pagecount() + 1),
                         ha='left',
                         fontsize=8)
            if add_filename:
                fig.text(filename_pos_x,
                         filename_pos_y,
                         str(filename),
                         ha='left',
                         fontsize=8)
            pb.savefig()  # save fig to plybook

            # failmat_safety
            fig, _ = plt.subplots()
            plt.title('FAILMAT_SAFETY')
            N = 5
            ind = np.arange(N)  # the x locations for the groups
            # the width of the bars: can also be len(x) sequence
            width = 1.0 / 9
            for i, mat_name in enumerate(self.materials.iterkeys()):
                plt.bar(ind + i * width,
                        self.materials[mat_name].failmat()[0][18:18 + N],
                        width,
                        color=cm_dict[mat_name],
                        label=mat_name)
                if i == 1:
                    matprops_labels = self.materials[mat_name].failmat()[1]

            plt.xticks(ind + .5, matprops_labels[18:18 + N])
            plt.legend(loc='best', prop={'size': 10}, framealpha=0.5)
            # add page number and filename to figure
            if add_page:
                fig.text(page_pos_x,
                         page_pos_y,
                         str(pb.get_pagecount() + 1),
                         ha='left',
                         fontsize=8)
            if add_filename:
                fig.text(filename_pos_x,
                         filename_pos_y,
                         str(filename),
                         ha='left',
                         fontsize=8)
            pb.savefig()  # save fig to plybook

        fig, _ = plt.subplots()
        plt.title('DPs')
        for di, dk in enumerate(sorted(self.DPs, reverse=True)):
            plt.plot(self.s, self.DPs[dk].arc, label=dk[-2:])
        plt.legend(loc='best', prop={'size': 6}, bbox_to_anchor=(1, 1))
        # draw station lines
        for s in self.s:
            plt.plot([self.s, self.s], [-1, 1], 'k', linewidth=0.5)
        if slim:
            plt.xlim((slim[0], slim[1]))
        # add page number and filename to figure
        if add_page:
            fig.text(page_pos_x,
                     page_pos_y,
                     str(pb.get_pagecount() + 1),
                     ha='left',
                     fontsize=8)
        if add_filename:
            fig.text(filename_pos_x,
                     filename_pos_y,
                     str(filename),
                     ha='left',
                     fontsize=8)
        pb.savefig()  # save fig to plybook

        def _region_sets(reg_type):
            ''' Compares all regions of reg_type and creates a list of unique reg_types

            :param reg_type: self.regions or self.webs or self.bonds
            :return: list: unique region sets
            '''

            # list of rthicks and region cum thicknesses
            rthicks = []
            rmaxthicks = []
            for i, rv in enumerate(reg_type.itervalues()):
                # init thicknesses
                rv.init_stack()
                rthicks.append(rv.thick_matrix)
                rmaxthicks.append(np.sum(rv.thick_max))
            # maximum thickness of sets
            rmaxthick = np.max(rmaxthicks)
            # check for identic regions
            rsets = []
            for rt0 in rthicks:
                i0_idents = []
                for i, rt in enumerate(rthicks):
                    if np.array_equal(rt0, rt):
                        i0_idents.append(i)
                rsets.append(i0_idents)
            # remove duplicate entries
            rsets = map(list, OrderedDict.fromkeys(map(tuple, rsets)))
            return rsets, rmaxthick

        def _plot_region(rsets, reg_type):
            ''' Adds plots of region sets to plybook

            :param rsets: list of region sets
            :param reg_type: self.regions or self.webs or self.bonds
            '''
            if reg_type == self.regions:
                rtype = 'region'
            elif reg_type == self.webs:
                rtype = 'web'
            elif reg_type == self.bonds:
                rtype = 'bond'

            for rset in rsets:
                r = reg_type['%s%02d' % (rtype, rset[0])]
                fig1, ax1 = plt.subplots()
                #fig1 = plt.figure()
                #ax1 = fig1.add_subplot(111)
                plt.title(rtype.upper() + ' ' + str(rset))
                # draw station lines
                for s in self.s:
                    ax1.plot([self.s, self.s], [0, maxthick],
                             'k',
                             linewidth=0.5)
                t = np.zeros_like(self.s)
                for k, l in r.layers.iteritems():
                    mat_name = k[:-2]
                    mat_count = k[-2:]
                    if vmode == 'stack':
                        # draw layer box
                        plt.plot(self.s, t + l.thickness, 'k')
                        # draw layer thickness distro
                        plt.fill_between(self.s,
                                         t,
                                         t + l.thickness,
                                         color=cm_dict[mat_name],
                                         label=mat_name if int(mat_count) == 0
                                         else "_nolegend_")
                        t = t + l.thickness
                    elif vmode == 'explode':
                        # check for layer drops
                        drops = []
                        drop_prev = 0
                        for s, thick in enumerate(l.thickness):
                            if t[s] + thick > t[s]:
                                drop = 1
                            else:
                                drop = 0
                            if drop != drop_prev and drop_prev == 0:
                                drops.append(s)
                            elif drop != drop_prev and drop_prev == 1:
                                drops.append(s - 1)
                            drop_prev = drop
                        if len(drops) == 1:
                            drops.append(len(l.thickness) - 1)
                        max_thick = np.max(l.thickness)
                        # draw layer box
                        for di in range(len(drops) - 1):
                            # draw box per layer
                            north_west = [
                                self.s[drops[di]], t[drops[di]] + max_thick
                            ]
                            south_west = [self.s[drops[di]], t[drops[di]]]
                            north_east = [
                                self.s[drops[di + 1]],
                                t[drops[di + 1]] + max_thick
                            ]
                            south_east = [
                                self.s[drops[di + 1]], t[drops[di + 1]]
                            ]
                            if drops[di] > 0:  # we have a plydrop up
                                north_west = [
                                    self.s[drops[di] - 1],
                                    t[drops[di]] + max_thick
                                ]
                                south_west = [
                                    self.s[drops[di] - 1], t[drops[di]]
                                ]
                                south_south_west = [
                                    self.s[drops[di]], t[drops[di]]
                                ]
                                north_mid_west = [
                                    self.s[drops[di]],
                                    (t + l.thickness)[drops[di]]
                                ]
                                # draw layer thickness distro drop
                                ax1.add_patch(
                                    patches.Polygon(
                                        [
                                            south_west, north_mid_west,
                                            south_south_west
                                        ],
                                        linewidth=0,
                                        facecolor=cm_dict[mat_name]))
                            # we have a plydrop down
                            if drops[di + 1] < len(self.s) - 1:
                                south_east = [
                                    self.s[drops[di + 1] + 1], t[drops[di + 1]]
                                ]
                                north_east = [
                                    self.s[drops[di + 1] + 1],
                                    t[drops[di + 1]] + max_thick
                                ]
                                south_south_east = [
                                    self.s[drops[di + 1]], t[drops[di + 1]]
                                ]
                                north_mid_east = [
                                    self.s[drops[di + 1]],
                                    (t + l.thickness)[drops[di + 1]]
                                ]
                                # draw layer thickness distro drop
                                ax1.add_patch(
                                    patches.Polygon(
                                        [
                                            north_mid_east, south_east,
                                            south_south_east
                                        ],
                                        linewidth=0,
                                        facecolor=cm_dict[mat_name]))
                            ax1.add_patch(
                                patches.Polygon([
                                    south_west, north_west, north_east,
                                    south_east
                                ],
                                                fill=False))
                        # draw layer thickness distro
                        plt.fill_between(self.s,
                                         t,
                                         t + l.thickness,
                                         where=t < t + l.thickness,
                                         color=cm_dict[mat_name],
                                         label=mat_name if int(mat_count) == 0
                                         else "_nolegend_")
                        t = t + max_thick
                plt.ylim([0, maxthick])  # set all plot limits to maxthickness
                plt.legend(loc='best', prop={'size': 10}, framealpha=0.5)
                if slim:
                    plt.xlim((slim[0], slim[1]))
                # add page number and filename to figure
                if add_page:
                    fig1.text(page_pos_x,
                              page_pos_y,
                              str(pb.get_pagecount() + 1),
                              ha='left',
                              fontsize=8)
                if add_filename:
                    fig1.text(filename_pos_x,
                              filename_pos_y,
                              str(filename),
                              ha='left',
                              fontsize=8)
                pb.savefig(fig1)  # save fig to plybook

        rsets, rmaxthick = _region_sets(self.regions)
        wsets, wmaxthick = _region_sets(self.webs)
        if hasattr(self, 'bonds'):
            bsets, bmaxthick = _region_sets(self.bonds)
            maxthick = np.max([rmaxthick, wmaxthick])  # , bmaxthick])
        else:
            maxthick = np.max([rmaxthick, wmaxthick])

        _plot_region(rsets, reg_type=self.regions)
        _plot_region(wsets, reg_type=self.webs)
        if hasattr(self, 'bonds'):
            _plot_region(bsets, reg_type=self.bonds)

        pb.close()  # close plybook