def plot_wlp(self, **kwargs):
     """
     Plot weighted log prior
     """
     if self.lp_func is None:
         return
     plt.plot(np.asarray(self.record.lp) * self.wlp, **kwargs)
Beispiel #2
0
    def test_screenstate_1(self):
        from gdesk import gui
        from pylab import plt
        from pathlib import Path

        gui.load_layout('console')

        samplePath = Path(r'./samples')

        gui.img.select(1)
        gui.img.open(samplePath / 'kodim05.png')
        gui.img.zoom_fit()
        plt.plot(gui.vs.mean(2).mean(1))
        plt.title('Column means of image 1')
        plt.xlabel('Column Number')
        plt.ylabel('Mean')
        plt.grid()
        plt.show()

        gui.img.select(2)
        gui.img.open(samplePath / 'kodim23.png')
        gui.img.zoom_full()
        plt.figure()
        plt.plot(gui.vs.mean(2).mean(0))
        plt.title('Row means of image 2')
        plt.xlabel('Row Number')
        plt.ylabel('Mean')
        plt.grid()
        plt.show()
    def plot2(self,
              figNum,
              time1,
              data1,
              time2,
              data2,
              title='',
              units='',
              options=''):
        plt.figure(figNum)
        #         plt.hold(True);
        plt.grid(True)
        if title:
            self.title = title
        if not units:
            self.units = units

    #     plt.cla()
        if self.preTitle:
            fig = plt.gcf()
            fig.canvas.set_window_title("Figure %d - %s" %
                                        (figNum, self.preTitle))
        plt.title("%s" % (self.title))
        plt.plot(time1, data1, options)
        plt.plot(time2, data2, options)
        plt.ylabel('(%s)' % (self.units))
        plt.xlabel('Time (s)')
        plt.margins(0.04)
Beispiel #4
0
def print_statistics(a1, a2, a1_type, a2_type):
    ''' Prints selected statistics.        
        Parameters
        ==========
        a1, a2: ndarray objects
            results objects from simulation
        '''
    sta1 = scs.describe(a1)
    sta2 = scs.describe(a2)
    print('%14s %14s %14s' % ('statistic', 'data set 1', 'data set 2'))
    print(45 * "-")
    print('%14s %14.0f %14.0f' % ('size', sta1[0], sta2[0]))
    print('%14s %14.3f %14.3f' % ('min', sta1[1][0], sta2[1][0]))
    print('%14s %14.3f %14.3f' % ('max', sta1[1][1], sta2[1][1]))
    print('%14s %14.3f %14.3f' % ('mean', sta1[2], sta2[2]))
    print('%14s %14.3f %14.3f' % ('std', np.sqrt(sta1[3]), np.sqrt(sta2[3])))
    print('%14s %14.3f %14.3f' % ('skew', sta1[4], sta2[4]))
    print('%14s %14.3f %14.3f' % ('kurtosis', sta1[5], sta2[5]))
    a1_sort = np.sort(a1)
    a2_sort = np.sort(a2)

    plt.scatter(x=a1_sort, y=a2_sort, marker='.', color='darkred')
    plt.plot(a1_sort, a1_sort, linestyle='dashed', color='darkblue', alpha=0.4)
    plt.xlabel(a1_type)
    plt.ylabel(a2_type)
    def subplotSingle2x(self,
                        figNum,
                        plotNum,
                        numRows,
                        numCols,
                        time,
                        data,
                        title='',
                        units='',
                        options=''):

        print("subplotSingle2x")

        plt.figure(figNum)
        if title:
            self.title = title
        if not units:
            self.units = units
        if self.preTitle:
            fig = plt.gcf()
            fig.canvas.set_window_title("%s" % (figNum, self.preTitle))
        if not figNum in self.sharex.keys():
            self.sharex[figNum] = plt.subplot(numRows, numCols, plotNum)
            plt.plot(time, data, options)

        plt.subplot(numRows, numCols, plotNum, sharex=self.sharex[figNum])
        #         plt.hold(True);
        plt.grid(True)
        plt.title("%s" % (self.title))
        plt.plot(time, data, options)
        plt.ylabel('(%s)' % (self.units))
        plt.margins(0.04)
Beispiel #6
0
def plot_precision_recall(precisions, recalls, thresholds):
    """
    Plots precision and recall by thresholds.
    
    Requires imports:
    from sklearn.metrics import precision_recall_curve, cross_val_predict
    
    Returns:
    Nothing

    """
    from pylab import mpl, plt
    import matplotlib.pyplot as plt
    import numpy as np
    plt.style.use('seaborn')
    mpl.rcParams['font.family'] = 'arial'

    np.random.seed(1000)
    np.set_printoptions(suppress=True, precision=4)

    plt.plot(thresholds, precisions[:-1], 'b--', label='Precision')
    plt.plot(thresholds, recalls[:-1], 'g-', label='Recall')
    plt.xlabel('Threshold')
    plt.legend(loc='center left')
    plt.ylim([0, 1])
Beispiel #7
0
def plot_roc_curve(fpr, tpr, label=None):
    """
    Plots Rceiver Operating Characteristic (ROC) curve from false_positive_rate(fpr), true_positive_rate(tpr)
    
    Requires imports:
    from sklearn.metrics import roc_curve
    
    Returns:
    Nothing
    """

    from pylab import mpl, plt
    import matplotlib.pyplot as plt
    import numpy as np
    plt.style.use('seaborn')
    mpl.rcParams['font.family'] = 'arial'
    np.random.seed(1000)
    np.set_printoptions(suppress=True, precision=4)

    plt.plot(fpr, tpr, linewidth=2, label=label)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.axis([0, 1, 0, 1])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Negatove Rate')
    plot_roc_curve(fpr, tpr)
Beispiel #8
0
    def initWidgets(self):
        self.fig = plt.figure(1)
        self.manager=get_current_fig_manager()
        self.img = subplot(2,1,1)
        self.TempGraph=subplot(2,1,2)
        x1=sp.linspace(0.0,5.0)
        y1=sp.cos(2*sp.pi*x1)*sp.exp(-x1)
        plt.plot(x1,y1)





        row=0
        self.grid()
        self.lblPower=tk.Label(self,text="Power")
        self.lblPower.grid(row=row,column=0)
        self.sclPower=tk.Scale(self,from_=0,to_=100000,orient=tk.HORIZONTAL)
        self.sclPower.grid(row=row,column=1,columnspan=3)




        #lastrow
        row=row+1
        self.btnOne=tk.Button(master=self,text="Run")
        self.btnOne["command"]=self.Run
        self.btnOne.grid(row=row,column=0)
        self.btnTwo=tk.Button(master=self,text="Soak")
        self.btnTwo["command"]=self.Soak
        self.btnTwo.grid(row=row,column=2)

        self.QUIT=tk.Button(master=self,text="QUIT")
        self.QUIT["command"]=self.quit
        self.QUIT.grid(row=row,column=3)
