Beispiel #1
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 #2
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
Beispiel #3
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 #4
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
    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 #6
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 #7
0
def plot_inv_conv(fvals, name, direc):
    plt.figure()
    plt.semilogy(fvals, 'ko-')
    plt.xlabel('Iterations')
    plt.ylabel('Cost Function')
    plt.savefig(os.path.join(direc, name + '.png'), dpi=300)
    plt.close()
Beispiel #8
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()
Beispiel #9
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()
Beispiel #10
0
    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 #11
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 #12
0
    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)
def visual_results(Image_data, preds, Labels=None, Top=0):
    from pylab import plt
    pred_age_value = preds['age']
    pred_gender_value = preds['gender']
    pred_smile_value = preds['smile']
    pred_glass_value = preds['glass']
    Num = Image_data.shape[0] if Top == 0 else Top

    for k in xrange(Num):
        print k, Num
        plt.figure(1)
        plt.imshow(de_preprocess_image(Image_data[k]))
        title_str = 'Prediction: Age %0.1f, %s, %s, %s.' % (
            pred_age_value[k], gender_list[pred_gender_value[k]],
            glass_list[pred_glass_value[k]], smile_list[pred_smile_value[k]])
        x_label_str = 'GT: '
        try:
            x_label_str = x_label_str + 'Age %0.1f' % Labels['age'][k]
        except:
            pass
        try:
            x_label_str = x_label_str + '%s, %s, %s' % (gender_list[int(
                Labels['gender'][k])], glass_list[int(
                    Labels['glass'][k])], smile_list[int(Labels['smile'][k])])
        except:
            pass

        plt.title(title_str)
        plt.xlabel(x_label_str)
        plt.show()
Beispiel #14
0
def graph_error_mean_per_hour(dataset, pred, column):
    data = dataset.iloc[dataset.shape[0] - len(pred):]
    data["Pred"] = np.around(pred, 5)
    if column == "Diff":
        res = np.delete(data["Close"].to_numpy(), -1)
        res = np.insert(res, 0, 0)
        data["Pred"] = data["Pred"] + res
    data["AEM"] = np.abs(np.around(data.Close - data.Pred, 5))
    data['Hour'] = data.Date.apply(lambda x: x.hour)
    data["Diff"] = data.Close.diff().apply(abs).fillna(0)

    plt.figure(figsize=(14, 6))
    plt.hist(data.where((data.Hour > 5) & (data.Hour < 20)).dropna()["AEM"],
             150,
             density=True,
             range=(0, 0.003))
    plt.show()

    diff_mean = data.groupby("Hour").mean().Diff
    x_ch = diff_mean.index
    y_ch = diff_mean

    diff_mean_aem = data.groupby("Hour").mean().AEM
    x = diff_mean_aem.index
    y = diff_mean_aem

    plt.figure(figsize=(14, 6))
    plt.bar(x_ch, y_ch, color="green")
    plt.bar(x, y, color="r", alpha=0.7)
    plt.title(
        "Absolute mean of error in predictions per hour compared to absolute mean of price changes",
        fontsize=16)
    plt.show()
def plot_response(data, plate_name, save_folder = 'Figures/'):
    """
    """
    if not os.path.isdir(save_folder):
        os.makedirs(save_folder)

    for block in data:
        #
        group = group_similar(data[block].keys())
        names = data[block].keys()
        names.sort()
        #
        plt.figure(figsize=(16, 4 + len(names)/8), dpi=300)
        #
        for i, name in enumerate(names):
            a, b, c = get_index(group, name)
            color, pattern = color_shade_pattern(a, b, c, group)
            mean = data[block][name]['mean'][0]
            std = data[block][name]['std'][0]

            plt.barh([i], [mean], height=1.0, color=color, hatch=pattern)
            plt.errorbar([mean], [i+0.5], xerr=[std], ecolor = [0,0,0], linestyle = '')

        plt.yticks([i+0.5 for i in xrange(len(names))], names, size = 8)
        plt.title(plate_name)
        plt.ylim(0, len(names))
        plt.xlabel('change')
        plt.tight_layout()

        plt.savefig(save_folder + 'response_' + str(block + 1))
    #
    return None
Beispiel #16
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)
 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 #18
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)
 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 #20
0
def link_level_bars(levels, usages, quantiles, scheme, direction, color, nnames, lnames, admat=None):
    """
    Bar plots of nodes' link usage of links at different levels.
    """
    if not admat:
        admat = np.genfromtxt('./settings/eadmat.txt')
    if color == 'solar':
        cmap = Oranges_cmap
    elif color == 'wind':
        cmap = Blues_cmap
    elif color == 'backup':
        cmap = 'Greys'
    nodes, links = usages.shape
    usageLevels = np.zeros((nodes, levels))
    usageLevelsNorm = np.zeros((nodes, levels))
    for node in range(nodes):
        nl = neighbor_levels(node, levels, admat)
        for lvl in range(levels):
            ll = link_level(nl, lvl, nnames, lnames)
            ll = np.array(ll, dtype='int')
            usageSum = sum(usages[node, ll])
            linkSum = sum(quantiles[ll])
            usageLevels[node, lvl] = usageSum / linkSum
            if lvl == 0:
                usageLevelsNorm[node, lvl] = usageSum
            else:
                usageLevelsNorm[node, lvl] = usageSum / usageLevelsNorm[node, 0]
        usageLevelsNorm[:, 0] = 1

    # plot all nodes
    usages = usageLevels.transpose()
    plt.figure(figsize=(11, 3))
    ax = plt.subplot()
    plt.pcolormesh(usages[:, loadOrder], cmap=cmap)
    plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11)
    ax.set_yticks(np.linspace(.5, levels - .5, levels))
    ax.set_yticklabels(range(1, levels + 1))
    ax.yaxis.set_tick_params(width=0)
    ax.xaxis.set_tick_params(width=0)
    ax.set_xticks(np.linspace(1, nodes, nodes))
    ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10)
    plt.ylabel('Link level')
    plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total' + '_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight')
    plt.close()

    # plot all nodes normalised to usage of first level
    usages = usageLevelsNorm.transpose()
    plt.figure(figsize=(11, 3))
    ax = plt.subplot()
    plt.pcolormesh(usages[:, loadOrder], cmap=cmap)
    plt.colorbar().set_label(label=r'$U_n^{(l)}$', size=11)
    ax.set_yticks(np.linspace(.5, levels - .5, levels))
    ax.set_yticklabels(range(1, levels + 1))
    ax.yaxis.set_tick_params(width=0)
    ax.xaxis.set_tick_params(width=0)
    ax.set_xticks(np.linspace(1, nodes, nodes))
    ax.set_xticklabels(loadNames, rotation=60, ha="right", va="top", fontsize=10)
    plt.ylabel('Link level')
    plt.savefig(figPath + '/levels/' + str(scheme) + '/' + 'total_norm_cont_' + str(direction) + '_' + color + '.pdf', bbox_inches='tight')
    plt.close()
