Ejemplo n.º 1
0
# Construct and compile neural event model
ne_clf = manifold.TSNE(n_components=2)
ne_embedded = nc_clf.fit_transform(train_proc_neural)

# Plot both embeddings in the same figure
f, axs = plt.subplots(3)
for idx, bc in enumerate(np.unique(behavior_clusters)):
    axs[0].scatter(be_embedded[behavior_clusters == bc, 0],
                   be_embedded[behavior_clusters == bc, 1],
                   c=cm.Reds_r(idx))
axs[0].set_title('Behavior embeddings colored by state.')

for idx, nc in enumerate(np.unique(neural_clusters)):
    axs[1].scatter(ne_embedded[neural_clusters == nc, 0],
                   ne_embedded[neural_clusters == nc, 1],
                   c=cm.Greens_r(idx))
axs[1].set_title('Neural embeddings colored by state.')
axs[2].plot(be_embedded[:, 0], be_embedded[:, 1], 'r', alpha=1)
axs[2].plot(ne_embedded[:, 0], ne_embedded[:, 1], 'g', alpha=0.6)

# Write a brief report and save associated data.
report = 'We applied a cluster analysis to behavior and neural ' +\
    'data, identifying "states" in each. There are different ' +\
    'numbers of clusters in each. This suggests that better ' +\
    'decoding performance could be achieved by selecting ' +\
    'the behavior and neural dimensions that best harmonize ' +\
    'the two data sources.'

# Make predictions on the test set and save for the competition
fn = c_utils.savefig(team_name)
c_utils.movefile_for_eval(fn)
Ejemplo n.º 2
0
    frame = event.frame
    image_feat = recog_net.feat_extract(frame)
    image_feature[counter, :] = image_feat.data.squeeze().unsqueeze_(0).numpy()
    counter += 1
event = env.step(action=dict(action='RotateRight', rotation=90.0))

# low dimensional embedding
svd = TruncatedSVD(n_components=50, n_iter=10)
image_feature_SVD = svd.fit_transform(image_feature)
image_embedded = TSNE(n_components=2).fit_transform(image_feature_SVD)

# plot embeddings
ff1 = plt.figure(figsize=(8, 6))
counter = 0
for i in range(100):
    plt.scatter(image_embedded[counter,0], image_embedded[counter,1],c=cm.Purples_r(i / 100.0))
    counter += 1
for i in range(100):
    plt.scatter(image_embedded[counter,0], image_embedded[counter,1],c=cm.Greens_r(i / 100.0))
    counter += 1
for i in range(100):
    plt.scatter(image_embedded[counter,0], image_embedded[counter,1],c=cm.Blues_r(i / 100.0))
    counter += 1
for i in range(100):
    plt.scatter(image_embedded[counter,0], image_embedded[counter,1],c=cm.Oranges_r(i / 100.0))
    counter += 1
