Python pylab.ylabel() Examples

The following are 30 code examples of pylab.ylabel(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pylab , or try the search function .
Example #1
Source File: __init__.py    From EDeN with MIT License 11 votes vote down vote up
def plot_confusion_matrix(y_true, y_pred, size=None, normalize=False):
    """plot_confusion_matrix."""
    cm = confusion_matrix(y_true, y_pred)
    fmt = "%d"
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        fmt = "%.2f"
    xticklabels = list(sorted(set(y_pred)))
    yticklabels = list(sorted(set(y_true)))
    if size is not None:
        plt.figure(figsize=(size, size))
    heatmap(cm, xlabel='Predicted label', ylabel='True label',
            xticklabels=xticklabels, yticklabels=yticklabels,
            cmap=plt.cm.Blues, fmt=fmt)
    if normalize:
        plt.title("Confusion matrix (norm.)")
    else:
        plt.title("Confusion matrix")
    plt.gca().invert_yaxis() 
Example #2
Source File: __init__.py    From EDeN with MIT License 7 votes vote down vote up
def plot_roc_curve(y_true, y_score, size=None):
    """plot_roc_curve."""
    false_positive_rate, true_positive_rate, thresholds = roc_curve(
        y_true, y_score)
    if size is not None:
        plt.figure(figsize=(size, size))
        plt.axis('equal')
    plt.plot(false_positive_rate, true_positive_rate, lw=2, color='navy')
    plt.plot([0, 1], [0, 1], color='gray', lw=1, linestyle='--')
    plt.xlabel('False positive rate')
    plt.ylabel('True positive rate')
    plt.ylim([-0.05, 1.05])
    plt.xlim([-0.05, 1.05])
    plt.grid()
    plt.title('Receiver operating characteristic AUC={0:0.2f}'.format(
        roc_auc_score(y_true, y_score))) 
Example #3
Source File: homework1.py    From principles-of-computing with MIT License 7 votes vote down vote up
def plot_question7():
    '''
    graph of total resources generated as a function of time,
    for upgrade_cost_increment == 1
    '''
    data = resources_vs_time(1.0, 50)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]
    a, b, c = pylab.polyfit(time, resource, 2)
    print 'polyfit with argument \'2\' fits the data, thus the degree of the polynomial is 2 (quadratic)'

    # plot in pylab on logarithmic scale (total resources over time for upgrade growth 0.0)
    #pylab.loglog(time, resource, 'o')

    # plot fitting function
    yp = pylab.polyval([a, b, c], time)
    pylab.plot(time, yp)
    pylab.scatter(time, resource)
    pylab.title('Silly Homework, Question 7')
    pylab.legend(('Resources for increment 1', 'Fitting function' + ', slope: ' + str(a)))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.grid()
    pylab.show() 
Example #4
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_it():
    '''
    helper function to gain insight on provided data sets background,
    using pylab
    '''
    data1 = [[1.0, 1], [2.25, 3.5], [3.58333333333, 7.5], [4.95833333333, 13.0], [6.35833333333, 20.0], [7.775, 28.5], [9.20357142857, 38.5], [10.6410714286, 50.0], [12.085515873, 63.0], [13.535515873, 77.5]]
    data2 = [[1.0, 1], [1.75, 2.5], [2.41666666667, 4.5], [3.04166666667, 7.0], [3.64166666667, 10.0], [4.225, 13.5], [4.79642857143, 17.5], [5.35892857143, 22.0], [5.91448412698, 27.0], [6.46448412698, 32.5], [7.00993867244, 38.5], [7.55160533911, 45.0], [8.09006687757, 52.0], [8.62578116328, 59.5], [9.15911449661, 67.5], [9.69036449661, 76.0], [10.2197762613, 85.0], [10.7475540391, 94.5], [11.2738698286, 104.5], [11.7988698286, 115.0]]
    time1 = [item[0] for item in data1]
    resource1 = [item[1] for item in data1]
    time2 = [item[0] for item in data2]
    resource2 = [item[1] for item in data2]
    
    # plot in pylab (total resources over time)
    pylab.plot(time1, resource1, 'o')
    pylab.plot(time2, resource2, 'o')
    pylab.title('Silly Homework')
    pylab.legend(('Data Set no.1', 'Data Set no.2'))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_it() 
