def prices_and_profits(pool_backup, fig_name=None, ax_price=None, ax_profit=None):

    # Create figure and axes if not given in args
    if ax_price is None or ax_profit is None:

        fig = plt.figure(figsize=(4, 5), dpi=200)

        n_rows = 2
        n_cols = 1

        ax_price = fig.add_subplot(n_rows, n_cols, 1)
        ax_profit = fig.add_subplot(n_rows, n_cols, 2)

    prices_over_fov(pool_backup, ax_price)
    profits_over_fov(pool_backup, ax_profit)

    if fig_name is not None:

        # Cut margins
        plt.tight_layout()

        # Create directories if not already existing
        os.makedirs(os.path.dirname(fig_name), exist_ok=True)

        # Save fig
        plt.savefig(fig_name)

        plt.close()
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
def plot_bw(ax, x, y, file_name, fig_folder):

    ax.scatter(x, y, facecolor="black", edgecolor='none', s=25, alpha=0.15)

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}_gray.pdf".format(fig_folder, file_name))

    plt.show()
Esempio n. 4
0
    def plot_macd(self):

        fig, ax = subplots(ncols=1, nrows=2, sharex=True)
        ax[0] = self._plot_m_line(ax[0])
        ax[1] = self._plot_macd(ax[1], label='')
        plt.tight_layout(h_pad=0)

        for _ax in ax:
            _ax.legend(loc='best')

        return fig
def plot_color(fig, ax, x, y, z, file_name, fig_folder):

    abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)
    fig.colorbar(abc, label="Profits")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}.pdf".format(fig_folder, file_name))

    plt.show()
def profit_firmA_against_profit_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)
    parameters = bkp.parameters

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = np.arange(parameters.t_max)
    y = np.zeros((2, parameters.t_max))

    for f in range(2):
        for t in range(parameters.t_max):
            y[f, t] = np.mean(bkp.profits[:t + 1, f] / profit_max)

        # y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        # y_err = np.array([np.std(for_y[i][t]) for t in range(parameters.t_max)])

    fig = plt.Figure()

    plt.plot(x, y[0], label="Firm A")
    plt.plot(x, y[1], label="Firm B")
    # plt.fill_between(x, y - (y_err / 2), y + (y_err / 2), color="C{}".format(i), alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("Evolution of profits over time ($r={}$)".format(
        bkp.field_of_view / 2))

    plt.tight_layout()

    plt.savefig("{}/{}_mean_profit.pdf".format(folder, file_name))

    plt.show()