Beispiel #9
0
def lagger():
    
    global cols, scores
    lag_counts = range(1, lags + 1)
    cols = []
    scores = []
    
    for lag in range(1, lags + 1):
        col = 'lag_{}'.format(lag)
        data[col] = np.sign(data['returns'].shift(lag))
        cols.append(col)
        data.dropna(inplace=True)
        print('Iteration number: {}'.format(lag))
        %time model.fit(data[cols], np.sign(data['returns']))
        model.predict(data[cols])
        data['prediction'] = model.predict(data[cols])
        data['prediction'].value_counts()
        score = accuracy_score(data['prediction'], np.sign(data['returns']))
        scores.append(score)
        
    plt.figure()
    plt.plot(lag_counts, scores, lw=2)
    plt.xlabel('# of Lags')
    plt.ylabel('Test Score')
    
    return scores, cols
Beispiel #10
0
def geometric_brownian_motion_option_pricing(
        initial_val=100,
        num_samples=10000,
        riskless_rate=0.05,
        volatility_sigma=0.25,
        time_year=2.0,
        num_time_interval_discretization=50):
    dt = time_year / num_time_interval_discretization
    samples = np.zeros((num_time_interval_discretization + 1, num_samples))
    samples[0] = initial_val

    for t in range(1, num_time_interval_discretization + 1):
        samples[t] = samples[t - 1] * np.exp(
            (riskless_rate - 0.5 * (volatility_sigma**2)) * dt +
            volatility_sigma * np.sqrt(dt) * npr.standard_normal(num_samples))

    print(45 * "=")
    print(samples[1])
    plt.figure(figsize=(10, 6))
    plt.hist(samples[50], bins=50)
    plt.title("Geometric Brownian Motion")
    plt.xlabel('index level')
    plt.ylabel('frequency')
    plt.show()

    plt.figure(figsize=(10, 6))
    plt.plot(samples[:, :10], lw=1.5)
    plt.xlabel('time')
    plt.ylabel('index level')
    plt.title('Sample Path')
    plt.show()

    return samples
 def test_run(self):
     plt.style.use('seaborn')
     mpl.rcParams['font.family'] = 'serif'
     # 生成市场环境
     me_gbm = MarketEnvironment('me_gbm', dt.datetime(2020, 1, 1))
     me_gbm.add_constant('initial_value', 36.0)
     me_gbm.add_constant('volatility', 0.2)
     me_gbm.add_constant('final_date', dt.datetime(2020, 12, 31))
     me_gbm.add_constant('currency', 'EUR')
     me_gbm.add_constant('frequency', 'M')
     me_gbm.add_constant('paths', 1000)
     csr = ConstantShortRate('csr', 0.06)
     me_gbm.add_curve('discount_curve', csr)
     # 生成几何布朗运动模拟类
     gbm = GeometricBrownianMotion('gbm', me_gbm)
     gbm.generate_time_grid()
     print('时间节点:{0};'.format(gbm.time_grid))
     paths_1 = gbm.get_instrument_values()
     print('paths_1: {0};'.format(paths_1.round(3)))
     gbm.update(volatility=0.5)
     paths_2 = gbm.get_instrument_values()
     # 可视化结果
     plt.figure(figsize=(10, 6))
     p1 = plt.plot(gbm.time_grid, paths_1[:, :10], 'b')
     p2 = plt.plot(gbm.time_grid, paths_2[:, :10], 'r-')
     legend1 = plt.legend([p1[0], p2[0]],
                          ['low volatility', 'high volatility'],
                          loc=2)
     plt.gca().add_artist(legend1)
     plt.xticks(rotation=30)
     plt.show()
Beispiel #12
0
def square_root_diffusion_exact(initial_val=0.05,
                                kappa=3.0,
                                theta=0.02,
                                sigma=0.1,
                                time_year=2,
                                num_samples=10000,
                                num_time_interval_discretization=50):
    x = np.zeros((num_time_interval_discretization + 1, num_samples))
    x[0] = initial_val
    dt = time_year / num_time_interval_discretization

    for t in range(1, num_time_interval_discretization + 1):
        df = 4 * theta * kappa / sigma**2
        c = (sigma**2 * (1 - np.exp(-kappa * dt))) / (4 * kappa)
        nc = np.exp(-kappa * dt) / c * x[t - 1]
        x[t] = c * npr.noncentral_chisquare(df, nc, size=num_samples)

    plt.figure(figsize=(10, 6))
    plt.hist(x[-1], bins=50)
    plt.title("Square root diffusion Exact")
    plt.xlabel('value')
    plt.ylabel('frequency')
    plt.show()

    plt.figure(figsize=(10, 6))
    plt.plot(x[:, :10], lw=1.5)
    plt.xlabel('time')
    plt.ylabel('index level')
    plt.title('Sample Path SRD Exact')
    plt.show()

    return x
Beispiel #13
0
def square_root_diffusion_euler(initial_val=0.05,
                                kappa=3.0,
                                theta=0.02,
                                sigma=0.1,
                                time_year=2,
                                num_samples=10000,
                                num_time_interval_discretization=50):
    dt = time_year / num_time_interval_discretization

    xh = np.zeros((num_time_interval_discretization + 1, num_samples))
    x = np.zeros_like(xh)
    xh[0] = initial_val
    x[0] = initial_val
    for t in range(1, num_time_interval_discretization + 1):
        xh[t] = (xh[t - 1] + kappa * (theta - np.maximum(xh[t - 1], 0)) * dt +
                 sigma * np.sqrt(np.maximum(xh[t - 1], 0)) * math.sqrt(dt) *
                 npr.standard_normal(num_samples))
    x = np.maximum(xh, 0)

    plt.figure(figsize=(10, 6))
    plt.hist(x[-1], bins=50)
    plt.xlabel('value')
    plt.ylabel('frequency')
    plt.title('Square root diffusion Approx Euler')
    plt.show()

    plt.figure(figsize=(10, 6))
    plt.plot(x[:, :10], lw=1.5)
    plt.xlabel('time')
    plt.ylabel('index level')
    plt.title('Sample Path SRD approx')
    plt.show()

    return x
Beispiel #14
0
    def plot_fit(self, size=None, tol=0.1, axis_on=True):

        n, d = self.D.shape

        if size:
            nrows, ncols = size
        else:
            sq = np.ceil(np.sqrt(n))
            nrows = int(sq)
            ncols = int(sq)

        ymin = np.nanmin(self.D)
        ymax = np.nanmax(self.D)
        print 'ymin: {0}, ymax: {1}'.format(ymin, ymax)

        numplots = np.min([n, nrows * ncols])
        plt.figure()

        for n in xrange(numplots):
            plt.subplot(nrows, ncols, n + 1)
            plt.ylim((ymin - tol, ymax + tol))
            plt.plot(self.L[n, :] + self.S[n, :], 'r')
            plt.plot(self.L[n, :], 'b')
            if not axis_on:
                plt.axis('off')
 def plot_wlp(self,**kwargs):
     """
     Plot weighted log prior
     """
     if self.lp_func is None:
         return         
     plt.plot(np.asarray(self.record.lp)*self.wlp,**kwargs)