Beispiel #21
0
    def plot3setYspan(self, figNum, yspan=None):
        plt.figure(figNum)

        if yspan is None:
            return

        if not figNum in self.sharex.keys():
            self.sharex[figNum] = plt.subplot(3, 1, 1)

        # Plot 1
        subplt = plt.subplot(3, 1, 1, sharex=self.sharex[figNum])
        yl = subplt.get_ylim()
        med = (yl[1] - yl[0]) * 0.5 + yl[0]
        yl = [med - yspan * 0.5, med + yspan * 0.5]
        subplt.set_ylim(yl)

        # Plot 2
        subplt = plt.subplot(3, 1, 2, sharex=self.sharex[figNum])
        yl = subplt.get_ylim()
        med = (yl[1] - yl[0]) * 0.5 + yl[0]
        yl = [med - yspan * 0.5, med + yspan * 0.5]
        subplt.set_ylim(yl)

        # Plot 3
        subplt = plt.subplot(3, 1, 3, sharex=self.sharex[figNum])
        yl = subplt.get_ylim()
        med = (yl[1] - yl[0]) * 0.5 + yl[0]
        yl = [med - yspan * 0.5, med + yspan * 0.5]
        subplt.set_ylim(yl)
Beispiel #22
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 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 #24
0
    def generate_start_time_figures(self):
        recording_time_grouped_by_patient = self.pain_data[["PatientID", "NRSTimeFromEndSurgery_mins"]].groupby("PatientID")
        recording_start_minutes = recording_time_grouped_by_patient.min()

        fig1 = "fig1.pdf"
        fig2 = "fig2.pdf"

        plt.figure(figsize=[8,4])
        plt.title("Pain score recording start times", fontsize=14).set_y(1.05) 
        plt.ylabel("Occurrences", fontsize=14)
        plt.xlabel("Recording Start Time (minutes)", fontsize=14)
        plt.hist(recording_start_minutes.values, bins=20, color="0.5")
        plt.savefig(os.path.join(self.tmp_directory, fig1), bbox_inches="tight")

        plt.figure(figsize=[8,4])
        plt.title("Pain score recording start times, log scale", fontsize=14).set_y(1.05) 
        plt.ylabel("Occurrences", fontsize=14)
        plt.xlabel("Recording Start Time (minutes)", fontsize=14)
        plt.hist(recording_start_minutes.values, bins=20, log=True, color="0.5")
        plt.savefig(os.path.join(self.tmp_directory, fig2), bbox_inches="tight")

        #save the figures in panel format
        f = open(os.path.join(self.tmp_directory, "tmp.tex"), 'w')
        f.write(r"""
            \documentclass[%
            ,float=false % this is the new default and can be left away.
            ,preview=true
            ,class=scrartcl
            ,fontsize=20pt
            ]{standalone}
            \usepackage[active,tightpage]{preview}
            \usepackage{varwidth}
            \usepackage{graphicx}
            \usepackage[justification=centering]{caption}
            \usepackage{subcaption}
            \usepackage[caption=false,font=footnotesize]{subfig}
            \renewcommand{\thesubfigure}{\Alph{subfigure}}
            \begin{document}
            \begin{preview}
            \begin{figure}[h]
                \begin{subfigure}{0.5\textwidth}
                        \includegraphics[width=\textwidth]{""" + fig1 + r"""}
                        \caption{Normal scale}
                \end{subfigure}\begin{subfigure}{0.5\textwidth}
                        \includegraphics[width=\textwidth]{""" + fig2 + r"""}
                        \caption{Log scale}
                \end{subfigure}
            \end{figure}
            \end{preview}
            \end{document}
        """)
        f.close()
        subprocess.call(["pdflatex", 
                            "-halt-on-error", 
                            "-output-directory", 
                            self.tmp_directory, 
                            os.path.join(self.tmp_directory, "tmp.tex")])
        shutil.move(os.path.join(self.tmp_directory, "tmp.pdf"), 
                    os.path.join(self.output_directory, "pain_score_start_times.pdf"))
Beispiel #25
0
 def plot_charts(self):
     print(self.final_portfolio_valuation)
     plt.figure(figsize=(10, 6))
     plt.hist( self.final_portfolio_valuation, bins=100)
     plt.title("Final Exit Valuation complete Portfolio after {} year as Geometric Brownian Motion".format(self.max_year))
     plt.xlabel('Exit Valuation')
     plt.ylabel('frequency');
     plt.show()
Beispiel #26
0
    def plot(self, new_plot=False, xlim=None, ylim=None, title=None, figsize=None,
             xlabel=None, ylabel=None, fontsize=None, show_legend=True, grid=True):
        """
        Plot data using matplotlib library. Use show() method for matplotlib to see result or ::

            %pylab inline

        in IPython to see plot as cell output.

        :param bool new_plot: create or not new figure
        :param xlim: x-axis range
        :param ylim: y-axis range
        :type xlim: None or tuple(x_min, x_max)
        :type ylim: None or tuple(y_min, y_max)
        :param title: title
        :type title: None or str
        :param figsize: figure size
        :type figsize: None or tuple(weight, height)
        :param xlabel: x-axis name
        :type xlabel: None or str
        :param ylabel: y-axis name
        :type ylabel: None or str
        :param fontsize: font size
        :type fontsize: None or int
        :param bool show_legend: show or not labels for plots
        :param bool grid: show grid or not

        """
        xlabel = self.xlabel if xlabel is None else xlabel
        ylabel = self.ylabel if ylabel is None else ylabel
        figsize = self.figsize if figsize is None else figsize
        fontsize = self.fontsize if fontsize is None else fontsize
        self.fontsize_ = fontsize
        self.show_legend_ = show_legend
        title = self.title if title is None else title
        xlim = self.xlim if xlim is None else xlim
        ylim = self.ylim if ylim is None else ylim
        new_plot = self.new_plot or new_plot

        if new_plot:
            plt.figure(figsize=figsize)

        plt.xlabel(xlabel, fontsize=fontsize)
        plt.ylabel(ylabel, fontsize=fontsize)
        plt.title(title, fontsize=fontsize)
        plt.tick_params(axis='both', labelsize=fontsize)
        plt.grid(grid)

        if xlim is not None:
            plt.xlim(xlim)

        if ylim is not None:
            plt.ylim(ylim)

        self._plot()

        if show_legend:
            plt.legend(loc='best', scatterpoints=1)