def plot_baseline(data, plate_name, save_folder = r'Figures/'):
    """
    """
    colors = ((0.2, 0.2, 0.2),
              (0.5, 0.5, 0.5),
              (0.7, 0.7, 0.7),
              (0.3, 0.3, 0.3))

    names = data.keys()
    names.sort()
    fig, axs = plt.subplots(figsize=(8,3))
    for index, name in enumerate(names):
        for value in data[name]['original_data']:
            plot_color = colors[index % len(colors)]
            
            if abs(value - data[name]['mean'][0]) > data[name]['std'][0] * 2.0:
                axs.plot([value], [index], 'ko', markerfacecolor = [1,1,1])
            else:
                axs.plot([value], [index], 'ko', color = plot_color)

        axs.plot([data[name]['mean'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                  'k-')
        axs.plot([data[name]['mean'][0] - data[name]['std'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                 'k--')
        axs.plot([data[name]['mean'][0] + data[name]['std'][0] for _ in xrange(2)],
                 [index-0.25, index+0.25],
                 'k--')

    plt.yticks([i for i in xrange(len(names))], names, size = 10)
    plt.title(plate_name)
    plt.ylim(-0.5,len(names)-0.5)
    plt.xlabel('Fluorescent intensity')
    plt.tight_layout()

    save_filename = save_folder + 'baseline_average'

    pdf = PdfPages(save_filename.split('.')[0] + '.pdf')
    pdf.savefig(fig)
    pdf.close()

    plt.savefig(save_filename)
    #
    return None
def convolve(arrays, melBank, genere, filter_idx):
  x = []
  melBank_time = np.fft.ifft(melBank) #need to transform melBank to time domain
  for eachClip in arrays:
    result = np.convolve(eachClip, melBank_time)
    x.append(result)
    plotBeforeAfterFilter(eachClip, melBank, melBank_time, result, genere, filter_idx)

  m = np.asmatrix(np.array(x))
  fig, ax = plt.subplots()
  ax.matshow(m.real) #each element has imaginary part. So just plot real part
  plt.axis('equal')
  plt.axis('tight')
  plt.title(genere)
  plt.tight_layout()
  # filename = "./figures/convolution/Convolution_"+"Filter"+str(filter_idx)+genere+".png"
  # plt.savefig(filename)
  plt.show()
Esempio n. 9
0
def plot(results, path=os.path.expanduser("~/Desktop/results.pdf")):

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

    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    ax.scatter(x, y, color='black', alpha=0.25)
    ax.set_xlabel("$r$")
    ax.set_ylabel("Diff of profits between $h_0$ and $h_1$")
    ax.set_title("Does strategic depth impact profits?")

    add_fitting_curve(ax, x, y)

    plt.tight_layout()

    plt.savefig(path)
    plt.show()
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
Esempio n. 11
0
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 pos_firmA_over_pos_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)

    pos = bkp.positions[-1000:]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.scatter(pos[:, 0], pos[:, 1], color="black", alpha=0.05)
    ax.axvline(0.5, color="white", linewidth=0.5, linestyle="--")
    ax.axhline(0.5, color="white", linewidth=0.5, linestyle="--")

    plt.xlim(-1, bkp.parameters.n_positions)
    plt.ylim(-1, bkp.parameters.n_positions)
    plt.xticks(
        range(0, bkp.parameters.n_positions + 1,
              round(bkp.parameters.n_positions / 5)))
    plt.yticks(
        range(0, bkp.parameters.n_positions + 1,
              round(bkp.parameters.n_positions / 5)))

    plt.xlabel("Position A")
    plt.ylabel("Position B")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("$r={:.2f}$".format(bkp.field_of_view / 2))
    ax.set_aspect(1)
    plt.tight_layout()
    plt.savefig("{}/{}_evo_positions.pdf".format(folder, file_name))
    plt.show()
Esempio n. 13
0
    def plot_proportions(self):

        # Container for proportions of agents having this or that in hand according to their type
        #  - rows: type of agent
        # - columns: type of good

        fig = plt.figure(figsize=(25, 12))
        fig.patch.set_facecolor('white')

        n_lines = self.n_goods
        n_columns = 1

        x = np.arange(len(self.proportions))

        for agent_type in range(self.n_goods):

            # First subplot
            ax = plt.subplot(n_lines, n_columns, agent_type + 1)
            ax.set_title(
                "Proportion of agents of type {} having good i in hand\n".
                format(agent_type))

            y = []
            for i in range(self.n_goods):
                y.append([])

            for proportions_at_t in self.proportions:
                for good in range(self.n_goods):
                    y[good].append(proportions_at_t[agent_type, good])

            ax.set_ylim([-0.02, 1.02])

            for good in range(self.n_goods):
                ax.plot(x, y[good], label="Good {}".format(good), linewidth=2)

            ax.legend()

        plt.tight_layout()

        plt.savefig(filename=self.proportions_figure_name)
Esempio n. 14
0
    def savePdfPage( self ):

        # Delete any unused subplots        
        if self.subPlots < self.spots:
            print self.axarr
            for i in range( self.subPlots, self.spots ):
                print "Deleting subplot with id: ",i
                self.fig.delaxes( self.getActiveAx() )
                self.subPlots += 1
        
        # Ensure tight layout so everything is visible
        plt.tight_layout()
        
        # Do the save
        print "Saving pdf page"
        self.pp.savefig( self.fig, dpi=100 )
        
        # Clear figures
        plt.cla()
        
        # We have to explicitly clear color bars due to the way they are added
        self.clearColorbars()
def pos_firmA_over_pos_firmB(backup, fig_name):

    os.makedirs(os.path.dirname(fig_name), exist_ok=True)

    position_max = backup.parameters.n_positions - 1

    pos = backup.positions[-1000:] / position_max

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.scatter(pos[:, 0], pos[:, 1], color="black", alpha=0.05, zorder=10)
    ax.axvline(0.5, color="0.5", linewidth=0.5, linestyle="--", zorder=1)
    ax.axhline(0.5, color="0.5", linewidth=0.5, linestyle="--", zorder=1)

    plt.xlim(0, 1)
    plt.ylim(0, 1)
    plt.xticks((0, 0.5, 1))
    plt.yticks((0, 0.5, 1))

    plt.xlabel("Position $a$")
    plt.ylabel("Position $b$")

    for tick in ax.get_xticklabels():
        tick.set_fontsize("small")
    for tick in ax.get_yticklabels():
        tick.set_fontsize("small")

    plt.title("$r={:.2f}$".format(backup.parameters.r))
    ax.set_aspect(1)

    # Cut margins
    plt.tight_layout()

    # Save fig
    plt.savefig(fig_name)

    plt.close()
Fv = []
# For each frequency bin, estimate the stats
t_init = time()
for t in time_bins:
    covmats = covest.fit_transform(epochs_data[:, ::1, t:(t+window)])
    p_test = PermutationDistance(1000, metric='riemann', mode='pairwise')
    p, F = p_test.test(covmats, labels, verbose=False)
    pv.append(p)
    Fv.append(F[0])
duration = time() - t_init
# plot result
fig, axes = plt.subplots(1, 1, figsize=[6, 3], sharey=True)
sig = 0.05
times = np.array(time_bins)/float(Fs) + tmin

axes.plot(times, Fv, lw=2, c='k')
plt.xlabel('Time (sec)')
plt.ylabel('Score')

a = np.where(np.diff(np.array(pv) < sig))[0]
a = a.reshape(int(len(a)/2), 2)
st = (times[1] - times[0])/2.0
for p in a:
    axes.axvspan(times[p[0]]-st, times[p[1]]+st, facecolor='g', alpha=0.5)
axes.legend(['Score', 'p<%.2f' % sig])
axes.set_title('Pairwise distance - %.1f sec.' % duration)

sns.despine()
plt.tight_layout()
plt.show()
def analyse_profits(pool_backup, file_name="", folder=None):
    """
    Expected running_mode is 'discrete'
    :param pool_backup:
    :param file_name:
    :param folder:
    :return:
    """

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    def f_cond(xx):
        if xx < 0.25:
            return 0
        elif xx < 0.5:
            return 1
        elif xx < 0.75:
            return 2
        else:
            return 3

    n_pools = 4
    labels = [
        "0 <= FoV < 0.25", "0.25 <= FoV < 0.50", "0.50 <= FoV < 0.75",
        "0.75 <= FoV <= 1"
    ]

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    assert backups[
        0].running_mode == "discrete", "Expected running_mode is 'discrete'"

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = range(parameters.t_max)
    for_y = [[[] for j in range(parameters.t_max)] for i in range(n_pools)]

    for i, b in tqdm.tqdm(enumerate(backups), total=len(backups)):

        cond = f_cond(b.field_of_view)

        for t in range(parameters.t_max):

            for_y[cond][t].append(np.mean(b.profits[t, :]) / profit_max)

    for i in range(n_pools):
        y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        y_err = np.array(
            [np.std(for_y[i][t]) for t in range(parameters.t_max)])
        plt.plot(x, y, label=labels[i])
        plt.fill_between(x,
                         y - (y_err / 2),
                         y + (y_err / 2),
                         color="C{}".format(i),
                         alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    if file_name:
        plt.title(file_name)

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}_mean_profit_{}_cat.pdf".format(
            folder, file_name, n_pools))

    plt.show()
Esempio n. 18
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)
Esempio n. 19
0
    def mkplots(self):
        # run to make plots of the resulting posteriors. Modified from marginal_plots.py
        # from pymultinest. Produces basename+marg.pdf and basename+marge.png files
        prefix = self.basename

        parameters = json.load(file(prefix + 'params.json'))
        n_params = len(parameters)

        a = pymultinest.Analyzer(n_params=n_params,
                                 outputfiles_basename=prefix)
        s = a.get_stats()

        p = pymultinest.PlotMarginal(a)

        try:
            values = a.get_equal_weighted_posterior()
        except IOError as e:
            print 'Unable to open: %s' % e
            return

        assert n_params == len(s['marginals'])
        modes = s['modes']

        dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2'
        nbins = 100 if n_params < 3 else 20
        if dim2:
            plt.figure(figsize=(5.1 * n_params, 5 * n_params))
            for i in range(n_params):
                plt.subplot(n_params, n_params, i + 1)
                plt.xlabel(parameters[i])

                m = s['marginals'][i]
                plt.xlim(m['5sigma'])

                oldax = plt.gca()
                x, w, patches = oldax.hist(values[:, i],
                                           bins=nbins,
                                           edgecolor='grey',
                                           color='grey',
                                           histtype='stepfilled',
                                           alpha=0.2)
                oldax.set_ylim(0, x.max())

                newax = plt.gcf().add_axes(oldax.get_position(),
                                           sharex=oldax,
                                           frameon=False)
                p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                newax.set_ylim(0, 1)

                ylim = newax.get_ylim()
                y = ylim[0] + 0.05 * (ylim[1] - ylim[0])
                center = m['median']
                low1, high1 = m['1sigma']
                print center, low1, high1
                newax.errorbar(x=center,
                               y=y,
                               xerr=np.transpose(
                                   [[center - low1, high1 - center]]),
                               color='blue',
                               linewidth=2,
                               marker='s')
                oldax.set_yticks([])
                #newax.set_yticks([])
                newax.set_ylabel("Probability")
                ylim = oldax.get_ylim()
                newax.set_xlim(m['5sigma'])
                oldax.set_xlim(m['5sigma'])
                #plt.close()

                for j in range(i):
                    plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1)
                    p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r)
                    for m in modes:
                        plt.errorbar(x=m['mean'][i],
                                     y=m['mean'][j],
                                     xerr=m['sigma'][i],
                                     yerr=m['sigma'][j])
                    ax = plt.gca()
                    if j == i - 1:
                        plt.xlabel(parameters[i])
                        plt.ylabel(parameters[j])
                        [l.set_rotation(45) for l in ax.get_xticklabels()]
                    else:
                        ax.set_xticklabels([])
                        ax.set_yticklabels([])

                    plt.xlim([
                        m['mean'][i] - 5 * m['sigma'][i],
                        m['mean'][i] + 5 * m['sigma'][i]
                    ])
                    plt.ylim([
                        m['mean'][j] - 5 * m['sigma'][j],
                        m['mean'][j] + 5 * m['sigma'][j]
                    ])
                    #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True)
                    #plt.close()

            plt.tight_layout()
            plt.savefig(prefix + 'marg.pdf')
            plt.savefig(prefix + 'marg.png')
            plt.close()
        else:
            from matplotlib.backends.backend_pdf import PdfPages
            print '1dimensional only. Set the D environment variable D=2 to force'
            print '2d marginal plots.'
            pp = PdfPages(prefix + 'marg1d.pdf')

            for i in range(n_params):
                plt.figure(figsize=(5, 5))
                plt.xlabel(parameters[i])

                m = s['marginals'][i]
                plt.xlim(m['5sigma'])

                oldax = plt.gca()
                x, w, patches = oldax.hist(values[:, i],
                                           bins=20,
                                           edgecolor='grey',
                                           color='grey',
                                           histtype='stepfilled',
                                           alpha=0.2)
                oldax.set_ylim(0, x.max())

                newax = plt.gcf().add_axes(oldax.get_position(),
                                           sharex=oldax,
                                           frameon=False)
                p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                newax.set_ylim(0, 1)

                ylim = newax.get_ylim()
                y = ylim[0] + 0.05 * (ylim[1] - ylim[0])
                center = m['median']
                low1, high1 = m['1sigma']
                print center, low1, high1
                newax.errorbar(x=center,
                               y=y,
                               xerr=np.transpose(
                                   [[center - low1, high1 - center]]),
                               color='blue',
                               linewidth=2,
                               marker='s')
                oldax.set_yticks([])
                newax.set_ylabel("Probability")
                ylim = oldax.get_ylim()
                newax.set_xlim(m['5sigma'])
                oldax.set_xlim(m['5sigma'])
                plt.savefig(pp, format='pdf', bbox_inches='tight')
                plt.close()
            pp.close()
