Esempio n. 1
0
def plot(most_probable_params, best_step, chain, lnprob, nwalkers, ndim, niter):
	# PLOT WALKERS
	fig=plt.figure()
	Y_PLOT=2
	X_PLOT=5
	alpha=0.1
	
	# Walkers
	burnin=0.5*niter
	print 'burnin', burnin
	for n in range(ndim):
		ax=fig.add_subplot(Y_PLOT+1,X_PLOT,n+1)
		for i in range(nwalkers): # Risem za posamezne walkerje
			d=np.array(chain[i][burnin:,n])
			ax.plot(d, color='black', alpha=alpha)
		ax.set_xlabel(thetaText[n+1])
		if best_step-burnin>0:
			plt.axvline(x=best_step-burnin, linewidth=1, color='red')
		
	# Lnprob
	ax=fig.add_subplot(Y_PLOT+1,1,Y_PLOT+1)
	for i in range(nwalkers):
		ax.plot((lnprob[i][burnin:]), color='black', alpha=alpha)
	if best_step-burnin>0:
		plt.axvline(x=best_step-burnin, linewidth=1, color='red')
	
	#~ import triangle
	#~ fig = triangle.corner(sampler.flatchain, truths=most_probable_params) # labels=thetaText
	
	plt.show()
Esempio n. 2
0
def mark_cross(center, **kwargs):
    """Mark a cross. Correct for matplotlib imshow funny coordinate system.
    """
    N = 20
    plt.hold(1)
    plt.axhline(y=center[1]-0.5, **kwargs)
    plt.axvline(x=center[0]-0.5, **kwargs)
Esempio n. 3
0
 def segmentation(self, threshold):
     img = self.spectrogram["data"]
     mask = (img > threshold).astype(np.float)
     hist, bin_edges = np.histogram(img, bins=60)
     bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])
     binary_img = mask > 0.5
     plt.figure(figsize=(11,8))
     plt.subplot(131)
     plt.imshow(img)
     plt.axis('off')
     plt.subplot(132)
     plt.plot(bin_centers, hist, lw=2)
     print(threshold)
     plt.axvline(threshold, color='r', ls='--', lw=2)
     plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes)
     plt.text(0.45, 0.75, 'threshold = '+ str(threshold)[0:5], fontsize=15, transform = plt.gca().transAxes)
     plt.yticks([])
     plt.subplot(133)     
     plt.imshow(binary_img)
     plt.axis('off')
     plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)
     plt.show()
     print(img.max())
     print(binary_img.max())
     
     return mask
Esempio n. 4
0
def plot_spikes(time,voltage,APTimes,titlestr):
    """
    plot_spikes takes four arguments - the recording time array, the voltage
    array, the time of the detected action potentials, and the title of your
    plot.  The function creates a labeled plot showing the raw voltage signal
    and indicating the location of detected spikes with red tick marks (|)
    """
# Make a plot and markup
    plt.figure()
    plt.title(titlestr)
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (uV)") 

    plt.plot(time, voltage)
    
# Vertical positions for red marker
# The following attributes are configurable if required    
    vertical_markers_indent = 0.01 # 1% of Voltage scale height
    vertical_markers_height = 0.03 # 5% of Voltage scale height
    y_scale_height = 100 # Max of scale
    
    marker_ymin = 0.5 + ( max(voltage) / y_scale_height / 2 ) + vertical_markers_indent
    marker_ymax = marker_ymin + vertical_markers_height

# Drawing red markers for detected spikes
    for spike in APTimes:
        plt.axvline(spike, ymin=marker_ymin, ymax=marker_ymax, color='red')
    
    plt.draw()
Esempio n. 5
0
def plot_beta_dist( ctr, trials, success, alphas, betas, turns ):
	"""
	Pass in the ctr, trials and success, alphas, betas returned
	by the `experiment` function and the number of turns 
	and plot the beta distribution for all the arms in that turn
	"""
	subplot_num = len(turns) / 2
	x = np.linspace( 0.001, .999, 200 )
	fig = plt.figure( figsize = ( 14, 7 ) ) 

	for idx, turn in enumerate(turns):

		plt.subplot( subplot_num, 2, idx + 1 )

		for i in range( len(ctr) ):
			y = beta( alphas[i] + success[ turn, i ], 
					  betas[i] + trials[ turn, i ] - success[ turn, i ] ).pdf(x)
			line = plt.plot( x, y, lw = 2, label = "arm {}".format( i + 1 ) )
			color = line[0].get_color()
			plt.fill_between( x, 0, y, alpha = 0.2, color = color )
			plt.axvline( x = ctr[i], color = color, linestyle = "--", lw = 2 )
			plt.title("Posteriors After {} turns".format(turn) )
			plt.legend( loc = "upper right" )

	return fig
Esempio n. 6
0
def showKernel(dataOrMatrix, fileName = None, useLabels = True, **args) :
 
    labels = None
    if hasattr(dataOrMatrix, 'type') and dataOrMatrix.type == 'dataset' :
	data = dataOrMatrix
	k = data.getKernelMatrix()
	labels = data.labels
    else :
	k = dataOrMatrix
	if 'labels' in args :
	    labels = args['labels']

    import matplotlib

    if fileName is not None and fileName.find('.eps') > 0 :
        matplotlib.use('PS')
    from matplotlib import pylab

    pylab.matshow(k)
    #pylab.show()

    if useLabels and labels.L is not None :
	numPatterns = 0
	for i in range(labels.numClasses) :
	    numPatterns += labels.classSize[i]
	    #pylab.figtext(0.05, float(numPatterns) / len(labels), labels.classLabels[i])
	    #pylab.figtext(float(numPatterns) / len(labels), 0.05, labels.classLabels[i])
	    pylab.axhline(numPatterns, color = 'black', linewidth = 1)
	    pylab.axvline(numPatterns, color = 'black', linewidth = 1)
    pylab.axis([0, len(labels), 0, len(labels)])
    if fileName is not None :
        pylab.savefig(fileName)
	pylab.close()
Esempio n. 7
0
File: pca.py Progetto: id774/sandbox
def test(args):
    data = multivariate_normal([0, 0], [[1, 2], [2, 5]], int(args[1]))
    print(data)
    # PCA
    result = pca(data, base_num=int(args[2]))
    pc_base = result[0]
    print(pc_base)

    # Plotting
    fig = plt.figure()
    fig.add_subplot(1, 1, 1)
    plt.axvline(x=0, color="#000000")
    plt.axhline(y=0, color="#000000")
    # Plot data
    plt.scatter(data[:, 0], data[:, 1])
    # Draw the 1st principal axis
    pc_line = sp.array([-3.0, 3.0]) * (pc_base[1] / pc_base[0])
    plt.arrow(0, 0, -pc_base[0] * 2, -pc_base[1] * 2, fc="r", width=0.15, head_width=0.45)
    plt.plot([-3, 3], pc_line, "r")
    # Settings
    plt.xticks(size=15)
    plt.yticks(size=15)
    plt.xlim([-3, 3])
    plt.tight_layout()
    plt.show()
    plt.savefig("image.png")

    return 0
Esempio n. 8
0
def my_lines(ax, pos, *args, **kwargs):
    if ax == 'x':
        for p in pos:
            plt.axvline(p, *args, **kwargs)
    else:
        for p in pos:
            plt.axhline(p, *args, **kwargs)
Esempio n. 9
0
 def plot_vrad_chi2(self, fig):
     fig.clf()
     ax = fig.add_subplot(111)
     ax.plot(self.v_rads, self.v_rad_grid)
     ax.set_xlabel('v_rad [km/s]')
     ax.set_ylabel('Chi2')
     ax.axvline(self.v_rad, color='red', linewidth=2)
     ax.set_title('v_rad = %.2f' % self.v_rad)
Esempio n. 10
0
def show_hist(datai, mean1, mean2, avg, title="Histogram", bins=100):
    # mean1,mean2.min(),npdata.max()
    # avg=(mean1+mean2)/2
    fig, ax = subplots(1, 1, sharex=True, sharey=True, figsize=(10, 10))
    n, bins, patches = ax.hist(datai.flat, bins=bins, range=(mean1, mean2), histtype="bar")
    axvline(x=avg, alpha=0.7, linewidth=3, color="r")
    ax.set_title("histogram")
    show()