Beispiel #27
0
def create_plot(x, y, styles, labels, axlabels):
    plt.figure(figsize=(10, 6))

    plt.scatter(x[0], y[0])
    plt.scatter(x[1], y[1])
    plt.xlabel(axlabels[0])
    plt.ylabel(axlabels[1])
    plt.legend(loc=0)
    plt.show()
def displayRetireWRate(month, rates, terms):
    plt.figure('retireRate')
    plt.clf()
    for rate in rates:
        xvals, yvals = retire(month, rate, terms)
        plt.plot(xvals,
                 yvals,
                 label='monthly: ' + str(month) + ' rate of:     ' +
                 str(int(rate * 100)))
        plt.legend(loc='upper left')
Beispiel #29
0
def convert_all_to_png(vis_path, out_dir="maps_png", size=None):

    units = {
        'gas_density': 'Gas Density [g/cm$^3$]',
        'Tm': 'Temperature [K]',
        'Tew': 'Temperature [K]',
        'S': 'Entropy []',
        'dm': 'DM Density [g/cm$^3$]',
        'v': 'Velocity [km/s]'
    }

    log_list = ['gas_density']

    for vis_file in os.listdir(vis_path):
        if ".dat" not in vis_file:
            continue
        print "converting %s" % vis_file
        map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1)

        (image, pixel_size,
         axis_values) = read_visualization_data(vis_path + "/" + vis_file,
                                                size)
        print "image width in Mpc/h: ", axis_values[-1] * 2.0

        x, y = np.meshgrid(axis_values, axis_values)

        cmap_max = image.max()
        cmap_min = image.min()
        ''' plotting '''
        plt.figure(figsize=(5, 4))

        if map_type in log_list:
            plt.pcolor(x, y, image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min))
        else:
            plt.pcolor(x, y, image, vmax=cmap_max, vmin=cmap_min)

        cbar = plt.colorbar()
        if map_type in units.keys():
            cbar.ax.set_ylabel(units[map_type])

        plt.axis(
            [axis_values[0], axis_values[-1], axis_values[0], axis_values[-1]])

        del image

        plt.xlabel(r"$Mpc/h$", fontsize=18)
        plt.ylabel(r"$Mpc/h$", fontsize=18)

        out_file = vis_file.replace("dat", "png")

        plt.savefig(out_dir + "/" + out_file, dpi=150)

        plt.close()
        plt.clf()
def displayRetireWMonthlies(monthlies, rate, terms):
    plt.figure('retireMonth')
    plt.clf()
    for monthly in monthlies:
        xvals, yvals = retire(
            monthly, rate,
            terms)  # using base and savings list as x and y values
        plt.plot(xvals,
                 yvals,
                 label='retire with monthly inst of ' + str(monthly))
        plt.legend()
Beispiel #31
0
    def detect(self, img):
        bboxes = None

        # pnet
        if not self.pnet:
            return None
        bboxes = self.detect_pnet(img)

        if bboxes is None:
            return None

        ## 可视化PNET的结果
        if SHOW_FIGURE:
            plt.figure()
            tmp = img.copy()
            for i in bboxes:
                x0 = int(i[0])
                y0 = int(i[1])
                x1 = x0 + int(i[2])
                y1 = y0 + int(i[3])
                cv2.rectangle(tmp, (x0, y0), (x1, y1), (0, 0, 255), 2)
            plt.imshow(tmp[:, :, ::-1])
            plt.title("pnet result")

        # rnet
        if not self.rnet:
            return bboxes
        bboxes = bboxes[:, 0:4].astype(np.int32)
        bboxes = self.detect_ronet(img, bboxes, 24)

        if bboxes is None:
            return None

        ## 可视化RNET的结果
        if SHOW_FIGURE:
            plt.figure()
            tmp = img.copy()
            for i in bboxes:
                x0 = int(i[0])
                y0 = int(i[1])
                x1 = x0 + int(i[2])
                y1 = y0 + int(i[3])
                cv2.rectangle(tmp, (x0, y0), (x1, y1), (0, 0, 255), 2)
            plt.imshow(tmp[:, :, ::-1])
            plt.title("rnet result")

        #onet
        if not self.onet:
            return bboxes
        bboxes = bboxes[:, 0:4].astype(np.int32)
        bboxes = self.detect_ronet(img, bboxes, 48)

        return bboxes
Beispiel #32
0
def plot_treward(agent):
    ''' Function to plot the total reward
        per training eposiode.
    '''
    plt.figure(figsize=(10, 6))
    x = range(1, len(agent.averages) + 1)
    y = np.polyval(np.polyfit(x, agent.averages, deg=3), x)
    plt.plot(x, agent.averages, label='moving average')
    plt.plot(x, y, 'r--', label='regression')
    plt.xlabel('episodes')
    plt.ylabel('total reward')
    plt.legend()
def displayRetireWMonthsandRates(monthlies, rates, terms):
    plt.figure('retire both')
    plt.clf()
    plt.xlim(30 * 12,
             40 * 12)  # focusing only on the last 10 years of investment
    for monthly in monthlies:
        for rate in rates:
            xvals, yvals = retire(monthly, rate, terms)
            plt.plot(xvals,
                     yvals,
                     label='retire with ' + str(monthly) + ":" +
                     str(int(rate * 100)))
            plt.legend(loc='upper left')