Esempio n. 20
0
def plot(data):

    gs = gridspec.GridSpec(2, 2, width_ratios=[1, 1.5])
    plt.figure(figsize=(9, 4))

    # -------------------------- Nationalities hist ---------------------------------- #
    ax = plt.subplot(gs[:, 0])
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.tick_params(length=0)
    plt.title("Nationality")

    # data
    dic_nationality = {}
    for n in np.unique(data.nationality):
        dic_nationality[n] = np.sum(data.nationality == n)
    nationalities = sorted(dic_nationality.items(), key=operator.itemgetter(1))
    labels = [i[0].capitalize() for i in nationalities]
    labels_pos = np.arange(len(labels))
    values = [round((i[1] / len(data.age)) * 100, 2) for i in nationalities]

    # text
    ax.set_yticks(labels_pos)
    ax.set_yticklabels(labels)
    ax.set_xticks([])
    for i, v in enumerate(values):
        ax.text(v + 1, i - 0.05, "{:.2f}%".format(v))

    # create
    ax.barh(labels_pos, values, edgecolor="white", align="center", alpha=0.5)

    # -------------------------- Gender pie ---------------------------------- #

    ax = plt.subplot(gs[0, 1])
    ax.axis('equal')
    plt.title("Gender")

    # get data
    genders = np.unique(data.gender)
    labels = [i.capitalize() for i in genders]
    values = [np.sum(data.gender == i) for i in genders]

    # create
    ax.pie(values,
           labels=labels,
           explode=(0.01, 0.05),
           autopct='%1.1f%%',
           startangle=90,
           shadow=False)
    # -------------------------- Age hist ---------------------------------- #
    ax = plt.subplot(gs[1, 1])
    plt.title("Age", y=1.05)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.tick_params(length=0)

    # get data
    n_ages = len(data.age)
    ages = [
        list(i[1])
        for i in itertools.groupby(sorted(data.age), lambda x: x // 10)
    ]
    decades = [
        "{}0-{}9".format(int(i[0] / 10), int(i[0] /
                                             10)) if i[0] >= 20 else "18-19"
        for i in ages
    ]
    decades_pos = np.arange(len(decades))
    values = np.array([round((len(i) / n_ages) * 100) for i in ages])

    # text
    ax.set_xticks(decades_pos)
    ax.set_xticklabels(decades)
    ax.set_yticks([])
    for i, v in enumerate(values):
        ax.text(i - 0.1, v + 1, "{}%".format(v))
    ax.text(
        3.5, 20,
        "Mean: {:.2f} $\pm$ {:.2f} (SD)".format(np.mean(data.age),
                                                np.std(data.age)))

    # create
    ax.bar(decades_pos, values, edgecolor="white", align="center", alpha=0.5)

    plt.tight_layout()

    plt.savefig("fig/demographics.pdf")
    plt.show()
def distance_over_fov(file_name, pool_backup, fig_folder=None):

    span_ratio = 0.33

    if fig_folder is None:
        fig_folder = "data/figures"

    os.makedirs(fig_folder, exist_ok=True)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    n_positions = parameters.n_positions
    p_max = parameters.p_max

    # Compute profit max
    profit_max = n_positions * p_max

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span = int(span_ratio * parameters.t_max)

    for i, b in enumerate(backups):

        try:
            # Save the parameter that affected the customers field of view
            x[i] = b.field_of_view / 2
        except AttributeError:
            x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(b.positions[-span:, 0] -
                           b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Mean distance")

    ax.set_title("Mean distance between firms over $r$")

    # add comment with file name
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    # show random
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)
    fig.colorbar(abc, label="Profits")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}.pdf".format(fig_folder, file_name))

    plt.show()
Esempio n. 22
0
def distance(pool_backup, fig_name=None, ax=None):

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    n_simulations = len(parameters["seed"])
    n_positions = parameters["n_positions"]
    t_max = parameters["t_max"]

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    z = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    for i, b in enumerate(backups):

        x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(
            b.positions[-span:, 0] -
            b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)

        y[i] = spacing

        # Get std
        y_err[i] = np.std(data)

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :])

    # Plot this
    if ax is None:
        fig = plt.figure(figsize=(5, 5), dpi=200)
        ax = fig.add_subplot()

    # Enhance aesthetics
    ax.set_xlim(-0.009, 1.005)
    ax.set_ylim(-0.009, 1.005)
    # if max(y) < 0.5:
    #     ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 1.1, 0.25))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Distance")

    # ax.set_title("Mean distance between firms over $r$")

    # Display line for indicating 'random' level
    # seed = 123
    # np.random.seed(seed)
    # random_pos = np.random.random(size=(2, 10 ** 6))
    # random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1]))
    # ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1)

    # if color:
    #     _color(fig=fig, ax=ax, x=x, y=y, z=z)
    # else:
    _bw(ax=ax, x=x, y=y, y_err=y_err)

    if fig_name:
        # Cut the margins
        plt.tight_layout()

        # Create directories if not already existing
        os.makedirs(os.path.dirname(fig_name), exist_ok=True)
        # Save fig
        plt.savefig(fig_name)

        plt.close()
Esempio n. 23
0
def plot(results, parameters, fig_name):

    # What is common to all subplots
    fig = plt.figure(figsize=(25, 12))

    fig.patch.set_facecolor('white')

    line_width = 2

    n_lines = 3
    n_columns = 3

    counter = it.count(1)

    # ----- FOR EACH GENERATION ------ #

    # FITNESS

    x = range(len(results["fitness"]))
    y = results["fitness"]

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title("Fitness average\naccording to number of generations\n")
    ax.plot(x, y, linewidth=line_width)

    # PROPORTION OF EACH TYPE OF EXCHANGE

    x_max = len(results["exchanges"])
    x = range(x_max)

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title(
        "Proportion of each type of exchange\naccording to number of generations\n"
    )

    type_of_exchanges = sorted([i for i in results["exchanges"][0].keys()])
    y = []
    for i in range(len(type_of_exchanges)):
        y.append([])

    for i in range(x_max):

        for exchange_idx in range(len(type_of_exchanges)):

            y[exchange_idx].append(
                results["exchanges"][i][type_of_exchanges[exchange_idx]])

    ax.set_ylim([-0.02, 1.02])

    for exchange_idx in range(len(type_of_exchanges)):

        ax.plot(x,
                y[exchange_idx],
                label="Exchange {}".format(type_of_exchanges[exchange_idx]),
                linewidth=line_width)

    ax.legend(fontsize=8)

    # NUMBER OF EXCHANGES GENERATION

    x = range(len(results["n_exchanges"]))
    y = results["n_exchanges"]

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title(
        "Total number of exchanges\naccording to number of generations\n")
    ax.plot(x, y, linewidth=line_width)

    # NUMBER OF INTERVENTION OF EACH GOOD

    x_max = len(results["n_exchanges"])
    x = range(x_max)
    y = []
    for i in range(len(results["n_goods_intervention"][0].keys())):
        y.append([])

    for i in range(x_max):

        for key in results["n_goods_intervention"][0].keys():
            y[key].append(results["n_goods_intervention"][i][key])

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title(
        "Number of interventions of each good\naccording to number of generations\n"
    )

    for key in results["n_goods_intervention"][0].keys():

        ax.plot(x, y[key], label="Good {}".format(key), linewidth=line_width)

    ax.legend(fontsize=8)

    # DIVERSITY OF PRODUCTION

    x = range(len(results["production_diversity"]))
    y = results["production_diversity"]

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title("Production diversity\naccording to number of generations\n")
    ax.plot(x, y, linewidth=line_width)

    # N PRODUCERS

    n_goods = len(results["n_producers"][0])

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title("Number of producers for each good \n")

    for i in range(n_goods):
        y = [j[i] for j in results["n_producers"]]
        x = range(len(y))
        ax.plot(x, y, linewidth=line_width, label="Good {}".format(i))

    ax.legend(fontsize=8)

    # GLOBAL PRODUCTION

    n_goods = len(results["production"][0])

    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title("Global production for each good \n")

    for i in range(n_goods):
        y = [j[i] for j in results["production"]]
        x = range(len(y))
        ax.plot(x, y, linewidth=line_width, label="Good {}".format(i))

    ax.legend(fontsize=8)

    # ------ PARAMETERS ----- #

    # 5th subplot: PARAMETERS
    ax = plt.subplot(n_lines, n_columns, next(counter))
    ax.set_title("Parameters")
    ax.axis('off')

    msg = ""
    for key in sorted(parameters.keys()):
        msg += "{}: {}; \n".format(key, parameters[key])

    ax.text(0.5, 0.5, msg, ha='center', va='center', size=12)

    plt.tight_layout()

    plt.savefig(fig_name)

    plt.close()