Example #5
Source File: rnnrbm.py    From bachbot with MIT License 6 votes vote down vote up
def generate(self, filename, show=True):
        '''Generate a sample sequence, plot the resulting piano-roll and save
        it as a MIDI file.
        filename : string
            A MIDI file will be created at this location.
        show : boolean
            If True, a piano-roll of the generated sequence will be shown.'''

        piano_roll = self.generate_function()
        midiwrite(filename, piano_roll, self.r, self.dt)
        if show:
            extent = (0, self.dt * len(piano_roll)) + self.r
            pylab.figure()
            pylab.imshow(piano_roll.T, origin='lower', aspect='auto',
                         interpolation='nearest', cmap=pylab.cm.gray_r,
                         extent=extent)
            pylab.xlabel('time (s)')
            pylab.ylabel('MIDI note number')
            pylab.title('generated piano-roll') 
Example #6
Source File: helper.py    From KittiSeg with MIT License 6 votes vote down vote up
def modBev_plot(ax, rangeX = [-10, 10 ], rangeXpx= [0, 400], numDeltaX = 5, rangeZ= [8,48 ], rangeZpx= [0, 800], numDeltaZ = 9, fontSize = None, xlabel = 'x [m]', ylabel = 'z [m]'):
    '''

    @param ax:
    '''
    #TODO: Configureabiltiy would be nice!
    if fontSize==None:
        fontSize = 8
 
    ax.set_xlabel(xlabel, fontsize=fontSize)
    ax.set_ylabel(ylabel, fontsize=fontSize)
        
    zTicksLabels_val = np.linspace(rangeZpx[0], rangeZpx[1], numDeltaZ)
    ax.set_yticks(zTicksLabels_val)
    #ax.set_yticks([0, 100, 200, 300, 400, 500, 600, 700, 800])
    xTicksLabels_val = np.linspace(rangeXpx[0], rangeXpx[1], numDeltaX)
    ax.set_xticks(xTicksLabels_val)
    xTicksLabels_val = np.linspace(rangeX[0], rangeX[1], numDeltaX)
    zTicksLabels = map(lambda x: str(int(x)), xTicksLabels_val)
    ax.set_xticklabels(zTicksLabels,fontsize=fontSize)
    zTicksLabels_val = np.linspace(rangeZ[1],rangeZ[0], numDeltaZ)
    zTicksLabels = map(lambda x: str(int(x)), zTicksLabels_val)
    ax.set_yticklabels(zTicksLabels,fontsize=fontSize) 
Example #7
Source File: estimator_utils.py    From EDeN with MIT License 6 votes vote down vote up
def plot_learning_curve(train_sizes, train_scores, test_scores):
    """plot_learning_curve."""
    plt.figure(figsize=(15, 5))
    plt.title('Learning Curve')
    plt.xlabel("Training examples")
    plt.ylabel("AUC ROC")
    tr_ys = compute_stats(train_scores)
    te_ys = compute_stats(test_scores)
    plot_stats(train_sizes, tr_ys,
               label='Training score',
               color='navy')
    plot_stats(train_sizes, te_ys,
               label='Cross-validation score',
               color='orange')
    plt.grid(linestyle=":")
    plt.legend(loc="best")
    plt.show() 
Example #8
Source File: helper.py    From KittiSeg with MIT License 6 votes vote down vote up
def modBev_plot(ax, rangeX = [-10, 10 ], rangeXpx= [0, 400], numDeltaX = 5, rangeZ= [8,48 ], rangeZpx= [0, 800], numDeltaZ = 9, fontSize = None, xlabel = 'x [m]', ylabel = 'z [m]'):
    '''

    @param ax:
    '''
    #TODO: Configureabiltiy would be nice!
    if fontSize==None:
        fontSize = 8
 
    ax.set_xlabel(xlabel, fontsize=fontSize)
    ax.set_ylabel(ylabel, fontsize=fontSize)
        
    zTicksLabels_val = np.linspace(rangeZpx[0], rangeZpx[1], numDeltaZ)
    ax.set_yticks(zTicksLabels_val)
    #ax.set_yticks([0, 100, 200, 300, 400, 500, 600, 700, 800])
    xTicksLabels_val = np.linspace(rangeXpx[0], rangeXpx[1], numDeltaX)
    ax.set_xticks(xTicksLabels_val)
    xTicksLabels_val = np.linspace(rangeX[0], rangeX[1], numDeltaX)
    zTicksLabels = map(lambda x: str(int(x)), xTicksLabels_val)
    ax.set_xticklabels(zTicksLabels,fontsize=fontSize)
    zTicksLabels_val = np.linspace(rangeZ[1],rangeZ[0], numDeltaZ)
    zTicksLabels = map(lambda x: str(int(x)), zTicksLabels_val)
    ax.set_yticklabels(zTicksLabels,fontsize=fontSize) 