Beispiel #34
0
def convert_all_to_png(vis_path, out_dir = "maps_png", size = None) :

    units = { 'gas_density' : 'Gas Density [g/cm$^3$]',
              'Tm' : 'Temperature [K]',
              'Tew' : 'Temperature [K]',
              'S' : 'Entropy []',
              'dm' : 'DM Density [g/cm$^3$]',
              'v' : 'Velocity [km/s]' }

    log_list = ['gas_density']

    for vis_file in os.listdir(vis_path) :
        if ".dat" not in vis_file :
            continue
        print "converting %s" % vis_file
        map_type = re.search('sigma_(.*)_[xyz]', vis_file).group(1)

        (image, pixel_size, axis_values) = read_visualization_data(vis_path+"/"+vis_file, size)
        print "image width in Mpc/h: ", axis_values[-1]*2.0

        x, y = np.meshgrid( axis_values, axis_values )

        cmap_max = image.max()
        cmap_min = image.min()


        ''' plotting '''
        plt.figure(figsize=(5,4))

        if map_type in log_list:
            plt.pcolor(x,y,image, norm=LogNorm(vmax=cmap_max, vmin=cmap_min))
        else :
            plt.pcolor(x,y,image, vmax=cmap_max, vmin=cmap_min)

        cbar = plt.colorbar()
        if map_type in units.keys() :
            cbar.ax.set_ylabel(units[map_type])

        plt.axis([axis_values[0], axis_values[-1],axis_values[0], axis_values[-1]])

        del image

        plt.xlabel(r"$Mpc/h$", fontsize=18)
        plt.ylabel(r"$Mpc/h$", fontsize=18)

        out_file = vis_file.replace("dat", "png")

        plt.savefig(out_dir+"/"+out_file, dpi=150 )

        plt.close()
        plt.clf()
def draw_spectrum(data_list):
    T = 3600

    amp_spec, power_spec, freq = spectrum(data_list, T)

    print('Max amp in spectrum: {np.max(amp_spec)}')
    plt.figure(figsize=(18, 5))

    plt.subplot(131)
    x = list(range(len(data_list)))
    y = data_list
    plt.title("Observation wind data of Kyoto")
    plt.xlabel('Hours')
    plt.ylabel('Observation wind data of Kyoto')
    plt.plot(x, y, color='green')

    data_len = len(x)

    plt.subplot(132)
    plt.title("Power Spectrum of Wind ")
    x = freq[int(data_len / 2):]
    y = power_spec[int(data_len / 2):]

    # set 0 to 0Hz (DC component)
    y[0] = 0

    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Intensity')
    plt.plot(x, y, color='orange')
    ax = plt.gca()

    x = x[1:]
    y = y[1:]

    ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
    coeffs = np.polyfit(np.log(x), np.log(y), 1)
    beta = -coeffs[0]
    dimension = 1 + (3 - beta) / 2
    print(beta)
    print("The fractal dimension is", dimension)

    plt.subplot(133)
    plt.title("the Curve of log(power-spectrum) and log(frequency)")
    plt.scatter(np.log(x), np.log(y), marker='o', s=10, c=list(range(len(x))))
    # plt.plot(np.log(x), np.log(y), 'o', mfc='none')
    plt.plot(np.log(x), np.polyval(coeffs, np.log(x)))
    plt.xlabel('log freq')
    plt.ylabel('log intensity')
    plt.savefig("../pics/kyoto_wind.png")

    plt.show()
Beispiel #36
0
def drawAdoptionNetworkMPL(G, fnum=1, show=False, writeFile=None):
    """Draws the network to matplotlib, coloring the nodes based on adoption. 
    Looks for the node attribute 'adopted'. If the attribute is True, colors 
    the node a different color, showing adoption visually. This function assumes
    that the node attributes have been pre-populated.
    
    :param networkx.Graph G: Any NetworkX Graph object.
    :param int fnum: The matplotlib figure number. Defaults to 1.
    :param bool show: 
    :param str writeFile: A filename/path to save the figure image. If not
                             specified, no output file is written.
    """
    Gclean = G.subgraph([n for n in G.nodes() if n not in nx.isolates(G)])
    plt.figure(num=fnum, figsize=(6,6))
    # clear figure
    plt.clf()
    
    # Blue ('b') node color for adopters, red ('r') for non-adopters. 
    nodecolors = ['b' if Gclean.node[n]['adopted'] else 'r' \
                  for n in Gclean.nodes()]
    layout = nx.spring_layout(Gclean)
    nx.draw_networkx_nodes(Gclean, layout, node_size=80, 
                           nodelist=Gclean.nodes(), 
                           node_color=nodecolors)
    nx.draw_networkx_edges(Gclean, layout, alpha=0.5) # width=4
    
    # TODO: Draw labels of Ii values. Maybe vary size of node.
    # TODO: Color edges blue based on influences from neighbors
    
    influenceEdges = []
    for a in Gclean.nodes():
        for n in Gclean.node[a]['influence']:
            influenceEdges.append((a,n))
    
    if len(influenceEdges)>0:
        nx.draw_networkx_edges(Gclean, layout, alpha=0.5, width=5,
                               edgelist=influenceEdges,
                               edge_color=['b']*len(influenceEdges))
    
    #some extra space around figure
    plt.xlim(-0.05,1.05)
    plt.ylim(-0.05,1.05)
    plt.axis('off')
    
    if writeFile != None:
        plt.savefig(writeFile)
    
    if show:
        plt.show()
Beispiel #37
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 #38
0
def main():
    s = 2.0
    img = imread('cameraman.png')

    # Create all the images with each a differen order of convolution
    img1 = gD(img, s, 0, 0)
    img2 = gD(img, s, 1, 0)
    img3 = gD(img, s, 0, 1)
    img4 = gD(img, s, 2, 0)
    img5 = gD(img, s, 0, 2)
    img6 = gD(img, s, 1, 1)

    fig = plt.figure()
    ax1 = fig.add_subplot(2, 3, 1)
    ax1.set_title("Fzero")
    ax1.imshow(img1, cmap=cm.gray)
    ax2 = fig.add_subplot(2, 3, 2)
    ax2.set_title("Fx")
    ax2.imshow(img2, cmap=cm.gray)
    ax3 = fig.add_subplot(2, 3, 3)
    ax3.set_title("Fy")
    ax3.imshow(img3, cmap=cm.gray)
    ax4 = fig.add_subplot(2, 3, 4)
    ax4.set_title("Fxx")
    ax4.imshow(img4, cmap=cm.gray)
    ax5 = fig.add_subplot(2, 3, 5)
    ax5.set_title("Fyy")
    ax5.imshow(img5, cmap=cm.gray)
    ax6 = fig.add_subplot(2, 3, 6)
    ax6.set_title("Fxy")
    ax6.imshow(img6, cmap=cm.gray)
    show()