def profits_over_distance(file_name, folder=None, separate_A_and_B=True):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    pool_backup = backup.PoolBackup.load(file_name=file_name)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros((2, n_simulations))

    for i, b in enumerate(backups):

        # Compute the mean distance between the two firms
        data = np.absolute(b.positions[:, 0] -
                           b.positions[:, 1]) / parameters.n_positions

        spacing = np.mean(data)
        x[i] = spacing

        # Get profits
        profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value
        for f in range(2):
            y[f, i] = np.mean(b.profits[:, f]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    # ax.set_xlim(-0.01, 1.01)
    # ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    add_title_and_labels(ax)
    add_comment_with_file_name(fig=fig, file_name=file_name)

    if separate_A_and_B is True:
        ax.scatter(x, y[0], zorder=10, alpha=0.25, label="Firm A")
        ax.scatter(x, y[1], zorder=10, alpha=0.25, label="Firm B")
        add_fitting_curve(ax=ax, x=x, y=y[0])
        add_fitting_curve(ax=ax, x=x, y=y[1])
        plt.legend()

    else:
        ax.scatter(x, np.mean(y, axis=0), zorder=10, alpha=0.25, color="black")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}_profits_over_distance.pdf".format(
            folder, file_name))

    plt.show()
def distance_over_fov(pool_backup, fig_name):

    # Create directories if not already existing
    os.makedirs(os.path.dirname(fig_name), exist_ok=True)

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    n_simulations = len(parameters["seed"])
    n_positions = parameters["n_positions"]
    t_max = parameters["t_max"]

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    for i, b in enumerate(backups):

        x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(
            b.positions[-span:, 0] -
            b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :])

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    # Enhance aesthetics
    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Mean distance")

    ax.set_title("Mean distance between firms over $r$")

    # Display line for indicating 'random' level
    seed = 123
    np.random.seed(seed)
    random_pos = np.random.random(size=(2, 10 ** 6))
    random_dist = np.mean(np.absolute(random_pos[0] - random_pos[1]))
    ax.axhline(random_dist, color='0.5', linewidth=0.5, linestyle="--", zorder=1)

    # Do the scatter plot
    scat = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)

    # Add a color bar
    fig.colorbar(scat, label="Profits")

    # Cut the margins
    plt.tight_layout()

    # Save fig
    plt.savefig(fig_name)

    plt.close()
Esempio n. 26
0
def main(force):

    backups = backup.get_data(force)

    bins = np.arange(0, 3800, 500)

    bounds = ["{}~{}".format(i, j) for i, j in zip(bins[:-1], bins[1:])]

    fig = plt.figure(figsize=(12, 8))
    axes = fig.add_subplot(211), fig.add_subplot(212)

    for s, ax in zip((1, 0), axes):

        scores = {0.25: [], 0.5: []}

        for b in backups:

            if b.pvp and b.display_opponent_score is bool(s):
                for player in (0, 1):
                    sum_profit = np.sum(b.profits[:, player])
                    scores[b.r].append(sum_profit)

        if np.max([max(i) for i in scores.values()]) > max(bins):
            raise Exception("Max bound has been reached")

        y_upper_bound = 55

        ind = np.arange(len(bins) - 1)

        for r, color in zip((0.25, 0.50), ("C0", "C1")):

            sc = np.array(scores[r])

            print(
                "Score (r = {:.2f}, s = {}) mean: {:.2f}, std: {:.2f}, min:{}, max: {}"
                .format(r, s, np.mean(sc), np.std(sc), np.min(sc), np.max(sc)))

            d = np.digitize(sc, bins=bins)

            n = len(sc)

            y = []
            for i in ind:

                y.append(len(sc[d == i]) / n * 100)

            if np.max(y) > y_upper_bound:
                raise Exception(
                    "Max bound has been reached ({:.2f} > {})".format(
                        np.max(y), y_upper_bound))

            width = 0.35  # the width of the bars

            ax.bar(ind - width / 2 if r == 0.25 else ind + width / 2,
                   y,
                   width,
                   label='r = {:.2f}'.format(r),
                   alpha=0.5,
                   edgecolor=color)

        ax.set_xticks(ind)
        ax.set_xticklabels(bounds, fontsize=8)

        ax.set_ylim(0, y_upper_bound)

        ax.set_ylabel("Proportion (%)")

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.tick_params(length=0)
        ax.set_title('s = {}'.format(s))

    plt.tight_layout()
    plt.legend()
    plt.savefig("fig/pool_score_distribution.pdf")
    plt.show()