def create_image(csv_path):
    csv_data, _, _ = read_csv_data(csv_path)
    plt.figure()
    plt.plot(csv_data)
    plt.axis('off')

    plt.savefig('wind_data.png', bbox_inches='tight', dpi=500)
Beispiel #17
0
    def plot_spectral_points(self, spectra, fmt='r+', labels=None, lpos=None):
        '''
        Plots spectral profiles in feature space.
        '''
        m, n, c = self.__dims__
        assert type(spectra) in (
            list, tuple,
            np.ndarray), 'Expected spectra to be a list, tuple, or numpy array'

        if labels is not None and lpos is None:
            lpos = [(30, -30)] * len(labels)

        for i, spec in enumerate(spectra):
            plt.plot(spec[m], spec[n], fmt, ms=20, mew=2)

            if labels is not None:
                xy = (spec[m], spec[n])
                plt.annotate(labels[i],
                             xy=xy,
                             xytext=lpos[i],
                             textcoords='offset points',
                             ha='right',
                             va='bottom',
                             fontsize=14,
                             arrowprops=dict(arrowstyle='->',
                                             connectionstyle='arc3,rad=0'))
    def draw(cls, t_max, agents_proportions, eco_idx, parameters):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max), agents_proportions[:, agent_type],
                     color=color_set[agent_type], linewidth=2.0, label="Type-{} agents".format(agent_type))

            plt.ylim([-0.1, 1.1])

        plt.xlabel("$t$")
        plt.ylabel("Proportion of indirect exchanges")

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        plt.legend(loc='upper right', fontsize=12)

        print(parameters)

        plt.title(
            "Workforce: {}, {}, {};   displacement area: {};   vision area: {};   alpha: {};   tau: {}\n"
            .format(
                parameters["x0"],
                parameters["x1"],
                parameters["x2"],
                parameters["movement_area"],
                parameters["vision_area"],
                parameters["alpha"],
                parameters["tau"]
                          ), fontsize=12)

        if not path.exists("../../figures"):
            mkdir("../../figures")

        plt.savefig("../../figures/figure_{}.pdf".format(eco_idx))
        plt.show()
Beispiel #19
0
    def run_evo_plot(self):
        """ Awesome! All agents become chips!"""

        t_max = 100
        culture_length = 5
        env = Environment(culture_length=culture_length,
                          t_max=t_max,
                          n_agent=1000,
                          influence_type='linear')
        all_possible_cultures = list(
            product([False, True], repeat=culture_length))
        all_time_cul = np.zeros((t_max, len(all_possible_cultures)))
        #TODO: try to understand why
        #all_time_cul = np.zeros((t_max, len(all_possible_cultures)))
        #   do not work
        print(len(all_possible_cultures))
        print(2**culture_length)

        # env.plot()

        for t in tqdm(range(t_max)):
            env.one_step()
            for agent in env.agents:
                all_time_cul[
                    t, all_possible_cultures.index(tuple(agent.culture))] += 1

        plt.figure()
        plt.plot(all_time_cul)
Beispiel #20
0
def serve_css(name, length, keys, values):
    from pylab import plt, mpl
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False
    from matplotlib.font_manager import FontProperties
    # font = FontProperties(fname="d:\Users\ll.tong\Desktop\msyh.ttf", size=12)
    font = FontProperties(fname="/usr/share/fonts/msyh.ttf", size=11)
    plt.xlabel(u'')
    plt.ylabel(u'出现次数',fontproperties=font)
    plt.title(u'词频统计',fontproperties=font)
    plt.grid()
    keys = keys.decode("utf-8").split(' ')
    values = values.split(' ')
    valuesInt = []
    for value in values:
        valuesInt.append(int(value))

    plt.xticks(range(int(length)), keys)
    plt.plot(range(int(length)), valuesInt)
    plt.xticks(rotation=defaultrotation, fontsize=9,fontproperties=font)
    plt.yticks(fontsize=10,fontproperties=font)
    name = name + str(datetime.now().date()).replace(':', '') + '.png'
    imgUrl = 'static/temp/' + name
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(12.2, 2)
    plt.savefig(imgUrl, bbox_inches='tight', figsize=(20,4), dpi=100)
    plt.close()
    tempfile = static_file(name, root='./static/temp/')
    #os.remove(imgUrl)
    return tempfile
Beispiel #21
0
def MakePlot(x, y, styles, labels, axlabels):
    plt.figure(figsize=(10, 6))
    for i in range(len(x)):
        plt.plot(x[i], y[i], styles[i], label=labels[i])
        plt.xlabel(axlabels[0])
        plt.ylabel(axlabels[1])
    plt.legend(loc=0)
Beispiel #22
0
def plot(fn, marker, label):
    result_file = fn
    fid = vj.inv.ResultFileReader(result_file)
    epochs = fid.epochs
    rms = fid.rms_inland_at_epoch

    plt.plot(epochs, rms, 'o-', label=label)    
def plot_slip(slip, nx, ny,
              label='x-',
              legend = None
              ):
    epochs = slip.get_epochs()
    s = slip.get_cumu_slip_at_subfault(nx, ny)
    plt.plot(epochs, s, label, label=legend)
Beispiel #24
0
def plot_stat(rows, cache):
    "Use matplotlib to plot DAS statistics"
    if not PLOT_ALLOWED:
        raise Exception('Matplotlib is not available on the system')
    if cache in ['cache', 'merge']:  # cachein, cacheout, mergein, mergeout
        name_in = '%sin' % cache
        name_out = '%sout' % cache
    else:  # webip, webq, cliip, cliq
        name_in = '%sip' % cache
        name_out = '%sq' % cache

    def format_date(date):
        "Format given date"
        val = str(date)
        return '%s-%s-%s' % (val[:4], val[4:6], val[6:8])

    date_range = [r['date'] for r in rows]
    formated_dates = [format_date(str(r['date'])) for r in rows]
    req_in = [r[name_in] for r in rows]
    req_out = [r[name_out] for r in rows]

    plt.plot(date_range, req_in , 'ro-',\
             date_range, req_out, 'gv-',)
    plt.grid(True)
    plt.axis([min(date_range), max(date_range), \
                0, max([max(req_in), max(req_out)])])
    plt.xticks(date_range, tuple(formated_dates), rotation=17)
    #    plt.xlabel('dates [%s, %s]' % (date_range[0], date_range[-1]))
    plt.ylabel('DAS %s behavior' % cache)
    plt.savefig('das_%s.pdf' % cache, format='pdf', transparent=True)
    plt.close()
 def test_run(self):
     # 生成几何布朗运动市场环境
     me_gbm = MarketEnvironment('me_gbm', dt.datetime(2020, 1, 1))
     me_gbm.add_constant('initial_value', 36.0)
     me_gbm.add_constant('volatility', 0.2)
     me_gbm.add_constant('final_date', dt.datetime(2020, 12, 31))
     me_gbm.add_constant('currency', 'EUR')
     me_gbm.add_constant('frequency', 'M')
     me_gbm.add_constant('paths', 1000)
     csr = ConstantShortRate('csr', 0.06)
     me_gbm.add_curve('discount_curve', csr)
     # 生成几何布朗运动模拟类
     gbm = GeometricBrownianMotion('gbm', me_gbm)
     gbm.generate_time_grid()
     # 生成跳跃扩散市场环境
     me_srd = MarketEnvironment('me_srd', dt.datetime(2020, 1, 1))
     me_srd.add_constant('initial_value', .25)
     me_srd.add_constant('volatility', 0.05)
     me_srd.add_constant('final_date', dt.datetime(2020, 12, 31))
     me_srd.add_constant('currency', 'EUR')
     me_srd.add_constant('frequency', 'W')
     me_srd.add_constant('paths', 10000)
     # specific to simualation class
     me_srd.add_constant('kappa', 4.0)
     me_srd.add_constant('theta', 0.2)
     me_srd.add_curve('discount_curve', ConstantShortRate('r', 0.0))
     srd = SquareRootDiffusion('srd', me_srd)
     srd_paths = srd.get_instrument_values()[:, :10]
     plt.figure(figsize=(10, 6))
     plt.plot(srd.time_grid, srd.get_instrument_values()[:, :10])
     plt.axhline(me_srd.get_constant('theta'), color='r', ls='--', lw=2.0)
     plt.xticks(rotation=30)
     plt.show()