Esempio n. 11
0
 def plotline(x):
     ax = x['ax']
     xk = x['xk']
     plt.sca(ax)
     trans = blended_transform_factory(ax.transData,ax.transAxes)
     plt.axvline(smpar[xk],ls='--')
     plt.text(smpar[xk],0.9,'SM',transform=trans)
     
     if libpar is not None:
         plt.axvline(libpar[xk])
         plt.text(libpar[xk],0.9,'LIB',transform=trans)
Esempio n. 12
0
def plot_example(x, y, q_vals):
    q = q_vals[np.argmax(np.array([var_sums(x, y, q) for q in q_vals]))]
    beta, grid = gtv_cvlam(x, y, (q, ))
    bins = np.linspace(0, 1, 100)[:, np.newaxis]
    predictions = predict(bins, beta, grid)
    plt.scatter(x[:, 0], y, color='blue')
    plt.plot(bins, predictions, color='orange')
    for b in breakpoints[1:-1]:
        plt.axvline(b, ls='--', lw=3, color='green')
    plt.savefig('plots/1d-example.pdf', bbox_inches='tight')
    plt.close()
Esempio n. 13
0
File: utils.py Progetto: ozcell/olbr
 def save_fig(self, idx_episode, list_rwd):
     fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(20, 15))
     ax.plot(range(idx_episode + 1), list_rwd)
     ax.grid(True)
     ax.set_ylabel('Total reward')
     ax.set_xlabel('Episode')
     plt.axhline(0, color='black')
     plt.axvline(0, color='black')
     fig.savefig('{}/reward_total.png'.format(self.path_summary))
     plt.draw()
     plt.close(fig)
Esempio n. 14
0
    def plot_policy(self, policy, prefix, policy_folder):
        plt.clf()
        for idx in range(len(policy)):
            i, j = self.env.get_state_xy(idx)

            dx = 0
            dy = 0
            if policy[idx] == 0:  # up
                dy = 0.35
            elif policy[idx] == 1:  # right
                dx = 0.35
            elif policy[idx] == 2:  # down
                dy = -0.35
            elif policy[idx] == 3:  # left
                dx = -0.35
            elif self.env.not_wall(i, j) and policy[idx] == 4:  # termination
                circle = plt.Circle(
                    (j + 0.5, self.config.input_size[0] - i + 0.5 - 1),
                    0.025,
                    color='k')
                plt.gca().add_artist(circle)

            if self.env.not_wall(i, j):
                plt.arrow(j + 0.5,
                          self.config.input_size[0] - i + 0.5 - 1,
                          dx,
                          dy,
                          head_width=0.05,
                          head_length=0.05,
                          fc='k',
                          ec='k')
            else:
                plt.gca().add_patch(
                    patches.Rectangle(
                        (j, self.config.input_size[0] - i - 1),  # (x,y)
                        1.0,  # width
                        1.0,  # height
                        facecolor="gray"))

        plt.xlim([0, self.config.input_size[1]])
        plt.ylim([0, self.config.input_size[0]])

        for i in range(self.config.input_size[1]):
            plt.axvline(i, color='k', linestyle=':')
        plt.axvline(self.config.input_size[1], color='k', linestyle=':')

        for j in range(self.config.input_size[0]):
            plt.axhline(j, color='k', linestyle=':')
        plt.axhline(self.config.input_size[0], color='k', linestyle=':')

        plt.savefig(
            os.path.join(policy_folder,
                         "SuccessorFeatures_" + prefix + 'policy.png'))
        plt.close()
Esempio n. 15
0
 def plotline(x):
     ax = x['ax']
     xk = x['xk']
     plt.sca(ax)
     trans = blended_transform_factory(ax.transData,ax.transAxes)
     plt.axvline(smpar[xk],ls='--')
     plt.text(smpar[xk],0.9,'SM',transform=trans)
     
     if libpar is not None:
         plt.axvline(libpar[xk])
         plt.text(libpar[xk],0.9,'LIB',transform=trans)
Esempio n. 16
0
def hist_pos(dream2015_therapy, synergy_score, drug, outputfile):
    df_synergy = pd.read_csv(dream2015_therapy)
    syn = df_synergy['SYNERGY_SCORE']
    fig = plt.figure()
    plt.hist(syn, synergy_score)
    plt.axvline(synergy_score, color='r', linestyle='dashed', linewidth=4)
    ax = fig.add_subplot(111)
    ax.text(synergy_score, 450, drug)
    ax.set_xlabel('synergy score')
    ax.set_ylabel('frequency')
    plt.savefig(outputfile, dpi=600)
Esempio n. 17
0
def test_r_wet_init(constants, r_dry, plot=False):
    # Arrange
    T = 280
    RH = .9
    f_org = .607
    kappa = .356

    class Particulator:
        formulae = Formulae(surface_tension='CompressedFilm_Ovadnevaite')

    class Env:
        particulator = Particulator()
        thermo = {
            'T': CPU.Storage.from_ndarray(np.full(1, T)),
            'RH': CPU.Storage.from_ndarray(np.full(1, RH))
        }

        def __getitem__(self, item):
            return self.thermo[item]

    r_dry_arr = np.full(1, r_dry)

    # Plot
    if plot:
        r_wet = np.logspace(np.log(.9 * r_dry),
                            np.log(10 * si.nm),
                            base=np.e,
                            num=100)
        sigma = Env.particulator.formulae.surface_tension.sigma(
            np.nan, Env.particulator.formulae.trivia.volume(r_wet),
            Env.particulator.formulae.trivia.volume(r_dry), f_org)
        RH_eq = Env.particulator.formulae.hygroscopicity.RH_eq(
            r_wet, T, kappa, r_dry**3, sigma)
        pylab.plot(r_wet / si.nm, (RH_eq - 1) * 100, label='RH_eq')
        pylab.axhline((RH - 1) * 100, color='orange', label='RH')
        pylab.axvline(r_dry / si.nm, label='a', color='red')
        pylab.axvline(Env.particulator.formulae.hygroscopicity.r_cr(
            kappa, r_dry**3, T, const.sgm_w) / si.nm,
                      color='green',
                      label='b')
        pylab.grid()
        pylab.xscale('log')
        pylab.xlabel('Wet radius [nm]')
        pylab.xlim(r_wet[0] / si.nm, r_wet[-1] / si.nm)
        pylab.ylabel('Equilibrium supersaturation [%]')
        pylab.legend()
        pylab.show()

    # Act & Assert
    r_wet_init(r_dry=r_dry_arr,
               environment=Env(),
               kappa_times_dry_volume=Env.particulator.formulae.trivia.volume(
                   r_dry_arr) * kappa,
               f_org=np.full(1, f_org))
Esempio n. 18
0
    def plotPolicy(self, policy, prefix):
        plt.clf()
        for idx in range(len(policy)):
            i, j = self.env.getStateXY(idx)

            dx = 0
            dy = 0
            if policy[idx] == 0:  # up
                dy = 0.35
            elif policy[idx] == 1:  # right
                dx = 0.35
            elif policy[idx] == 2:  # down
                dy = -0.35
            elif policy[idx] == 3:  # left
                dx = -0.35
            elif self.matrixMDP[i][j] != -1 and policy[idx] == 4:  # termination
                circle = plt.Circle((j + 0.5, self.numRows - i + 0.5 - 1),
                                    0.025,
                                    color="k")
                plt.gca().add_artist(circle)

            if self.matrixMDP[i][j] != -1:
                plt.arrow(
                    j + 0.5,
                    self.numRows - i + 0.5 - 1,
                    dx,
                    dy,
                    head_width=0.05,
                    head_length=0.05,
                    fc="k",
                    ec="k",
                )
            else:
                plt.gca().add_patch(
                    patches.Rectangle(
                        (j, self.numRows - i - 1),  # (x,y)
                        1.0,  # width
                        1.0,  # height
                        facecolor="gray",
                    ))

        plt.xlim([0, self.numCols])
        plt.ylim([0, self.numRows])

        for i in range(self.numCols):
            plt.axvline(i, color="k", linestyle=":")
        plt.axvline(self.numCols, color="k", linestyle=":")

        for j in range(self.numRows):
            plt.axhline(j, color="k", linestyle=":")
        plt.axhline(self.numRows, color="k", linestyle=":")

        plt.savefig(self.outputPath + prefix + "policy.png")
        plt.close()