Example #9
Source File: main.py    From scTDA with GNU General Public License v3.0 6 votes vote down vote up
def plot_CDR_correlation(self, doplot=True):
        """
        Displays correlation between sampling time points and CDR. It returns the two
        parameters of the linear fit, Pearson's r, p-value and standard error. If optional argument 'doplot' is
        False, the plot is not displayed.
        """
        pel2, tol = self.get_gene(self.rootlane, ignore_log=True)
        pel = numpy.array([pel2[m] for m in self.pl])*tol
        dr2 = self.get_gene('_CDR')[0]
        dr = numpy.array([dr2[m] for m in self.pl])
        po = scipy.stats.linregress(pel, dr)
        if doplot:
            pylab.scatter(pel, dr, s=9.0, alpha=0.7, c='r')
            pylab.xlim(min(pel), max(pel))
            pylab.ylim(0, max(dr)*1.1)
            pylab.xlabel(self.rootlane)
            pylab.ylabel('CDR')
            xk = pylab.linspace(min(pel), max(pel), 50)
            pylab.plot(xk, po[1]+po[0]*xk, 'k--', linewidth=2.0)
            pylab.show()
        return po 
Example #10
Source File: transfer_learning.py    From plastering with MIT License 6 votes vote down vote up
def plot_confusion_matrix(test_label, pred):

    mapping = {1:'co2',2:'humidity',3:'pressure',4:'rmt',5:'status',6:'stpt',7:'flow',8:'HW sup',9:'HW ret',10:'CW sup',11:'CW ret',12:'SAT',13:'RAT',17:'MAT',18:'C enter',19:'C leave',21:'occu',30:'pos',31:'power',32:'ctrl',33:'fan spd',34:'timer'}
    cm_ = CM(test_label, pred)
    cm = normalize(cm_.astype(np.float), axis=1, norm='l1')
    fig = pl.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(cm, cmap=Color.YlOrBr)
    fig.colorbar(cax)
    for x in range(len(cm)):
        for y in range(len(cm)):
            ax.annotate(str("%.3f(%d)"%(cm[x][y], cm_[x][y])), xy=(y,x),
                        horizontalalignment='center',
                        verticalalignment='center',
                        fontsize=9)
    cm_cls =np.unique(np.hstack((test_label, pred)))
    cls = []
    for c in cm_cls:
        cls.append(mapping[c])
    pl.yticks(range(len(cls)), cls)
    pl.ylabel('True label')
    pl.xticks(range(len(cls)), cls)
    pl.xlabel('Predicted label')
    pl.title('Confusion Matrix (%.3f)'%(ACC(pred, test_label)))
    pl.show() 
Example #11
Source File: vim-profiler.py    From vim-profiler with GNU General Public License v3.0 6 votes vote down vote up
def plot(self):
        """
        Plot startup data.
        """
        import pylab

        print("Plotting result...", end="")
        avg_data = self.average_data()
        avg_data = self.__sort_data(avg_data, False)
        if len(self.raw_data) > 1:
            err = self.stdev_data()
            sorted_err = [err[k] for k in list(zip(*avg_data))[0]]
        else:
            sorted_err = None
        pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1],
                   xerr=sorted_err, align='center', alpha=0.4)
        pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0])
        pylab.xlabel("Average startup time (ms)")
        pylab.ylabel("Plugins")
        pylab.show()
        print(" done.") 