Beispiel #26
0
    def plot_profits(self, player, period):

        profits = self.results["profits"][-period:]

        plt.title("Profits")
        time_window = 100
        x = np.arange(len(profits[:, player]))
        y = []
        for i in x:
            if i < time_window:
                y_value = np.mean(profits[:i + 1, player])

            else:
                y_value = np.mean(profits[i - time_window:i + 1, player])

            y.append(y_value)

        plt.plot(x, y, color="black")
        maximum_profit = \
            self.parameters["n_positions"] * \
            self.parameters["n_prices"]
        plt.ylim(0, maximum_profit)

        plt.annotate("Time window: {}".format(time_window),
                     xy=(0.8, 0.1),
                     xycoords='axes fraction',
                     fontsize=6)

        # plt.annotate(self.string_parameters, xy=(-0.05, -0.1), xycoords='axes fraction', fontsize=6)

        plt.savefig(self.format_fig_name("profits_player{}".format(player)))
        plt.close()
Beispiel #27
0
 def test_run(self):
     # 生成几何布朗运动市场环境
     me_gbm = MarketEnvironment('me_gbm', dt.datetime(2020, 1, 1))
     me_gbm.add_constant('initial_value', 36.0)
     me_gbm.add_constant('volatility', 0.2)
     me_gbm.add_constant('final_date', dt.datetime(2020, 12, 31))
     me_gbm.add_constant('currency', 'EUR')
     me_gbm.add_constant('frequency', 'M')
     me_gbm.add_constant('paths', 1000)
     csr = ConstantShortRate('csr', 0.06)
     me_gbm.add_curve('discount_curve', csr)
     # 生成几何布朗运动模拟类
     gbm = GeometricBrownianMotion('gbm', me_gbm)
     gbm.generate_time_grid()
     # 生成跳跃扩散市场环境
     me_jd = MarketEnvironment('me_jd', dt.datetime(2020, 1, 1))
     me_jd.add_constant('lambda', 0.3)
     me_jd.add_constant('mu', -0.75)
     me_jd.add_constant('delta', 0.1)
     me_jd.add_environment(me_gbm)
     # 生成跳跃扩散模拟类
     jd = JumpDiffusion('jd', me_jd)
     paths_3 = jd.get_instrument_values()
     jd.update(lamb=0.9)
     paths_4 = jd.get_instrument_values()
     # 绘制图形
     plt.figure(figsize=(10, 6))
     p1 = plt.plot(gbm.time_grid, paths_3[:, :10], 'b')
     p2 = plt.plot(gbm.time_grid, paths_4[:, :10], 'r-')
     lengend1 = plt.legend([p1[0], p2[0]],
                           ['low intensity', 'high intensity'],
                           loc=3)
     plt.gca().add_artist(lengend1)
     plt.xticks(rotation=30)
     plt.show()
Beispiel #28
0
def plot_stat(rows, cache):
    "Use matplotlib to plot DAS statistics"
    if  not PLOT_ALLOWED:
        raise Exception('Matplotlib is not available on the system')
    if  cache in ['cache', 'merge']: # cachein, cacheout, mergein, mergeout
        name_in  = '%sin' % cache
        name_out = '%sout' % cache
    else: # webip, webq, cliip, cliq
        name_in  = '%sip' % cache
        name_out = '%sq' % cache
    def format_date(date):
        "Format given date"
        val = str(date)
        return '%s-%s-%s' % (val[:4], val[4:6], val[6:8])
    date_range = [r['date'] for r in rows]
    formated_dates = [format_date(str(r['date'])) for r in rows]
    req_in  = [r[name_in] for r in rows]
    req_out = [r[name_out] for r in rows]

    plt.plot(date_range, req_in , 'ro-',
             date_range, req_out, 'gv-',
    )
    plt.grid(True)
    plt.axis([min(date_range), max(date_range), \
                0, max([max(req_in), max(req_out)])])
    plt.xticks(date_range, tuple(formated_dates), rotation=17)
#    plt.xlabel('dates [%s, %s]' % (date_range[0], date_range[-1]))
    plt.ylabel('DAS %s behavior' % cache)
    plt.savefig('das_%s.pdf' % cache, format='pdf', transparent=True)
    plt.close()
Beispiel #29
0
 def plot_cells(self, color='k', lw=0.5, offset=(0, 0)):
     ox, oy = offset
     if self.tess == 'II':
         for c in xrange(self.nC):
             xmin, ymin = self._xmins[c]
             xmax, ymax = self._xmaxs[c]
             #            if (xmin == self.XMINS[0] or
             #                ymin == self.XMINS[1] or
             #                xmax == self.XMAXS[0] or
             #                ymax == self.XMAXS[1]):
             #                plt.plot([xmin,xmax,xmax,xmin,xmin],
             #                         [ymin,ymin,ymax,ymax,ymin], color=color,lw=lw*10)
             #            else:
             plt.plot(np.asarray([xmin, xmax, xmax, xmin, xmin]) + ox,
                      np.asarray([ymin, ymin, ymax, ymax, ymin]) + oy,
                      color=color,
                      lw=lw)
     else:
         for c in xrange(self.nC):
             verts = self.tessellation.cells_verts_homo_coo[c, :, :-1]
             x = np.asarray(
                 [verts[0, 0], verts[1, 0], verts[2, 0], verts[0, 0]])
             y = np.asarray(
                 [verts[0, 1], verts[1, 1], verts[2, 1], verts[0, 1]])
             plt.plot(x + ox, y + oy, color=color, lw=lw)
    def plot_fit(self, size=None, tol=0.1, axis_on=True):

        n, d = self.D.shape

        if size:
            nrows, ncols = size
        else:
            sq = np.ceil(np.sqrt(n))
            nrows = int(sq)
            ncols = int(sq)

        ymin = np.nanmin(self.D)
        ymax = np.nanmax(self.D)
        print('ymin: {0}, ymax: {1}'.format(ymin, ymax))

        numplots = np.min([n, nrows * ncols])
        plt.figure()

        for n in range(numplots):
            plt.subplot(nrows, ncols, n + 1)
            plt.ylim((ymin - tol, ymax + tol))
            plt.plot(self.L[n, :] + self.S[n, :], 'r')
            plt.plot(self.L[n, :], 'b')
            if not axis_on:
                plt.axis('off')