Beispiel #39
0
def createCoreDiffusionPlot(experimentCaseLog, outFilePath, plotTitle=None):
    """Function to generate the Core Diffusion vs Peripheral Density
    plot. (Basically a clone of `createPeripheralDiffusionPlot`)
    """
    # Generate plot of Core Diffusion vs. Nx density beyond the core
    # x axis: pties/total possible ties
    # y axis: # core adopters / # core nodes
    
    mc = marker_cycle()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    for Ai in experimentCaseLog.keys():
        # x axis is peripheral density, y axis is the core diffusion
        x,y = experimentCaseLog[Ai][0], experimentCaseLog[Ai][2]
        ax.plot(x,y, label="Ambiguity=%d"%Ai, marker=mc.next())
    
    ax.set_xlabel("Network Density Beyond the Core")
    ax.set_ylabel("Core Diffusion")
    ax.legend(loc="best")
    if plotTitle == None:
        ax.set_title("Extent of Core Diffusion for Varying Ambiguity "
                     "and Network Density")
    else:
        ax.set_title(plotTitle)
    
    outPlotFilename = "Plot-CoreDiffusionVsDensity.png"
    fig.savefig(pathjoin(outFilePath, outPlotFilename))
def render_confusion(file_name, queue, vmin, vmax, divergent, array_shape):
    from pylab import plt
    import matplotlib.animation as animation
    plt.close()
    fig = plt.figure()

    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

    ani = animation.FuncAnimation(fig, update_img, frames=IterableQueue(queue))

    ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
Beispiel #41
0
    def initWidgets(self):
        self.fig = plt.figure(1)
        self.img = subplot(111)
        self.manager=get_current_fig_manager()
        self.img = subplot(2,1,2)
        self.TempGraph=subplot(2,1,1)






        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_=100,orient=tk.HORIZONTAL)
        self.sclPower.grid(row=row,column=1,columnspan=3)

        row=row+1
        self.lblTime=tk.Label(self,text="Time={0}".format(self.time))
        self.lblTime.grid(row=row,column=0)

        #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 #42
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')
def show_prediction_result(image, label_image, clf):
    size = (8, 8)
    plt.figure(figsize=(15, 10))
    plt.imshow(image, cmap='gray_r')
    candidates = []
    predictions = []
    for region in regionprops(label_image):
        # skip small images
        #     if region.area < 100:
        #         continue
        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region.bbox
        # make regions square
        maxwidth = np.max([maxr - minr, maxc - minc])
        minr, maxr = int(0.5 * ((maxr + minr) - maxwidth)) - 3, int(0.5 * ((maxr + minr) + maxwidth)) + 3
        minc, maxc = int(0.5 * ((maxc + minc) - maxwidth)) - 3, int(0.5 * ((maxc + minc) + maxwidth)) + 3
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2, alpha=0.2)
        plt.gca().add_patch(rect)
        # predict digit
        candidate = image[minr:maxr, minc:maxc]
        candidate = np.array(imresize(candidate, size), dtype=float)
        # invert
        # candidate = np.max(candidate) - candidate
        #     print im
        # rescale to 16 in integer
        candidate = (candidate - np.min(candidate))
        if np.max(candidate) == 0:
            continue
        candidate /= np.max(candidate)
        candidate[candidate < 0.2] = 0.0
        candidate *= 16
        candidate = np.array(candidate, dtype=int)
        prediction = clf.predict(candidate.reshape(-1))
        candidates.append(candidate)
        predictions.append(prediction)
        plt.text(minc - 10, minr - 10, "{}".format(prediction), fontsize=50)
    plt.xticks([], [])
    plt.yticks([], [])
    plt.tight_layout()
    plt.show()
    return candidates, predictions
def plotScale(imgFile, minVal, maxVal):
	imgSize = (2, 4)
	fig = plt.figure(figsize=imgSize, dpi=100, frameon=True, facecolor='w')
	for i in xrange(10):
		val = minVal + i * (maxVal - minVal) / 10
		col = getColor(val, minVal, maxVal)
		X = [float(i) / 10, float(i + 1) / 10, float(i + 1) / 10, float(i) / 10, float(i) / 10]
		Y = [1, 1, 0, 0, 1]
		fill(X, Y, col, lw=1, ec=col)
	savefig(imgFile)
	close()
Beispiel #45
0
def plot_wireframe(df, ax=None, *args, **kwargs):
    if ax is None:
        fig = plt.figure()
        ax = Axes3D(fig)

    res = _3d_values(df)
    X, Y, Z = res['values']
    x_name, y_name = res['labels']

    ax.plot_wireframe(X, Y, Z, *args, **kwargs)
    ax.set_xlabel(x_name)
    ax.set_ylabel(y_name)
    return ax
Beispiel #46
0
def main(args=sys.argv[1:]):
    # there are some cases when this script is run on systems without DISPLAY variable being set
    # in such case matplotlib backend has to be explicitly specified
    # we do it here and not in the top of the file, as inteleaving imports with code lines is discouraged
    import matplotlib
    matplotlib.use('Agg')
    from pylab import plt, ylabel, grid, xlabel, array

    parser = argparse.ArgumentParser()
    parser.add_argument("rst_file", help="location of rst file in TRiP98 format", type=str)
    parser.add_argument("output_file", help="location of PNG file to save", type=str)
    parser.add_argument("-s", "--submachine", help="Select submachine to plot.", type=int, default=1)
    parser.add_argument("-f", "--factor", help="Factor for scaling the blobs. Default is 1000.", type=int, default=1000)
    parser.add_argument("-v", "--verbosity", action='count', help="increase output verbosity", default=0)
    parser.add_argument('-V', '--version', action='version', version=pt.__version__)
    args = parser.parse_args(args)

    file = args.rst_file
    sm = args.submachine
    fac = args.factor

    a = pt.Rst()
    a.read(file)

    # convert data in submachine to a nice array
    b = a.machines[sm]

    x = []
    y = []
    z = []
    for _x, _y, _z in b.raster_points:
        x.append(_x)
        y.append(_y)
        z.append(_z)

    title = "Submachine: {:d} / {:d} - Energy: {:.3f} MeV/u".format(sm, len(a.machines), b.energy)
    print(title)
    cc = array(z)

    cc = cc / cc.max() * fac

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(x, y, c=cc, s=cc, alpha=0.75)
    ylabel("mm")
    xlabel("mm")
    grid(True)
    plt.title(title)
    plt.savefig(args.output_file)
    plt.close()