Esempio n. 19
0
def dissimilar(twosier, slot=50, show=True):
    '''
    Compare each part of two time series data with a fixed sliding window, 
    and those below the overall Pearson correlation coefficient are detected 
    as dissimilar.
    
    Parameters
    ----------       
    twosier : two 1-D array-like
         Time series data to compare.
    Returns
    -------
    ind : 1-D array-like
        Indices of dissimilar parts.

    '''
    seir1, seir2 = twosier
    assert len(seir1) == len(seir2)

    nsample = len(seir1)

    sp1 = [seir1[i:i + slot] for i in np.arange(nsample - slot + 1)]
    sp2 = [seir2[i:i + slot] for i in np.arange(nsample - slot + 1)]

    res = []
    for i in np.arange(len(sp1)):
        res.append(scipy.stats.pearsonr(sp1[i], sp2[i]))

    ind = detect_onset(-np.array(res)[:, 0],
                       n_above=5,
                       threshold=-scipy.stats.pearsonr(seir1, seir2)[0])

    #    if len(ind):
    #        for tmpind in ind:
    #            if np.diff(tmpind) >= slot:
    #                tmpind[0] += slot
    #        tmpind[-1][1] == nsample - slot

    if show:
        plt.figure()
        plt.subplot(221)
        plt.plot(seir1)
        plt.subplot(222)
        plt.plot(seir2)
        plt.subplot(223)
        plt.plot(1 - np.array(res)[:, 0])
        plt.subplot(224)
        plt.plot(seir1)
        plt.plot(seir2)
        for oneind in ind:
            plt.axvline(x=oneind[0], color='b', lw=1, ls='--')
            plt.axvline(x=oneind[1], color='b', lw=1, ls='--')

    return ind
def main():
    # --- setup
    times = 10**np.linspace(0, 11.0, 100)
    nodes = np.linspace(0.0, 1.0, 100)
    # nodes = nodes**2; nodes[0] = NaN
    # big range
    tmin = times[0]
    tmax = times[-1]
    dmin = 1
    dmax = 1e+17
    # --- main
    plt.figure(figsize=(15, 10))
    for ship in ships:
        print(ship[5], ship[1] * 1e-3, " km/s", ship[0] * 1e-3, "kW/kg")
        st, vt = timeToDistace(times,
                               ship[0],
                               ship[1],
                               ship[2],
                               ship[3],
                               ship[4],
                               nodes=nodes)
        plt.plot(st, times, label=ship[5], color=ship[6], ls=ship[7])
        #text ( st[-1], times[-1], ship[5], color='k', horizontalalignment='left', verticalalignment='center')
    for time, txt in zip(timeLines, timeTexts):
        if (time < tmax) and (time > tmin):
            plt.axhline(time, color='k', alpha=0.5)
            plt.text(dmax,
                     time,
                     txt,
                     color='k',
                     horizontalalignment='right',
                     verticalalignment='baseline')
    for dist, txt in zip(distLines, distTexts):
        if (dist < dmax) and (dist > dmin):
            plt.axvline(dist, color='k', alpha=0.5)
            plt.text(dist,
                     tmin,
                     txt,
                     rotation=90,
                     color='k',
                     horizontalalignment='left',
                     rotation_mode='anchor',
                     verticalalignment='baseline')
    plt.legend(loc=2, prop={'family': 'monospace'})
    plt.xscale('log')
    plt.yscale('log')
    plt.xlim(dmin, dmax)
    plt.ylim(tmin, tmax)
    plt.ylabel(r"Flight Time [ s ]")
    plt.xlabel(r"Distance    [ m ]")
    plt.grid()
    #plt.savefig( "timeToDistance.png", bbox_inches='tight' )
    plt.show()
Esempio n. 21
0
	def tf_analysis(self, plot_Z = True, frequencies = None, vis_frequency_limits = [1.8, 2.2], nr_cycles = 16, analysis_sample_rate = 100):
		self.assert_data_intern()

		if frequencies == None:
			frequencies = np.linspace(1.0, self.analyzer.low_pass_pupil_f, 40)

		down_sample_factor = int(self.sample_rate/analysis_sample_rate)
		resampled_signal = self.pupil_bp_pt[:,::down_sample_factor]

		# complex tf results per trial
		self.tf_trials = mne.time_frequency.cwt_morlet(resampled_signal, analysis_sample_rate, frequencies, use_fft=True, n_cycles=nr_cycles, zero_mean=True)
		self.instant_power_trials = np.abs(self.tf_trials)

		# z-score power
		self.Z_tf_trials = np.zeros_like(self.instant_power_trials)
		m = self.instant_power_trials.mean(axis = -1)
		sd = self.instant_power_trials.std(axis = -1)

		for z in range(len(self.Z_tf_trials)):
			self.Z_tf_trials[z] = ((self.instant_power_trials[z].T - m[z]) / sd[z] ).T

		# some obvious conditions
		if plot_Z:
			tf_to_plot = self.Z_tf_trials
		else:
			tf_to_plot = self.instant_power_trials

		f = pl.figure(figsize = (24,24))
		for x in range(len(self.trial_indices)):
			s = f.add_subplot(len(self.trial_indices), 2, (x*2)+1)
			pl.imshow(np.squeeze(tf_to_plot[x,(frequencies > vis_frequency_limits[0]) & (frequencies < vis_frequency_limits[1]),::100]), cmap = 'seismic', extent = [self.from_zero_timepoints[0], self.from_zero_timepoints[-1], vis_frequency_limits[-1], vis_frequency_limits[0]], aspect='auto')
			sn.despine(offset=10)
			s = f.add_subplot(len(self.trial_indices), 2, (x*2)+2)
			# pl.imshow(np.squeeze(tf_to_plot[x,:,::100]), cmap = 'gray')
			pl.plot(self.from_zero_timepoints[::down_sample_factor], np.squeeze(np.squeeze(tf_to_plot[x,(frequencies > vis_frequency_limits[0]) & (frequencies < vis_frequency_limits[1]),:])).mean(axis = 0), 'k')
			if len(self.events) != 0:
				events_this_trial = self.events[(self.events['EL_timestamp'] > self.timestamps_pt[x][0]) & (self.events['EL_timestamp'] < self.timestamps_pt[x][-1])]
				for sc, scancode in enumerate(self.scancode_list):
					these_event_times = events_this_trial[events_this_trial['scancode'] == scancode]['EL_timestamp']
					for tet in these_event_times:
						pl.axvline(x = (tet - self.timestamps_pt[x,0]) / self.sample_rate, c = self.colors[sc], lw = 5.0)
			sn.despine(offset=10)
		pl.tight_layout()
		pl.savefig(os.path.join(self.analyzer.fig_dir, self.file_alias + '_%i_tfr.pdf'%nr_cycles))

		with pd.get_store(self.analyzer.h5_file) as h5_file: 
			for name, data in zip(['tf_complex_real', 'tf_complex_imag', 'tf_power', 'tf_power_Z'], 
				np.array([np.real(self.tf_trials), np.imag(self.tf_trials), self.instant_power_trials, self.Z_tf_trials], dtype = np.float64)):
				opd = pd.Panel(data, 
								items = pd.Series(self.trial_indices), 
								major_axis = pd.Series(frequencies), 
								minor_axis = self.from_zero_timepoints[::down_sample_factor])
				h5_file.put("/%s/tf/cycles_%s_%s"%(self.file_alias, nr_cycles, name), opd)