plt.tight_layout()
plt.savefig('embedding3_ResNet3.png')
plt.close(ff1)

    def plot(self):
        import matplotlib.pyplot as plt
        from matplotlib import cm
        import matplotlib.dates as mdates
        import seaborn as sns
        sns.set_style("darkgrid")

        start_date = "2007-01-01"  # Day 1 of simulation
        date_format = "%Y-%m-%d"

        foo = mdates.strpdate2num(date_format)

        daynum = np.arange(self.n_tstep)
        daydates_list = []
        daydates_mdates = np.array([])
        for dayn in daynum:
            hold = convert_to_date(dayn, start_date, date_format=date_format)
            daydates_list.append(hold)
            daydates_mdates = np.append(daydates_mdates, foo(hold))

        print(daydates_mdates)

        maxpop_ever = 0
        for sim_id, data in self.RDT_prev_by_node.items():
            for j in range(self.n_nodes):
                maxp = np.max(self.pop_by_node[sim_id][j])
                if maxp > maxpop_ever:
                    maxpop_ever = maxp

        plt.figure(figsize=(12, 5))
        for sim_id, data in self.RDT_prev_by_node.items():
            for j in range(self.n_nodes):
                maxp = np.max(self.pop_by_node[sim_id][j])
                pop_ratio = np.float(maxp) / np.float(maxpop_ever)
                plt.plot_date(daydates_mdates,
                              self.RDT_prev_by_node[sim_id][j],
                              fmt='-',
                              alpha=pop_ratio,
                              color=cm.Greens_r(pop_ratio),
                              zorder=1)

        catch = self.catch.itervalues().next()

        # Look up catchment prevalence data from precomputed file:
        base = 'C:/Users/jsuresh/OneDrive - IDMOD/Projects/zambia-gridded-sims/'
        df = pd.read_csv(
            base +
            "data/interventions/kariba/2017-11-27/cleaned/catch_prevalence.csv"
        )
        catch_prev = np.array(df[catch])

        round_dates = [
            "2012-07-01", "2012-09-30", "2012-11-30", "2013-07-01",
            "2013-08-31", "2013-10-31", "2014-12-31", "2015-03-01",
            "2015-09-30", "2016-02-29"
        ]
        # round_dates = {
        #     "1": "2012-07-01",
        #     "2": "2012-09-30",
        #     "3": "2012-11-30",
        #     "4": "2013-07-01",
        #     "5": "2013-08-31",
        #     "6": "2013-10-31",
        #     "7": "2014-12-31",
        #     "8": "2015-03-01",
        #     "9": "2015-09-30",
        #     "10":"2016-02-29"
        # }

        round_dates_mdate = []
        for i in range(10):
            day_mdate = foo(round_dates[i])
            round_dates_mdate.append(day_mdate)
        round_dates_array = np.array(round_dates_mdate)

        if catch in [
                "chabbobboma", "chipepo", "gwembe", "lukande", "nyanga chaamwe"
        ]:
            plt.scatter(round_dates_array[:-4],
                        catch_prev[:-4],
                        c='red',
                        s=70,
                        label='Data for {}'.format(catch.capitalize()),
                        zorder=10)
            plt.scatter(round_dates_array[-4:],
                        catch_prev[-4:],
                        c='gray',
                        s=70,
                        label='HFCA not in MDA round',
                        zorder=10)
        elif catch in ["chisanga"]:
            plt.scatter(np.append(round_dates_array[:3],
                                  round_dates_array[5:]),
                        np.append(catch_prev[:3], catch_prev[5:]),
                        c='red',
                        s=70,
                        label='Data for {}'.format(catch.capitalize()),
                        zorder=10)
            plt.scatter(round_dates_array[3:5],
                        catch_prev[3:5],
                        c='gray',
                        s=70,
                        label='HFCA not in MDA round',
                        zorder=10)
        else:
            plt.scatter(round_dates_array,
                        catch_prev,
                        c='red',
                        s=70,
                        label='Data for {}'.format(catch.capitalize()),
                        zorder=10)

        # # Plot Chiyabi interventions as vertical lines:
        # if True:
        #     # plot_only_first = False
        #
        #     # Event information files
        #     itn_event_file = "C:/Users/jsuresh/OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_itn_events.csv"
        #     irs_event_file = "C:/Users/jsuresh/OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_irs_events.csv"
        #     msat_event_file = "C:/Users/jsuresh/OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_msat_events.csv"
        #     mda_event_file = "C:/Users/jsuresh/OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_mda_events.csv"
        #     healthseek_event_file = "C:/Users/jsuresh//OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_healthseek_events.csv"
        #     stepd_event_file = "C:/Users/jsuresh//OneDrive - IDMOD/Code/zambia/cbever/chiyabi_hfca_stepd_events.csv"
        #
        #     # Import event info
        #     itn_events = pd.read_csv(itn_event_file)
        #     irs_events = pd.read_csv(irs_event_file)
        #     msat_events = pd.read_csv(msat_event_file)
        #     mda_events = pd.read_csv(mda_event_file)
        #     healthseek_events = pd.read_csv(healthseek_event_file)
        #     stepd_events = pd.read_csv(stepd_event_file)
        #
        #     # for date in itn_events['fulldate']: plt.axvline(convert_to_day(date, start_date, date_format=date_format), ls='dashed', color='C0') #,label='ITN Events')
        #     # for date in irs_events['fulldate']: plt.axvline(convert_to_day(date, start_date, date_format=date_format), ls='dashed', color='C1') #,label='IRS Events')
        #     # for date in msat_events['fulldate']: plt.axvline(convert_to_day(date, start_date, date_format=date_format), ls='dashed', color='C2') #,label='MSAT Events')
        #     # for date in mda_events['fulldate']: plt.axvline(convert_to_day(date, start_date, date_format=date_format), ls='dashed', color='C3') #,label='MDA Events')
        #
        #     for date in itn_events['fulldate']: plt.axvline(foo(date), ls='dashed', color='blue') #,label='ITN Events')
        #     for date in irs_events['fulldate']: plt.axvline(foo(date), ls='dashed', color='green') #,label='IRS Events')
        #     for date in msat_events['fulldate']:plt.axvline(foo(date), ls='dashed', color='red') #,label='MSAT Events')
        #     for date in mda_events['fulldate']: plt.axvline(foo(date), ls='dashed', color='purple') #,label='MDA Events')
        #
        #
        #     # colors:
        #     # c0 = blue = ITN
        #     # c1 = green = IRS
        #     # c2 = red = MSAT
        #     # c3 = purple = MDA

        plt.legend()
        # plt.xlim([3000,7000])
        plt.xlim([foo("2010-01-01"), foo("2019-01-01")])
        # plt.show()
        plt.tight_layout()
        plt.savefig(base + "data/figs/{}_prev_node.png".format(catch))