Example #12
Source File: analyser.py    From spotpy with MIT License 6 votes vote down vote up
def plot_Geweke(parameterdistribution,parametername):
    '''Input:  Takes a list of sampled values for a parameter and his name as a string
       Output: Plot as seen for e.g. in BUGS or PyMC'''
    import matplotlib.pyplot as plt

    # perform the Geweke test
    Geweke_values = _Geweke(parameterdistribution)

    # plot the results
    fig = plt.figure()
    plt.plot(Geweke_values,label=parametername)
    plt.legend()
    plt.title(parametername + '- Geweke_Test')
    plt.xlabel('Subinterval')
    plt.ylabel('Geweke Test')
    plt.ylim([-3,3])

    # plot the delimiting line
    plt.plot( [2]*len(Geweke_values), 'r-.')
    plt.plot( [-2]*len(Geweke_values), 'r-.') 
Example #13
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_question2():
    '''
    graph of total resources generated as a function of time,
    for four various upgrade_cost_increment values
    '''
    for upgrade_cost_increment in [0.0, 0.5, 1.0, 2.0]:
        data = resources_vs_time(upgrade_cost_increment, 5)
        time = [item[0] for item in data]
        resource = [item[1] for item in data]
    
        # plot in pylab (total resources over time for each constant)
        pylab.plot(time, resource, 'o')
        
    pylab.title('Silly Homework')
    pylab.legend(('0.0', '0.5', '1.0', '2.0'))
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_question2()   


# Question 3 
Example #14
Source File: helpers.py    From sklearn_pydata2015 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_iris_knn():
    iris = datasets.load_iris()
    X = iris.data[:, :2]  # we only take the first two features. We could
                        # avoid this ugly slicing by using a two-dim dataset
    y = iris.target

    knn = neighbors.KNeighborsClassifier(n_neighbors=3)
    knn.fit(X, y)

    x_min, x_max = X[:, 0].min() - .1, X[:, 0].max() + .1
    y_min, y_max = X[:, 1].min() - .1, X[:, 1].max() + .1
    xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
                         np.linspace(y_min, y_max, 100))
    Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pl.figure()
    pl.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    pl.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    pl.xlabel('sepal length (cm)')
    pl.ylabel('sepal width (cm)')
    pl.axis('tight') 
Example #15
Source File: plot_contrast_sensitive.py    From SceneChangeDet with MIT License 6 votes vote down vote up
def main():

    l2_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/l2_5,6,7/roc'
    cos_base_dir = '/media/admin228/00027E210001A5BD/train_pytorch/change_detection/CMU/prediction_cons/dist_cos_new_5,6,7/roc'
    CSF_dir = os.path.join(l2_base_dir)
    CSF_fig_dir = os.path.join(l2_base_dir,'fig.png')
    end_number = 22
    csf_conv5_l2_ls,csf_fc6_l2_ls,csf_fc7_l2_ls,x_l2 = get_csf_ls(l2_base_dir,end_number)
    csf_conv5_cos_ls,csf_fc6_cos_ls,csf_fc7_cos_ls,x_cos = get_csf_ls(cos_base_dir,end_number)
    Fig = pylab.figure()
    setFigLinesBW(Fig)
    #pylab.plot(x,csf_conv4_ls, color='k',label= 'conv4')
    pylab.plot(x_l2,csf_conv5_l2_ls, color='m',label= 'l2:conv5')
    pylab.plot(x_l2,csf_fc6_l2_ls, color = 'b',label= 'l2:fc6')
    pylab.plot(x_l2,csf_fc7_l2_ls, color = 'g',label= 'l2:fc7')
    pylab.plot(x_cos,csf_conv5_cos_ls, color='c',label= 'cos:conv5')
    pylab.plot(x_cos,csf_fc6_cos_ls, color = 'r',label= 'cos:fc6')
    pylab.plot(x_cos,csf_fc7_cos_ls, color = 'y',label= 'cos:fc7')
    pylab.legend(loc='lower right', prop={'size': 10})
    pylab.ylabel('RMS Contrast', fontsize=14)
    pylab.xlabel('Epoch', fontsize=14)
    pylab.savefig(CSF_fig_dir) 