Esempio n. 22
0
def histograms_x2(tensor1, tensor2):
    """
    Crea los histogramas de las listas pasadas,
    con anotaciones y líneas marcadas.

    :param tensor1: Primera lista
    :param tensor2: Segunda lista
    :return: None
    """

    # Promedio de los valores de las listas pasadas
    promedio_valores_1 = promedio_valores(tensor1)
    promedio_valores_2 = promedio_valores(tensor2)

    # Crea la figura que va a contener ambos histogramas
    plt.figure(figsize=(15, 5))

    # Figura número 1
    plt.subplot(121)
    cantidad_valores_por_clase_1, clases_1, patches1 = plt.hist(tensor1)
    promedio_cantidades = promedio_valores(cantidad_valores_por_clase_1)

    pyl.axvline(promedio_valores_1, color='r', linewidth=3, linestyle="--")
    pyl.axhline(promedio_cantidades, color='#db9723', linewidth=3, linestyle="--")
    plt.xlabel('Magnitud de los valores')
    plt.ylabel('Cantidad de valores por clase')
    plt.title('Histograma {} valores'.format(len(tensor1)))
    plt.text(promedio_valores_1 * 1.05, max(cantidad_valores_por_clase_1) * .9,
             "Promedio valores \naleatorios creados:\n{}".format(round(promedio_valores_1, 5)),
             bbox={'facecolor': 'red', 'alpha': 0.75, 'pad': 2})
    plt.text(clases_1[0], promedio_cantidades * .8,
             "Promedio de cantidad\nde valores por clase:\n{}".format(promedio_cantidades),
             bbox={'facecolor': 'orange', 'alpha': 0.75, 'pad': 2})
    plt.grid()

    # Figura número 2
    plt.subplot(122)
    cantidad_valores_por_clase_2, clases_2, patches2 = plt.hist(tensor2)
    cantidad_máxima_2 = max(cantidad_valores_por_clase_2)
    promedio_cantidades = promedio_valores(cantidad_valores_por_clase_2)
    pyl.axvline(promedio_valores_2, color='r', linewidth=3, linestyle="--")
    pyl.axhline(promedio_cantidades, color='#db9723', linewidth=3, linestyle="--")

    plt.xlabel('Magnitud de los valores')
    plt.ylabel('Cantidad de valores por clase')
    plt.title('Histograma {} valores'.format(len(tensor2)))
    plt.text(promedio_valores_2 * 1.05, cantidad_máxima_2 * .9,
             "Promedio valores \naleatorios creados:\n{}".format(round(promedio_valores_2, 5)),
             bbox={'facecolor': 'red', 'alpha': 0.75, 'pad': 2})
    plt.text(clases_2[0], promedio_cantidades * 0.81,
             "Promedio de cantidad\nde valores por clase:\n{}".format(promedio_cantidades),
             bbox={'facecolor': 'orange', 'alpha': 0.75, 'pad': 2})
    plt.grid()
Esempio n. 23
0
def plot_themepark_score():
    data = pickle.load(
        open(
            'results/results_cust_all_only_strat31jan/park_score_clust_all_only_strat.p',
            'rb'))
    data2 = [
        1098, 1093, 1089, 1101, 1084, 1096, 1104, 1118, 1092, 1093, 1102, 1097,
        1072, 1064, 1112, 1078, 1100, 1078, 1095, 1108, 1121, 1069, 1079, 1072,
        1067, 1072, 1090, 1086, 1057, 1102, 1106, 1051, 1082, 1080, 1108, 1098,
        1125, 1068, 1092, 1081, 1097, 1108, 1074, 1110, 1119, 1086, 1085, 1110,
        1078, 1086, 1047, 1057, 1121, 1139, 1107, 1072, 1102, 1121, 1114, 1063,
        1119, 1156, 1146, 1099, 1067
    ]
    data3 = pickle.load(
        open('results/results_cust_all_only_strat31jan/park_score.p', 'rb'))
    data4 = pickle.load(
        open(
            'results/results_cust_all_only_strat31jan/park_score_clusterd_diff_strat.p',
            'rb'))

    STRATEGIES = [
        "Adaptive", "Noise", "Random", "0.00", "0.25", "0.50", "0.75", "1.00"
    ]

    x_pos = np.arange(len(STRATEGIES))
    values = data.values()
    values = list(values)

    total = []
    total.append(data4)
    total.append(data2)
    total.append(values[0])
    total.append(values[1])
    total.append(values[2])
    total.append(values[3])
    total.append(values[4])
    total.append(values[5])

    ticks = STRATEGIES
    fig, axes = plt.subplots()

    boxplot = axes.boxplot(total, patch_artist=True, widths=0.8)
    plt.xticks(x_pos + 1, STRATEGIES)

    # adding horizontal grid lines
    axes.yaxis.grid(True)
    plt.axvline(x=3.5, color='gray', linestyle='--')
    # plt.yticks(np.arange(0, 100, 20))
    # axes.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: ('%g') % (x / 1160)))
    axes.set_title("Park score")
    axes.set_xlabel('Strategy')
    axes.set_ylabel('Score')
    plt.show()
Esempio n. 24
0
def annotates_peak(peaks, color='red', I_level=1e3, symbol=''):
    for p in peaks:
        angle = p['2𝜃 (deg)']

        if angle > np.max(twth):
            break

        plt.axvline(x=angle, linewidth=1, color=color, alpha=0.7)

        linename = p['hkl'].replace('(', '').replace(')', '')
        text_y_position = I_level + 300 * np.gcd.reduce(p['hkl_tuple'])
        plt.text(angle, text_y_position, linename, rotation=0, color=color)
Esempio n. 25
0
    def errorInfo(self, xRange, yVals, errors, label):
        numXVals = 50
        lowerError, upperError = errors

        pl.title(r"$\Delta$" + label + r" vs. $\Delta$NLL")
        pl.xlabel(r"$\Delta$" + label)
        pl.ylabel("$\Delta NLL$")
        pl.axvline(x = -lowerError, linestyle=':', color='r')
        pl.axvline(x = upperError, linestyle=':', color='r')
        pl.axhline(y = 0.5, linewidth=0.5, linestyle='--', color='dimgray')
        pl.plot(xRange, yVals)
        pl.show()
Esempio n. 26
0
def worker_rate_hist(avg_rates, target_rate=10):
    fig_labels = {
        'fig_title': 'Worker Rates',
        'x_label': 'Hourly rate (USD)',
        'y_label': '# Workers',
    }
    bins = np.arange(0, avg_rates.max())
    avg_rates.plot(kind='hist', bins=bins)
    center_bin_labels(bins, fontsize=20)
    plt.axvline(x=target_rate + 0.5, color='r', linewidth=3, linestyle='--')
    plt.legend(['Target Rate'], fontsize=12)
    make_standard_fig(fig_labels, save=True)
Esempio n. 27
0
def epi_vs_gain_volcano_plot(filtered_gain_snps, filtered_epi_snps, gain_vals, epi_vals, max_p, min_I3):
    gain_I3 = []
    gain_log_p = []
    for snps in filtered_gain_snps:
        gain_I3.append(gain_vals[snps])

        order = switch_snp_key_order(snps)
        if epi_vals.has_key(order[0]):
            gain_log_p.append(epi_vals[order[0]])
        elif epi_vals.has_key(order[1]):
            gain_log_p.append(epi_vals[order[1]])
    gain_log_p = -1 * np.log10(gain_log_p)

    epi_I3 = []
    epi_log_p = []
    for snps in filtered_epi_snps:
        order = switch_snp_key_order(snps)
        if gain_vals.has_key(order[0]):
            epi_I3.append(gain_vals[order[0]])
        elif gain_vals.has_key(order[1]):
            epi_I3.append(gain_vals[order[1]])

        epi_log_p.append(epi_vals[snps])
    epi_log_p = -1 * np.log10(epi_log_p)

    mp.figure(1)
    mp.xlabel("I3")
    mp.ylabel("-log10(P)")
    mp.title("Volcano plot - EPISTASIS and GAIN")
    mp.plot(epi_I3, epi_log_p, "bo")
    mp.plot(gain_I3, gain_log_p, "ro")
    mp.axhline(y=(-1 * np.log10(max_p)), linewidth=2, color="g")
    mp.axvline(x=min_I3, linewidth=2, color="g")
    # label max point
    max_x = np.max(gain_I3)
    max_y = np.max(gain_log_p)
    best_connection = ""
    # label best edge
    for snps in epi_vals:
        if -1 * np.log10(epi_vals[snps]) == max_y:
            best_connection = str(snps)
    mp.text(
        np.max(gain_I3),
        np.max(gain_log_p),
        best_connection,
        fontsize=10,
        horizontalalignment="center",
        verticalalignment="center",
    )
    mp.show()

    print
Esempio n. 28
0
def counter_histogram(library_barcode_counter, total_element_count, xlabel):
    median = np.median(list(library_barcode_counter.values()))
    stdev = np.std(list(library_barcode_counter.values()))
    expected_per_variant = total_element_count / 2800
    bins = np.linspace(0, max(library_barcode_counter.values()), 100)
    plt.hist(list(library_barcode_counter.values()), bins=bins, density=True)
    plt.axvline(expected_per_variant, color='k', linestyle='dashed')
    plt.xlabel(xlabel)
    plt.ylabel('Count')
    plt.text(50, 0.14, 'Median: {0}\nExpected: {1}'.format(
        round(median, 2), round(expected_per_variant, 2)))
    plt.savefig('hist_barcode_per_variant.png', dpi=300)
    plt.close()