Beispiel #31
0
def square_root_diffusion_euler():
    x0 = 0.25
    kappa = 3.0
    theta = 0.15
    sigma = 0.1
    I = 10000
    M = 50
    dt = T / M
    xh = np.zeros((M + 1, I))
    x = np.zeros_like(xh)
    xh[0] = x0
    x[0] = x0
    for t in range(1, M + 1):
        xh[t] = (xh[t - 1] + kappa * (theta - np.maximum(xh[t - 1], 0)) * dt +
                 sigma * np.sqrt(np.maximum(xh[t - 1], 0)) * math.sqrt(dt) *
                 npr.standard_normal(I))
    x = np.maximum(xh, 0)
    plt.figure(figsize=(10, 6))
    plt.hist(x[-1], bins=50)
    plt.xlabel('value(SRT(T)')
    plt.ylabel('frequency')
    plt.show()
    plt.figure(figsize=(10, 6))
    plt.plot(x[:, :100], lw=1.5)
    plt.xlabel('time')
    plt.ylabel('index level')
    plt.show()
    return x
Beispiel #32
0
def jump_diffusion():
    S0 = 100.0
    r = 0.05
    sigma = 0.2
    lamb = 0.05
    mu = -0.6
    delta = 0.25
    rj = lamb * (math.exp(mu + 0.5 * delta**2) - 1)
    T = 1.0
    M = 50
    I = 10000
    dt = T / M

    S = np.zeros((M + 1, I))
    S[0] = S0
    sn1 = npr.standard_normal((M + 1, I))
    sn2 = npr.standard_normal((M + 1, I))
    poi = npr.poisson(lamb * dt, (M + 1, I))
    for t in range(1, M + 1, 1):
        S[t] = S[t - 1] * (np.exp(
            (r - rj - 0.5 * sigma**2) * dt + sigma * math.sqrt(dt) * sn1[t]) +
                           (np.exp(mu + delta * sn2[t]) - 1) * poi[t])
    S[t] = np.maximum(S[t], 0)
    plt.figure(figsize=(10, 6))
    plt.hist(S[-1], bins=50)
    plt.xlabel('value')
    plt.ylabel('frequency')
    plt.show()

    plt.figure(figsize=(10, 6))
    plt.plot(S[:, :100], lw=1.)
    plt.xlabel('time')
    plt.ylabel('index level')
    plt.show()
    def draw(cls, t_max, agents_proportions, eco_idx, parameters):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max),
                     agents_proportions[:, agent_type],
                     color=color_set[agent_type],
                     linewidth=2.0,
                     label="Type-{} agents".format(agent_type))

            plt.ylim([-0.1, 1.1])

        plt.xlabel("$t$")
        plt.ylabel("Proportion of indirect exchanges")

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        plt.legend(loc='upper right', fontsize=12)

        print(parameters)

        plt.title(
            "Workforce: {}, {}, {};   displacement area: {};   vision area: {};   alpha: {};   tau: {}\n"
            .format(parameters["x0"], parameters["x1"], parameters["x2"],
                    parameters["movement_area"], parameters["vision_area"],
                    parameters["alpha"], parameters["tau"]),
            fontsize=12)

        if not path.exists("../../figures"):
            mkdir("../../figures")

        plt.savefig("../../figures/figure_{}.pdf".format(eco_idx))
        plt.show()
Beispiel #34
0
def cumulative_freq_plot(rast,
                         band=0,
                         mask=None,
                         bins=100,
                         xlim=None,
                         nodata=-9999):
    '''
    Plots an empirical cumulative frequency curve for the input raster array
    in a given band.
    '''
    if mask is not None:
        arr = binary_mask(rast, mask)

    else:
        arr = rast.copy()

    if nodata is not None:
        arr = subarray(arr)

    values, base = np.histogram(arr, bins=bins)
    cumulative = np.cumsum(values)  # Evaluate the cumulative distribution
    plt.plot(base[:-1], cumulative, c='blue')  # Plot the cumulative function
    plt.set_title('Empirical Cumulative Distribution: Band %d' % band)

    if xlim is not None:
        axes = plt.gca()
        axes.set_xlim(xlim)

    plt.show()
    return arr
Beispiel #35
0
def plot(fn, marker, label):
    result_file = fn
    fid = vj.inv.ResultFileReader(result_file)
    epochs = fid.epochs
    rms = fid.rms_inland_at_epoch

    plt.plot(epochs, rms, 'o-', label=label)
Beispiel #36
0
    def plot_xy_points(self,
                       coords,
                       fmt='r+',
                       labels=None,
                       lpos=None,
                       dd=True):
        '''
        Add point(s) to the plot, given by their longitude-latitude (XY)
        coordinates, which will be displayed at the appropriate feature space
        coordinates.
        '''
        assert not self.__raveled__, 'Cannot do this when the input array is raveled'
        m, n, c = self.__dims__
        pcoords = xy_to_pixel(coords, gt=self.__gt__, wkt=self.__wkt__, dd=dd)

        if labels is not None and lpos is None:
            lpos = [(10, -10)] * len(labels)

        # http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
        for i, (x, y) in enumerate(pcoords):
            spec = self.features[x, y, :]
            plt.plot(spec[m], spec[n], fmt, ms=20, mew=2)

            if labels is not None:
                plt.annotate(labels[i],
                             xy=(spec[m], spec[n]),
                             xytext=lpos[i],
                             textcoords='offset points',
                             ha='right',
                             va='bottom',
                             fontsize=14,
                             arrowprops=dict(arrowstyle='->',
                                             connectionstyle='arc3,rad=0'))
Beispiel #37
0
    def disp_deformed_grid_lines(self,level,color=None,lw=1):
#        return
        if self.hlines is None or self.vlines is None:
            raise ValueError
        hlines,vlines=self.hlines,self.vlines