Esempio n. 27
0
    def mkplots(self):
        # run to make plots of the resulting posteriors. Modified from marginal_plots.py
        # from pymultinest. Produces basename+marg.pdf and basename+marge.png files
        prefix = self.basename
        
        parameters = json.load(file(prefix + 'params.json'))
        n_params = len(parameters)
        
        a = pymultinest.Analyzer(n_params = n_params, outputfiles_basename = prefix)
        s = a.get_stats()
        
        p = pymultinest.PlotMarginal(a)
        
        try:
            values = a.get_equal_weighted_posterior()
        except IOError as e:
            print 'Unable to open: %s' % e
            return
            
        assert n_params == len(s['marginals'])
        modes = s['modes']

        dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2'
        nbins = 100 if n_params < 3 else 20
        if dim2:
                plt.figure(figsize=(5.1*n_params, 5*n_params))
                for i in range(n_params):
                        plt.subplot(n_params, n_params, i + 1)
                        plt.xlabel(parameters[i])

                        m = s['marginals'][i]
                        plt.xlim(m['5sigma'])

                        oldax = plt.gca()
                        x,w,patches = oldax.hist(values[:,i], bins=nbins, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2)
                        oldax.set_ylim(0, x.max())

                        newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False)
                        p.plot_marginal(i, ls='-', color='blue', linewidth=3)
                        newax.set_ylim(0, 1)

                        ylim = newax.get_ylim()
                        y = ylim[0] + 0.05*(ylim[1] - ylim[0])
                        center = m['median']
                        low1, high1 = m['1sigma']
                        print center, low1, high1
                        newax.errorbar(x=center, y=y,
                                xerr=np.transpose([[center - low1, high1 - center]]), 
                                color='blue', linewidth=2, marker='s')
                        oldax.set_yticks([])
                        #newax.set_yticks([])
                        newax.set_ylabel("Probability")
                        ylim = oldax.get_ylim()
                        newax.set_xlim(m['5sigma'])
                        oldax.set_xlim(m['5sigma'])
                        #plt.close()

                        for j in range(i):
                                plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1)
                                p.plot_conditional(i, j, bins=20, cmap = plt.cm.gray_r)
                                for m in modes:
                                        plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j])
                                ax = plt.gca()
                                if j == i-1:
                                    plt.xlabel(parameters[i])
                                    plt.ylabel(parameters[j])
                                    [l.set_rotation(45) for l in ax.get_xticklabels()]
                                else:
                                    ax.set_xticklabels([])
                                    ax.set_yticklabels([])


                                plt.xlim([m['mean'][i]-5*m['sigma'][i],m['mean'][i]+5*m['sigma'][i]])
                                plt.ylim([m['mean'][j]-5*m['sigma'][j],m['mean'][j]+5*m['sigma'][j]])
                                #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True)
                                #plt.close()

                plt.tight_layout()
                plt.savefig(prefix + 'marg.pdf')
                plt.savefig(prefix + 'marg.png')
                plt.close()
        else:
        	from matplotlib.backends.backend_pdf import PdfPages
        	print '1dimensional only. Set the D environment variable D=2 to force'
        	print '2d marginal plots.'
        	pp = PdfPages(prefix + 'marg1d.pdf')
        	
        	for i in range(n_params):
        		plt.figure(figsize=(5, 5))
        		plt.xlabel(parameters[i])
        		
        		m = s['marginals'][i]
        		plt.xlim(m['5sigma'])
        	
        		oldax = plt.gca()
        		x,w,patches = oldax.hist(values[:,i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2)
        		oldax.set_ylim(0, x.max())
        	
        		newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False)
        		p.plot_marginal(i, ls='-', color='blue', linewidth=3)
        		newax.set_ylim(0, 1)
        	
        		ylim = newax.get_ylim()
        		y = ylim[0] + 0.05*(ylim[1] - ylim[0])
        		center = m['median']
        		low1, high1 = m['1sigma']
        		print center, low1, high1
        		newax.errorbar(x=center, y=y,
        			xerr=np.transpose([[center - low1, high1 - center]]), 
        			color='blue', linewidth=2, marker='s')
        		oldax.set_yticks([])
        		newax.set_ylabel("Probability")
        		ylim = oldax.get_ylim()
        		newax.set_xlim(m['5sigma'])
        		oldax.set_xlim(m['5sigma'])
        		plt.savefig(pp, format='pdf', bbox_inches='tight')
        		plt.close()
        	pp.close()