Esempio n. 29
0
def plot_cost_function_deltas(criterion, final_sizes):
    colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
    for scale, data in criterion.items():
        if scale in final_sizes:
            x, y = zip(*data)
            y = np.array(y)
            plt.plot(x, y - min(y) + 1, color=colors[scale - 2], label=scale)
            plt.xscale("log")
            plt.yscale("log")
            plt.axvline(final_sizes[scale], color=colors[scale - 2])
    plt.legend()
    plt.ylabel("$\Delta(-\log{L})$", fontsize=12)
    plt.xlabel("Distance (meters)", fontsize=12)
Esempio n. 30
0
    def plotPredictiveMarginals(self,
                                plotGridSize=0.001,
                                matrixPlotSide=(2, 2)):

        plt.figure(177)

        # For each parameter
        for ii in range(self.nPars):
            plt.subplot(matrixPlotSide[0], matrixPlotSide[1], ii + 1)

            # Form grid for parameter
            grid1 = np.arange(self.lowerBounds[ii], self.upperBounds[ii],
                              plotGridSize)
            grid1 = grid1.reshape((len(grid1), 1))

            # Stack grids together, fix all other parameters to thhat
            grid2 = np.zeros((len(grid1), 1))

            for kk in range(self.nPars):
                if (kk == ii):
                    grid2 = np.hstack((grid2, grid1))
                else:
                    grid2 = np.hstack((grid2, np.ones(
                        (len(grid1), 1)) * self.thhat[kk]))

            # Remove the first column
            grid2 = grid2[:, range(1, self.nPars + 1)]

            # Make prediction
            ypred, s2 = self.m.predict(grid2)

            # Compensate for normalization
            ypred = (ypred * np.sqrt(self.ynormVar)) + self.ynormMean
            s2 = s2 * self.ynormVar

            # Plot 95% CIs
            plt.plot(grid1,
                     ypred + 1.96 * np.sqrt(s2),
                     linewidth=0.5,
                     color='k')
            plt.plot(grid1,
                     ypred - 1.96 * np.sqrt(s2),
                     linewidth=0.5,
                     color='k')

            # Plot mean function and data
            plt.plot(grid1, ypred)
            plt.plot(self.x[:, ii], self.y, 'k.')

            # Plot thhat
            plt.axvline(self.thhat[ii], linewidth=2, color='k')
Esempio n. 31
0
    def lcReview(self, fibre, eventList=[], save=False, saveName='default.png'):
        """
        """
        time, flux, xpos, ypos, apts, msky, qual = self.getFullData(fibre)
        
        TA = TimingAnalysis()
        result, rms = TA.standardscore(time, flux, 2.0)
        wmflux = result[0]
        mSNR = np.median(wmflux/rms)

        plt.figure(100, figsize=(8,12))
        plt.clf()
        plt.subplots_adjust(hspace=0.2)
        
        plt.subplot(4,1,1)
        plt.plot(time, flux, 'k+-', drawstyle='steps-mid')
        plt.plot(time, wmflux, 'r-', label='averaged')
        if len(eventList) == 0:
            pass
        else:
            for value in eventList:
                plt.axvline(x=value, color='red', ls='--')
        plt.xlim(time[0], time[-1])
        plt.ylim(0, np.median(flux) + 0.5*np.median(flux))
        plt.ylabel('Flux (count)')
        plt.xticks(visible=False)
        plt.legend()
        plt.title('{}, fibre {}. mSNR: {:.2f}'.format(self.filename[:-5], fibre, mSNR))
        
        plt.subplot(4,1,2, sharex=plt.subplot(4,1,1))
        plt.plot(time, xpos, 'b+', time, ypos, 'r+')
        plt.xlim(time[0], time[-1])
        plt.ylim(5,35)
        plt.xticks(visible=False)
        plt.ylabel('Position (pixel)')
        
        plt.subplot(4,1,3, sharex=plt.subplot(4,1,1))
        plt.plot(time, apts, 'k+')
        plt.xlim(time[0], time[-1])
        plt.ylim(0, np.mean(apts) + 0.5*np.mean(apts))
        plt.xticks(visible=False)
        plt.ylabel('Apt Size (pixel)')
        
        plt.subplot(4,1,4, sharex=plt.subplot(4,1,1))
        plt.plot(time, msky, 'k+')
        plt.xlim(time[0], time[-1])
        plt.ylim(0, np.median(msky) + 0.5*np.median(msky))
        plt.xlabel('Time (s)')
        plt.ylabel('Mean Sky Value (count)')
        
        plt.show()
Esempio n. 32
0
def marks(channel, begin, end, unit_index, show_original=False):
    signal = channel['raw' if bool(show_original) else 'filtered']
    plt.plot(signal[int(begin):int(end)], color='b')
    peaks = channel['peaks']
    units = channel['units']
    times_in_range = peaks.value[np.where(units.value == int(unit_index))[0]]
    plt.axhline(-channel.attrs['threshold'], color='r')
    for t in times_in_range:
        if t < int(begin):
            continue
        if t > int(end):
            break
        plt.axvline(t, color='g')
    plt.show()