Example #16
Source File: thermo_bulk.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_entropy(self):
        """

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        plt.plot(
            self.temperatures,
            self.eV_to_J_per_mol / self.num_atoms * self.get_entropy_p(),
            label="S$_p$",
        )
        plt.plot(
            self.temperatures,
            self.eV_to_J_per_mol / self.num_atoms * self.get_entropy_v(),
            label="S$_V$",
        )
        plt.legend()
        plt.xlabel("Temperature [K]")
        plt.ylabel("Entropy [J K$^{-1}$ mol-atoms$^{-1}$]") 
Example #17
Source File: thermo_bulk.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contour_entropy(self):
        """

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        s_coeff = np.polyfit(self.volumes, self.entropy.T, deg=self._fit_order)
        s_grid = np.array([np.polyval(s_coeff, v) for v in self.volumes]).T
        x, y = self.meshgrid()
        plt.contourf(x, y, s_grid)
        plt.plot(self.get_minimum_energy_path(), self.temperatures)
        plt.xlabel("Volume [$\AA^3$]")
        plt.ylabel("Temperature [K]") 
Example #18
Source File: homework1.py    From principles-of-computing with MIT License 6 votes vote down vote up
def plot_question3():
    '''
    graph of total resources generated as a function of time;
    for upgrade_cost_increment == 0
    '''
    data = resources_vs_time(0.0, 100)
    time = [item[0] for item in data]
    resource = [item[1] for item in data]

    # plot in pylab on logarithmic scale (total resources over time for upgrade growth 0.0)
    pylab.loglog(time, resource)
        
    pylab.title('Silly Homework')
    pylab.legend('0.0')
    pylab.xlabel('Current Time')
    pylab.ylabel('Total Resources Generated')
    pylab.show()

#plot_question3()


# Question 4 
Example #19
Source File: thermo_bulk.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_contourf(self, ax=None, show_min_erg_path=False):
        """

        Args:
            ax:
            show_min_erg_path:

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        x, y = self.meshgrid()
        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.contourf(x, y, self.energies)
        if show_min_erg_path:
            plt.plot(self.get_minimum_energy_path(), self.temperatures, "w--")
        plt.xlabel("Volume [$\AA^3$]")
        plt.ylabel("Temperature [K]")
        return ax 
Example #20
Source File: thermo_bulk.py    From pyiron with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_min_energy_path(self, *args, ax=None, **qwargs):
        """

        Args:
            *args:
            ax:
            **qwargs:

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        if ax is None:
            fig, ax = plt.subplots(1, 1)
            ax.xlabel("Volume [$\AA^3$]")
            ax.ylabel("Temperature [K]")
        ax.plot(self.get_minimum_energy_path(), self.temperatures, *args, **qwargs)
        return ax 
Example #21
Source File: experiment.py    From pymeasure with MIT License 6 votes vote down vote up
def pcolor(self, xname, yname, zname, *args, **kwargs):
        """Plot the results from the experiment.data pandas dataframe in a pcolor graph.
        Store the plots in a plots list attribute."""
        title = self.title
        x, y, z = self._data[xname], self._data[yname], self._data[zname]
        shape = (len(y.unique()), len(x.unique()))
        diff = shape[0] * shape[1] - len(z)
        Z = np.concatenate((z.values, np.zeros(diff))).reshape(shape)
        df = pd.DataFrame(Z, index=y.unique(), columns=x.unique())
        ax = sns.heatmap(df)
        pl.title(title)
        pl.xlabel(xname)
        pl.ylabel(yname)
        ax.invert_yaxis()
        pl.plt.show()
        self.plots.append(
            {'type': 'pcolor', 'x': xname, 'y': yname, 'z': zname, 'args': args, 'kwargs': kwargs,
             'ax': ax})
        if ax.get_figure() not in self.figs:
            self.figs.append(ax.get_figure()) 