Beispiel #47
0
def my_2D_plot_of_arrays(xa, ya, title, xlabel, ylabel,  *add_graphs):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    lines=ax.plot(xa, ya, 'b-o',  markersize=2, color="green")

    line = lines[0]
    
    line.set_linewidth( 1.5 )
    line.set_color( 'green' )
    line.set_linestyle( '-' )
    line.set_marker('s')
    line.set_markerfacecolor('red')
    line.set_markeredgecolor( '0.1' ) 
    line.set_markersize( 3 ) 
    
    ## format the ticks
    adl = mdates.AutoDateLocator()
    ax.xaxis.set_major_locator(adl)
    myformatter = MyAutoDateFormatter(adl)
    #myformatter = mdates.AutoDateFormatter(adl)
    ax.xaxis.set_major_formatter(myformatter)
    
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    labels = getp(ax, 'xticklabels')
    setp(labels, color='g', fontsize=9, fontname="Verdana" )
    labels = getp(ax, 'yticklabels')
    setp(labels, color='g', fontsize=9, fontname="Verdana" )
    
    
    ax.grid(True)
    fig.autofmt_xdate(bottom=0.18,  rotation=60)
    
    min_y=min(ya)
    max_y=max(ya)
    if (min_y<0) and (max_y >0):
        ax.axhline(0, color='r', lw=4, alpha=0.5)
        ax.fill_between(xa, ya, facecolor='red',  alpha=0.5, interpolate=True)

    #plot additional graphs
    if len(add_graphs):
        draw_add_2D_plot_of_arrays(add_graphs, ax)
        
    plt.show()
Beispiel #48
0
 def start_plot(self,w=1.3,connect=False):
     self.fig=plt.figure()
     self.ax=plt.axes()
     plt.axhline(y=0,color='grey', zorder=-1)
     plt.axvline(x=0,color='grey', zorder=-2)
     self.plot_data(connect=connect)
     #plt.axis('equal')
     self.ax.set_aspect('equal', 'datalim')
     if self.center is not None:
         cx,cy=self.center.real,self.center.imag; r=self.radius
         self.ax.axis([cx-w*r,cx+w*r,cy-w*r,cy+w*r])
     else:
         xmx=amax(self.x); ymn,ymx=amin(self.y),amax(self.y)
         cx=0.5*xmx; cy=0.5*(ymn+ymx); r=0.5*(ymx-ymn)
         self.ax.axis([cx-w*r,cx+w*r,cy-w*r,cy+w*r])
     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')
Beispiel #49
0
def draw_tag_volume(labels, volumes, levels=None, xlabel="tag", ylabel="UAX", title="Expenses grouped by tags."):
  '''
    - It draws a graph tag/volume.

    @testable = false
  '''
  all_colors = 'rgbkymc';
  fig = plt.figure(figsize=(15, 5), dpi=400)
  axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
  ticks = range(len(labels))
  axes.set_xticks(ticks)
  axes.set_xticklabels(labels, fontsize=8)
  if levels == None:
    colors = None
  else:
    colors = [ all_colors[level] for level in levels ]
  axes.bar(ticks, volumes, color=colors)
  axes.set_xlabel(xlabel)
  axes.set_ylabel(ylabel)
  axes.set_title(title);
def plotLive(combine_Type, combine_Name, lat_Name, long_Name, massFlow_Name, filename):
    data = pd.read_csv(filename)

    if combine_Type != 0:

        comb_df = data[data[combine_Name] == combine_Type]
        lat_df = comb_df[lat_Name]
        lon_df = comb_df[long_Name]
        y = comb_df[massFlow_Name]

    else:

        lat_df = data[lat_Name]
        lon_df = data[long_Name]
        y = data[massFlow_Name]

    e,n = convertToUTM(lat_df, lon_df)

    def makeFig():
        plt.plot(x,y)


    plt.ylabel('Easting')
    plt.xlabel('Northing')


    plt.ion() # enable interactivity
    plt.grid()
    fig = plt.figure() # make a figure

    x=list()
    y=list()

    for i in arange(len(n)):
        x.append(n[i])
        y.append(e[i])
        i+=1
        drawnow(makeFig)
Beispiel #51
0
    def get_parameters(self, case):
        
        parameters = case.keys(iotype = 'in', flatten = True)
        numParms = range(len(parameters))
        self.data = []
        place = []
        self.scaleList =  []
        for parm in numParms:
            self.data.append([])
        self.data.append([])
        
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title(self.title)
        self.ax.set_xlabel('Iterations')
        self.ax.set_ylabel('Value')
        self.ax.grid()
        self.fig.canvas.mpl_connect('pick_event', self.onpick)  
        
        output_keys = case.keys(iotype='out', flatten=True)        
        self.labels = case.keys(iotype='in', flatten=True)
        self.labels.append(output_keys[0])
        
        self.lineColors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', \
                      'b--', 'g--', 'r--', 'c--', 'm--', 'y--', 'k--', \
                      'b:', 'g:', 'r:', 'c:', 'm:', 'y:', 'k:']

        i = 0
        for line in self.data:
            self.ax.plot(place, self.data[i], self.lineColors[i], lw=2 )
            self.leg = self.ax.legend(self.labels, fancybox=True, shadow=True)
            self.leg.get_frame().set_alpha(0.6) 
            i += 1
            
        if self.logscale:
            plt.yscale('symlog')
def render_weights(file_name, queue, vmin, vmax, divergent, array_shape):
    from pylab import plt
    import matplotlib.animation as animation

    plotter = WeightsPlotter()
    fig = plt.figure(facecolor='gray', frameon=False)
    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.axis('off')


    if divergent:
        my_colormap = brewer2mpl.get_map('PiYG', 'diverging', 11).mpl_colormap
    else:
        my_colormap = brewer2mpl.get_map('OrRd', 'sequential', 9).mpl_colormap

    my_colormap.set_bad('#6ECFF6', 1.0)

    im = {}
    def update_img(array):
        array = plotter.plot_weights(array)
        if im.get('im', None) is None:
            im['im'] = ax.imshow(array, cmap=my_colormap, interpolation='nearest', vmin=vmin, vmax=vmax)
            aspect = array.shape[0] / float(array.shape[1])
            fig.set_size_inches([7.2, 7.2*aspect]) # 720 pixels wide, variable height
            fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
        im['im'].set_data(array)
        return im['im']

    #legend(loc=0)
    ani = animation.FuncAnimation(fig,update_img, frames=IterableQueue(queue))
    #writer = animation.writers['ffmpeg'](fps=30, bitrate=27*1024)

    ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