#        for lines,c in zip([hlines,vlines],['r','b']):    
#            pts_at_0=np.asarray([lines[:,0,:].flatten(),
#                                 lines[:,1,:].flatten()]).T
#            pts_at_0 = CpuGpuArray(pts_at_0.copy())        
#            pts_at_T=CpuGpuArray.zeros_like(pts_at_0)                          
#            self.calc_T_fwd(pts_src=pts_at_0,                              
#                      pts_fwd=pts_at_T,
#                      level=level,verbose=0,int_quality=1) 
#            if self.nCols != self.nCols:
#                            raise NotImplementedError 
#            pts_at_T.gpu2cpu()
#            lines_new_x=pts_at_T.cpu[:,0].reshape(lines[:,0,:].shape).copy()
#            lines_new_y=pts_at_T.cpu[:,1].reshape(lines[:,0,:].shape).copy()  
#            for line_new_x,line_new_y in zip(lines_new_x,lines_new_y):
#                         
#                        plt.plot(line_new_x,line_new_y,c)
        if color is None:
            colors=['r','b']
        else:
            colors=[color,color]
                     
        s = hlines.shape
        if s[2]<=1:
            raise ValueError
        p = 0
        L = 50000
        
        if L >=s[2]:
                
            while p < np.ceil(s[2]):     
                hlines=self.hlines[:,:,p:p+L]
                vlines=self.vlines[:,:,p:p+L]            
                p+=L
                
                
                for lines,c in zip([hlines,vlines],colors):    
                    pts_at_0=np.asarray([lines[:,0,:].flatten(),
                                         lines[:,1,:].flatten()]).T
                    if pts_at_0.size==0:
                        break
                    pts_at_0 = CpuGpuArray(pts_at_0.copy())  
                    pts_at_T=CpuGpuArray.zeros_like(pts_at_0)                          
                    self.calc_T_fwd(pts_src=pts_at_0,                              
                              pts_fwd=pts_at_T,
                              level=level,int_quality=1) 
                    if self.nCols != self.nCols:
                                    raise NotImplementedError 
                    pts_at_T.gpu2cpu()
                    lines_new_x=pts_at_T.cpu[:,0].reshape(lines[:,0,:].shape).copy()
                    lines_new_y=pts_at_T.cpu[:,1].reshape(lines[:,0,:].shape).copy()  
                    for line_new_x,line_new_y in zip(lines_new_x,lines_new_y):
                        plt.plot(line_new_x,line_new_y,c,lw=lw)                   
        else:
            raise NotImplementedError
 def plot_wlp_plus_ll(self,**kwargs):
     """
     Plot log likelihood + weighted log prior
     """
     if self.lp_func is None:
         return 
     plt.plot(np.asarray(self.record.ll)+
              np.asarray(self.record.lp)*self.wlp,**kwargs)
 def plot_data(self):
     plt.clf()  # clear the figure
     plt.title("Parent incomes vs. student grade")
     plt.plot(self.incomes,
              self.grades,
              color='orange',
              marker='o',
              linestyle='')
 def plot_wlp_plus_ll(self, **kwargs):
     """
     Plot log likelihood + weighted log prior
     """
     if self.lp_func is None:
         return
     plt.plot(
         np.asarray(self.record.ll) + np.asarray(self.record.lp) * self.wlp,
         **kwargs)
 def test_dip(self):
     xf = arange(0, 425)
     dips = self.fm.get_dip(xf)
     plt.plot(xf,dips)
     plt.grid('on')
     plt.gca().set_xticks(self.fm.Y_PC)
     plt.ylim([0, 30])
     plt.gca().invert_yaxis()
     plt.savefig(join(self.outs_dir, '~y_fc_dips.png'))
     plt.close()
Beispiel #42
0
    def test_respace(self):
        fn = '/home/zy/workspace/viscojapan/tests/share/slip0.h5'

        arr = vj.epoch_3d_array.Slip.load(fn)

        epochs = [0, 100, 200, 300]
        arr1 = arr.respace(epochs)

        nx= 2
        ny = 13
        plt.plot(arr.get_epochs(), arr.get_cumu_slip_at_subfault(nx, ny))
        plt.plot(arr1.get_epochs(), arr1.get_cumu_slip_at_subfault(nx, ny), 'x')
Beispiel #43
0
 def plot_smoothed_alpha_comparison(self,rmsval,suffix=''):
     plt.plot(self.f,self.alpha,'ko',label='data set')
     plt.plot(self.f,self.salpha,'c-',lw=2,label='smoothed angle $\phi$')
     plt.xlabel('frequency in Hz')
     plt.ylabel('angle $\phi$ in coordinates of circle')
     plt.legend()
     ylims=plt.axes().get_ylim()
     plt.yticks((arange(9)-4)*0.5*pi, ['$-2\pi$','$-3\pi/2$','$-\pi$','$-\pi/2$','$0$','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$'])
     plt.ylim(ylims)
     plt.title('RMS offset from smooth curve: {:.4f}'.format(rmsval))
     if self.show: plt.show()
     else: plt.savefig(join(self.sdc.plotpath,'salpha','c{}_salpha_on_{}_circle'.format(self.sdc.case,self.ZorY)+self.sdc.suffix+self.sdc.outsuffix+suffix+'.png'), dpi=240)
     plt.close()
    def draw(cls, t_max, agents_proportions, suffix):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max), agents_proportions[:, agent_type],
                     color=color_set[agent_type], linewidth=1.0)

            plt.ylim([0, 1])

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        # plt.legend(loc='lower left', frameon=False)

        plt.savefig("figure_{}.pdf".format(suffix))
    def plot_axis_control(self, axis, 
                          show_mux_cmd=True, show_asctec_cmd=True, show_vicon_meas=True, show_imu_meas=True):
        axismap = {'roll': (self.v.control.roll_cmd, 2, +1, self.v.asctec_ctrl_input.roll_cmd, -1),
                   'pitch': (self.v.control.pitch_cmd, 1, -1, self.v.asctec_ctrl_input.pitch_cmd, -1),
                   'yaw': (self.v.control.yaw_cmd, 0, -1, self.v.asctec_ctrl_input.yaw_rate_cmd, +1) # not sure about the multiplier here
                   }
        control_mode_cmd, state_axis, imu_mult, asctec_cmd, asctec_cmd_mult = axismap[axis]
        newfig("%s Axis Control" % axis.capitalize(), "time [s]", "%s [deg]" % axis.capitalize())
        # np.clip() and the [1:] stuff in the following to attempt deal with bogus initial data points in IMU data:
        if show_mux_cmd:
            plt.plot(self.v.control.t[self.v.control.istart:self.v.control.iend],
                     control_mode_cmd[self.v.control.istart:self.v.control.iend], label='cmd (from mux)')
        if show_vicon_meas:
            plt.plot(self.v.state.t[self.v.state.istart:self.v.state.iend], 
                     self.v.state.ori_ypr[self.v.state.istart:self.v.state.iend, state_axis], label='meas (Vicon)')
        if show_imu_meas:
            plt.plot(np.clip(self.v.imu.t[self.v.imu.istart:self.v.imu.iend], 0, np.inf), 
                     imu_mult*self.v.imu.ori_ypr[self.v.imu.istart:self.v.imu.iend, state_axis], label='meas (IMU)')
        if show_asctec_cmd and axis is not 'yaw':
            plt.plot(self.v.asctec_ctrl_input.t[self.v.asctec_ctrl_input.istart:self.v.asctec_ctrl_input.iend], 
                     asctec_cmd_mult*asctec_cmd[self.v.asctec_ctrl_input.istart:self.v.asctec_ctrl_input.iend],
                    label='cmd (AscTec)')
        # Plot difference between vicon and imu: (broken, comment it out for now..)
