def plot3d():
            fig = plt.figure()
            ax = Axes3D(fig)

            X_seq, T_seq = self.point_info_manager.X_seq, self.point_info_manager.T_seq
            if self.gt_available:
                c_true, lower, upper = normalization.zero_one_normalization(self.z)
                c_true = cm.bwr(c_true * 255)
                ax.scatter([x[0] for x in self.X_grid.astype(float)], [x[1] for x in self.X_grid.astype(float)],
                           [x[2] for x in self.X_grid.astype(float)],
                           c=c_true, marker='o',
                           alpha=0.5, s=5)
                c = cm.bwr(normalization.zero_one_normalization(T_seq, self.z.min(), self.z.max())[0] * 255)

            else:
                c = cm.bwr(normalization.zero_one_normalization(T_seq)[0] * 255)

            ax.scatter([x[0] for x in X_seq], [x[1] for x in X_seq], [x[2] for x in X_seq], c='y', marker='o',
                       alpha=0.5)

            if self.does_pairwise_sampling:
                ax.scatter(X_seq[-1][0], X_seq[-1][1], X_seq[-1][2], c='m', s=50, marker='o', alpha=1.0)
                ax.scatter(X_seq[-2][0], X_seq[-2][1], X_seq[-2][2], c='m', s=100, marker='o', alpha=1.0)
            else:
                ax.scatter(X_seq[-1][0], X_seq[-1][1], X_seq[-1][2], c='m', s=50, marker='o', alpha=1.0)
Exemplo n.º 2
0
def plot_links(
    ax: Axes, points: array_like, score_matrix: np.ndarray, inside_spheres: np.ndarray
):
    """
    Plot scored links between points.

    Parameters
    ----------
    ax: Axes
        Matplotlib Axes object.
    points : (N, D) array_like
        Input points.
    score_matrix : (N, N) ndarray
        Score matrix.
    inside_spheres : (N,) ndarray
        Boolean array.
        Element i is True if position i is inside the combined sphere volume.

    """
    for i, point_i in enumerate(points):
        for j, point_j in enumerate(points):

            if inside_spheres[i] and inside_spheres[j]:
                score = score_matrix[i, j]

                if score != 0:
                    # Plot line coloured by score
                    connect_points(
                        ax,
                        point_i,
                        point_j,
                        c=cm.bwr(score),
                        linestyle='-',
                        linewidth=0.75,
                    )
Exemplo n.º 3
0
def show_active_areas(finger_idx, part_idx, object_name, intent):
    filename = osp.join('data', 'object_models', f'{object_name}.ply')
    mesh = o3dio.read_triangle_mesh(filename)
    mesh.compute_vertex_normals()

    filename = osp.join(
        'data',
        f'{object_name}_{intent}_{finger_idx}_{part_idx}_active_areas.npy')
    c = np.load(filename)
    mesh.vertex_colors = o3du.Vector3dVector(cm.bwr(c)[:, :3])
    o3dv.draw_geometries([mesh])
Exemplo n.º 4
0
def update_func(step, dual_graph, demvec, repvec, nodes):
    # the step parameter is mandatory for matplotlib
    # Set new value for figure data
    # update node color here
	value_map = []
	for i in range(dual_graph.number_of_nodes()):
		if demvec[step][i] == 0 and repvec[step][i] == 0:
			value_map.append(0.5)
		else:
			value_map.append((repvec[step][i]/(demvec[step][i] + repvec[step][i])))
	value_map = cm.bwr(np.array(value_map).astype(float))
	nodes.set_color(value_map)
	return nodes
Exemplo n.º 5
0
def plot_sh_in_spherical_coos(ell, m, args):
    # inspired by http://balbuceosastropy.blogspot.com/2015/06/spherical-harmonics-in-python.html

    #ensure valid input
    assert np.abs(m) <= ell

    outfile = args.outfile
    if outfile is None:
        outfile = 'l{0}m{1}_sp{2}.png'.format(ell, m,
                                              '_s' if args.square else '')

    PHI, THETA = np.mgrid[0:2 * np.pi:200j, 0:np.pi:100j]
    R = sp.sph_harm(m, ell, PHI, THETA)

    if args.square:
        R = abs(R)
        RS = R
    else:
        R = R.real
        RS = R**2

    # Convert to cartesian coordinates for the 3D representation
    X = RS * np.sin(THETA) * np.cos(PHI)
    Y = RS * np.sin(THETA) * np.sin(PHI)
    Z = RS * np.cos(THETA)

    fig = plt.figure(figsize=(args.size, args.size), tight_layout={'pad': 0})
    ax = fig.add_subplot(projection='3d')

    limit = max(X.max(), Y.max(), Z.max())

    ax.set_xlim([-limit, limit])
    ax.set_ylim([-limit, limit])
    ax.set_zlim([-limit, limit])
    ax.axis('off')
    ax.grid(b=None)
    ax.relim()

    norm = colors.Normalize()

    im = ax.plot_surface(X,
                         Y,
                         Z,
                         rstride=1,
                         cstride=1,
                         facecolors=cm.bwr(norm(R)))
    m = cm.ScalarMappable(cmap=cm.bwr)
    m.set_array(R)
    fig.savefig(outfile, dpi=args.dpi, bbox_inches=0)

    print('\nWrote ' + outfile)
Exemplo n.º 6
0
def update(frame):

    scat._offsets3d = (avg[frame, :, 0], avg[frame, :, 1], avg[frame, :, 2])
    # scat.set_offsets(avg[frame,:,[1,2]].T)

    cols = np.isin(np.unique(cond), pos_conds[PS[frame, :].argmax()])

    scat._facecolor3d = cm.bwr(cols / cols.max())
    # scat._facecolor = cm.bwr(cols/cols.max())
    ax.title.set_text(str(pos_conds[PS[frame, :].argmax()]))
    # scat2._offsets3d
    # util.set_axes_equal(ax)
    # plt.draw()
    return fig,
Exemplo n.º 7
0
    def plot_bader_dos(self, **args):
        if 'types_to_plot' in args:
            types_to_plot = args['types_to_plot']
        else:
            types_to_plot = self.atomtypes

        if 'range_to_plot' in args:
            range_to_plot = args['range_to_plot']
        else:
            range_to_plot = [[] for i in range(3)]
            for i in range(3):
                tempvar = zeros(3)
                tempvar[i] += 1.0
                range_to_plot[i].append(-1.5 * norm(dot(tempvar, self.lv)))
                range_to_plot[i].append(1.5 * norm(dot(tempvar, self.lv)))

        self.baderdosfig, self.baderdosax = plt.subplots(1, 1)

        atoms_to_plot = []
        colorlist = []
        for i in range(len(self.coord)):
            for j in range(len(self.atomtypes)):
                if i < sum(self.atomnums[:j + 1]):
                    break
            if self.atomtypes[j] in types_to_plot:
                for k in range(3):
                    if self.coord[i][k] < min(
                            range_to_plot[k]) or self.coord[i][k] > max(
                                range_to_plot[k]):
                        break
                else:
                    atoms_to_plot.append(i)
                    colorlist.append(self.numvalence[j] - self.charges[i])

        cnorm = Normalize(vmin=min(colorlist), vmax=max(colorlist))
        for i, j in zip(atoms_to_plot, colorlist):
            tempy = zeros(len(self.energies))
            for k in range(len(self.dos[i + 1])):
                tempy += self.dos[i + 1][k]
            self.baderdosax.plot(self.energies, tempy, color=bwr(cnorm(j)))
        self.baderdosax.set(xlabel='energy - $E_f$ / eV')
        self.baderdosax.set(ylabel='DOS / states $eV^{-1}$')
        self.baderdosax.set_facecolor('grey')
        cbar = plt.colorbar(ScalarMappable(norm=cnorm, cmap='bwr'))
        plt.set_cmap('bwr')
        cbar.set_label('net charge of {}'.format(', '.join(types_to_plot)))
        cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%+.3f'))
        plt.show()
        print('{} DOS curves plotted'.format(len(colorlist)))
Exemplo n.º 8
0
 def disp_one_line(self, ax, subtext, subvals, height):
     cl_s = cm.bwr(subvals)
     for i, (ch, cl) in enumerate(zip(subtext, cl_s)):
         ax.text(0.01 + i * self.font_rw,
                 height,
                 ch,
                 fontname=self.fontname,
                 fontsize=self.fontsize,
                 bbox={
                     'facecolor': cl,
                     'edgecolor': cl,
                     'alpha': 0.8,
                     'pad': 1
                 })
     return ax
Exemplo n.º 9
0
def plot_neurosynth(t_stat,pvals,topic_terms,title='',test='chi2',ax=None):
    if not ax:
        fig = plt.figure(figsize=(4,6))
        ax = fig.add_subplot(1,1,1)
    colors=np.ones(len(topic_terms))*0.7
    colors[pvals<0.05/len(topic_terms)]=1
    cols=cm.bwr(colors)
    
    ordered_pvals=pvals[np.argsort(t_stat)]
    ax.barh(np.arange(len(t_stat)),np.sort(t_stat),color=cols[np.argsort(t_stat)])
    topic_terms[np.argsort(pvals)],t_stat[np.argsort(pvals)],np.sort(pvals)
    ax.set_yticks(np.arange(len(topic_terms)))
    ax.set_yticklabels(topic_terms[np.argsort(t_stat)])
    #plt.yticks(np.arange(len(topics))[ordered_pvals<0.05],topic_terms[np.argsort(t_stat)][ordered_pvals<0.05])
    ax.set_title(title)
    ax.set_xlabel(test)
    return ax
Exemplo n.º 10
0
        def create_edge(x1, y1, x2, y2, weight, maximum, minimum):

            # scale weight to value between 0 and 1
            scaled_weight = (weight - minimum) / (maximum - minimum)

            # map the weight to a color on red-blue color scale
            color = 'rgb' + str(
                tuple([i * 255 for i in cm.bwr(scaled_weight)[:-1]]))

            # return the edge that connects (x1, y1) to (x2, y2)
            return go.Scatter(x=[x1, x2],
                              y=[y1, y2],
                              line={
                                  'width': line_width,
                                  'color': color
                              },
                              mode='lines')
Exemplo n.º 11
0
 def onclick(self, event):
     if event.inaxes == self.ax:
         self.x = event.xdata
         self.y = event.ydata
         xlim0, xlim1 = self.ax.get_xlim()
         if self.x <= xlim0 + (xlim1 - xlim0) * self.clicklim:
             self.horizontal_line.set_ydata(self.y)
             self.text.set_text("{0:.2f}".format(self.y))
             self.text.set_position((xlim0, self.y))
             self.fig.canvas.draw()
         self.diff = (self.mean + (self.confint / 2)) - self.y
         self.diff[self.diff < 0] = 0
         self.ax.bar(self.values,
                     self.mean,
                     yerr=self.confint,
                     edgecolor='black',
                     color=cm.bwr(tuple(self.diff / 10000)))
         plt.draw()