Esempio n. 33
0
def panel_cluster_mean(cluster_id, cluster_means, cluster_predictive_score, cluster_poly_proportion, count, vlim, color, cid, lines=True, xlabels=True, ylabels=True):
    plt.imshow(cluster_means[cluster_id], interpolation='none', origin='lower', cmap=cm.bwr, aspect=0.3, vmin=-vlim, vmax=vlim);
    plt.axvline(x=16, ymin=0.0, ymax = 1.0, linewidth=1.0, color='r', ls='--');
    if lines:
        plt.axvline(x=19, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=24, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=32, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=4, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=10, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=27, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=56, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
    if xlabels:
        plt.xticks(np.arange(0, 48, 3), np.asarray((np.arange(0, 769, 48) - 256) / 512.0 * 1000, dtype='int'), size=15, rotation=90);
    else:
        plt.xticks([])
    if ylabels:
        plt.yticks(np.arange(0, 146, 10), np.arange(4, 150, 10), size=15);
        #plt.ylabel('Frequency (Hz)', size=16);
    else:
        plt.yticks([])
    plt.title('Activity of %s (%d) probes' % (color.upper(), count), size=16, color=color);
    plt.text(1, 129, str(cluster_id + 1), fontsize=20)
    per_cid_stds = [0.11, 0.10, 0.10, 0.09, 0.10, 0.08, 0.10, 0.12]
    plt.text(26, 132, 'F1 = %.4f ± %.2f' % (cluster_predictive_score[cluster_id], per_cid_stds[cid]), fontsize=15)
    plt.text(31, 118, 'Poly %d' % cluster_poly_proportion[cluster_id] + '%', fontsize=15)
Esempio n. 34
0
def panel_importance(importances, title, lines):
    plt.imshow(importances, interpolation='none', origin='lower', cmap=cm.Blues, aspect='auto');
    cb = plt.colorbar();
    cb.ax.tick_params(labelsize=16);
    plt.axvline(x=16, ymin=0.0, ymax = 1.0, linewidth=1.0, color='r', ls='--')
    if lines:
        plt.axvline(x=19, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=24, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=32, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=4, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=10, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=27, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=56, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
    
    # small axis 
    #plt.xticks(np.arange(0, 48, 1.5), np.asarray((np.arange(0, 769, 24) - 256) / 512.0 * 1000, dtype='int'), size=11, rotation=90);
    #plt.yticks(np.arange(0, 146, 5), np.arange(4, 150, 5), size=12);
    
    # med axis
    plt.xticks(np.arange(0, 48, 2), np.asarray((np.arange(0, 769, 32) - 256) / 512.0 * 1000, dtype='int'), size=18, rotation=90);
    plt.yticks(np.arange(0, 146, 7), np.arange(4, 150, 7), size=18);
    
    # big axis
    #plt.xticks(np.arange(0, 48, 3), np.asarray((np.arange(0, 769, 48) - 256) / 512.0 * 1000, dtype='int'), size=24, rotation=90);
    #plt.yticks(np.arange(0, 146, 9), np.arange(4, 150, 9), size=20);
    
    plt.ylabel('Frequency (Hz)', size=24);
    plt.xlabel('Time (ms)', size=24);
    if title is not None:
        plt.title(title, size=26);
Esempio n. 35
0
def panel_fitfdiff(diff, title, lines):
    cm2rb = LinearSegmentedColormap.from_list('red_blue', ['blue', 'white', 'gray', 'red'], N=4)
    plt.imshow(diff, interpolation='none', origin='lower', cmap=cm2rb, aspect='auto', vmin=-1.0, vmax=2.0);
    plt.axvline(x=16, ymin=0.0, ymax = 1.0, linewidth=1.0, color='r', ls='--')
    if lines:
        plt.axvline(x=19, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=24, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axvline(x=32, ymin=0.0, ymax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=4, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=10, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=27, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
        plt.axhline(y=56, xmin=0.0, xmax = 1.0, linewidth=0.5, color='gray', ls='-')
    
    # small axis
    #plt.xticks(np.arange(0, 48, 1.5), np.asarray((np.arange(0, 769, 24) - 256) / 512.0 * 1000, dtype='int'), size=16, rotation=90);
    #plt.yticks(np.arange(0, 146, 7), np.arange(4, 150, 7), size=16);
    
    # big axis
    plt.xticks(np.arange(0, 48, 3), np.asarray((np.arange(0, 769, 48) - 256) / 512.0 * 1000, dtype='int'), size=24, rotation=90);
    plt.yticks(np.arange(0, 146, 9), np.arange(4, 150, 9), size=24);

    plt.ylabel('Frequency (Hz)', size=24);
    plt.xlabel('Time (ms)', size=24);
    if title is not None:
        plt.title(title, size=16);
Esempio n. 36
0
    def plot_cdf(self):

      import matplotlib 
      import matplotlib.pylab as plt

      matplotlib.rcParams.update({'font.size': 16.0})
      fig=plt.figure(figsize=(11,8))
      fig.set_facecolor('w')
      self.data.hist(cumulative=True, density=1,bins=500)
      perc95=self.data.quantile(q=0.95)
      plt.axvline(perc95,color='r')
      plt.title('CDF of JJA daily precip over Champaign, IL')
      plt.xlabel('Daily precipitation (mm)')
      plt.text(20.2,0.8,'95th percentile = '+str(perc95))
def draw_reward_zone():
    for stripe in range(8):
        if stripe % 2 == 0:
            plt.axvline(91.25 + stripe * 2.5,
                        color='limegreen',
                        linewidth=5.5,
                        alpha=0.4,
                        zorder=0)
        else:
            plt.axvline(91.25 + stripe * 2.5,
                        color='k',
                        linewidth=5.5,
                        alpha=0.4,
                        zorder=0)
Esempio n. 38
0
def plot_ccf(w,tspec,mspec):
    lag,tmccf = ccf(tspec,mspec)

    dv = restwav.loglambda_wls_to_dv(w) 
    dv = lag*dv

    dvmax = ccs.findpeak(dv,tmccf)
    plt.plot(dv,tmccf,'k',label='tspec')    
    plt.axvline(dvmax,color='RoyalBlue',lw=2,alpha=0.4,zorder=0)

    AddAnchored("dv (max) = %.2f km/s" % dvmax,**annkw)
    plt.xlim(-50,50)
    plt.xlabel('dv (km/s)')

    return dvmax
Esempio n. 39
0
def test_prox_hinge_2(q, rho=0.8, doplot=True):
    from matplotlib import pylab as plt
    n = 100000
    p = np.linspace(-0.5, 0.5, n)
    res = ww(p) + 0.5 * rho * (p-q)**2
    index_min = np.argmin(res)
    p_min = p[index_min]
    plt.clf()
    plt.plot(p, res, color='red')
    print 'p_min: %s' % p_min
    plt.axvline(p_min, color='blue')
    qq = np.array([q])
    prox = prox_ww(qq, rho)
    plt.axvline(p_min, color='orange', linestyle='--')
    assert abs(prox-p_min) < 1e-5
Esempio n. 40
0
def plot_ccf(w,tspec,mspec):
    lag,tmccf = ccf(tspec,mspec)

    dv = restwav.loglambda_wls_to_dv(w) 
    dv = lag*dv

    dvmax = ccs.findpeak(dv,tmccf)
    plt.plot(dv,tmccf,'k',label='tspec')    
    plt.axvline(dvmax,color='RoyalBlue',lw=2,alpha=0.4,zorder=0)

    AddAnchored("dv (max) = %.2f km/s" % dvmax,**annkw)
    plt.xlim(-50,50)
    plt.xlabel('dv (km/s)')

    return dvmax
Esempio n. 41
0
def butter_lowpass_filter(data, sample_rate, cutoff=10, order=4, plot=False):
    """
        `Low-pass filter <http://stackoverflow.com/questions/25191620/
        creating-lowpass-filter-in-scipy-understanding-methods-and-units>`_ data by the [order]th order zero lag Butterworth filter
        whose cut frequency is set to [cutoff] Hz.

        :param data: time-series data,
        :type data: numpy array of floats
        :param: sample_rate: data sample rate
        :type sample_rate: integer
        :param cutoff: filter cutoff
        :type cutoff: float
        :param order: order
        :type order: integer
        :return y: low-pass-filtered data
        :rtype y: numpy array of floats

        :Examples:

        >>> from mhealthx.signals import butter_lowpass_filter
        >>> data = np.random.random(100)
        >>> sample_rate = 10
        >>> cutoff = 5
        >>> order = 4
        >>> y = butter_lowpass_filter(data, sample_rate, cutoff, order)

    """


    nyquist = 0.5 * sample_rate
    normal_cutoff = cutoff / nyquist
    b, a = butter(order, normal_cutoff, btype='low', analog=False)

    if plot:
        w, h = freqz(b, a, worN=8000)
        plt.subplot(2, 1, 1)
        plt.plot(0.5*sample_rate*w/np.pi, np.abs(h), 'b')
        plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
        plt.axvline(cutoff, color='k')
        plt.xlim(0, 0.5*sample_rate)
        plt.title("Lowpass Filter Frequency Response")
        plt.xlabel('Frequency [Hz]')
        plt.grid()
        plt.show()

    y = lfilter(b, a, data)

    return y
Esempio n. 42
0
    def plotGeneral(self, initFlux, normFlux, xpos, ypos, quality, direction, variance, threshold):
        plt.figure('General')
        plt.clf()
        
        plt.subplot(5,1,1)
        plt.plot(self.time, initFlux, 'k-', drawstyle='steps-mid')
        for event in self.eventList:
            plt.axvline(x=self.time[event], color='red', ls='--')
        plt.xlim(self.time[0], self.time[-1])
        plt.ylabel('Original LCs')
        plt.xticks(visible=False)
        plt.title('{}, f{}'.format(self.fileName, self.fibre))
        
        plt.subplot(5,1,2, sharex=plt.subplot(5,1,1))
        plt.plot(self.time, normFlux, 'g+')
        plt.plot(self.time, normFlux, 'k-', drawstyle='steps-mid')
        for event in self.eventList:
            plt.axvline(x=self.time[event], color='red', ls='--')
        plt.xlim(self.time[0], self.time[-1])
        plt.ylim(0.0, 1.5)
        plt.ylabel('Normalised LCs')
        plt.xticks(visible=False)
    
        plt.subplot(5,1,3, sharex=plt.subplot(5,1,1))
        plt.plot(self.time, quality, 'k-', drawstyle='steps-mid', label='quality')
        plt.plot(self.time, direction, 'r-', drawstyle='steps-mid', label='direction')
        plt.xlim(self.time[0], self.time[-1])
        plt.ylim(-2, 2)
        plt.xticks(visible=False)
        plt.legend()
        
        plt.subplot(5,1,4, sharex=plt.subplot(5,1,1))
        plt.plot(self.time, xpos, 'b-', drawstyle='steps-mid', label='x')
        plt.plot(self.time, ypos, 'r-', drawstyle='steps-mid', label='y')
        plt.xlim(self.time[0], self.time[-1])
        plt.ylim(1,40)
        plt.xticks(visible=False)
        plt.legend()
    
        plt.subplot(5,1,5, sharex=plt.subplot(5,1,1))
        plt.plot(self.time, variance, 'k-', drawstyle='steps-mid')
        plt.plot(self.time, threshold, 'r-', label=r'{}$\sigma$'.format(self.dTL))
        plt.xlim(self.time[0], self.time[-1])
        plt.ylabel('Variance')
        plt.xlabel('Time (s)')
        plt.legend()

        plt.show()
Esempio n. 43
0
def k_sensitivity(mutant_expression: float):
    system = S_OPEN_2
    enz = get_parameter_set()

    initial_con = get_random_concentrations(1, system)

    s_array = np.linspace(0.1, 10, 30).tolist()
    s_array.append(1)
    pa_level = []
    print(enz.get(E_SINK).v)
    for f in s_array:
        enz.get(E_SOURCE).k *= f

        if f == 1:
            print(enz.get(E_SOURCE).k)

        wt_output = get_concentration_profile(system, initial_con, enz,
                                              ode_end_time, ode_slices)

        enz[E_DAGK].mutate(mutant_expression)
        rdga_output = get_concentration_profile(system, initial_con, enz,
                                                ode_end_time, ode_slices)
        enz[E_DAGK].mutate(1 / mutant_expression)
        enz[E_LAZA].mutate(mutant_expression)
        laza_output = get_concentration_profile(system, initial_con, enz,
                                                ode_end_time, ode_slices)
        enz[E_LAZA].mutate(1 / mutant_expression)

        rdga = [
            get_pa_ratio(wt_output[-1], rdga_output[-1]),
            get_dag_ratio(wt_output[-1], rdga_output[-1])
        ]
        laza = [
            get_pa_ratio(wt_output[-1], laza_output[-1]),
            get_dag_ratio(wt_output[-1], laza_output[-1])
        ]

        pa_level.append(get_pa_ratio(wt_output[-1], laza_output[-1]))

        enz.get(E_SOURCE).k /= f

    plt.scatter(s_array, pa_level)
    plt.xlabel("Factor (x $k_{source}$)")
    plt.ylabel("PA/Pi ratio in LAZA")
    plt.title(system)
    plt.axvline(1)
    plt.axhline(2.5)
    plt.show()
Esempio n. 44
0
    def onClick(self, event):
        """
		Process a mouse click event. If a mouse is right clicked within a
		subplot, the return value is set to a (subPlotNr, xVal, yVal) tuple and
		the plot is closed. With right-clicking and dragging, the plot can be
		moved.
		
		Arguments:
		event -- a MouseEvent event
		"""

        if event.button == 1:

            #			for i in range(self.nSubPlots):
            #				subPlot = self.selectSubPlot(i)
            marker = plot.axvline(event.xdata, 0, 1, linestyle='--', \
             linewidth=2, color='gray')
            self.markers.append(marker)

            self.fig.canvas.draw()
            self.retVal['x'] = np.append(self.retVal['x'], event.xdata)
            self.retVal['y'] = np.append(self.retVal['y'], event.ydata)

        if event.button == 3:
            plot.close()
Esempio n. 45
0
	def raw_signal_plot(self):
		self.assert_data_intern()

		f = pl.figure(figsize = (24,24))
		for x in range(len(self.trial_indices)):
			s = f.add_subplot(len(self.trial_indices), 1, x+1)
			pl.plot(self.timestamps_pt[x][::100], self.pupil_bp_pt[x][::100], 'k')
			if len(self.events) != 0:
				events_this_trial = self.events[(self.events['EL_timestamp'] > self.timestamps_pt[x][0]) & (self.events['EL_timestamp'] < self.timestamps_pt[x][-1])]
				for sc, scancode in enumerate(self.scancode_list):
					these_event_times = events_this_trial[events_this_trial['scancode'] == scancode]['EL_timestamp']
					for tet in these_event_times:
						pl.axvline(x = tet, c = self.colors[sc], lw = 5.0)
			sn.despine(offset=10)
		pl.tight_layout()
		pl.savefig(os.path.join(self.analyzer.fig_dir, self.file_alias + '_raw.pdf'))
Esempio n. 46
0
def graphs_distribution_shifts():
    """ This graphs plots the distribution of latent utilities for varying levels of the location
    parameter.
    """
    grid = np.linspace(-3, 3, 100)

    ax = plt.figure(figsize=(12, 8)).add_subplot(111)

    negative_mean = norm.pdf(grid, -1, 1)
    zero_mean = norm.pdf(grid, 0, 1)

    plt.plot(grid, negative_mean, label=r"$\theta$", linewidth=5, color='red')
    plt.plot(grid, zero_mean, label=r"$\theta'$", linewidth=5, color='blue')

    ax.tick_params(labelsize=18,
                   direction='out',
                   axis='both',
                   top='off',
                   right='off')
    plt.axvline(x=0, linewidth=5, color='black')
    ax.set_ylabel('Density Function', fontsize=16)
    ax.set_xlabel(r'Latent Utility', fontsize=16)

    ax.yaxis.get_major_ticks()[0].set_visible(False)
    ax.set_xlim(-3, 3)
    ax.set_ylim(0, 0.45)

    ax.text(-2.5, 0.4, r'$D = 0$', fontsize=30)
    ax.text(+1.8, 0.4, r'$D = 1$', fontsize=30)

    ax.fill_between(grid,
                    zero_mean,
                    negative_mean,
                    where=grid > 0.0,
                    color='lightblue')

    ax.legend(loc='upper center',
              bbox_to_anchor=(0.5, -0.10),
              fancybox=False,
              frameon=False,
              shadow=False,
              ncol=3,
              fontsize=20)

    plt.savefig('../images/distribution_shift.png',
                bbox_inches='tight',
                format='png')
Esempio n. 47
0
def plotDifference(bst, dtest, target = None):
    p = bst.predict(dtest)
    l = 0
    if (target is None):    
        l = dtest.get_label()
    else:
        l = target
    res = np.abs((l-p)/l)
    res = res[~np.isnan(res)]
    res = res[~np.isinf(res)]
    xmax = 0.2
    for y in np.arange(0,xmax,xmax/8):    
        plt.axvline(y, color='g', linestyle='dashed')
    plt.hist(res, range=(0,xmax), bins=50, color='red')
    plt.axvline(res.mean(), color='c', linestyle='dashed', linewidth=2)
    for y in range(200,1600,200):    
        plt.axhline(y, color='g', linestyle='dashed')
Esempio n. 48
0
def plot(model, x_obs, y_obs, argmin_a_x, a, x):
    y_mean, y_sigma = model.predict(x, return_std=True)
    y_sigma = np.atleast_2d(y_sigma).T
    a_x = a(x)
    plt.plot(x, y_mean, 'r-')
    plt.plot(x_obs, y_obs, 'o')

    plt.axvline(argmin_a_x)

    plt.plot(
        x,
        a_x*(1/np.max(a_x)),
        'g--',
    )

    plt.plot(x, f(x), 'm--')
    plot_confidences(x, y_mean, y_sigma, confidences=[1])
Esempio n. 49
0
 def plot(self,plt=None):
     u = self.solver.u
     t = self.solver.t
     if plt is None:
         #import scitools.std as plt
         import matplotlib.pylab as plt
     plt.plot(t,u,"r")
     plt.axvline(self.solver.t_r) # mark a straight line at t = t_r
     plt.hold("on")
     theta2name = {0:"FE", 1:"BE", 0.5:"CN"}
     name = theta2name.get(self.solver.theta,"")
     legends = ["numerical %s" %name]
     plt.legend(legends)
     plt.xlabel("t")
     plt.ylabel("u")
     plt.title("theta = %g , dt = %g" %(self.solver.theta, self.solver.dt))
     return plt
def rDist(r,sd1 = 10, sd2 = 10):
	mup = 50 + (100*(r/2))
	mlow = 50 - (100*(r/2))
	y2 = np.random.normal(mup,sd1,10000)
	y1 = np.random.normal(mlow,sd1,10000)
	plt.grid(True)
	plt.hist(y1,50, label = '$Control\ Group$', alpha = .7, color = 'b')
	plt.hist(y2,50, label = '$Experimental\ Group$', alpha = .5, color = 'g')
	plt.xlim(0, 100)
	plt.legend(	loc= 'right')
	plt.title('$Binomial\ Effect\ Size\ Display\ (BESD).$')
	plt.xlabel('Bin number for each one percentage bin')
	plt.ylabel('Frequency of each value occurring')
	plt.axvline(mup, ms = 3, color= 'r')
	plt.axvline(mlow, ms = 3, color = 'r')
	plt.show()
	return
Esempio n. 51
0
    def plotPredictiveMarginals(self, plotGridSize=0.001, matrixPlotSide=(2, 2)):

        plt.figure(177)

        # For each parameter
        for ii in range(self.nPars):
            plt.subplot(matrixPlotSide[0], matrixPlotSide[1], ii + 1)

            # Form grid for parameter
            grid1 = np.arange(self.lowerBounds[ii], self.upperBounds[
                              ii], plotGridSize)
            grid1 = grid1.reshape((len(grid1), 1))

            # Stack grids together, fix all other parameters to thhat
            grid2 = np.zeros((len(grid1), 1))

            for kk in range(self.nPars):
                if (kk == ii):
                    grid2 = np.hstack((grid2, grid1))
                else:
                    grid2 = np.hstack(
                        (grid2, np.ones((len(grid1), 1)) * self.thhat[kk]))

            # Remove the first column
            grid2 = grid2[:, range(1, self.nPars + 1)]

            # Make prediction
            ypred, s2 = self.m.predict(grid2)

            # Compensate for normalization
            ypred = (ypred * np.sqrt(self.ynormVar)) + self.ynormMean
            s2 = s2 * self.ynormVar

            # Plot 95% CIs
            plt.plot(grid1, ypred + 1.96 * np.sqrt(s2),
                     linewidth=0.5, color='k')
            plt.plot(grid1, ypred - 1.96 * np.sqrt(s2),
                     linewidth=0.5, color='k')

            # Plot mean function and data
            plt.plot(grid1, ypred)
            plt.plot(self.x[:, ii], self.y, 'k.')

            # Plot thhat
            plt.axvline(self.thhat[ii], linewidth=2, color='k')
Esempio n. 52
0
File: zero.py Progetto: frodo81/psms
def fplot(x0):
    """plot f(x) in the neighborhood of the initial guess"""
    #build x and f vectors
    points = 200
    xmin = x0 - 5.0
    xmax = x0 + 5.0
    xvec = linspace(xmin,xmax, num=points,endpoint = True)
    fvec = matrix (0, (points, 1), 'd')
    for item, x in enumerate(xvec):
        fvec[item] = Function.fcall(x)
    # graphical commands
    fig = pyplot.figure()
    pyplot.hold(True)
    pyplot.plot(xvec, fvec, 'k')
    pyplot.axhline(linestyle=':',color = 'k')
    pyplot.axvline(linestyle=':',color = 'k')
    pyplot.xlabel('$x$')
    pyplot.ylabel('$f(x)$')
    pyplot.savefig('zeroplot.eps',format='eps')
    pyplot.show()
Esempio n. 53
0
def plot_spikes(time,voltage,APTimes,titlestr):
    """
    plot_spikes takes four arguments - the recording time array, the voltage
    array, the time of the detected action potentials, and the title of your
    plot.  The function creates a labeled plot showing the raw voltage signal
    and indicating the location of detected spikes with red tick marks (|)
    """
    plt.figure()
    plt.title(titlestr)
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (uV)")
    plt.plot(time, voltage)
    #plt.axhline(np.mean(voltage), color='green')
    #plt.axhline(3*np.std(voltage), color='green')
    #plt.axhline(-3*np.std(voltage), color='green')

    for x in APTimes:
        plt.axvline(x=x, ymin=0.9, linewidth=1, color='red')

    plt.show()
Esempio n. 54
0
 def drawDataLine(self):
          #--------- Update position indicator --------- 
     plt.figure('Data')
     if len(self.vLine) > 0:
         for item in self.vLine:
             item.remove()
     self.vLine = []
     self.vLine.append(plt.axvline(self.currentIndex.get(),ls='dashed',c='k'))
     plt.tight_layout()
     self.canvas['Data'].draw()        
     return
Esempio n. 55
0
def plot_rough(data=None, use_fb=True, levels=20, colorbars=False):
        if data is None: data = read_rough('rough')
        (x, y) = ('fb_x', 'fb_y') if use_fb else ('x', 'y')
        fig = pl.figure()
        #pos = np.genfromtxt("rough_pos")
        pos = None
        print pos
        for n,signal in enumerate(['psd_x', 'psd_y', 'sum_x', 'sum_y']):
                pl.subplot(2,2,n+1)
                pl.contourf(data[x][:,:,0], data[y][:,:,0], data[signal][:,:,0], levels)
                pl.title(signal)
                pl.axis('equal')
                pl.axis('tight')
                if colorbars:
                        pl.colorbar()

                if pos is not None:
                        pl.axvline(pos[0], alpha=0.3)
                        pl.axhline(pos[1], alpha=0.3)

        fig.show()
Esempio n. 56
0
    def plot_abc(self, uarg, param):
        """Plot a() and b() functions on the same plot.

        """
        plt.figure(figsize=(8, 4))

        plt.subplot(1, 3, 1)
        plt.plot(uarg, self.afun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$a(u)$')
        plt.xlabel('$u$')

        plt.subplot(1, 3, 2)
        plt.plot(uarg, self.bfun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$b(u)$')
        plt.xlabel('$u$')

        plt.subplot(1, 3, 3)
        plt.plot(uarg, self.cfun(uarg, param))
        plt.axhline(0)
        plt.axvline(0)
        plt.ylabel('$c(u)$')
        plt.xlabel('$u$')

        plt.tight_layout()
        plt.show()
Esempio n. 57
0
def plot_days_after_sales(messages=None, purchase_dates=None):

    count_of_days = sales_days_from_messages(messages=messages, purchase_dates=purchase_dates, randomize=False)
    n_days, n_sales = days_sales(count_of_days)

    plt.clf()
    plt.subplot(2, 1, 1)
    plt.plot(n_days, n_sales, color='blue', marker='o', linestyle='-')
    plt.axvline(x=0, linestyle='--', color='red')
    plt.title('Normal')
    plt.xlabel('N days after message')
    plt.ylabel('N sales')

    count_of_days_randomized = sales_days_from_messages(messages=messages, purchase_dates=purchase_dates, randomize=True)
    n_days_randomized, n_sales_randomized = days_sales(count_of_days_randomized)

    plt.subplot(2, 1, 2)
    plt.plot(n_days_randomized, n_sales_randomized, color='blue', marker='o', linestyle='-')
    plt.axvline(x=0, linestyle='--', color='red')
    plt.title('Users randomized')
    plt.xlabel('N days after message')
    plt.ylabel('N sales')
Esempio n. 58
0
    def plotMadMedian(self, events, figsize=(5, 5), save=False,
                      figname='mam-median-evts', figtype='png'):
        """ Plots the median and the medan absolute value of the input
            array events

            **Parameters**

            events : double
                The spike events

            figsize : float
                A tuple of the sizes of the figure

            save : boolean
                Indicates if the figure will be saved

            figname : string
                The name of the saved figure

            figtype : string
                The type of the saved figure (supports png and pdf)
        """
        events_median = np.apply_along_axis(np.median, 0, events)
        events_mad = np.apply_along_axis(mad, 0, events)

        plt.figure(figsize=figsize)
        plt.plot(events_median, color='red', lw=2)
        plt.axhline(y=0, color='black')
        for i in np.arange(0, 400, 100):
            plt.axvline(x=i, c='k', lw=2)
        for i in np.arange(0, 400, 10):
            plt.axvline(x=i, c='grey')
        plt.plot(events_median, 'r', lw=2)
        plt.plot(events_mad, 'b', lw=2)
        if save:
            if figtype == 'pdf':
                plt.savefig(figname+'pdf', dpi=90)
            else:
                plt.savefig(figname+'png')
Esempio n. 59
0
def plot_spikes(time,voltage,APTimes,titlestr):
    """
    plot_spikes takes four arguments - the recording time array, the voltage
    array, the time of the detected action potentials, and the title of your
    plot.  The function creates a labeled plot showing the raw voltage signal
    and indicating the location of detected spikes with red tick marks (|)
    """
    plt.figure()
    
    ##Your Code Here 
    
    plt.figure()
    plt.title(titlestr)
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (uV)") 

    plt.plot(time, voltage)
    
    for i in APTimes:
        plt.axvline(x=i, ymin=0.93, ymax=0.96, color='red')
    
    plt.show()