#        tout, data_out = uniform_resample((('linear', self.v.imu.t[self.v.asctec_ctrl_input.istart:self.v.asctec_ctrl_input.iend], 
#                                                      self.v.imu.ori_ypr[self.v.asctec_ctrl_input.istart:self.v.asctec_ctrl_input.iend,state_axis]), 
#                                           ('linear', self.v.state.t[self.v.state.istart:self.v.state.iend], 
#                                                      self.v.state.ori_ypr[self.v.state.istart:self.v.state.iend, state_axis])), 
#                                           0.02)
#        plt.plot(tout, imu_mult*data_out[0][0] - data_out[1][0], label='IMU - Vicon')
        plt.legend()
        self._timeseries_postplot()
Beispiel #46
0
def plot_fault_framework(fault_framework):
    fm = fault_framework
    plt.plot(fm.Y_PC, fm.DEP, '-o')
    plt.axis('equal')
    plt.axhline(0, color='black')
    plt.gca().set_yticks(fm.DEP)
    plt.gca().set_xticks(fm.Y_PC)
    plt.grid('on')
    plt.xlabel('From trench to continent(km)')
    plt.ylabel('depth (km)')

    for xi, yi, dip in zip(fm.Y_PC, fm.DEP, fm.DIP_D):
        plt.text(xi, yi, 'dip = %.1f'%dip)

    plt.gca().invert_yaxis()
Beispiel #47
0
 def plot_characteristic_freqs(self,annotate=True,size=8,spread=0.15):
     cx,cy=self.center.real,self.center.imag; r=self.radius
     if self.ZorY == 'Z':
         philist,flist=[self.phi_a,self.phi_p,self.phi_n],[self.fa,self.fp,self.fn]
     elif self.ZorY == 'Y':
         philist,flist=[self.phi_m,self.phi_s,self.phi_r],[self.fm,self.fs,self.fr]
     for p,f in zip(philist,flist):
         if f is not None:
             xpos=cx+r*cos(p); ypos=cy+r*sin(p); xos=spread*(xpos-cx); yos=spread*(ypos-cy)
             plt.plot([0,xpos],[0,ypos],'co-')
             if annotate:
                 self.ax.annotate('{:.3f} Hz'.format(f), xy=(xpos,ypos),  xycoords='data',
                                  xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points',
                                  arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10), size=size
                                  )
Beispiel #48
0
    def plot(*args):
        """
        Recibe señales que se desee graficar
        Y muestra todas ellas en un mismo gráfico
        """
        import numpy as np
        from pylab import plt
        plotargs = []

        for arg in args:
            x = np.arange(0, len(arg))
            y = np.array([int(i) for i in arg])
            plotargs.extend([x, y])

        plt.plot(*plotargs)
        plt.show()
    def update_img((expected, output)):
        plt.cla()
        plt.ylim((vmin, vmin+vmax))
        plt.xlim((vmin, vmin+vmax))
        ax = fig.add_subplot(111)
        plt.plot([vmin, vmin+vmax], [vmin, vmin+vmax])
        ax.grid(True)
        plt.xlabel("expected output")
        plt.ylabel("network output")
        plt.legend()

        expected = expected*vmax + vmin
        output = output*vmax + vmin
        #scat.set_offsets((expected, output))
        scat = ax.scatter(expected, output)
        return scat
    def test_dep(self):
        xf = arange(0, 425)
        deps = self.fm.get_dep(xf)
        plt.plot(xf,deps)

        plt.gca().set_yticks(self.fm.DEP)
        plt.gca().set_xticks(self.fm.Y_PC)
        
        plt.grid('on')
        plt.title('Ground x versus depth')
        plt.xlabel('Ground X (km)')
        plt.ylabel('depth (km)')
        plt.axis('equal')
        plt.gca().invert_yaxis()
        plt.savefig(join(self.outs_dir, '~Y_PC_vs_deps.png'))
        plt.close()
Beispiel #51
0
def plot(site):
    tp = np.loadtxt('../post_offsets/%s.post'%site)

    t = dc.asmjd([ii[0] for ii in tp]) + dc.adjust_mjd_for_plot_date
    e = [ii[1] for ii in tp]
    n = [ii[2] for ii in tp]
    u = [ii[3] for ii in tp]

    plt.plot_date(t,e,'x-', label = 'eastings')
    plt.plot(t,n,'x-', label = 'northings')
    plt.plot(t,u,'x-', label = 'upings')
    plt.gcf().autofmt_xdate()
    plt.legend(loc=0)
    plt.title(site)
    plt.savefig('%s.png'%site)
    #plt.show()
    plt.close()
Beispiel #52
0
def plotter(mode,Bc,Tc,Q):
    col = ['#000080','#0000FF','#4169E1','#6495ED','#00BFFF','#B0E0E6']
    plt.figure()
    ax = plt.subplot(111)
    for p in range(Bc.shape[1]):
        plt.plot(Tc[:,p],Bc[:,p],'-',color=str(col[p]))
    plt.xlabel('Tc [TW]')
    plt.ylabel('Bc normalised to total EU load')
    plt.title(str(mode)+' flow')
    
    # Shrink current axis by 25% to make room for legend
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])

    plt.legend(\
        ([str(Q[i]*100) for i in range(len(Q))]),\
        loc='center left', bbox_to_anchor=(1, 0.5),title='Quantiles')
    
    plt.savefig('figures/bctc_'+str(mode)+'.eps')
Beispiel #53
0
def _plot_base(dep, val, deplim_small, xlim_small, xlabel):
    plt.subplot(1,2,1)
    plt.plot(val, dep)
    plt.gca().invert_yaxis()
    plt.grid('on')
    plt.ylabel('depth/km')
    plt.xlabel(xlabel)
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=-45)

    plt.subplot(1,2,2)
    plt.plot(val, dep)
    plt.gca().invert_yaxis()
    plt.grid('on')
    plt.ylim(deplim_small)
    plt.xlim(xlim_small)
    plt.xlabel(xlabel)
    locs, labels = plt.xticks()
    plt.setp(labels, rotation=-45)
def plot_axis_control(v, axis):
    axismap = {'roll': (v.control.roll_cmd, 2, +1, v.asctec_ctrl_input.roll_cmd, -1),
               'pitch': (v.control.pitch_cmd, 1, -1, v.asctec_ctrl_input.pitch_cmd, -1),
               'yaw': (v.control.yaw_cmd, 0, -1, v.asctec_ctrl_input.yaw_rate_cmd, +1) # not sure about the multiplier here
               }
    control_mode_cmd, state_axis, imu_mult, asctec_cmd, asctec_cmd_mult = axismap[axis]
    newfig("%s Axis Control" % axis.capitalize(), "time [s]", "%s [deg]" % axis.capitalize())
    # np.clip() and the [1:] stuff in the following to attempt deal with bogus initial data points in IMU data:
    plt.plot(v.control.t, control_mode_cmd, label='cmd (from mux)')
    plt.plot(v.state.t[1:], v.state.ori_ypr[1:,state_axis], label='meas (Vicon)')
    plt.plot(np.clip(v.imu.t[1:], 0, np.inf), imu_mult*v.imu.ori_ypr[1:,state_axis], label='meas (IMU)')
    if axis is not 'yaw':
        plt.plot(v.asctec_ctrl_input.t, asctec_cmd_mult*asctec_cmd, label='cmd (AscTec)')
    # Plot difference between vicon and imu:
    tout, data_out = uniform_resample((('linear', v.imu.t[1:], v.imu.ori_ypr[1:,state_axis]), 
                                       ('linear', v.state.t[1:], v.state.ori_ypr[1:,state_axis])), 
                                       0.02)
    plt.plot(tout, imu_mult*data_out[0][0] - data_out[1][0], label='IMU - Vicon')

    plt.legend()