Beispiel #53
0
    del cpa_calcs
    print cpa_space
    
    cpa_covs = CpaCovs(cpa_space,scale_spatial=(1.0) * 10, scale_value=2,
                           left_blk_rel_scale=1,
                                        right_vec_scale=1)
    
    mu = cpa_space.get_zeros_theta()         
    Avees = cpa_space.theta2Avees(np.random.multivariate_normal(mean=mu,cov=cpa_covs.cpa_cov))             
    As=cpa_space.Avees2As(Avees)      
  
    cpa_space.update_pat(Avees)
     
    plt.close('all')
    if TF.plot:
        plt.figure()



    params_flow_int_ref = copy.deepcopy(params_flow_int)
    
    N = int(params_flow_int_ref.nTimeSteps) * 1
    
    # in general, this doesn't have to evenly spaced. Just in the right range.
    x_dense=cpa_space.get_x_dense(nPts=1000) 
    # This needs to be evenly spaced. 
    interval = np.linspace(-3,3,x_dense.size)
    
    
    Nvals = range(N)    
    Nvals=Nvals[-1:]
Beispiel #54
0
print 'int_data_domain = ', int_data_domain
print 'int_data =',[round( int_data[g], 3 ) for g in range(len(int_data))]

#create lisets for the the vel and acc data
vel_data = [(int_data[i+1]-int_data[i])/h for i in range(len(int_data)-1)]
print 'vel_data = ',vel_data
acc_data = [(vel_data[i+1]-vel_data[i])/h for i in range(len(vel_data)-1)]
print 'acc_data =',acc_data


acc_domain = int_data_domain[1:-1]

#import matplotlib.gridspec as gridspec
#gs = gridspec.GridSpec(1,3)

fig = plt.figure()

x_plot = fig.add_subplot(111)#gs[0,0])#----------------------linear displacements
plt.plot(int_data_domain, int_data, 'bo', wpt_domain, wpt, 'ro',acc_domain,acc_data)
title('interpolated data',fontsize=10)
'''
dx_plot = fig.add_subplot(gs[0,1])
plt.plot(int_data_domain[:-1], vel_data)
title('velocity',fontsize=10)

ddx_plot = fig.add_subplot(gs[0,2])
plt.plot(int_data_domain[:-2],acc_data)
title('acceleration',fontsize=10)
'''
show()
#==================================================================================
Beispiel #55
0
        xx = xx.astype(np.float)
        yy = yy.astype(np.float)
       
        dimx = float(dimx)
        dimy=float(dimy)        
        nTimesInX = np.floor(xx / M).max() + 1
 
        seg_cpu = np.floor(yy / M)  * nTimesInX + np.floor(xx / M)
        seg_cpu = seg_cpu.astype(np.int32)
        return seg_cpu


def random_permute_seg(seg):
    p=np.random.permutation(seg.max()+1)   
    seg2 = np.zeros_like(seg)
    for c in range(seg.max()+1):             
        seg2[seg==c]=p[c]
    return seg2.astype(np.int32)


if __name__ == "__main__":  
    tic = time.clock()
    seg= get_init_seg(500, 500,17,True)      
#    seg= get_init_seg(512, 512,50,False)  
    toc = time.clock()
    print toc-tic 
    print 'k = ', seg.max()+1
    plt.figure(1)
    plt.clf()  
    plt.imshow(seg,interpolation="Nearest")
    plt.axis('scaled') 
    # Create some increasing function
    y = cdf_1d_gaussian(x,mu=-4,sigma=1)  
    y *=0.3
    y += 0.7*cdf_1d_gaussian(x,mu=4,sigma=2)    
    y *=10     
    y +=3
    
    range_start=y.min()
    range_end=y.max()
    
    # Add noise
    y += 0.4*np.random.standard_normal(y.shape)
    
    
    if 1:
        plt.figure(0)
        of.plt.set_figure_size_and_location(1000,0,1000,500)
        plt.clf()
        plt.subplot(121)
        plt.cla()
        plt.plot(x,y,'.',lw=3)
        plt.title('data')
        ax = plt.gca()
        ax.tick_params(axis='y', labelsize=50)
        ax.tick_params(axis='x', labelsize=30)
        
         
    
     

    
Beispiel #57
0
def plot_variable(u, name, direc, cmap=cmaps.parula, scale='lin', numLvls=100,
                  umin=None, umax=None, \
                  tp=False, \
                  tpAlpha=1.0, show=False,
                  hide_ax_tick_labels=False, label_axes=True, title='',
                  use_colorbar=True, hide_axis=False, colorbar_loc='right'):
  """
    show -- whether to show the plot on the screen 
    tp -- show triangle
    cmap -- colors:
      gist_yarg - grey 
      gnuplot, hsv, gist_ncar
      jet - typical colors
  """
  mesh = u.function_space().mesh()
  v    = u.compute_vertex_values(mesh)
  x    = mesh.coordinates()[:,0]
  y    = mesh.coordinates()[:,1]
  t    = mesh.cells()
  

  if not os.path.isdir( direc ): 
      os.makedirs(direc)
 
  full_path = os.path.join(direc, name)

  if umin != None:
    vmin = umin
  else:
    vmin = v.min()
  if umax != None:
    vmax = umax
  else:
    vmax = v.max()

  # countour levels :
  if scale == 'log':
    v[v < vmin] = vmin + 1e-12
    v[v > vmax] = vmax - 1e-12
    from matplotlib.ticker import LogFormatter
    levels      = np.logspace(np.log10(vmin), np.log10(vmax), numLvls)
    
    tick_numLvls = min( numLvls, 8 )
    tick_levels = np.logspace(np.log10(vmin), np.log10(vmax), tick_numLvls)
    
    formatter   = LogFormatter(10, labelOnlyBase=False)
    norm        = colors.LogNorm()

  elif scale == 'lin':
    v[v < vmin] = vmin + 1e-12
    v[v > vmax] = vmax - 1e-12
    from matplotlib.ticker import ScalarFormatter
    levels    = np.linspace(vmin, vmax, numLvls)
    
    tick_numLvls = min( numLvls, 8 )
    tick_levels = np.linspace(vmin, vmax, tick_numLvls)
    
    formatter = ScalarFormatter()
    norm      = None

  elif scale == 'bool':
    from matplotlib.ticker import ScalarFormatter
    levels    = [0, 1, 2]
    formatter = ScalarFormatter()
    norm      = None

  fig = plt.figure(figsize=(5,5))
  ax  = fig.add_subplot(111)

  c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm,
                     cmap=plt.get_cmap(cmap))
  plt.axis('equal')

  if tp == True:
    p = ax.triplot(x, y, t, '-', lw=0.2, alpha=tpAlpha)
  ax.set_xlim([x.min(), x.max()])
  ax.set_ylim([y.min(), y.max()])
  if label_axes:
    ax.set_xlabel(r'$x$')
    ax.set_ylabel(r'$y$')
  if hide_ax_tick_labels:
    ax.set_xticklabels([])
    ax.set_yticklabels([])
  if hide_axis:
    plt.axis('off')

  # include colorbar :
  if scale != 'bool' and use_colorbar:
    divider = make_axes_locatable(plt.gca())
    cax  = divider.append_axes(colorbar_loc, "5%", pad="3%")
    cbar = plt.colorbar(c, cax=cax, format=formatter,
                        ticks=tick_levels)
    tit = plt.title(title)

  if use_colorbar:
    plt.tight_layout(rect=[.03,.03,0.97,0.97])
  else:
    plt.tight_layout()
  plt.savefig( full_path + '.eps', dpi=300)
  if show:
    plt.show()
  plt.close(fig)