Exemplo n.º 12
0
 def __init__(self, ax, mean, confint, values, clicklim=0.05):
     self.fig = ax.figure
     self.diff = confint
     self.values = values
     self.ax = ax
     self.mean = mean
     self.confint = confint
     self.y = 0
     self.x = 0
     self.clicklim = clicklim
     self.horizontal_line = ax.axhline(y=0.5, color='black', alpha=0.5)
     self.text = ax.text(0, 0.5, "")
     print(self.horizontal_line)
     self.ax.bar(self.values,
                 self.mean,
                 yerr=self.confint,
                 edgecolor='black',
                 color=cm.bwr(tuple(self.diff / 10000)))
     self.fig.canvas.mpl_connect('button_press_event', self.onclick)
def main():
    """Make the dispersion plot."""
    eq_pot_stdev = 0.05
    file_name = 'files/simulationParameters.json'
    data = io.read_json_params(file_name, "Martin's experiment")
    time_end = 2 * (data["pot_rev"] - data["pot_start"]) / data["nu"]
    num_time_pts = int(np.ceil(200 * data["freq"] * time_end))
    time_step = time_end / (num_time_pts - 1)
    time = np.linspace(0, time_end, num_time_pts)

    eq_pot_grid = gt.hermgauss_param(5, data["eq_pot"], eq_pot_stdev, False)

    color_scale = eq_pot_grid[0]
    # Rescale to [0,1]
    color_scale = (color_scale - np.min(color_scale))\
               / (np.max(color_scale) - np.min(color_scale))

    colors = [cm.bwr(x) for x in color_scale] #pylint: disable=no-member

    #Generate currents
    # Start with capacitive current
    eq_rate = data["eq_rate"]
    data["eq_rate"] = 0
    cap_current, _ = st.solve_reaction_from_json(time_step, num_time_pts, data)
    data["eq_rate"] = eq_rate

    disp_current = np.zeros(num_time_pts)

    # Now, compute the component currents.
    for color, eq_pot, weight in zip(colors, *eq_pot_grid):
        data["eq_pot"] = eq_pot
        current, _ = st.solve_reaction_from_json(time_step, num_time_pts, data)
        current -= cap_current
        current *= weight
        plot_envelopes(time, current, color)
        disp_current += current

    plt.fill_between(time, disp_current, -disp_current)
    plt.show(block=True)
Exemplo n.º 14
0
def make_colormaps(images, limit=1.0): 
	""" input argments: 
	- images: anomaly maps 
		(# of images) by (height) by (width) 
	- limit: lower or upper bound 
		the magnitudes of the lower and upper bound set equally 

	output arguments: 
	- scaled: anomaly maps painted as red(excessive) or blue(insufficient) colors 
		(# of images) by (rgb channel) by (height) by (width) 
		if masks is not None, the pad information is also displayed 
	"""

	images = images.double()  
	images.clamp_(-limit, limit) 

	scaled = (images+limit)/(2*limit) 
	scaled = cm.bwr(scaled)    

	scaled = torch.tensor(scaled)[:,:,:,:3]
	scaled = scaled.permute(0, 3, 1, 2) 

	return scaled 
Exemplo n.º 15
0
    def generate_pymol_image(self, g):
        """
        This function generates the pymol image representing one ensemble. It scales the structure color with respect
        the variability of the residues among representative conformations using own pymol metric.
        :param g: graph of representative conformations of one ensemble
        """

        # Load the structure conformations
        structure = PDBParser(QUIET=True).get_structure(self._id, self._path)

        # Creating pymol folder
        os.makedirs('data/pymol', exist_ok=True)

        # Build the matrix with the features of the representative conformations
        representative_features = []
        first = True

        models = [int(m) for m in g.nodes()]
        for model in models:
            representative_features.append(self._features[model])
            # If not done yet, open the structure for Pymol
            if first:
                print('\n\t- Model {} used for Pymol image'.format(model))
                io = PDBIO()
                io.set_structure(structure[model])
                io.save("data/pymol/{}.pdb".format(self._id))
                first = False

        representative_features = np.matrix(representative_features)

        # Build feature matrices for representative conformations
        asa = extract_vectors_model_feature(self._residues,
                                            key='ASA',
                                            features=representative_features)
        ss = extract_vectors_model_feature(self._residues,
                                           key='SS',
                                           features=representative_features)
        temp_dist = extract_vectors_model_feature(
            self._residues, key='DIST', features=representative_features)

        # Reshape distance matrix (linear to square)
        dist = np.zeros(
            (len(representative_features), self._residues, self._residues))
        for k in range(len(representative_features)):
            idx = np.triu_indices(self._residues, k=1)
            dist[k][idx] = temp_dist[k]
            dist[k] = dist[k] + dist[k].T

        # For each residue, determine the window around it and apply the metric
        residue_variability = []
        window_size = 9
        for residue in range(self._residues):
            start = max(0, residue - window_size)
            end = min(self._residues - 1, residue + window_size)
            residue_variability.append(
                self.pymol_metric(asa[:, start:end], ss[:, start:end],
                                  dist[:, start:end]))

        # Pymol image generation
        cmd.delete("all")
        cmd.load("data/pymol/{}.pdb".format(self._id),
                 self._id)  # Load from file
        cmd.remove("resn hoh")  # Remove water molecules
        cmd.hide("lines", "all")  # Hide lines
        cmd.show("cartoon", "all")  # Show cartoon
        cmd.orient()
        cmd.zoom()
        norm = colors.Normalize(vmin=min(residue_variability),
                                vmax=max(residue_variability))

        # Changing of the residue color according to its window variability
        for i, residue in enumerate(
                Selection.unfold_entities(structure[0], "R")):
            rgb = cm.bwr(norm(residue_variability[i]))
            cmd.set_color("col_{}".format(i), list(rgb)[:3])
            cmd.color("col_{}".format(i), "resi {}".format(residue.id[1]))

        # Pymol image saving
        cmd.png("{}/{}_pymol.png".format(self._output_folder, self._id), ray=1)
        print('\t- Successfully saved {}_pymol.png in {}'.format(
            self._id, self._output_folder))

        # Showing Pymol image
        pymol_image = Image.open("{}/{}_pymol.png".format(
            self._output_folder, self._id))

        fig, axes = plt.subplots()
        axes.imshow(pymol_image)
        axes.set_xticks([])
        axes.set_yticks([])
        plt.show()
Exemplo n.º 16
0
def main(argv):
	parser = argparse.ArgumentParser(description='Plotting 3DConv 4 Model Activations')
	parser.add_argument('--mov_name', help='Name of movie to process')

	args = parser.parse_args()
	arg_dict = args.__dict__

	if 'mov_name' in arg_dict.keys() and arg_dict['mov_name'] is not None:
		video_pattern = os.path.splitext(args.mov_name)[0]

	reader = imageio.get_reader(video_pattern+'.avi')
	writer = imageio.get_writer(video_pattern+'_out_Activations.avi', fps=30, codec='mpeg4', quality=10)
	im_iter = reader.iter_data()

	label_file = video_pattern+'_crop_raw.npy'
	label_data=[]
	with open(label_file,'rb') as file:
		while True:
			try:
				if sys.version_info[0]==2:
					label_data.append(np.load(file))
				else:
					label_data.append(np.load(file, encoding = 'bytes', allow_pickle = False))
			except IOError:
				break
			except ValueError:
				break

	label_data = np.reshape(label_data, [-1, np.shape(label_data)[-1]])

	# Save the new format because it's that much faster
	np.save(label_file, label_data, allow_pickle=False)

	label_data = np.reshape(label_data, [-1, int(np.shape(label_data)[-1]/2), 2])
	label_data_softmax = softmax(label_data)
	predictions_all = label_data_softmax[:,:,1]
	mean_pred = np.mean(predictions_all, axis=1)
	mean_pred = np.convolve(mean_pred, np.ones((46))/(46), mode='same')

	input_size = 112
	time_depth = 16
	frames = [np.zeros([input_size, input_size, 1]) for x in range(time_depth)]

	frame_num = 0
	n_models = 4
	prediction_size = 16
	while True:
		try:
			frame = np.uint8(next(im_iter))
			new_frame = np.copy(frame)
			new_frame = np.pad(new_frame, ((0,0),((1+n_models*prediction_size),0),(0,0)), 'constant', constant_values=0)

			# Plot the activations...
			predictions = predictions_all[frame_num,:]
			mean_cons = mean_pred[frame_num]
			# Black out the background behind...
			new_frame[0:(1+8*prediction_size+n_models*prediction_size),0:(1+n_models*prediction_size),:] = 0
			for i in range(int(np.shape(predictions)[0]/n_models)):
				for j in range(n_models):
					cur_result = predictions[i*n_models+j]
					new_frame[(1+prediction_size*i):(prediction_size+prediction_size*i),(1+prediction_size*j):(prediction_size+prediction_size*j),:] = np.multiply(cm.bwr(cur_result)[0:3],255)
			# Consensus prediction
			if mean_cons > 0.4811055:
				new_frame[1+8*prediction_size:(8*prediction_size+n_models*prediction_size),1:n_models*prediction_size,:] = [200,0,0]
			else:
				new_frame[1+8*prediction_size:(8*prediction_size+n_models*prediction_size),1:n_models*prediction_size,:] = [0,0,200]
			writer.append_data(new_frame.astype('u1'))
			frame_num = frame_num + 1

		except StopIteration:
			break
	reader.close()
	writer.close()