Esempio n. 28
0
def plotIce(di,
            u,
            name,
            direc,
            u2=None,
            u2_levels=None,
            u2_color='k',
            title='',
            cmap='gist_yarg',
            scale='lin',
            umin=None,
            umax=None,
            numLvls=12,
            levels=None,
            levels_2=None,
            tp=False,
            tpAlpha=0.5,
            contour_type='filled',
            params=None,
            extend='neither',
            show=True,
            ext='.png',
            res=150,
            cb=True,
            cb_format='%.1e',
            zoom_box=False,
            zoom_box_kwargs=None,
            plot_pts=None,
            plot_continent=False,
            cont_plot_params=None,
            box_params=None):
    """
  Args:

    :di:      DataInput object with desired projection
    :u:       solution to plot; can be either a function on a 2D mesh, or a
              string key to matrix variable in <di>.data.
    :name:    title of the plot, latex accepted
    :direc:   directory string location to save image.
    :cmap:    colormap to use - see images directory for sample and name
    :scale:   scale to plot, either 'log', 'lin', or 'bool'
    :numLvls: number of levels for field values
    :levels:  manual levels, if desired.
    :tp:      boolean determins plotting of triangle overlay
    :tpAlpha: alpha level of triangles 0.0 (transparent) - 1.0 (opaque)
    :extends: for the colorbar, extend upper range and may be ["neither",
              "both", "min", "max"]. default is "neither".

    for plotting the zoom-box, make <zoom_box> = True and supply dict
    *zoom_box_kwargs* with parameters
    
    :zoom:             ammount to zoom 
    :loc:              location of box
    :loc1:             loc of first line
    :loc2:             loc of second line
    :x1:               first x-coord
    :y1:               first y-coord
    :x2:               second x-coord
    :y2:               second y-coord
    :scale_font_color: scale font color
    :scale_length:     scale length in km
    :scale_loc:        1=top, 2=bottom
    :plot_grid:        plot the triangles
    :axes_color:       color of axes
    :plot_points:      dict of points to plot
  
  Returns:
 
    A sigle *direc/name.ext* in the source directory.
  
  """
    # get the original projection coordinates and data :
    if isinstance(u, str):
        s = "::: plotting %s's \"%s\" field data directly :::" % (di.name, u)
        print_text(s, '242')
        vx, vy = np.meshgrid(di.x, di.y)
        v = di.data[u]

    elif isinstance(u, Function) \
      or isinstance(u, dolfin.functions.function.Function):
        s = "::: plotting FEniCS Function \"%s\" :::" % name
        print_text(s, '242')
        mesh = u.function_space().mesh()
        coord = mesh.coordinates()
        fi = mesh.cells()
        v = u.compute_vertex_values(mesh)
        vx = coord[:, 0]
        vy = coord[:, 1]

    # get the projection info :
    if isinstance(di, dict) and 'pyproj_Proj' in di.keys() \
       and 'continent' in di.keys():
        lon, lat = di['pyproj_Proj'](vx, vy, inverse=True)
        cont = di['continent']
    elif isinstance(di, DataInput):
        lon, lat = di.proj(vx, vy, inverse=True)
        cont = di.cont
    else:
        s = ">>> plotIce REQUIRES A 'DataFactory' DICTIONARY FOR " + \
            "PROJECTION STORED AS KEY 'pyproj_Proj' AND THE CONTINENT TYPE " + \
            "STORED AS KEY 'continent' <<<"
        print_text(s, 'red', 1)
        sys.exit(1)

    # Antarctica :
    if params is None:
        if cont is 'antarctica':
            w = 5513335.22665
            h = 4602848.6605
            fig = plt.figure(figsize=(14, 10))
            ax = fig.add_subplot(111)

            lon_0 = 0
            lat_0 = -90

            # new projection :
            m = Basemap(ax=ax,
                        width=w,
                        height=h,
                        resolution='h',
                        projection='stere',
                        lat_ts=-71,
                        lon_0=lon_0,
                        lat_0=lat_0)

            offset = 0.015 * (m.ymax - m.ymin)

            # draw lat/lon grid lines every 5 degrees.
            # labels = [left,right,top,bottom]
            m.drawmeridians(np.arange(0, 360, 20.0),
                            color='black',
                            labels=[True, False, True, True])
            m.drawparallels(np.arange(-90, 90, 5.0),
                            color='black',
                            labels=[True, False, True, True])
            m.drawmapscale(-130,
                           -68,
                           0,
                           -90,
                           400,
                           yoffset=offset,
                           barstyle='fancy')

        # Greenland :
        elif cont is 'greenland':
            w = 1532453.49654
            h = 2644074.78236
            fig = plt.figure(figsize=(8, 11.5))
            ax = fig.add_subplot(111)

            lon_0 = -41.5
            lat_0 = 71

            # new projection :
            m = Basemap(ax=ax,
                        width=w,
                        height=h,
                        resolution='h',
                        projection='stere',
                        lat_ts=71,
                        lon_0=lon_0,
                        lat_0=lat_0)

            offset = 0.015 * (m.ymax - m.ymin)

            # draw lat/lon grid lines every 5 degrees.
            # labels = [left,right,top,bottom]
            m.drawmeridians(np.arange(0, 360, 5.0),
                            color='black',
                            labels=[False, False, False, True])
            m.drawparallels(np.arange(-90, 90, 5.0),
                            color='black',
                            labels=[True, False, True, False])
            m.drawmapscale(-34,
                           60.5,
                           -41.5,
                           71,
                           400,
                           yoffset=offset,
                           barstyle='fancy')

    elif type(params) is dict:
        llcrnrlat = params['llcrnrlat']
        urcrnrlat = params['urcrnrlat']
        llcrnrlon = params['llcrnrlon']
        urcrnrlon = params['urcrnrlon']
        scale_color = params['scale_color']
        scale_length = params['scale_length']
        scale_loc = params['scale_loc']
        figsize = params['figsize']
        lat_interval = params['lat_interval']
        lon_interval = params['lon_interval']
        plot_grid = params['plot_grid']
        plot_scale = params['plot_scale']
        axes_color = params['axes_color']

        dlon = (urcrnrlon - llcrnrlon) / 2.0
        dlat = (urcrnrlat - llcrnrlat) / 2.0
        lon_0 = llcrnrlon + dlon
        lat_0 = llcrnrlat + dlat

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

        # new projection :
        m = Basemap(ax=ax,
                    llcrnrlat=llcrnrlat,
                    urcrnrlat=urcrnrlat,
                    llcrnrlon=llcrnrlon,
                    urcrnrlon=urcrnrlon,
                    resolution='h',
                    projection='stere',
                    lon_0=lon_0,
                    lat_0=lat_0)

        offset = 0.015 * (m.ymax - m.ymin)

        # draw lat/lon grid lines every degree.
        # labels = [left,right,top,bottom]
        if plot_grid:
            m.drawmeridians(np.arange(0, 360, lon_interval),
                            color='black',
                            labels=[False, False, False, True])
            m.drawparallels(np.arange(-90, 90, lat_interval),
                            color='black',
                            labels=[True, False, False, False])

        if scale_loc == 1:
            fact = 1.8
        elif scale_loc == 2:
            fact = 0.2

        if plot_scale:
            dx = (m.xmax - m.xmin) / 2.0
            dy = (m.ymax - m.ymin) / 2.0
            xmid = m.xmin + dx
            ymid = m.ymin + fact * dy
            slon, slat = m(xmid, ymid, inverse=True)
            m.drawmapscale(slon,
                           slat,
                           slon,
                           slat,
                           scale_length,
                           barstyle='fancy',
                           fontcolor=scale_color)

        for axis in ['top', 'bottom', 'left', 'right']:
            ax.spines[axis].set_color(axes_color)

    else:
        s = ">>> plotIce REQUIRES A 'dict' OF SPECIFIC PARAMETERS FOR 'custom' <<<"
        print_text(s, 'red', 1)
        sys.exit(1)

    # convert to new projection coordinates from lon,lat :
    x, y = m(lon, lat)

    m.drawcoastlines(linewidth=0.5, color='black')
    #m.shadedrelief()
    #m.bluemarble()
    #m.etopo()

    if plot_continent:
        if cont is 'greenland':
            llcrnrlat = 57
            urcrnrlat = 80.1
            llcrnrlon = -57
            urcrnrlon = 15

            axcont = inset_locator.inset_axes(ax, **cont_plot_params)
            axcont.xaxis.set_ticks_position('none')
            axcont.yaxis.set_ticks_position('none')

            # continent projection :
            mc = Basemap(ax=axcont,
                         llcrnrlat=llcrnrlat,
                         urcrnrlat=urcrnrlat,
                         llcrnrlon=llcrnrlon,
                         urcrnrlon=urcrnrlon,
                         resolution='c',
                         projection='stere',
                         lon_0=lon_0,
                         lat_0=lat_0)

            mc.drawcoastlines(linewidth=0.5, color='black')

            x_c, y_c = mc(lon, lat)

            v_cont = v.copy()
            v_cont[:] = 1.0

            axcont.tricontourf(x_c, y_c, fi, v_cont, cmap=pl.get_cmap('Reds'))

    #=============================================================================
    # plotting :
    if umin != None and levels is None:
        vmin = umin
    elif levels is not None:
        vmin = levels.min()
    else:
        vmin = v.min()

    if umax != None and levels is None:
        vmax = umax
    elif levels is not None:
        vmax = levels.max()
    else:
        vmax = v.max()

    # set the extended colormap :
    cmap = pl.get_cmap(cmap)
    #cmap.set_under(under)
    #cmap.set_over(over)

    # countour levels :
    if scale == 'log':
        if levels is None:
            levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls)
        v[v < vmin] = vmin + 2e-16
        v[v > vmax] = vmax - 2e-16
        formatter = LogFormatter(10, labelOnlyBase=False)
        norm = colors.LogNorm()

    # countour levels :
    elif scale == 'sym_log':
        if levels is None:
            levels = np.linspace(vmin, vmax, numLvls)
        v[v < vmin] = vmin + 2e-16
        v[v > vmax] = vmax - 2e-16
        formatter = LogFormatter(e, labelOnlyBase=False)
        norm = colors.SymLogNorm(vmin=vmin,
                                 vmax=vmax,
                                 linscale=0.001,
                                 linthresh=0.001)

    elif scale == 'lin':
        if levels is None:
            levels = np.linspace(vmin, vmax, numLvls)
        norm = colors.BoundaryNorm(levels, cmap.N)

    elif scale == 'bool':
        v[v < 0.0] = 0.0
        levels = [0, 1, 2]
        norm = colors.BoundaryNorm(levels, cmap.N)

    # please do zoom in!
    if zoom_box:
        zoom = zoom_box_kwargs['zoom']
        loc = zoom_box_kwargs['loc']
        loc1 = zoom_box_kwargs['loc1']
        loc2 = zoom_box_kwargs['loc2']
        llcrnrlat = zoom_box_kwargs['llcrnrlat']
        urcrnrlat = zoom_box_kwargs['urcrnrlat']
        llcrnrlon = zoom_box_kwargs['llcrnrlon']
        urcrnrlon = zoom_box_kwargs['urcrnrlon']
        plot_zoom_scale = zoom_box_kwargs['plot_zoom_scale']
        scale_font_color = zoom_box_kwargs['scale_font_color']
        scale_length = zoom_box_kwargs['scale_length']
        scale_loc = zoom_box_kwargs['scale_loc']
        plot_grid = zoom_box_kwargs['plot_grid']
        axes_color = zoom_box_kwargs['axes_color']
        zb_plot_pts = zoom_box_kwargs['plot_points']

        x1, y1 = m(llcrnrlon, llcrnrlat)
        x2, y2 = m(urcrnrlon, urcrnrlat)

        axins = inset_locator.zoomed_inset_axes(ax, zoom, loc=loc)
        inset_locator.mark_inset(ax,
                                 axins,
                                 loc1=loc1,
                                 loc2=loc2,
                                 fc="none",
                                 ec=axes_color)
        for axis in ['top', 'bottom', 'left', 'right']:
            axins.spines[axis].set_color(axes_color)
            #axins.spines[axis].set_linewidth(2)

        if scale_loc == 1:
            fact = 1.8
        elif scale_loc == 2:
            fact = 0.2

        dx = (x2 - x1) / 2.0
        dy = (y2 - y1) / 2.0
        xmid = x1 + dx
        ymid = y1 + fact * dy
        slon, slat = m(xmid, ymid, inverse=True)

        # new projection :
        mn = Basemap(ax=axins,
                     width=w,
                     height=h,
                     resolution='h',
                     projection='stere',
                     lat_ts=lat_0,
                     lon_0=lon_0,
                     lat_0=lat_0)

        if plot_zoom_scale:
            mn.drawmapscale(slon,
                            slat,
                            slon,
                            slat,
                            scale_length,
                            yoffset=0.025 * 2.0 * dy,
                            barstyle='fancy',
                            fontcolor=scale_font_color)

        mn.drawcoastlines(linewidth=0.5, color='black')

        axins.set_xlim(x1, x2)
        axins.set_ylim(y1, y2)

        axins.xaxis.set_ticks_position('none')
        axins.yaxis.set_ticks_position('none')

    if isinstance(u, str):
        #cs = ax.pcolor(x, y, v, cmap=get_cmap(cmap), norm=norm)
        if contour_type == 'filled':
            cs = ax.contourf(x,
                             y,
                             v,
                             levels=levels,
                             cmap=cmap,
                             norm=norm,
                             extend=extend)
            if zoom_box:
                axins.contourf(x,
                               y,
                               v,
                               levels=levels,
                               cmap=cmap,
                               norm=norm,
                               extend=extend)
        if contour_type == 'lines':
            cs = ax.contour(x, y, v, levels=levels, colors='k')
            for line in cs.collections:
                if line.get_linestyle() != [(None, None)]:
                    line.set_linestyle([(None, None)])
                    line.set_color('red')
                    line.set_linewidth(1.5)
            if levels_2 is not None:
                cs2 = ax.contour(x, y, v, levels=levels_2, colors='k')
                for line in cs2.collections:
                    if line.get_linestyle() != [(None, None)]:
                        line.set_linestyle([(None, None)])
                        line.set_color('#c1000e')
                        line.set_linewidth(0.5)
            ax.clabel(cs, inline=1, colors='k', fmt='%i')
            if zoom_box:
                axins.contour(x, y, v, levels=levels, colors='k')

    elif isinstance(u, Function) \
      or isinstance(u, dolfin.functions.function.Function):
        #cs = ax.tripcolor(x, y, fi, v, shading='gouraud',
        #                  cmap=get_cmap(cmap), norm=norm)
        if contour_type == 'filled':
            cs = ax.tricontourf(x,
                                y,
                                fi,
                                v,
                                levels=levels,
                                cmap=cmap,
                                norm=norm,
                                extend=extend)
            if zoom_box:
                axins.tricontourf(x,
                                  y,
                                  fi,
                                  v,
                                  levels=levels,
                                  cmap=cmap,
                                  norm=norm,
                                  extend=extend)
        elif contour_type == 'lines':
            cs = ax.tricontour(x,
                               y,
                               fi,
                               v,
                               linewidths=2.0,
                               levels=levels,
                               colors='k')
            for line in cs.collections:
                if line.get_linestyle() != [(None, None)]:
                    line.set_linestyle([(None, None)])
                    line.set_color('red')
                    line.set_linewidth(1.5)
            if levels_2 is not None:
                cs2 = ax.tricontour(x,
                                    y,
                                    fi,
                                    v,
                                    levels=levels_2,
                                    colors='0.30')
                for line in cs2.collections:
                    if line.get_linestyle() != [(None, None)]:
                        line.set_linestyle([(None, None)])
                        line.set_color('#c1000e')
                        line.set_linewidth(0.5)
            ax.clabel(cs, inline=1, colors='k', fmt='%i')
            if zoom_box:
                axins.tricontour(x, y, fi, v, levels=levels, colors='k')
                axins.clabel(cs, inline=1, colors='k', fmt='%1.2f')

    if u2 is not None:
        v2 = u2.compute_vertex_values(mesh)
        csu2 = ax.tricontour(x,
                             y,
                             fi,
                             v2,
                             linewidths=1.5,
                             levels=u2_levels,
                             colors=u2_color)
        #for line in csu2.collections:
        #  if line.get_linestyle() != [(None, None)]:
        #    line.set_linestyle([(None, None)])

    if plot_pts is not None:
        lat_a = plot_pts['lat']
        lon_a = plot_pts['lon']
        sty_a = plot_pts['style']
        clr_a = plot_pts['color']
        for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a):
            x_i, y_i = m(lon_i, lat_i)
            ax.plot(x_i, y_i, color=clr_i, marker=sty_i)

    if box_params is not None:
        x1, y1 = m(box_params['llcrnrlon'], box_params['llcrnrlat'])
        x2, y2 = m(box_params['urcrnrlon'], box_params['urcrnrlat'])
        box_x_s = [x1, x2, x2, x1, x1]
        box_y_s = [y1, y1, y2, y2, y1]
        ax.plot(box_x_s, box_y_s, '-', lw=1.0, color=box_params['color'])

    if zoom_box:
        if zb_plot_pts is not None:
            lat_a = zb_plot_pts['lat']
            lon_a = zb_plot_pts['lon']
            sty_a = zb_plot_pts['style']
            clr_a = zb_plot_pts['color']
            for lat_i, lon_i, sty_i, clr_i in zip(lat_a, lon_a, sty_a, clr_a):
                x_i, y_i = m(lon_i, lat_i)
                axins.plot(x_i, y_i, color=clr_i, marker=sty_i)

    # plot triangles :
    if tp == True:
        tp = ax.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha)
    if zoom_box and plot_grid:
        tpaxins = axins.triplot(x, y, fi, 'k-', lw=0.2, alpha=tpAlpha)

    # include colorbar :
    if cb and scale != 'bool':
        divider = make_axes_locatable(ax)  #plt.gca())
        cax = divider.append_axes("right", "5%", pad="3%")
        cbar = fig.colorbar(
            cs,
            cax=cax,  #format=formatter, 
            ticks=levels,
            format=cb_format)
        #cbar = plt.colorbar(cs, cax=cax, format=formatter,
        #                    ticks=np.around(levels,decimals=1))

    # title :
    tit = plt.title(title)
    #tit.set_fontsize(40)

    plt.tight_layout(rect=[.03, .03, 0.97, 0.97])
    d = os.path.dirname(direc)
    if not os.path.exists(d):
        os.makedirs(d)
    plt.savefig(direc + name + ext, res=res)
    if show:
        plt.show()
    plt.close(fig)

    return m