Example #22
Source File: experiment.py    From double-dqn with MIT License 6 votes vote down vote up
def plot_evaluation_episode_reward():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	average_scores = [0]
	median_scores = [0]
	for n in xrange(len(csv_evaluation)):
		params = csv_evaluation[n]
		episodes.append(params[0])
		average_scores.append(params[1])
		median_scores.append(params[2])
	pylab.plot(episodes, average_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("average score")
	pylab.savefig("%s/evaluation_episode_average_reward.png" % args.plot_dir)

	pylab.clf()
	pylab.plot(0, 0)
	pylab.plot(episodes, median_scores, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("median score")
	pylab.savefig("%s/evaluation_episode_median_reward.png" % args.plot_dir) 
Example #23
Source File: plotting.py    From smallrnaseq with GNU General Public License v3.0 6 votes vote down vote up
def plot_read_count_dists(counts, h=8, n=50):
    """Boxplots of read count distributions """

    scols,ncols = base.get_column_names(counts)
    df = counts.sort_values(by='mean_norm',ascending=False)[:n]
    df = df.set_index('name')[ncols]
    t = df.T
    w = int(h*(len(df)/60.0))+4
    fig, ax = plt.subplots(figsize=(w,h))
    if len(scols) > 1:
        sns.stripplot(data=t,linewidth=1.0,palette='coolwarm_r')
        ax.xaxis.grid(True)
    else:
        df.plot(kind='bar',ax=ax)
    sns.despine(offset=10,trim=True)
    ax.set_yscale('log')
    plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
    plt.ylabel('read count')
    #print (df.index)
    #plt.tight_layout()
    fig.subplots_adjust(bottom=0.2,top=0.9)
    return fig 
Example #24
Source File: dopri5_with_disc.py    From Assimulo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_example(with_plots=True):
    """
    Example of the use of DOPRI5 for a differential equation
    with a discontinuity (state event) and the need for an event iteration.
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
    """
    #Create an instance of the problem
    exp_mod = Extended_Problem() #Create the problem

    exp_sim = Dopri5(exp_mod) #Create the solver
    
    exp_sim.verbosity = 0
    exp_sim.report_continuously = True
    
    #Simulate
    t, y = exp_sim.simulate(10.0,1000) #Simulate 10 seconds with 1000 communications points
    
    #Plot
    if with_plots:
        import pylab as P
        P.plot(t,y)
        P.title(exp_mod.name)
        P.ylabel('States')
        P.xlabel('Time')
        P.show()
        
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0],8.0)
    nose.tools.assert_almost_equal(y[-1][1],3.0)
    nose.tools.assert_almost_equal(y[-1][2],2.0)
    
    return exp_mod, exp_sim 
Example #25
Source File: _pylab_tweaks.py    From spinmob with GNU General Public License v3.0 5 votes vote down vote up
def save_plot(axes="gca", path=None):
    """
    Saves the figure in my own ascii format
    """

    global line_attributes

    # choose a path to save to
    if path==None: path = _s.dialogs.Save("*.plot", default_directory="save_plot_default_directory")

    if path=="":
        print("aborted.")
        return

    if not path.split(".")[-1] == "plot": path = path+".plot"

    f = file(path, "w")

    # if no argument was given, get the current axes
    if axes=="gca": axes=_pylab.gca()

    # now loop over the available lines
    f.write("title="  +axes.title.get_text().replace('\n', '\\n')+'\n')
    f.write("xlabel="+axes.xaxis.label.get_text().replace('\n','\\n')+'\n')
    f.write("ylabel="+axes.yaxis.label.get_text().replace('\n','\\n')+'\n')

    for l in axes.lines:
        # write the data header
        f.write("trace=new\n")
        f.write("legend="+l.get_label().replace('\n', '\\n')+"\n")

        for a in line_attributes: f.write(a+"="+str(_pylab.getp(l, a)).replace('\n','')+"\n")

        # get the data
        x = l.get_xdata()
        y = l.get_ydata()

        # loop over the data
        for n in range(0, len(x)): f.write(str(float(x[n])) + " " + str(float(y[n])) + "\n")

    f.close() 
Example #26
Source File: analyser.py    From spotpy with MIT License 5 votes vote down vote up
def plot_bestmodelrun(results,evaluation,fig_name ='Best_model_run.png'):
    """
    Get a plot with the maximum objectivefunction of your simulations in your result
    array.
    The plot will be saved as a .png file.

    :results: Expects an numpy array which should of an index "like" for
              objectivefunctions and "sim" for simulations.
     type: Array

     :evaluation: Should contain the values of your observations. Expects that this list has the same lenght as the number of simulations in your result array.
     :type: list

    Returns:
        figure. Plot of the simulation with the maximum objectivefunction value in the result array as a blue line and dots for the evaluation data.
    """
    import pylab as plt
    fig= plt.figure(figsize=(16,9))
    for i in range(len(evaluation)):
        if evaluation[i] == -9999:
            evaluation[i] = np.nan
    plt.plot(evaluation,'ro',markersize=1, label='Observation data')
    simulation_fields = get_simulation_fields(results)
    bestindex,bestobjf = get_maxlikeindex(results,verbose=False)
    plt.plot(list(results[simulation_fields][bestindex][0]),'b-',label='Obj='+str(round(bestobjf,2)))
    plt.xlabel('Number of Observation Points')
    plt.ylabel ('Simulated value')
    plt.legend(loc='upper right')
    fig.savefig(fig_name,dpi=300)
    text='A plot of the best model run has been saved as '+fig_name
    print(text) 