Exemplo n.º 17
0
    def plot_map(self, size, **args):
        if type(size) == int:
            size = (size, size)
        if 'cmap' in args:
            self.cmap = args['cmap']

        if 'orbitals' in args:
            orbitals_to_plot = args['orbitals']
        else:
            orbitals_to_plot = [i for i in range(len(self.orbitals))]
        if len(orbitals_to_plot) == len(self.orbitals):
            self.orbitals = ['all']
        else:
            self.orbitals = [self.orbitals[i] for i in orbitals_to_plot]
        self.ldos = sum([self.ldos[i] for i in orbitals_to_plot])

        if 'smear' in args:
            self.smear_ldos(float(args['smear']))

        if 'normalize_ldos' in args:
            normalize_ldos = args['normalize_ldos']
        else:
            normalize_ldos = True

        if 'show_charges' in args:
            show_charges = args['show_charges']
            charge_list = []
            for i in self.plot_atoms:
                for j in range(len(self.atomtypes)):
                    if i < sum(self.atomnums[:j + 1]):
                        break
                if self.atomtypes[j] in show_charges:
                    charge_list.append(self.numvalence[j] - self.charges[i])
            cnorm = Normalize(vmin=min(charge_list), vmax=max(charge_list))
        else:
            show_charges = []

        self.ldosfig, self.ldosax = plt.subplots(1, 1)

        #plots the ldos
        for i in range(size[0] + 1):
            for j in range(size[1] + 1):
                if normalize_ldos:
                    ldosmap = self.ldosax.pcolormesh(
                        self.x + self.lv[0][0] * i + self.lv[1][0] * j,
                        self.y + self.lv[0][1] * i + self.lv[1][1] * j,
                        self.ldos / max([max(i) for i in self.ldos]),
                        cmap=self.cmap,
                        shading='nearest')
                else:
                    ldosmap = self.ldosax.pcolormesh(
                        self.x + self.lv[0][0] * i + self.lv[1][0] * j,
                        self.y + self.lv[0][1] * i + self.lv[1][1] * j,
                        self.ldos,
                        cmap=self.cmap,
                        shading='nearest')

        if 'show_colorbar' in args:
            map_cbar = self.ldosfig.colorbar(ldosmap)

        #holds the position and color of each atom
        tempx = []
        tempy = []
        colors = []
        sizes = []
        counter = 0
        #plots the overlaid atoms as a scatterplot
        for i in self.plot_atoms:
            for j in range(len(self.atomtypes)):
                if i < sum(self.atomnums[:j + 1]):
                    break
            for k in range(size[0] + 1):
                for l in range(size[1] + 1):
                    tempx.append(self.coord[i][0] + self.lv[0][0] * k +
                                 self.lv[1][0] * l)
                    tempy.append(self.coord[i][1] + self.lv[0][1] * k +
                                 self.lv[1][1] * l)
                    sizes.append(self.atom_sizes[j] / (max(size) + 1))
                    if self.atomtypes[j] in show_charges:
                        colors.append(bwr(cnorm(charge_list[counter])))
                    else:
                        colors.append(self.atom_colors[j])
            if self.atomtypes[j] in show_charges:
                counter += 1

        atom_scatter = self.ldosax.scatter(tempx, tempy, color=colors, s=sizes)
        self.ldosax.set(xlabel='x coordinate / $\AA$')
        self.ldosax.set(ylabel='y coordinate / $\AA$')
        self.ldosax.set(
            title=
            '{} to {} V | {} $\AA$ | $\phi$ = {} | $\sigma$ = {}\ncontributing orbitals: {}'
            .format(self.emin, self.emax, self.tip_disp, self.phi, self.sigma,
                    ', '.join(self.orbitals)))
        patches = []
        for i in range(len(self.atomtypes)):
            if self.atomtypes[i] not in show_charges:
                patches.append(
                    mpatches.Patch(color=self.atom_colors[i],
                                   label=self.atomtypes[i]))

        #if bader charges are plotted, a colorbar is displayed
        if len(show_charges) > 0:
            cbar = self.ldosfig.colorbar(ScalarMappable(norm=cnorm, cmap=bwr))
            cbar.set_label('net charge of {}'.format(', '.join(show_charges)))
            cbar.ax.yaxis.set_major_formatter(FormatStrFormatter('%+.3f'))

        self.ldosfig.legend(handles=patches)
        self.ldosfig.subplots_adjust(top=0.9)
        self.ldosax.set_aspect('equal')
        self.ldosfig.show()
Exemplo n.º 18
0
    #np.histogram2d()将两列数值转为矩阵
    heatmap, xedges, yedges = np.histogram2d(x, y, bins = bins)
    #高斯锐化模糊对象
    heatmap = gaussian_filter(heatmap, sigma = s)
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    return heatmap.T, extent

#读取森林地图底图
#Normalize归一化
#np.clip(x,a,b)将x中小于a的值设为a,大于b的值设为b
#cm.bwr 蓝白红
bg = imread('erangel.jpg')
hmap, extent = heatmap(plot_data_ev[:,0], plot_data_ev[:,1], 1.5, bins =800)
alphas = np.clip(Normalize(0, hmap.max()/100, clip=True)(hmap)*1.5,0.0,1.)
colors = Normalize(hmap.max()/100, hmap.max()/20, clip=True)(hmap)
colors = cm.bwr(colors)
colors[..., -1] = alphas

hmap2, extent2 = heatmap(plot_data_ek[:,0],plot_data_ek[:,1],1.5, bins = 800)
alphas2 = np.clip(Normalize(0, hmap2.max()/100, clip = True)(hmap2)*1.5, 0.0, 1.)
colors2 = Normalize(hmap2.max()/100, hmap2.max()/20, clip=True)(hmap2)
colors2 = cm.RdBu(colors2)
colors2[...,-1] = alphas2

#'森林死亡率图'
fig, ax = plt.subplots(figsize = (24,24))
ax.set_xlim(0, 4096);ax.set_ylim(0, 4096)
ax.imshow(bg)
ax.imshow(colors, extent = extent, origin = 'lower', cmap = cm.bwr, alpha = 1)
#ax.imshow(colors2, extent = extent2, origin = 'lower', cmap = cm.RdBu, alpha = 0.5)
plt.gca().invert_yaxis()
Exemplo n.º 19
0
               cmap='bwr',
               marker='o',
               s=100)
axs[1].set_xlim([-this_range, this_range])
axs[1].set_ylim([-this_range, this_range])
dicplt.square_axis(axs[1])

an1 = dicplt.LineAnime(np.stack([
    np.array(list(range(20)) + list(range(20, nepoch, 10))) for _ in range(3)
]),
                       np.array(PS)[list(range(20)) +
                                    list(range(20, nepoch, 10)), :].T,
                       ax=axs[0])
an2 = dicplt.LineAnime(weights_proj[:, :, 0].T,
                       weights_proj[:, :, 1].T,
                       colors=cm.bwr(grp / 1),
                       ax=axs[1])

dicplt.AnimeCollection(an1, an2).save(SAVE_DIR + '/vidya/tempmovie.mp4',
                                      fps=30)

#%%
this_grp = 0

ax = dicplt.scatter3d(8 * inp_coefs.T,
                      s=200,
                      marker='*',
                      c=cm.viridis(util.decimal(y_.T) / 7))