Ejemplo n.º 4
0
img_all = np.concatenate(spl_list)
h2_all = tsne.fit_transform(np.concatenate(h2_list, axis=0))
hmin, hmax = h2_all.min(), h2_all.max()
width = np.ceil(hmax - hmin).astype(int)
wall = np.zeros([64 * width, 64 * width, 3])
for s in range(len(samples)):
    x, y = np.int_(h2_all[s] - hmin) * 64
    wall[x:x + 64, y:y + 64] = (samples[s] + 1) * 255 / 2

wall[wall < 0] = 0
wall[wall > 255] = 255

from matplotlib import cm

cstart = cm.Greens_r(np.linspace(0, 1, 255))
cstop = cm.Reds_r(np.linspace(0, 1, 255))

n_iter = 5000
cmaps = np.zeros([int(n_iter / 10), 255, 3])
for i in range(255):
    for j in range(3):
        cmaps[:, i, j] = np.linspace(cstart[i, j], cstop[i, j],
                                     int(n_iter / 10))

h2_list, spl_list = [], []
for i_class in range(num_classes):
    ppgn.sampler_init(i_class)
    samples, h2 = ppgn.sample(i_class,
                              nbSamples=5000,
                              h2_start=None,
Ejemplo n.º 5
0
    def plot_elasticity(self, spline, strain):
        ''' Plot the youngs modulus '''

        out = np.array(self.youngs_modulus)
        x = out[:, 0]
        y = out[:, 1]

        plt.figure()
        plt.plot(x, y, 'x')
        plt.title("Youngs Modulus")
        plt.show()

        naturalShape = strain.naturalShape

        wholeShape = spline.spline
        wholeShape_UpperHalf = []

        for i in range(1, len(wholeShape[0]) - 1):
            if (wholeShape[1][i] > 0.0):
                wholeShape_UpperHalf.append(
                    [wholeShape[0][i], wholeShape[1][i]])

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        theta_grid = np.linspace(0, 2 * np.pi, 100)
        out = np.array(naturalShape)
        shape_x = out[:, 0]
        shape_y = out[:, 1]

        out = np.array(wholeShape_UpperHalf)
        wholeShape_x = out[:, 0]
        wholeShape_y = out[:, 1]

        r_points, theta_points = np.meshgrid(shape_y, theta_grid)
        r_wholeShape, theta_wholeShape = np.meshgrid(wholeShape_y, theta_grid)

        temp = [self.youngs_modulus[-1][0], self.youngs_modulus[-1][1]]
        self.youngs_modulus.append(temp)
        out = np.array(self.youngs_modulus)

        E_x = out[:, 0]
        E_y = out[:, 1]
        data, theta_points = np.meshgrid(E_y, theta_grid)

        print "Length E_y"
        print len(E_y)

        x_points, y_points = r_points * np.cos(
            theta_points), r_points * np.sin(theta_points)
        x_wholeShape, y_wholeShape = r_wholeShape * np.cos(
            theta_wholeShape), r_wholeShape * np.sin(theta_wholeShape)

        #ax.plot_surface(x_wholeShape, y_wholeShape, wholeShape_x, rstride=1, cstride=1, cmap=cm.YlGnBu_r)
        #plt.show()

        #ax.plot_surface(x_points, y_points, shape_x, rstride=1, cstride=1, cmap=cm.YlGnBu_r)

        #plt.show()

        E_range = max(E_y) - min(E_y)
        #print max(E_y)
        #print min(E_y)
        #N = data/E_range
        #N = data/E_range

        max_base = 0.0
        max_trans = 0.0
        max_shaft = 0.0
        max_tip = 0.0
        min_base = 100.0
        min_trans = 100.0
        min_shaft = 100.0
        min_tip = 100.0

        for i in range(0, len(self.youngs_modulus)):

            if (self.youngs_modulus[i][0] < self.params.r_base):
                if (max_base < self.youngs_modulus[i][1]):
                    max_base = self.youngs_modulus[i][1]
                if (min_base > self.youngs_modulus[i][1]):
                    min_base = self.youngs_modulus[i][1]

            if ((self.params.r_base < self.youngs_modulus[i][0]) &
                (self.youngs_modulus[i][0] <
                 self.params.L - self.params.r_shaft - self.params.r_tip)):
                if (max_trans < self.youngs_modulus[i][1]):
                    max_trans = self.youngs_modulus[i][1]
                if (min_trans > self.youngs_modulus[i][1]):
                    min_trans = self.youngs_modulus[i][1]

            if ((self.params.L - self.params.r_shaft - self.params.r_tip <
                 self.youngs_modulus[i][0]) &
                (self.youngs_modulus[i][0] <
                 self.params.L - self.params.r_tip)):
                if (max_shaft < self.youngs_modulus[i][1]):
                    max_shaft = self.youngs_modulus[i][1]
                if (min_shaft > self.youngs_modulus[i][1]):
                    min_shaft = self.youngs_modulus[i][1]

            if (self.params.L - self.params.r_tip < self.youngs_modulus[i][0]):
                if (max_tip < self.youngs_modulus[i][1]):
                    max_tip = self.youngs_modulus[i][1]
                if (min_shaft > self.youngs_modulus[i][1]):
                    min_tip = self.youngs_modulus[i][1]

        print "Youngs Modulus maxima and minima in different regions"
        print "Region\tMax\tMin"
        print "Global\t" + str(max(E_y)) + "\t" + str(min(E_y))
        print "Base\t" + str(max_base) + "\t" + str(min_base)
        print "Neck\t" + str(max_trans) + "\t" + str(min_trans)
        print "Base\t" + str(max_shaft) + "\t" + str(min_shaft)
        print "Tip\t" + str(max_tip) + "\t" + str(min_tip)

        N = data / 5.0
        #print data

        #print N
        #print cm.jet(N)

        #ax.plot_surface(x_wholeShape, y_wholeShape, wholeShape_x, rstride=1, cstride=1, cmap=cm.Reds)
        ax.plot_surface(x_points,
                        y_points,
                        shape_x,
                        rstride=1,
                        cstride=1,
                        facecolors=cm.Greens_r(N),
                        linewidth=0,
                        antialiased=False,
                        shade=False)
        #ax.set_zlim3d(0, cell_radius + shmoo_length)
        #ax.set_xlabel(r'$x$')
        #ax.set_ylabel(r'$y$')
        #ax.set_zlabel(r'$z$')

        ax.grid(False)
        for a in (ax.w_xaxis, ax.w_yaxis, ax.w_zaxis):
            for t in a.get_ticklines() + a.get_ticklabels():
                t.set_visible(False)
            a.line.set_visible(False)
            a.pane.set_visible(False)

        m = cm.ScalarMappable(cmap=cm.Greens_r)
        m.set_array(N)
        m.set_clim(0.0, 5.0)
        plt.colorbar(m)
        plt.show()

        plt.savefig("Youngs_Modulus.png")
        plt.savefig("Youngs_Modulus.eps", format="eps")
Ejemplo n.º 6
0
#ax.plot_surface(x_points, y_points, shape_x1, rstride=1, cstride=1, cmap=cm.YlGnBu_r)

#strain_range = max(strain_vol) - min(strain_vol)
#strain_range = max(strain_vol) - min(strain_vol)

N = data / 4.0

# print N
# print cm.jet(N)

ax.plot_surface(x_points,
                y_points,
                shape_x1,
                rstride=1,
                cstride=1,
                facecolors=cm.Greens_r(N),
                linewidth=1,
                antialiased=False,
                shade=False)

# ax.set_zlim3d(0, cell_radius + shmoo_length)
# ax.set_xlabel(r'$x$')
# ax.set_ylabel(r'$y$')
# ax.set_zlabel(r'$z$')

ax.grid(False)
for a in (ax.w_xaxis, ax.w_yaxis, ax.w_zaxis):
    for t in a.get_ticklines() + a.get_ticklabels():
        t.set_visible(False)
    a.line.set_visible(False)
    a.pane.set_visible(False)
Ejemplo n.º 7
0
fig = pl.figure(1, (10, 15))
ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(322)
ax3 = fig.add_subplot(323)
ax4 = fig.add_subplot(324)
ax5 = fig.add_subplot(325)
ax6 = fig.add_subplot(326)
for inh_count, inh_val in enumerate(inh_range):
    ax1.plot(exc_range,
             inh_exc_stn_fr[inh_count],
             color=cm.Reds_r(inh_count * 30),
             lw=3.,
             label=str(inh_val))
    ax3.plot(exc_range,
             inh_exc_stn_ff[inh_count],
             color=cm.Greens_r(inh_count * 30),
             lw=3.,
             label=str(inh_val))
    ax2.plot(exc_range,
             inh_exc_gpe_fr[inh_count],
             color=cm.Reds_r(inh_count * 30),
             lw=3.)
    ax4.plot(exc_range,
             inh_exc_gpe_ff[inh_count],
             color=cm.Greens_r(inh_count * 30),
             lw=3.)
    ax5.plot(exc_range,
             inh_exc_stn_spec[inh_count],
             color=cm.Blues_r(inh_count * 30),
             lw=3.,
             label=str(inh_val))