Example #27
Source File: euler_with_disc.py    From Assimulo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_example(with_plots=True):
    r"""
    Example of the use of Euler's method for a differential equation
    with a discontinuity (state event) and the need for an event iteration.
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
    """
    exp_mod = Extended_Problem() #Create the problem

    exp_sim = ExplicitEuler(exp_mod) #Create the solver
    
    exp_sim.verbosity = 0
    exp_sim.report_continuously = True
    
    #Simulate
    t, y = exp_sim.simulate(10.0,1000) #Simulate 10 seconds with 1000 communications points
    
   #Plot
    if with_plots:
        import pylab as P
        P.plot(t,y)
        P.title("Solution of a differential equation with discontinuities")
        P.ylabel('States')
        P.xlabel('Time')
        P.show()
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0],8.0)
    nose.tools.assert_almost_equal(y[-1][1],3.0)
    nose.tools.assert_almost_equal(y[-1][2],2.0)
    
    return exp_mod, exp_sim 
Example #28
Source File: radau5ode_with_disc.py    From Assimulo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_example(with_plots=True):
    #Create an instance of the problem
    exp_mod = Extended_Problem() #Create the problem

    exp_sim = Radau5ODE(exp_mod) #Create the solver
    
    exp_sim.verbosity = 0
    exp_sim.report_continuously = True
    
    #Simulate
    t, y = exp_sim.simulate(10.0,1000) #Simulate 10 seconds with 1000 communications points
    
    #Basic test
    nose.tools.assert_almost_equal(y[-1][0],8.0)
    nose.tools.assert_almost_equal(y[-1][1],3.0)
    nose.tools.assert_almost_equal(y[-1][2],2.0)
    
   #Plot
    if with_plots:
        import pylab as P
        P.plot(t,y)
        P.title("Solution of a differential equation with discontinuities")
        P.ylabel('States')
        P.xlabel('Time')
        P.show()
        
    return exp_mod, exp_sim 
Example #29
Source File: experiment.py    From double-dqn with MIT License 5 votes vote down vote up
def plot_training_episode_highscore():
	pylab.clf()
	sns.set_context("poster")
	pylab.plot(0, 0)
	episodes = [0]
	highscore = [0]
	for n in xrange(len(csv_training_highscore)):
		params = csv_training_highscore[n]
		episodes.append(params[0])
		highscore.append(params[1])
	pylab.plot(episodes, highscore, sns.xkcd_rgb["windows blue"], lw=2)
	pylab.xlabel("episodes")
	pylab.ylabel("highscore")
	pylab.savefig("%s/training_episode_highscore.png" % args.plot_dir) 
Example #30
Source File: rungekutta4_basic.py    From Assimulo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_example(with_plots=True):
    r"""
    Demonstration of the use of the use of Runge-Kutta 4 by solving the
    linear test equation :math:`\dot y = - y`
    
    on return:
    
       - :dfn:`exp_mod`    problem instance
    
       - :dfn:`exp_sim`    solver instance
       
    """

        
    #Defines the rhs
    def f(t,y):
        ydot = -y[0]
        return N.array([ydot])

    #Define an Assimulo problem
    exp_mod = Explicit_Problem(f, 4.0,
              name = 'RK4 Example: $\dot y = - y$')
    
    exp_sim = RungeKutta4(exp_mod) #Create a RungeKutta4 solver
    
    #Simulate
    t, y = exp_sim.simulate(5, 100) #Simulate 5 seconds
    
    #Basic test
    nose.tools.assert_almost_equal(float(y[-1]),0.02695179)
    
    #Plot
    if with_plots:
        import pylab as P
        P.plot(t, y)
        P.title(exp_mod.name)
        P.ylabel('y')
        P.xlabel('Time')
        P.show()
    
    return exp_mod, exp_sim