dicplt.LineAnime3D(
    weights_proj[:, grp == this_grp, 0].T,
    weights_proj[:, grp == this_grp, 1].T,
Exemplo n.º 20
0
def cmap(x):
    return cm.bwr(1 - x)
Exemplo n.º 21
0
    def features_training(num_images=1):
        """
        Function to analyse the features of the TRAINING set of the autoencoder
        """

        norm_coef = []
        losses_focus, peaks_focus, mins_focus = [], [], []
        losses_defocus, peaks_defocus, mins_defocus = [], [], []

        # ============================================================================================================ #
        ### Light Loss - see how the Low Orders modify the total intensity
        for j in range(N_ext):

            low_orders = ae_coefs[j, :N_low]
            norm_coef.append(np.linalg.norm(low_orders))

            input_focus = train_noisy[j, :N_crop**2].reshape((N_crop, N_crop))
            output_focus = train_clean[j, :N_crop**2].reshape((N_crop, N_crop))
            removed_features_focus = input_focus - output_focus
            loss_focus = np.sum(removed_features_focus)
            losses_focus.append(loss_focus)
            peaks_focus.append(np.max(removed_features_focus))
            mins_focus.append(np.min(removed_features_focus))

            input_defocus = train_noisy[j, N_crop**2:].reshape(
                (N_crop, N_crop))
            output_defocus = train_clean[j, N_crop**2:].reshape(
                (N_crop, N_crop))
            removed_features_defocus = input_defocus - output_defocus
            loss_defocus = np.sum(removed_features_defocus)
            losses_defocus.append(loss_defocus)
            peaks_defocus.append(np.max(removed_features_defocus))
            mins_defocus.append(np.min(removed_features_defocus))
        norm_coef = np.array(norm_coef)

        f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
        # Focused PSF
        p_sort = np.argsort(peaks_focus)
        ax1.scatter(norm_coef[p_sort],
                    np.sort(peaks_focus),
                    color=cm.bwr(
                        np.linspace(0.5 + np.min(peaks_focus), 1, N_ext)),
                    s=4,
                    label='Maxima')
        m_sort = np.argsort(mins_focus)
        ax1.scatter(norm_coef[m_sort],
                    np.sort(mins_focus),
                    color=cm.bwr(np.linspace(0, 0.5, N_ext)),
                    s=4,
                    label='Minima')
        loss_sort = np.argsort(losses_focus)
        ax1.legend(loc=2)
        leg = ax1.get_legend()
        leg.legendHandles[0].set_color('red')
        leg.legendHandles[1].set_color('blue')

        ax1.axhline(y=0.0, linestyle='--', color='black')
        ax1.set_title('Nominal PSF')
        ax1.set_ylabel(r'Light loss')
        ax1.set_ylim([-0.5, 0.5])

        ax3.scatter(norm_coef[loss_sort],
                    np.sort(losses_focus),
                    color='black',
                    s=3,
                    label='Total')
        ax3.legend(loc=2)
        ax3.axhline(y=0.0, linestyle='--', color='black')
        ax3.set_xlabel(r'Norm of low orders $\Vert a_{low} \Vert$')
        ax3.set_ylabel(r'Light loss')

        # Defocused PSF
        p_sort = np.argsort(losses_defocus)
        ax2.scatter(norm_coef[p_sort],
                    np.sort(peaks_defocus),
                    color=cm.bwr(
                        np.linspace(0.5 + np.min(peaks_defocus), 1, N_ext)),
                    s=4,
                    label='Maxima')
        m_sort = np.argsort(mins_defocus)
        ax2.scatter(norm_coef[m_sort],
                    np.sort(mins_defocus),
                    color=cm.bwr(np.linspace(0, 0.5, N_ext)),
                    s=4,
                    label='Minima')
        loss_sort = np.argsort(losses_defocus)
        ax2.legend(loc=2)
        leg = ax2.get_legend()
        leg.legendHandles[0].set_color('red')
        leg.legendHandles[1].set_color('blue')

        ax2.axhline(y=0.0, linestyle='--', color='black')
        ax2.set_title('Defocused PSF')

        ax4.scatter(norm_coef[loss_sort],
                    np.sort(losses_defocus),
                    color='black',
                    s=3,
                    label='Total')
        ax4.legend(loc=2)
        ax4.axhline(y=0.0, linestyle='--', color='black')
        ax4.set_xlabel(r'Norm of low orders $\Vert a_{low} \Vert$')

        # ============================================================================================================ #

        ### PCA analysis of the removed features
        # Focused PSF
        N_comp = N_low
        removed_features = train_noisy[:, :N_crop**2] - train_clean[:, :N_crop
                                                                    **2]
        pca = PCA(n_components=N_comp)
        pca.fit(X=removed_features)
        components = pca.components_.reshape((N_comp, N_crop, N_crop))
        variance_ratio = pca.explained_variance_ratio_
        total_variance = np.sum(variance_ratio)

        plt.figure()
        for i in range(N_comp):
            ax = plt.subplot(2, N_comp, i + 1)
            plt.imshow(components[i], cmap='seismic', origin='lower')
            ax.set_title(r'PCA #%d [$\sigma^2_r=%.2f/%.2f$]' %
                         (i + 1, variance_ratio[i], total_variance))
            plt.colorbar(orientation="horizontal")
            cmin = min(components[i].min(), -components[i].max())
            plt.clim(cmin, -cmin)
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

        removed_features_defocus = train_noisy[:, N_crop**
                                               2:] - train_clean[:, N_crop**2:]
        pca_defocus = PCA(n_components=N_comp)
        pca_defocus.fit(X=removed_features_defocus)
        components_defocus = pca_defocus.components_.reshape(
            (N_comp, N_crop, N_crop))
        variance_ratio_defocus = pca_defocus.explained_variance_ratio_
        total_variance_defocus = np.sum(variance_ratio_defocus)

        for i in range(N_comp):
            ax = plt.subplot(2, N_comp, i + 1 + N_comp)
            plt.imshow(components_defocus[i], cmap='seismic', origin='lower')
            ax.set_title(
                r'PCA #%d [$\sigma^2_r=%.2f/%.2f$]' %
                (i + 1, variance_ratio_defocus[i], total_variance_defocus))
            plt.colorbar(orientation="horizontal")
            cmin = min(components_defocus[i].min(),
                       -components_defocus[i].max())
            plt.clim(cmin, -cmin)
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

        ### Least Squares fit of the removed features
        def residuals_lsq(x, image_data, pca_components):
            model_image = np.dot(x, pca_components)
            return image_data - model_image

        # ============================================================================================================ #
        ### Compare the removed features to the true difference
        random_images = np.random.randint(train_noisy.shape[0],
                                          size=num_images)
        for j in random_images:
            im = removed_features[j]
            res_lsq = lsq(fun=residuals_lsq,
                          x0=np.zeros(N_comp),
                          args=(im, pca.components_))
            x_fit = res_lsq['x']
            im_fit = (np.dot(x_fit, pca.components_)).reshape((N_crop, N_crop))
            im = im.reshape((N_crop, N_crop))
            vmin_im = min(im.min(), -im.max())
            vmin_fit = min(im_fit.min(), -im_fit.max())
            vmin = min(vmin_im, vmin_fit)

            error = np.sum(np.abs(im_fit - im)) / np.sum(np.abs(im))

            plt.figure()
            cmap = 'seismic'
            ax1 = plt.subplot(1, 3, 1)
            plt.imshow(im, cmap=cmap)
            plt.colorbar(orientation="horizontal")
            plt.clim(vmin, -vmin)
            ax1.get_xaxis().set_visible(False)
            ax1.get_yaxis().set_visible(False)
            ax1.set_title(
                r'Removed features: $PSF(\Phi_{low} + \Phi_{high}) - PSF(\Phi_{high})$'
            )

            ax2 = plt.subplot(1, 3, 2)
            plt.imshow(im_fit, cmap=cmap)
            plt.colorbar(orientation="horizontal")
            plt.clim(vmin, -vmin)
            ax2.get_xaxis().set_visible(False)
            ax2.get_yaxis().set_visible(False)
            ax2.set_title(r'Least-Squares fit from PCA: $x_{lsq} \cdot PCA$')

            res = im_fit - im
            ax3 = plt.subplot(1, 3, 3)
            plt.imshow(res, cmap='bwr')
            plt.colorbar(orientation="horizontal")
            min_res = min(res.min(), -res.max())
            plt.clim(min_res, -min_res)
            ax3.get_xaxis().set_visible(False)
            ax3.get_yaxis().set_visible(False)
            ax3.set_title(r'Residuals ($\epsilon = %.2f$)' % error)

        # ============================================================================================================ #
        ### Show some examples of the true features

        random_images = np.random.choice(train_noisy.shape[0],
                                         size=48,
                                         replace=False)
        print(random_images)
        plt.figure()
        for i, img_j in enumerate(random_images):
            ax = plt.subplot(6, 8, i + 1)
            im = removed_features[img_j].reshape((N_crop, N_crop))
            plt.imshow(im, cmap='seismic')
            min_im = min(im.min(), -im.max())
            plt.clim(min_im, -min_im)
            ax.get_xaxis().set_visible(False)
            ax.get_yaxis().set_visible(False)

        plt.show()

        return pca
print("# width_out = " + str(np.round(p84_out, 2) - np.round(p16_out, 2)))

### plot
figure = plt.figure(figsize=(10, 2))
gs = gridspec.GridSpec(nrows=8, ncols=17)
plt.subplots_adjust(bottom=0.22, left=0.05, right=0.98, top=0.88)
ax1 = plt.subplot(gs[0:8, 0:8])
ax2 = plt.subplot(gs[0:8, 9:17])
ax1.grid(axis="x")
ax2.grid(axis="both")
plt.rcParams["font.size"] = 11
plt.rcParams["legend.fontsize"] = 9

# ax1
ylim = [0.0001, np.r_[y_in, y_out].max() * 1.4]
ax1.step(x_in, y_in, color=cm.bwr(1 / 1.), lw=1, alpha=1.0, where="mid")
ax1.bar(x_in,
        y_in,
        lw=0,
        color=cm.bwr(1 / 1.),
        alpha=0.2,
        width=x_in[1] - x_in[0],
        align="center",
        label="inside mask")
ax1.plot(p50_in_norm,
         ylim[1] * 0.95,
         "o",
         markeredgewidth=0,
         c=cm.bwr(1 / 1.),
         markersize=7,
         zorder=1)
esmall = [(u, v) for (u, v, d) in G.edges(data=True)
          if d['weight'] <= collEdgeCount.bins[1] and u not in remove
          and v not in remove]

# print esmall
# print remove
# # sys.exit()
# pos=nx.spring_layout(G, k=.5,iterations=20, weight=20) # positions for all nodes
# pos = nx.graphviz_layout(G, prog='neato')

pos = nx.spring_layout(G, weight=20)  # positions for all nodes
# pos=nx.circular_layout(G) # positions for all nodes

G.remove_nodes_from(remove)
# cm.Spectral(betc_value)
node_color = [cm.bwr(G.degree(v)) for v in G]
# nodes
nx.draw_networkx_nodes(G,
                       pos,
                       node_size=[float(G.degree(v)) * 2.5 for v in G],
                       alpha=0.6,
                       node_color=node_color)
# nx.draw_networkx_nodes(G,pos,nodelist=greater500Coll, node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#fdae61", with_labels=True, label=str(collSpecimenBreaks.bins[1]) + ' - ' + str(collSpecimenBreaks.bins[2] - 1))
# nx.draw_networkx_nodes(G,pos,nodelist=greater100Coll, node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#5e3c99", with_labels=True, label=str(collSpecimenBreaks.bins[1] -1) + ' - ' + str(collSpecimenBreaks.bins[0]))
# nx.draw_networkx_nodes(G,pos,nodelist=less100Coll,node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#b2abd2", with_labels=True, label='<= ' + str(collSpecimenBreaks.bins[0] - 1))
print[float(G.degree(v)) * .8 for v in G]

nx.draw_networkx_edges(G,
                       pos,
                       edgelist=slarge,
                       width=[float(G.degree(v)) * .8 for v in G],
Exemplo n.º 24
0
    def initialize_fields(self):
        self.num_export_particles = ti.field(dtype=ti.i32, shape=())
        self.num_export_TSDF_particles = ti.field(dtype=ti.i32, shape=())
        self.num_export_ESDF_particles = ti.field(dtype=ti.i32, shape=())
        self.input_R = ti.Matrix.field(3, 3, dtype=ti.f32, shape=())
        self.input_T = ti.Vector.field(3, dtype=ti.f32, shape=())
        self.export_x = ti.Vector.field(3, dtype=ti.f32, shape=self.max_disp_particles)
        self.export_color = ti.Vector.field(3, dtype=ti.f32, shape=self.max_disp_particles)
        self.export_TSDF = ti.field(dtype=ti.f32, shape=self.max_disp_particles)
        self.export_TSDF_xyz = ti.Vector.field(3, dtype=ti.f32, shape=self.max_disp_particles)
        self.export_ESDF = ti.field(dtype=ti.f32, shape=self.max_disp_particles)
        self.export_ESDF_xyz = ti.Vector.field(3, dtype=ti.f32, shape=self.max_disp_particles)
        
        self.voxel_size_ = ti.Vector([self.voxel_size, self.voxel_size, self.voxel_size])
        self.map_size_ = ti.Vector([self.map_size_xy, self.map_size_xy, self.map_size_z])
        self.NC_ = ti.Vector([self.N/2, self.N/2, self.Nz/2])
        self.N_ = ti.Vector([self.N, self.N, self.Nz])

        self.occupy = ti.field(dtype=ti.i32)
        self.TSDF = ti.field(dtype=ti.f32)
        self.W_TSDF = ti.field(dtype=ti.f32)
        self.ESDF = ti.field(dtype=ti.f32)
        self.observed = ti.field(dtype=ti.i8)
        self.TSDF_observed = ti.field(dtype=ti.i8)
        self.fixed = ti.field(dtype=ti.i8)
        self.parent_dir = ti.Vector.field(3, dtype=ti.i32)

        self.new_pcl_count = ti.field(dtype=ti.i32)
        self.new_pcl_sum_pos = ti.Vector.field(3, dtype=ti.f32) #position in sensor coor

        self.updated_TSDF = ti.field(dtype=ti.i32)

        if self.TEXTURE_ENABLED:
            self.color = ti.Vector.field(3, dtype=ti.f32)
            self.new_pcl_sum_color = ti.Vector.field(3, dtype=ti.f32)

        block_num_xy = self.block_num_xy
        block_num_z = self.block_num_z
        block_size = self.block_size

        self.max_queue_size = 1000000
        self.raise_queue = ti.Vector.field(3, dtype=ti.i32, shape=self.max_queue_size)
        self.lower_queue = ti.Vector.field(3, dtype=ti.i32, shape=self.max_queue_size)
        self.num_raise_queue = ti.field(dtype=ti.i32, shape=())
        self.num_lower_queue = ti.field(dtype=ti.i32, shape=())
        self.head_lower_queue = ti.field(dtype=ti.i32, shape=())
        self.head_raise_queue = ti.field(dtype=ti.i32, shape=())

        self.B, self.Broot = self.data_structures(block_num_xy, block_num_z, block_size)
        self.B.place(self.occupy, self.W_TSDF,self.TSDF, self.TSDF_observed, self.ESDF, self.observed, self.fixed, self.parent_dir)
        if self.TEXTURE_ENABLED:
            self.B.place(self.color)

        self.T, self.Troot = self.data_structures_pointer(block_num_xy, block_num_z, block_size)
        self.T.place(self.updated_TSDF)

        self.PCL, self.PCLroot = self.data_structures_pointer(block_num_xy, block_num_z, block_size)
        self.PCL.place(self.new_pcl_count, self.new_pcl_sum_pos)
        if self.TEXTURE_ENABLED:
            self.PCL.place(self.new_pcl_sum_color)

        self.neighbors = []
        for _di in range(-1, 2):
            for _dj in range(-1, 2):
                for _dk in range(-1, 2):
                    if _di !=0 or _dj !=0 or _dk != 0:
                        self.neighbors.append(ti.Vector([_di, _dj, _dk]))
        
        self.colormap = ti.Vector.field(3, float, shape=1024)
        self.color_rate = 2
        for i in range(1024):
            self.colormap[i][0] = cm.bwr(i/1024.0)[0]
            self.colormap[i][1] = cm.bwr(i/1024.0)[1]
            self.colormap[i][2] = cm.bwr(i/1024.0)[2]

        self.init_fields()
Exemplo n.º 25
0
def drawMarg(alphacolor, q, i, j, marg, J, hi, hj, score, margax, Cax, Jax):
    graytext = lambda x: {
        'text': "{:.2f}".format(x),
        'color': cm.gray_r(fnorm(x))
    }
    bwrtext = lambda x: {'text': "{:.2f}".format(x), 'color': cm.bwr(fnorm(x))}
    rwbtext = lambda x: {
        'text': "{:.2f}".format(x),
        'color': cm.bwr_r(fnorm(x))
    }
    mapi = alphacolor[i]
    mapj = alphacolor[j]

    for ax in (margax, Cax, Jax):
        ax.set_axis_off()
        ax.set_xlim(0, 6 + q)
        ax.set_ylim(0, 1 * (q + 5))

    fnorm = Normalize(0, 0.1, clip=True)
    drawGrid(margax,
             3,
             1,
             1,
             q,
             q, [[graytext(x) for x in r] for r in marg],
             mapi,
             mapj,
             '({}, {})   Bimarg'.format(i, j),
             list(map(graytext, sum(marg, axis=1))),
             list(map(graytext, sum(marg, axis=0))),
             labeltext=alphatext)

    fnorm = Normalize(-1, 1.0, clip=True)
    C = marg - outer(sum(marg, axis=1), sum(marg, axis=0))
    Cmax = np.max(np.abs(C))
    drawGrid(Cax,
             3,
             1,
             1,
             q,
             q, [[rwbtext(x) for x in r] for r in C / Cmax],
             mapi,
             mapj,
             '({}, {})   C * {}'.format(i, j, str(Cmax)),
             None,
             None,
             labeltext=alphatext)

    fnorm = Normalize(-1, 1.0, clip=True)
    drawGrid(Jax,
             3,
             1,
             1,
             q,
             q, [[bwrtext(x) for x in r] for r in J],
             mapi,
             mapj,
             '({}, {})   J score={:.2f}'.format(i, j, score),
             list(map(bwrtext, hi)),
             list(map(bwrtext, hj)),
             labeltext=alphatext)
Exemplo n.º 26
0
def main():
    # positions = []
    # myfile = open("p2data.txt", "r")
    # for line in myfile:
    #     positions.append((float(line[2:12]) - 0.5) * 2)
    #     positions.append((float(line[14:24]) - 0.5) * 2)
    #     positions.append((float(line[26:36]) - 0.5) * 2)
    # positions = np.array(positions, dtype=np.float32)

    data = np.loadtxt('p2data_v2.txt', dtype=np.float32)
    data[:, 0:3] = (data[:, 0:3] - 0.5) * 2
    #Fake Point
    data[0, 0] = -0.2
    data[0, 1] = 0.1
    data[0, 2] = -1.0
    myp = np.array([data[0, 0], data[0, 1], data[0, 2]])
    data[0, 4] = 900
    #End Fake Point
    pos = data[:, 0:3]
    norm = mpl.colors.Normalize(vmin=1, vmax=1000)
    data = np.append(data, cm.bwr(norm(data[:, 4])), axis=1)
    size0 = np.min(data[:, 3])
    mass = size0 * np.sqrt(data[:, 3] / 30000)
    mass = mass.reshape(mass.shape[0], 1)
    mass = np.maximum(mass, 1)
    mass[0] = 20
    data = np.delete(data, 3, 1)  # drop mass
    data = np.delete(data, 3, 1)  # drop age
    data = np.delete(data, 6, 1)  # drop Alpha
    #m = np.ones((data.shape[0], 1))
    #m = m * 80.0
    #m[0::2] = 20.0
    data = numpy.hstack((data, mass))
    data = data.astype(numpy.float32)

    #yt region
    # norm = mpl.colors.Normalize(vmin=1, vmax=1000)
    # colors = cm.bwr(norm(age))
    # colors = colors[:, 0:-1]
    # size0 = np.min(mass)
    # m = np.array(mass) / 30000
    # m = size0 * np.sqrt(m)
    # m = np.maximum(m, 1)
    # m = m.reshape(m.shape[0], 1)
    # data = np.hstack((position, colors, m))
    # data = data.astype(np.float32)

    pygame.init()
    #pygame.mouse.set_cursor(*pygame.cursors.diamond)
    display = (1000, 800)
    #display = (800, 600)
    aspect = display[0] / display[1]
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    myvao = glGenVertexArrays(1)
    glBindVertexArray(myvao)
    myvbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, myvbo)
    floatsize = 4  # 4 bytes, 32 bits
    size = floatsize * data.size
    glBufferData(GL_ARRAY_BUFFER, size, numpy.ravel(data), GL_STATIC_DRAW)

    glEnable(GL_PROGRAM_POINT_SIZE)
    vertexShaderSource = """
    #version 330
    in vec3 position;
    in vec3 vcolor;
    in float psize;

    uniform mat4 model;
    uniform mat4 view;
    uniform mat4 projection;

    uniform vec2 screenSize;
    uniform float spriteSize;

    out vec3 fcolor;
    


    void main()
    {
        gl_Position = projection * view * model *  vec4(position, 1.0);
        gl_PointSize = psize;
        fcolor = vcolor;
    }
    """
    fragmentShaderSource = """
    #version 330
    in vec3 fcolor;
    out vec4 FragColor;
    uniform sampler2D tex;
    void main()
    {
        vec4 texColor = texture(tex, gl_PointCoord);
        //texColor.a = 1.0 - texColor.r;
        FragColor = texColor * vec4(fcolor, 1.0);
    }
    """
    shader = shaders.compileProgram(
        shaders.compileShader(vertexShaderSource, GL_VERTEX_SHADER),
        shaders.compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER))
    positionAttrib = glGetAttribLocation(shader, "position")
    colorAttrib = glGetAttribLocation(shader, "vcolor")
    sizeAttrib = glGetAttribLocation(shader, "psize")
    #ctypes.c_void_p(offset)
    stride = 7 * floatsize
    glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                          ctypes.c_void_p(0))
    glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                          ctypes.c_void_p(3 * floatsize))
    glVertexAttribPointer(sizeAttrib, 1, GL_FLOAT, GL_FALSE, stride,
                          ctypes.c_void_p(6 * floatsize))
    glEnableVertexAttribArray(positionAttrib)
    glEnableVertexAttribArray(colorAttrib)
    glEnableVertexAttribArray(sizeAttrib)
    numpos = int(data.shape[0])

    glEnable(GL_POINT_SPRITE)
    #glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE)

    #texture
    textureobject = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, textureobject)
    #glEnable(GL_POINT_SPRITE)
    #glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    image = Image.open("halo.jpg")
    width, height = image.size
    print(width, height)
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, img_data)

    #Rotation Around Cluster Vectors
    #cameraPos = Vec3(-0.739, -0.637, 0.7)
    #cameraTarget = Vec3(-0.739, -0.637, 0.638)

    deltaTime = 0.0
    lastFrame = 0.0

    #yaw = -90.0
    yaw = 0.0
    pitch = 0.0
    xoffset = 0.0
    yoffset = 0.0
    lastX = display[0] / 2
    lastY = display[1] / 2
    fov = 45.0

    #Initialize matrix:
    projection = perspective(fov, aspect, 0.1, 100)
    view = Mat4x4()
    model = Mat4x4()

    #Look at Vectors
    worldUp = Vec3(0.0, 1.0, 0.0)
    origin = Vec3(0.0, 0.0, 0.0)
    cameraPos = Vec3(0.0, 0.0, 5.0)
    focus = Vec3(0.0, 0.0, 0.0)
    frontX = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch))
    frontY = math.sin(math.radians(pitch))
    frontZ = math.sin(math.radians(yaw)) * math.cos(math.radians(pitch))
    cameraFront = Vec3(frontX, frontY, frontZ)
    cameraFront = normalizeVec(cameraFront)
    right = cross(cameraFront, worldUp)
    up = cross(right, cameraFront)  #normalized internally
    delta = 0.0
    delta2 = 0.0
    d = 0.0
    fovdelta = 0.0
    pygame.mouse.set_visible(True)
    pygame.event.set_grab(True)
    middle = False

    #glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR)
    #glBlendFunc(GL_SRC_ALPHA, GL_ZERO)

    click = False
    moving = False
    ballradius = min(display[0] / 2, display[1] / 2)
    initial = True
    model = Mat4x4()
    newmodel = Mat4x4()
    oldmodel = Mat4x4()

    xoffset = 0.0
    yoffset = 0.0

    while True:
        timeValue = pygame.time.get_ticks()
        deltaTime = timeValue - lastFrame
        lastFrame = timeValue
        cameraSpeed = 0.009 * deltaTime
        #cameraSpeed = 0.2
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.MOUSEMOTION and not initial:
                motion = True
                #print("I am moving")
            else:
                #print("NOT moving")
                motion = False
            if event.type == pygame.MOUSEMOTION and click and not moving:
                print("Start")
                moving = True
                xpos, ypos = pygame.mouse.get_pos()
                xpos = (xpos - (display[0] / 2))
                ypos = ((display[1] / 2) - ypos)
                startRotationVector = convertXY(xpos, ypos, ballradius)
                startRotationVector = normalize(startRotationVector)
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    #Left Click Down
                    #Enable Rotate Mode
                    print("Left Click down")
                    click = True
                if event.button == 4:
                    # ZOOM IN
                    if middle:
                        print("ZOOM IN")
                        fovdelta = -.2
                if event.button == 5:
                    # ZOOM OUT
                    if middle:
                        print("ZOOM OUT")
                        fovdelta = 0.2
                if event.button == 2:
                    middle = True
                if event.button == 3:
                    #Reset initial conditions
                    deltaTime = 0.0
                    lastFrame = 0.0

                    initial = True
                    #yaw = -90.0
                    yaw = 0.0
                    pitch = 0.0
                    xoffset = 0.0
                    yoffset = 0.0
                    lastX = display[0] / 2
                    lastY = display[1] / 2
                    fov = 45.0

                    projection = perspective(fov, aspect, 0.1, 100)
                    view = Mat4x4()
                    model = Mat4x4()

                    #Look at Vectors
                    worldUp = Vec3(0.0, 1.0, 0.0)
                    origin = Vec3(0.0, 0.0, 0.0)
                    cameraPos = Vec3(0.0, 0.0, 5.0)
                    focus = Vec3(0.0, 0.0, 0.0)
                    frontX = math.cos(math.radians(yaw)) * math.cos(
                        math.radians(pitch))
                    frontY = math.sin(math.radians(pitch))
                    frontZ = math.sin(math.radians(yaw)) * math.cos(
                        math.radians(pitch))
                    cameraFront = Vec3(frontX, frontY, frontZ)
                    cameraFront = normalizeVec(cameraFront)
                    right = cross(cameraFront, worldUp)
                    up = cross(right, cameraFront)  #normalized internally
                    delta = 0.0
                    delta2 = 0.0
                    d = 0.0
                    fovdelta = 0.0
                    middle = False
                    click = False
                    moving = False
                    ballradius = min(display[0] / 2, display[1] / 2)
                    initial = True
                    model = Mat4x4()
                    newmodel = Mat4x4()
                    oldmodel = Mat4x4()

                    xoffset = 0.0
                    yoffset = 0.0

                    #Right Click to exit
                    #pygame.quit()
                    #quit()
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    #Left Click Up
                    print("STOP")
                    click = False
                    moving = False
                    initial = True
                if event.button == 2:
                    middle = False
                    print("DONE")
                    fovdelta = 0
            if event.type == pygame.KEYDOWN:
                if event.key == K_q:
                    pygame.quit()
                    quit()
                if event.key == pygame.K_LEFT:
                    delta = right * 0.01
                    #delta = cross(cameraFront, up) * cameraSpeed * -1
                    #cameraPos -= cross(cameraFront, up) * cameraSpeed
                if event.key == pygame.K_RIGHT:
                    delta = right * 0.01 * -1
                    #delta = cross(cameraFront, up) * cameraSpeed
                    #cameraPos += cross(cameraFront, up) * cameraSpeed
                if event.key == pygame.K_UP:
                    d = 0.01
                    delta2 = 0.01 * -1 * camFocus
                    #delta = cameraSpeed * cameraFront
                    #cameraPos += cameraSpeed * cameraFront
                if event.key == pygame.K_DOWN:
                    d = 0.01 * -1
                    delta2 = 0.01 * camFocus
                    #delta = cameraSpeed * cameraFront * -1
                    #cameraPos -= cameraSpeed * cameraFront
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    #print(delta)
                    delta = Vec3(0.0, 0.0, 0.0)
                if event.key == pygame.K_RIGHT:
                    #print(delta)
                    delta = Vec3(0.0, 0.0, 0.0)
                if event.key == pygame.K_UP:
                    d = 0.0
                    delta2 = Vec3(0.0, 0.0, 0.0)
                if event.key == pygame.K_DOWN:
                    d = 0.0
                    delta2 = Vec3(0.0, 0.0, 0.0)
        glClear(GL_COLOR_BUFFER_BIT)
        #glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glUseProgram(shader)
        glBindTexture(GL_TEXTURE_2D, textureobject)

        #Ray Tracing
        xpos, ypos = pygame.mouse.get_pos()
        #OpenGL Viewport, lower left is (0,0)
        #In Window Coordinates top left is (0,0)
        ypos = display[1] - ypos
        #xpos = (xpos - (display[0] / 2))
        #ypos = ((display[1] / 2) - ypos)
        #viewport = np.zeros((4, 1))
        viewport = np.array(glGetIntegerv(GL_VIEWPORT))
        m = convertnp(model)
        v = convertnp(view)
        mv = np.matmul(v, m)
        p = convertnp(projection)
        xyz_n = np.array(gluUnProject(xpos, ypos, 0.0, mv, p, viewport))
        xyz_f = np.array(gluUnProject(xpos, ypos, 1.0, mv, p, viewport))

        #Line Segment xyz_n and xyz_f
        #Pos: all points
        #Q: Points on line segment closest all points in Pos
        ray = xyz_f - xyz_n
        ray_dot = np.dot(ray, ray)
        p = pos - xyz_n
        p_ray_dot = np.dot(p, ray)
        t = p_ray_dot / ray_dot
        z = np.matmul(np.reshape(t, (t.shape[0], 1)),
                      np.reshape(ray, (3, 1)).T)
        q = xyz_n + z
        dist = np.linalg.norm(q - pos, axis=1)
        mindist = np.min(dist)
        #print(mindist)
        if (mindist < 0.02):
            pygame.mouse.set_cursor(*pygame.cursors.diamond)
        else:
            pygame.mouse.set_cursor(*pygame.cursors.arrow)
        #pLine = getPoint(xyz_n, xyz_f, myp)
        #dist = pLine - myp
        #x = np.linalg.norm(dist)
        # print(x)
        # if(x < 0.02):
        #     z = 5
        #     pygame.mouse.set_cursor(*pygame.cursors.diamond)
        # else:
        #     pygame.mouse.set_cursor(*pygame.cursors.arrow)

        #Transform
        # xpos, ypos = pygame.mouse.get_pos()
        # #xpos = (xpos/ (display[0] / 2)) - 1
        # #ypos = ((ypos / (display[1] / 2)) - 1)
        # screen_vec = np.zeros((4,1))
        # screen_vec[0, 0] = xpos
        # screen_vec[1, 0] = ypos
        # screen_vec[2, 0] = 0.0
        # screen_vec[3, 0] = 1.0
        # #Front XYZ in world coordinates
        # p = convertnp(projection)
        # v = convertnp(view)
        # m = convertnp(model)
        # pi = np.linalg.inv(p)
        # vi = np.linalg.inv(v)
        # mi = np.linalg.inv(m)
        # z = np.matmul(mi, np.matmul(vi, np.matmul(pi, screen_vec) ) )
        # print(z)
        #print(z[-1])
        #z = z[:-1]
        #zg = z * -1
        #z = z[:-1] / np.linalg.norm(z[:-1])

        if moving:
            xoffset = 0.0
            yoffset = 0.0
            #update Rotation Vector
            xpos, ypos = pygame.mouse.get_pos()
            xpos = (xpos - (display[0] / 2))
            ypos = ((display[1] / 2) - ypos)
            currentRotationVector = convertXY(xpos, ypos, ballradius)
            currentRotationVector = normalize(currentRotationVector)
            diff = currentRotationVector - startRotationVector
            mag = math.sqrt((diff.x) * (diff.x) + (diff.y) * (diff.y) +
                            (diff.z) * (diff.z))
            if mag > 1E-6:
                rotationAxis = cross(currentRotationVector,
                                     startRotationVector)  #normalized
                val = dotVec(currentRotationVector, startRotationVector)
                if val > (1 - 1E-10):
                    val = 1.0
                rotationAngle = math.degrees(math.acos(val))
                axis = Vec3(-rotationAxis.x, -rotationAxis.y, -rotationAxis.z)
                newmodel = Mat4x4()
                newmodel = rotate(newmodel, rotationAngle * 2, axis)
        else:
            oldmodel = model
            newmodel = Mat4x4()
        model = newmodel.__mul__(oldmodel)
        modelList = convert(model)
        modelLoc = glGetUniformLocation(shader, "model")
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, modelList)
        view = Mat4x4()
        #view = translate(view, Vec4(0.0, 0.0, -3.0, 0.0))
        #view = translate(view, Vec4(0.739, 0.637, -0.7, 0.0))

        #Rotation Around Cluster
        #radius = 0.2
        #camX = -0.739 + math.sin(timeValue) * radius
        #camZ = 0.638  + math.cos(timeValue) * radius
        #cameraPos = Vec3(camX, -0.637, camZ)
        #view = lookAt(cameraPos, cameraTarget, up)

        if not moving:
            xpos, ypos = pygame.mouse.get_pos()
            if xpos > display[0] - 5 or ypos > display[
                    1] - 5 or xpos < 5 or ypos < 5:
                pygame.mouse.set_pos(display[0] / 2, display[1] / 2)
                xoffset = 0
                yoffset = 0
                lastX = display[0] / 2
                lastY = display[1] / 2
            if initial:
                pygame.mouse.set_pos(display[0] / 2, display[1] / 2)
                xoffset = 0
                yoffset = 0
                lastX = display[0] / 2
                lastY = display[1] / 2

                initial = False
                oldV = Mat4x4()
            else:
                xoffset = xpos - lastX
                yoffset = ypos - lastY
                lastX = xpos
                lastY = ypos
        #xoffset, yoffset = pygame.mouse.get_rel()
        sensitivity = 0.3
        xoffset *= sensitivity
        yoffset *= -1
        yoffset *= sensitivity
        yaw = xoffset
        pitch = yoffset
        maxAngle = 89
        if pitch > maxAngle:
            pitch = maxAngle
        if pitch < maxAngle * -1:
            pitch = maxAngle * -1
        #cameraPos += delta
        #cameraPos = cameraPos + (d * cameraFront)
        frontX = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch))
        frontY = math.sin(math.radians(pitch))
        frontZ = math.sin(math.radians(yaw)) * math.cos(math.radians(pitch))
        #cameraFront = Vec3(frontX, frontY, frontZ)

        #cameraFront = near - cameraPos

        # print(near)
        # print(loc)
        #cameraFront = normalizeVec(cameraFront)
        #right = cross(cameraFront, worldUp) #normalized
        #up = cross(right, cameraFront)
        # # view = lookAt(cameraPos, normalizeVec(near), up)
        #view = lookAt(cameraPos, cameraPos + cameraFront, up)
        #viewList = convert(view)
        #viewLoc = glGetUniformLocation(shader, "view")
        #glUniformMatrix4fv(viewLoc, 1, GL_FALSE, viewList)
        #print(cameraSpeed)
        focus += delta
        cameraPos += delta + delta2
        #print(cameraPos)
        camFocus = cameraPos - focus
        right = cross(normalizeVec(camFocus), worldUp)
        #print(focus)
        up = cross(right, normalizeVec(camFocus))
        r = Mat4x4()
        r = rotate(r, yaw, up)
        r = rotate(r, pitch, right)
        r = convertnp(r)

        cf = np.array([camFocus.x, camFocus.y, camFocus.z, 1])
        cf = np.matmul(r, cf.T)
        cf = Vec3(cf[0], cf[1], cf[2])
        new_cameraPos = cf + focus
        view = lookAt(new_cameraPos, focus, up)
        cameraPos = new_cameraPos
        viewList = convert(view)
        viewLoc = glGetUniformLocation(shader, "view")
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, viewList)

        #Projection
        projection = Mat4x4()
        fov += fovdelta
        if fov <= 1.0:
            fov = 1.0
            print("MAX ZOOM REACHED")
        if fov >= 45.0:
            fov = 45.0
        projection = perspective(fov, aspect, 0.1, 100)
        projectionList = convert(projection)
        projectionLoc = glGetUniformLocation(shader, "projection")
        glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, projectionList)
        glBindVertexArray(myvao)
        #glPointSize(20.0)
        glDrawArrays(GL_POINTS, 0, numpos)
        #glDrawElements(GL_POINTS, 3 , GL_UNSIGNED_INT, 0)
        pygame.display.flip()
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <= collEdgeCount.bins[1] and u not in remove and v not in remove]