def multiple_subplots(attribute_list,
                      group,
                      dataset,
                      plot_type='hist',
                      row_category_split=0,
                      row_category_split_col='dummy',
                      sav_fig=0,
                      savefname=r'c:\data\temp\ans.png',
                      **kwargs):
    """ Create multiple subplots within a figure ( currently box, hist) based on the attribute list. May purpose is to ensure y-axis auto scaling for each subplot and does not share y axis.
        By default, it create n by column (default 3) number of subplot within a single figure. n is based on len(attribute_list)/column.

        Args:
            attribute_list (list): (row_category_split = 0)list of column names to plot. Each column name is put under one plot
                                   (row_category_split = 1)list of sub category to plot. Each sub cat is put under one plot
            group ('str'):          category option within a plot. Only avaliable for box plot. where the x-axis is group.
            dataset ('dataframe'):  attribute_list items, group and row_category_split_col must be present in the dataset.

        Kwargs:
            plot_type(str): hist (histogram) or box (boxplot) option.
            row_category_split: default 0. Applicable for boxplot. allow sub plot by splitting the plots based on target row (row_category_split_col)
            sav_fig (bool): default 0, if sav_fg = 1, will save figure beside showing it, will use savefname  as the save filename.

        Additional parameters:
            column_default (int): default 3. change the layout of the figure.
            
        Normally for box plot each plot is based on each column group by "group" (if row_category_split = 0)
        if row_category_split = 1 

   
    """
    if kwargs.has_key('column_default'):
        column_default = float(kwargs['column_default'])
    else:
        column_default = 3.0

    num_rows = int(math.ceil(len(attribute_list) / column_default))
    gs = gridspec.GridSpec(num_rows, int(column_default))

    row_index = 0
    temp_col = 0
    for n in attribute_list:
        ax = plt.subplot(gs[row_index, temp_col])

        if plot_type == 'hist':
            dataset[n].hist(ax=ax)  #may need to add title
            ax.set_title(n)

        if plot_type == 'box':
            if not row_category_split:
                dataset[[n, group]].boxplot(
                    by=group, sym='k.', vert=True, whis=1.5,
                    ax=ax)  #symbol is as a result of seaborn with pylab issue
            else:
                dataset[dataset[row_category_split_col] == n].boxplot(
                    by=group, sym='k.', vert=True, whis=1.5,
                    ax=ax)  #symbol is as a result of seaborn with pylab issue
                ax.set_title(n)

        temp_col = temp_col + 1
        if temp_col == 3:
            row_index = row_index + 1
            temp_col = 0

    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)
    plt.tight_layout()
    if sav_fig:
        plt.savefig(savefname)
    plt.show()