Beispiel #55
0
 def plot_cells(self,color='k',lw=0.5,offset=(0,0)):  
     ox,oy=offset
     if self.tess == 'II':               
         for c in xrange(self.nC):
             xmin,ymin=self._xmins[c]  
             xmax,ymax=self._xmaxs[c]  
 #            if (xmin == self.XMINS[0] or
 #                ymin == self.XMINS[1] or
 #                xmax == self.XMAXS[0] or
 #                ymax == self.XMAXS[1]):
 #                plt.plot([xmin,xmax,xmax,xmin,xmin],
 #                         [ymin,ymin,ymax,ymax,ymin], color=color,lw=lw*10)         
 #            else:    
             plt.plot(np.asarray([xmin,xmax,xmax,xmin,xmin])+ox,
                      np.asarray([ymin,ymin,ymax,ymax,ymin])+oy, color=color,lw=lw)         
     else:
         for c in xrange(self.nC):
             verts=self.tessellation.cells_verts_homo_coo[c,:,:-1]
             x=np.asarray([verts[0,0],verts[1,0],verts[2,0],verts[0,0]])
             y=np.asarray([verts[0,1],verts[1,1],verts[2,1],verts[0,1]])
             plt.plot(x+ox,y+oy, color=color,lw=lw)
Beispiel #56
0
 def plot_inference_summary(inference_record):
     ll = []
     lp = []
     wlp_plus_ll=[]
     for step in inference_record.steps:
         ll += step.ll[1:] # start from 1 and not 0: to skip the initial guess
         try:
             lp += step.lp[1:] 
             
             wlp_plus_ll += list((step.wlp * np.asarray(step.lp[1:]) + 
                                         np.asarray(step.ll[1:])).tolist())
         except AttributeError:
             pass
                 
     plt.title('ll',fontsize=30)
     plt.plot(ll,lw=2)
     plt.plot(lp,lw=2)
     plt.plot(wlp_plus_ll,lw=2)
     
      
     counter = 0
     for i,step in enumerate(inference_record.steps):
         if i%2==1:
             facecolor = ".2"
         else:
             facecolor = ".5"           
         plt.axvspan(counter, counter+step.nAccepted, facecolor=facecolor, alpha=0.2)
         counter += step.nAccepted 
def plot(mot_results):

    bool_mot_results = np.asarray(mot_results) == 1

    t_max = len(bool_mot_results)

    average_t = np.zeros(t_max)

    time_window = 10

    for t in range(t_max):

        if t < time_window:
            average_t[t] = np.mean(bool_mot_results[:t+1])
        else:
            average_t[t] = np.mean(bool_mot_results[t-10:t+1])

    try:
        plt.plot(np.arange(t_max), average_t, linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.show("figure.pdf")
    except:
        print("Could not show the figure but here are the results:")
        print(average_t)
    def plot(cls, data, msg=""):

        x = np.arange(len(data[:]))

        plt.plot(x, data[:, 0], c="red", linewidth=2)
        plt.plot(x, data[:, 1], c="blue", linewidth=2)
        plt.plot(x, data[:, 2], c="green", linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.text(0, -0.12, "{}".format(msg))

        plt.show()
Beispiel #59
0
 def __init__(self, width):
     # set plot to animated
     self.x1s = [0]
     self.y1s = [0]
     self.x2s = [0]
     self.y2s = [0]
     self.x3s = [0]
     self.y3s = [0]
     self.plt1, self.plt2, self.plt3 = plt.plot(
         self.x1s, self.y1s, 'rx',
         self.x2s, self.y2s, 'b.',
         self.x3s, self.y3s, 'gs',
         alpha=0.05, linewidth=3)
     self.latest = deque([0] * 20)
     self.plt3.set_alpha = 0.8
     plt.ylim([0, 100])
     plt.xlim([0, width])
     plt.ion()
Beispiel #60
0
 def plot_overview(self,suffix=''):
     x=self.x; y=self.y; r=self.radius; cx,cy=self.center.real,self.center.imag
     ax=plt.axes()
     plt.scatter(x,y, marker='o', c='b', s=40)
     plt.axhline(y=0,color='grey', zorder=-1)
     plt.axvline(x=0,color='grey', zorder=-2)
     t=linspace(0,2*pi,201)
     circx=r*cos(t) + cx
     circy=r*sin(t) + cy
     plt.plot(circx,circy,'g-')
     plt.plot([cx],[cy],'gx',ms=12)
     if self.ZorY == 'Z':
         philist,flist=[self.phi_a,self.phi_p,self.phi_n],[self.fa,self.fp,self.fn]
     elif self.ZorY == 'Y':
         philist,flist=[self.phi_m,self.phi_s,self.phi_r],[self.fm,self.fs,self.fr]
     for p,f in zip(philist,flist):
         if f is not None:
             xpos=cx+r*cos(p); ypos=cy+r*sin(p); xos=0.2*(xpos-cx); yos=0.2*(ypos-cy)
             plt.plot([0,xpos],[0,ypos],'co-')
             ax.annotate('{:.3f} Hz'.format(f), xy=(xpos,ypos),  xycoords='data',
                         xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points',
                         arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10)
                         )
     #plt.xlim(0,0.16)
     #plt.ylim(-0.1,0.1)
     plt.axis('equal')
     if self.ZorY == 'Z':
         plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm')
     if self.ZorY == 'Y':
         plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens')
     plt.title("fitting the admittance circle with Powell's method")
     tx1='best fit (fmin_powell):\n'
     tx1+='center at G+iB = {:.5f} + i*{:.8f}\n'.format(cx,cy)
     tx1+='radius = {:.5f};  '.format(r)
     tx1+='residue: {:.2e}'.format(self.resid)
     txt1=plt.text(-r,cy-1.1*r,tx1,fontsize=8,ha='left',va='top')
     txt1.set_bbox(dict(facecolor='gray', alpha=0.25))
     idxlist=self.to_be_annotated('triple')
     ofs=self.annotation_offsets(idxlist,factor=0.1,xshift=0.15)
     for i,j in enumerate(idxlist):
         xpos,ypos = x[j],y[j]; xos,yos = ofs[i].real,ofs[i].imag
         ax.annotate('{:.1f} Hz'.format(self.f[j]), xy=(xpos,ypos),  xycoords='data',
                     xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points',
                     arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10)
                     )
     if self.show: plt.show()
     else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+suffix+'.png'), dpi=240)
     plt.close()