# print esmall
# print remove
# # sys.exit()
# pos=nx.spring_layout(G, k=.5,iterations=20, weight=20) # positions for all nodes
# pos = nx.graphviz_layout(G, prog='neato')


pos=nx.spring_layout(G, weight=20) # positions for all nodes
# pos=nx.circular_layout(G) # positions for all nodes

G.remove_nodes_from(remove)
# cm.Spectral(betc_value)
node_color = [cm.bwr(G.degree(v)) for v in G]
# nodes
nx.draw_networkx_nodes(G,pos, node_size=[float(G.degree(v)) * 2.5 for v in G], alpha=0.6, node_color=node_color)
# nx.draw_networkx_nodes(G,pos,nodelist=greater500Coll, node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#fdae61", with_labels=True, label=str(collSpecimenBreaks.bins[1]) + ' - ' + str(collSpecimenBreaks.bins[2] - 1))
# nx.draw_networkx_nodes(G,pos,nodelist=greater100Coll, node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#5e3c99", with_labels=True, label=str(collSpecimenBreaks.bins[1] -1) + ' - ' + str(collSpecimenBreaks.bins[0]))
# nx.draw_networkx_nodes(G,pos,nodelist=less100Coll,node_size=[float(G.degree(v)) * 2.5 for v in G],alpha=0.6,node_color="#b2abd2", with_labels=True, label='<= ' + str(collSpecimenBreaks.bins[0] - 1))
print [float(G.degree(v)) * .8 for v in G]