Esempio n. 30
0
def plot_variable(u,
                  name,
                  direc,
                  cmap='gist_yarg',
                  scale='lin',
                  numLvls=12,
                  umin=None,
                  umax=None,
                  tp=False,
                  tpAlpha=0.5,
                  show=True,
                  hide_ax_tick_labels=False,
                  label_axes=True,
                  title='',
                  use_colorbar=True,
                  hide_axis=False,
                  colorbar_loc='right'):
    """
  """
    mesh = u.function_space().mesh()
    v = u.compute_vertex_values(mesh)
    x = mesh.coordinates()[:, 0]
    y = mesh.coordinates()[:, 1]
    t = mesh.cells()

    d = os.path.dirname(direc)
    if not os.path.exists(d):
        os.makedirs(d)

    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)
        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)
        formatter = ScalarFormatter()
        norm = None

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

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

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

    if tp == True:
        p = ax.triplot(x, y, t, 'k-', lw=0.25, 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=levels)
        pl.mpl.rcParams['axes.titlesize'] = 'small'
        tit = plt.title(title)

    plt.tight_layout()
    d = os.path.dirname(direc)
    if not os.path.exists(d):
        os.makedirs(d)
    plt.savefig(direc + name + '.pdf')
    if show:
        plt.show()
    plt.close(fig)
Esempio n. 31
0
def plot_mean_curve(time_data, data, additions, plate_name, save_folder = r'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()
        # -----------------
        # Plot each group individualy
        # -----------------
        data_per_inch = 5.0

        y_len = int(math.sqrt(len(names)))
        x_len = int(np.ceil(len(names) / float(y_len)))

        fig, axs = plt.subplots(y_len, x_len, sharex=True, sharey=True,
                                figsize=(x_len*data_per_inch,y_len*data_per_inch), dpi=300)

        y_min = data[block][names[0]]['original_data'].min()
        y_max = data[block][names[0]]['original_data'].max()

        for i, name in enumerate(names):
            if data[block][name]['original_data'].min() < y_min:
                y_min = data[block][name]['original_data'].min()
            if data[block][name]['original_data'].max() > y_max:
                y_max = data[block][name]['original_data'].max()
        y_range = y_max - y_min
                
        for i, name in enumerate(names):
            px = i / x_len
            py = i % x_len
            if y_len > 1:
                position = (px, py)
            else:
                position = py

            time = time_data[block][name]
            mean = np.array(data[block][name]['mean'])
            std = np.array(data[block][name]['std'])
            all_curve = data[block][name]['original_data']

            axs[position].plot(time, [1.0 for _ in time], 'k-')
            for curve in all_curve:
                axs[position].plot(time, curve, color = [0.7 for _ in xrange(3)])
            axs[position].plot(time, mean, color = [0.2 for _ in xrange(3)], linewidth = 2.5, label = name)
            axs[position].plot(time, mean+std, 'k--', color = [0.2 for _ in xrange(3)], linewidth = 2.5)
            axs[position].plot(time, mean-std, 'k--', color = [0.2 for _ in xrange(3)], linewidth = 2.5)

            for addition in additions[:block+1]:
                axs[position].plot([addition[0] for _ in xrange(2)], [0.0,3.0], 'k-')
                axs[position].text(addition[0], 0.98, addition[1], rotation=270)
            
            if i % x_len == 0:
                axs[position].set_ylabel('Normalized fluorescence', size = 14)
            if i / x_len == y_len - 1:
                axs[position].set_xlabel('Time / sec', size = 14)
                
            axs[position].set_xlim(0, time[-1])

            for j, text in enumerate(name.split(';')):
                axs[position].text(10, y_max - y_range*j*0.1, text, size = 14)

        axs[position].set_ylim(y_min-y_range*0.1, y_max+y_range*0.1)
        
#        plt.suptitle(plate_name)
        plt.subplots_adjust(wspace = 0.01, hspace = 0.01)
        plt.tight_layout()
        plt.savefig(save_folder + 'block_' + str(block + 1))
    #
    return None
Esempio n. 32
0
plt.ylabel("$y'$")
plt.savefig('plots/tlm_test_singlelines.png')
plt.xlim((-0.25, 0.25))
plt.ylim((-0.004, 0.004))
plt.savefig('plots/tlm_test_singlelines_closeup.png')

plt.show()

# compute mean response over all forecasts
tlm = np.mean(np.array(data['tlm']), axis=0)
finitdiff = np.mean(np.array(data['finitdiff']), axis=0)

plt.figure(figsize=(12, 4))
plt.subplot(121)
plt.plot(pert_scales, tlm, label='TLM')
plt.plot(pert_scales, finitdiff, label='NN')
plt.xlabel('$\sigma$')
plt.ylabel("$y'$")
plt.legend()
sns.despine()
plt.subplot(122)
plt.plot(pert_scales, tlm, label='TLM')
plt.plot(pert_scales, finitdiff, label='NN')
plt.xlabel('$\sigma$')
plt.ylabel("$y'$")
plt.legend()
sns.despine()
plt.xlim((-0.1, 0.1))
plt.ylim((-0.00005, 0.00005))
plt.tight_layout()
plt.savefig('plots/tlm_test.pdf', bbox='tight')
Esempio n. 33
0
def run(pool_results):

    # r = pool_results.results[30]
    # plt.plot(r.indirect_exchanges)
    # plt.show()
    # m = MoneyAnalysis.run(r)
    # print(m)
    #
    # for i, r in enumerate(pool_results.results):
    #
    #     plt.plot(r.indirect_exchanges)
    #     plt.title(i)
    #     plt.show()

    alphas = []
    taus = []
    qs = []
    gammas = []

    y = []

    for i, r in enumerate(pool_results.results):

        # if not r.parameters["x0"] == r.parameters["x1"] == r.parameters["x2"]:
        #    continue

        alphas.append(r.parameters["alpha"])
        taus.append(r.parameters["tau"])
        qs.append(r.parameters["q"])
        gammas.append(r.parameters["gamma"])
        m = MoneyAnalysis.run(r)
        print(i, m)
        y.append(m)

    fig = plt.figure(figsize=(10, 10))

    ax = fig.add_subplot(221)
    ax.scatter(taus, y, c="black", alpha=0.4, s=15)
    ax.set_ylabel("n monetary states")
    ax.set_xlabel(r"$\tau$")

    ax = fig.add_subplot(222)
    ax.scatter(alphas, y, c="black", alpha=0.4, s=15)
    ax.set_ylabel("n monetary states")
    ax.set_xlabel(r"$\alpha$")

    ax = fig.add_subplot(223)
    ax.scatter(qs, y, c="black", alpha=0.4, s=15)
    ax.set_ylabel("n monetary states")
    ax.set_xlabel(r"$q$")

    ax = fig.add_subplot(224)
    ax.scatter(gammas, y, c="black", alpha=0.4, s=15)
    ax.set_ylabel("n monetary states")
    ax.set_xlabel(r"$\gamma$")

    # ax = fig.add_subplot(224)
    # ax.scatter(x[X.x], y, c="black", alpha=0.4, s=15)
    # ax.set_ylabel("n monetary states")
    # ax.set_xlabel(r"n agents")

    # plt.text(0.005, 0.005, results_pool.file_name, transform=fig.transFigure, fontsize='x-small', color='0.5')

    plt.tight_layout()

    # plt.savefig("{}/separate_indirect_exchanges_proportions_{}.pdf"
    #           .format(analysis.parameters.fig_folder, results_pool.file_name))

    plt.show()