Beispiel #58
0
def plot_const(u, name , direc): 

   if not os.path.isdir( direc ): 
      os.makedirs(direc)
 
   full_path = os.path.join(direc, name)
   full_mesh = os.path.join(direc, 'mesh.svg')
   
   mesh = u.function_space().mesh() 
   v    = u.compute_vertex_values(mesh)
   x    = mesh.coordinates()[:,0]
   y    = mesh.coordinates()[:,1]
   t    = mesh.cells() 
   
   vmin = v.min()
   vmax = v.max() 
   
   v[v < vmin] = vmin + 1e-12
   v[v > vmax] = vmax - 1e-12
   numLvls=100
   from matplotlib.ticker import ScalarFormatter
   levels    = np.linspace(vmin, vmax, numLvls)
   
   tick_numLvls = min( numLvls, 8 )
   tick_levels = np.linspace(vmin, vmax, tick_numLvls)
    
   formatter = ScalarFormatter()
   norm      = None
   
   n = mesh.num_vertices()
   d = mesh.geometry().dim()

   # Create the triangulation
   mesh_coordinates = mesh.coordinates().reshape((n, d))
   triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
   triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                  mesh_coordinates[:, 1],
                                  triangles)

   # Plot the mesh
#   plt.figure()
#   plt.triplot(triangulation)
#   plt.savefig( full_mesh ) 

   
   
   # Plot of scalar field
   V = u.function_space() #FunctionSpace(mesh, 'CG', 2)
   #f_exp = Expression('sin(2*pi*(x[0]*x[0]+x[1]*x[1]))')
   #f = interpolate(f_exp, V)

   fig = plt.figure(figsize=(5,5))
   ax  = fig.add_subplot(111)

   # Get the z values for each vertex
   #   cmap = plt.cm.jet 
   
   cmap = cmaps.parula 
   c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm,
                     cmap=plt.get_cmap(cmap))
   
   plt.ioff()
   #fig = plt.figure()
   z = np.asarray([u(point) for point in mesh_coordinates])
   plt.tripcolor(triangulation, z, cmap=cmap)  # alt plt.tricontourf(...)
   plt.colorbar()
#   plt.savefig( full_path, bbox_inches='tight' )
   plt.savefig( full_path + '.eps', dpi=300)
   plt.close( fig )
def plotCircle(imgFile, label, centerColHex=rgb(255, 255, 255).tohex(), circleCols=[[rgb(200, 200, 200).tohex()]], innerRadTotal=0.2, outerRadTotal=0.5, width=5, tstep=0.01):
	"""Plot and save a circlePlot image using matplotlib module."""
	## image settings
	imgSize = (width, width)
	fig = plt.figure(figsize=imgSize, dpi=100, frameon=True, facecolor='w')
	axes([0, 0, 1, 1], frameon=True, axisbg='w')
	axis('off')
	circleWid = (outerRadTotal - innerRadTotal) / float(len(circleCols))

	## color center
	outerRadCenter = innerRadTotal
	outerRadCenter -= .01
	X = []
	Y = []
	x, y = polar(outerRadCenter, 0)
	X.append(x)
	Y.append(y)
	ti = 0
	while ti < 1:
		x, y = polar(outerRadCenter, ti)
		X.append(x)
		Y.append(y)
		ti += tstep
		if ti > 1:
			break
	x, y = polar(outerRadCenter, 1)
	X.append(x)
	Y.append(y)

	if centerColHex == None:
		# transparent center
		fill(X, Y, rgb(255, 255, 255).tohex(), lw=1, ec='none', fill=False)
	else:
		# color-filled center
		fill(X, Y, centerColHex, lw=1, ec=centerColHex)

	time0 = time()

	## color rings
	# this part is slow ~0.6 sec for one dataset (536 samples)
	for i in xrange(len(circleCols)):
		innerRadRing = (i * circleWid) + innerRadTotal
		outerRadRing = ((i + 1) * circleWid) + innerRadTotal - .01
		for j in xrange(len(circleCols[i])):
			t0 = float(j) / len(circleCols[i])
			t1 = float(j + 1) / len(circleCols[i])
			X = []
			Y = []
			x, y = polar(innerRadRing, t0)
			X.append(x)
			Y.append(y)
			ti = t0
			while ti < t1:
				x, y = polar(outerRadRing, ti)
				X.append(x)
				Y.append(y)
				ti += tstep
				if ti > t1:
					break
			x, y = polar(outerRadRing, t1)
			X.append(x)
			Y.append(y)
			ti = t1
			while ti > t0:
				x, y = polar(innerRadRing, ti)
				X.append(x)
				Y.append(y)
				ti -= tstep
				if ti < t0:
					break
			x, y = polar(innerRadRing, t0)
			X.append(x)
			Y.append(y)
			fill(X, Y, circleCols[i][j], lw=1, ec=circleCols[i][j])

#	log("%s to get ring colors\n" % (time() - time0))
	time0 = time()
	
	## save image
	text(0, 0, label, ha='center', va='center', size='xx-large')
	xlim(-0.5, 0.5)
	ylim(-0.5, 0.5)
	savefig(imgFile, transparent=True)
	close()

#	log("%s to savefig\n" % (time() - time0))
	time0 = time()