nx.draw_networkx_edges(G,pos,edgelist=slarge,
                    width=[float(G.degree(v)) * .8 for v in G],alpha=0.6,edge_color='#E71D36', style='solid', label=str(collEdgeCount.bins[1]) + ' - ' + str(collEdgeCount.bins[0] + 1))

nx.draw_networkx_edges(G,pos,edgelist=elarge,
                    width=.8,alpha=.4,edge_color='#FF9F1C', style='solid', label=str(collEdgeCount.bins[1]) + ' - ' + str(collEdgeCount.bins[0] + 1))
# edges
nx.draw_networkx_edges(G,pos,edgelist=esmall,
                    width=.7,alpha=0.3,edge_color='#32936F', style='dashed' , label='<= ' + str(collEdgeCount.bins[0]))
Exemplo n.º 28
0
brain = Brain("fsaverage", "lh", "inflated", views=['lat', 'med'], background="white")
CIs = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_consensus_CI')
coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates')
WMD = np.loadtxt('//Volumes/neuro/Rest/Thalamic_parcel/roiWMD')
WMD = WMD/100
WMD = WMD+1.5
WMD[WMD<0] =0
WMD = WMD/3
WMD[WMD>1] = 1

from matplotlib import cm
for i, coord in enumerate(coords):
	if CIs[i] != 0:
		if coord[0] < 0:
			#if wmd[i] > 80:
			brain.add_foci(coord, map_surface="white", color=cm.bwr(int(WMD[i]*255))[0:3])
brain.save_image("WMD_lat.tiff")


### to visualize hubs
subject_id = "fsaverage"
subjects_dir = os.environ["SUBJECTS_DIR"]

brain = Brain("fsaverage", "rh", "inflated", views=['lat', 'med'], background="white")
coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates')
PC = np.loadtxt('//Volumes/neuro/Rest/Thalamic_parcel/roipc')
wmd = np.loadtxt('//Volumes/neuro/Rest/Thalamic_parcel/wmdroi')

for i, coord in enumerate(coords):
	if coord[0] > 0:
		if wmd[i] > 80:
Exemplo n.º 29
0
    def compute_fret_efficiency(self, image_manager, cells_manager):

        heatmap = np.zeros(image_manager.phase_image.shape)

        print "computing FRET Efficiency"

        cell_average_E = []
        cyto_average_E = []
        membrane_average_E = []
        septum_average_E = []
        membsept_average_E = []

        for key in self.both_cells:
            ###################################################################
            # Whole Cell Calculations
            x0, y0, x1, y1 = cells_manager.cells[key].box
            cell_mask = cells_manager.cells[key].cell_mask

            donor_cell_image = image_manager.donor_image[x0:x1 + 1,
                                                         y0:y1 + 1] * cell_mask
            donor_cell_image = donor_cell_image - self.autofluorescence_donor - cells_manager.cells[
                key].stats["Baseline Donor"]
            donor_cell_image = donor_cell_image * (donor_cell_image > 0)
            nonzero_donor = np.nonzero(donor_cell_image)

            acceptor_cell_image = image_manager.acceptor_image[x0:x1 + 1,
                                                               y0:y1 +
                                                               1] * cell_mask
            acceptor_cell_image = acceptor_cell_image - self.autofluorescence_acceptor - cells_manager.cells[
                key].stats["Baseline Acceptor"]
            acceptor_cell_image = acceptor_cell_image * (acceptor_cell_image >
                                                         0)
            nonzero_acceptor = np.nonzero(acceptor_cell_image)

            fret_cell_image = image_manager.fret_image[x0:x1 + 1,
                                                       y0:y1 + 1] * cell_mask
            fret_cell_image = fret_cell_image - self.autofluorescence_fret - cells_manager.cells[
                key].stats["Baseline FRET"]
            fret_cell_image = fret_cell_image * (fret_cell_image > 0)
            nonzero_fret = np.nonzero(fret_cell_image)

            # TODO discuss if we shoudld use this pixels anyway
            cell_nonzero_ix = list(
                set(zip(list(nonzero_acceptor[0]),
                        list(nonzero_acceptor[1]))).intersection(
                            zip(list(nonzero_donor[0]),
                                list(nonzero_donor[1]))).intersection(
                                    zip(list(nonzero_fret[0]),
                                        list(nonzero_fret[1]))))

            e_values = []
            for ix in cell_nonzero_ix:
                Iaa = (self.fret_d * acceptor_cell_image[ix] -
                       self.fret_c * fret_cell_image[ix]) / (
                           self.fret_d - self.fret_c * self.fret_a)
                Idd = (self.fret_a * donor_cell_image[ix] -
                       self.fret_b * fret_cell_image[ix]) / (
                           self.fret_a - self.fret_b * self.fret_d)
                Fc = fret_cell_image[ix] - self.fret_a * Iaa - self.fret_d * Idd

                e = (Fc / self.fret_G) / (Idd + (Fc / self.fret_G))
                e_values.append(e)
                x, y = ix
                heatmap[x0 + x, y0 + y] = e

            if len(e_values) > 0:
                average = np.average(e_values)
                cell_average_E.append(average)
                cells_manager.cells[key].stats["Cell E"] = average
            else:
                cells_manager.cells[key].stats["Cell E"] = 0

            ###################################################################
            # Membrane Calculations
            cell_mask = cells_manager.cells[key].perim_mask

            donor_cell_image = image_manager.donor_image[x0:x1 + 1,
                                                         y0:y1 + 1] * cell_mask
            donor_cell_image = donor_cell_image - self.autofluorescence_donor - cells_manager.cells[
                key].stats["Baseline Donor"]
            donor_cell_image = donor_cell_image * (donor_cell_image > 0)
            nonzero_donor = np.nonzero(donor_cell_image)

            acceptor_cell_image = image_manager.acceptor_image[x0:x1 + 1,
                                                               y0:y1 +
                                                               1] * cell_mask
            acceptor_cell_image = acceptor_cell_image - self.autofluorescence_acceptor - cells_manager.cells[
                key].stats["Baseline Acceptor"]
            acceptor_cell_image = acceptor_cell_image * (acceptor_cell_image >
                                                         0)
            nonzero_acceptor = np.nonzero(acceptor_cell_image)

            fret_cell_image = image_manager.fret_image[x0:x1 + 1,
                                                       y0:y1 + 1] * cell_mask
            fret_cell_image = fret_cell_image - self.autofluorescence_fret - cells_manager.cells[
                key].stats["Baseline FRET"]
            fret_cell_image = fret_cell_image * (fret_cell_image > 0)
            nonzero_fret = np.nonzero(fret_cell_image)

            # TODO discuss if we shoudld use this pixels anyway
            membrane_nonzero_ix = list(
                set(zip(list(nonzero_acceptor[0]),
                        list(nonzero_acceptor[1]))).intersection(
                            zip(list(nonzero_donor[0]),
                                list(nonzero_donor[1]))).intersection(
                                    zip(list(nonzero_fret[0]),
                                        list(nonzero_fret[1]))))

            membrane_e_values = []
            for ix in membrane_nonzero_ix:
                Iaa = (self.fret_d * acceptor_cell_image[ix] -
                       self.fret_c * fret_cell_image[ix]) / (
                           self.fret_d - self.fret_c * self.fret_a)
                Idd = (self.fret_a * donor_cell_image[ix] -
                       self.fret_b * fret_cell_image[ix]) / (
                           self.fret_a - self.fret_b * self.fret_d)
                Fc = fret_cell_image[ix] - self.fret_a * Iaa - self.fret_d * Idd

                e = (Fc / self.fret_G) / (Idd + (Fc / self.fret_G))
                membrane_e_values.append(e)
                x, y = ix

            if len(membrane_e_values) > 0:
                average = np.average(membrane_e_values)
                membrane_average_E.append(average)
                cells_manager.cells[key].stats["Membrane E"] = average
            else:
                cells_manager.cells[key].stats["Membrane E"] = 0

            ###################################################################
            # Cytoplasm Calculations
            cell_mask = cells_manager.cells[key].cyto_mask

            donor_cell_image = image_manager.donor_image[x0:x1 + 1,
                                                         y0:y1 + 1] * cell_mask
            donor_cell_image = donor_cell_image - self.autofluorescence_donor - cells_manager.cells[
                key].stats["Baseline Donor"]
            donor_cell_image = donor_cell_image * (donor_cell_image > 0)
            nonzero_donor = np.nonzero(donor_cell_image)

            acceptor_cell_image = image_manager.acceptor_image[x0:x1 + 1,
                                                               y0:y1 +
                                                               1] * cell_mask
            acceptor_cell_image = acceptor_cell_image - self.autofluorescence_acceptor - cells_manager.cells[
                key].stats["Baseline Acceptor"]
            acceptor_cell_image = acceptor_cell_image * (acceptor_cell_image >
                                                         0)
            nonzero_acceptor = np.nonzero(acceptor_cell_image)

            fret_cell_image = image_manager.fret_image[x0:x1 + 1,
                                                       y0:y1 + 1] * cell_mask
            fret_cell_image = fret_cell_image - self.autofluorescence_fret - cells_manager.cells[
                key].stats["Baseline FRET"]
            fret_cell_image = fret_cell_image * (fret_cell_image > 0)
            nonzero_fret = np.nonzero(fret_cell_image)

            # TODO discuss if we shoudld use this pixels anyway
            cyto_nonzero_ix = list(
                set(zip(list(nonzero_acceptor[0]),
                        list(nonzero_acceptor[1]))).intersection(
                            zip(list(nonzero_donor[0]),
                                list(nonzero_donor[1]))).intersection(
                                    zip(list(nonzero_fret[0]),
                                        list(nonzero_fret[1]))))

            cyto_e_values = []
            for ix in cyto_nonzero_ix:
                Iaa = (self.fret_d * acceptor_cell_image[ix] -
                       self.fret_c * fret_cell_image[ix]) / (
                           self.fret_d - self.fret_c * self.fret_a)
                Idd = (self.fret_a * donor_cell_image[ix] -
                       self.fret_b * fret_cell_image[ix]) / (
                           self.fret_a - self.fret_b * self.fret_d)
                Fc = fret_cell_image[ix] - self.fret_a * Iaa - self.fret_d * Idd

                e = (Fc / self.fret_G) / (Idd + (Fc / self.fret_G))
                cyto_e_values.append(e)
                x, y = ix

            if len(cyto_e_values) > 0:
                average = np.average(cyto_e_values)
                cyto_average_E.append(average)
                cells_manager.cells[key].stats["Cytoplasm E"] = average
            else:
                cells_manager.cells[key].stats["Cytoplasm E"] = 0

            ###################################################################
            # Septum Calculations
            if cells_manager.cells[key].has_septum:
                x0, y0, x1, y1 = cells_manager.cells[key].box
                sept_mask = cells_manager.cells[key].sept_mask

                donor_cell_image = image_manager.donor_image[x0:x1 + 1, y0:y1 +
                                                             1] * sept_mask
                donor_cell_image = donor_cell_image - self.autofluorescence_donor - cells_manager.cells[
                    key].stats["Baseline Donor"]
                donor_cell_image = donor_cell_image * (donor_cell_image > 0)
                nonzero_donor = np.nonzero(donor_cell_image)

                acceptor_cell_image = image_manager.acceptor_image[
                    x0:x1 + 1, y0:y1 + 1] * sept_mask
                acceptor_cell_image = acceptor_cell_image - self.autofluorescence_acceptor - cells_manager.cells[
                    key].stats["Baseline Acceptor"]
                acceptor_cell_image = acceptor_cell_image * (
                    acceptor_cell_image > 0)
                nonzero_acceptor = np.nonzero(acceptor_cell_image)

                fret_cell_image = image_manager.fret_image[x0:x1 + 1, y0:y1 +
                                                           1] * sept_mask
                fret_cell_image = fret_cell_image - self.autofluorescence_fret - cells_manager.cells[
                    key].stats["Baseline FRET"]
                fret_cell_image = fret_cell_image * (fret_cell_image > 0)
                nonzero_fret = np.nonzero(fret_cell_image)

                # TODO discuss if we shoudld use this pixels anyway
                septum_nonzero_ix = list(
                    set(
                        zip(list(nonzero_acceptor[0]),
                            list(nonzero_acceptor[1]))).intersection(
                                zip(list(nonzero_donor[0]),
                                    list(nonzero_donor[1]))).intersection(
                                        zip(list(nonzero_fret[0]),
                                            list(nonzero_fret[1]))))

                septum_e_values = []
                for ix in septum_nonzero_ix:
                    Iaa = (self.fret_d * acceptor_cell_image[ix] -
                           self.fret_c * fret_cell_image[ix]) / (
                               self.fret_d - self.fret_c * self.fret_a)
                    Idd = (self.fret_a * donor_cell_image[ix] -
                           self.fret_b * fret_cell_image[ix]) / (
                               self.fret_a - self.fret_b * self.fret_d)
                    Fc = fret_cell_image[
                        ix] - self.fret_a * Iaa - self.fret_d * Idd

                    e = (Fc / self.fret_G) / (Idd + (Fc / self.fret_G))
                    septum_e_values.append(e)

                if len(septum_e_values) > 0:
                    average = np.average(septum_e_values)
                    septum_average_E.append(average)
                    cells_manager.cells[key].stats["Septum E"] = average
                else:
                    cells_manager.cells[key].stats["Septum E"] = 0

                ###################################################################
                # MembSept Calculations

                membsept_e_values = []
                membsept_e_values.extend(membrane_e_values)
                membsept_e_values.extend(septum_e_values)

                if len(membsept_e_values) > 0:
                    average = np.average(membsept_e_values)
                    membsept_average_E.append(average)
                    cells_manager.cells[key].stats["MembSept E"] = average
                else:
                    cells_manager.cells[key].stats["MembSept E"] = 0

            else:
                cells_manager.cells[key].stats["MembSept E"] = 0

            phase_img = image_manager.phase_image
            phase_img = img_as_float(gray2rgb(phase_img))

            ht_ix = np.nonzero(heatmap > 0)
            ht_ix = zip(list(ht_ix[0]), list(ht_ix[1]))
            min_val = 0
            max_val = 100

            for ix in ht_ix:
                cm_ix = int(
                    ((heatmap[ix] + np.sqrt(min_val * min_val)) * 256) /
                    (max_val + np.sqrt(min_val * min_val)))
                color = np.array(cm.bwr(cm_ix)[:3])
                phase_img[ix] = color

        self.cell_E = np.median(cell_average_E)
        self.cyto_E = np.median(cyto_average_E)
        self.membrane_E = np.median(membrane_average_E)
        self.membsept_E = np.median(membsept_average_E)
        self.septum_E = np.median(septum_average_E)
        self.fret_heatmap = phase_img
axHist.text(-0.15,
            0.95,
            'c',
            transform=axHist.transAxes,
            fontsize=14,
            fontweight='bold')

if len(zUppers) > 6:
    nOneSide = (len(zUppers) - 1) / 2
    colorsOneSide = numpy.array(
        [cm.cool(x) for x in numpy.linspace(0.0, 1.0, nOneSide)])
    #print colorsOneSide
else:
    nOneSide = 2
    colorsOneSide = numpy.flip(
        numpy.array([cm.bwr(x) for x in numpy.linspace(0.0, 1.0, nOneSide)]),
        0)
    colors = numpy.vstack((colorsOneSide, [0, 0, 0,
                                           1], numpy.flip(colorsOneSide, 0)))
colors = numpy.vstack((colorsOneSide, [0, 0, 0,
                                       1], numpy.flip(colorsOneSide, 0)))

for zUpper in zUppers:
    iDepth = iDepth + 1
    print "iDepth={}, zUpper={}".format(iDepth, zUpper)

    z = numpy.linspace(0., zLow, 1001)

    zLower = zUpper - 400.

    TRegional = numpy.zeros(z.shape)
Exemplo n.º 31
0
def att2img(attribution):
    return np.uint8(
        cm.bwr((np.clip(to_numpy(attribution) / MAXV, -1, 1) + 1) / 2) *
        255)[:, :, :3]
    def analyze_features(self, coef_removed):

        N_train = self.train[0].shape[0]
        norm_coef = norm(coef_removed, axis=1)
        light_loss = np.zeros((N_train, 3, 2))      # [[MAX, MIN, TOT]_focus, [MAX, MIN, TOT]_defocus]

        train_noisy, train_clean = self.train
        for k in range(N_train):
            input_focus = train_noisy[k, :N_crop**2].reshape((N_crop, N_crop))
            output_focus = train_clean[k, :N_crop**2].reshape((N_crop, N_crop))
            feat_focus = input_focus - output_focus
            light_loss[k, :, 0] = np.array([feat_focus.max(), feat_focus.min(), np.sum(feat_focus)])

            input_defocus = train_noisy[k, N_crop**2:].reshape((N_crop, N_crop))
            output_defocus = train_clean[k, N_crop**2:].reshape((N_crop, N_crop))
            feat_defocus = input_defocus - output_defocus
            light_loss[k, :, 1] = np.array([feat_defocus.max(), feat_defocus.min(), np.sum(feat_defocus)])

        peaks_focus, mins_focus, losses_focus = light_loss[:, 0, 0], light_loss[:, 1, 0], light_loss[:, 2, 0]
        f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
        # Focused PSF
        p_sort = np.argsort(peaks_focus)
        ax1.scatter(norm_coef[p_sort], np.sort(peaks_focus),
                    color=cm.bwr(np.linspace(0.5 + np.min(peaks_focus), 1, N_train)), s=4, label='Maxima')
        m_sort = np.argsort(mins_focus)
        ax1.scatter(norm_coef[m_sort], np.sort(mins_focus),
                    color=cm.bwr(np.linspace(0, 0.5, N_train)), s=4, label='Minima')
        loss_sort = np.argsort(losses_focus)
        ax1.legend(loc=2)
        leg = ax1.get_legend()
        leg.legendHandles[0].set_color('red')
        leg.legendHandles[1].set_color('blue')

        ax1.axhline(y=0.0, linestyle='--', color='black')
        ax1.set_title('Nominal PSF')
        ax1.set_ylabel(r'Light loss')
        ax1.set_ylim([-0.5, 0.5])

        ax3.scatter(norm_coef[loss_sort], np.sort(losses_focus), color='black', s=3, label='Total')
        ax3.legend(loc=2)
        ax3.axhline(y=0.0, linestyle='--', color='black')
        ax3.set_xlabel(r'Norm of low orders $\Vert a_{low} \Vert$')
        ax3.set_ylabel(r'Light loss')

        # Defocused PSF
        peaks_defocus, mins_defocus, losses_defocus = light_loss[:, 0, 1], light_loss[:, 1, 1], light_loss[:, 2, 1]
        p_sort = np.argsort(losses_defocus)
        ax2.scatter(norm_coef[p_sort], np.sort(peaks_defocus),
                    color=cm.bwr(np.linspace(0.5 + np.min(peaks_defocus), 1, N_train)), s=4, label='Maxima')
        m_sort = np.argsort(mins_defocus)
        ax2.scatter(norm_coef[m_sort], np.sort(mins_defocus),
                    color=cm.bwr(np.linspace(0, 0.5, N_train)), s=4, label='Minima')
        loss_sort = np.argsort(losses_defocus)
        ax2.legend(loc=2)
        leg = ax2.get_legend()
        leg.legendHandles[0].set_color('red')
        leg.legendHandles[1].set_color('blue')

        ax2.axhline(y=0.0, linestyle='--', color='black')
        ax2.set_title('Defocused PSF')

        ax4.scatter(norm_coef[loss_sort], np.sort(losses_defocus), color='black', s=3, label='Total')
        ax4.legend(loc=2)
        ax4.axhline(y=0.0, linestyle='--', color='black')
        ax4.set_xlabel(r'Norm of low orders $\Vert a_{low} \Vert$')