def _setup_eit(self): mesh_t = self._mesh # ms, el_pos el_dist, step = 1, 1 ex_mat = eit_scan_lines(16, el_dist) # Reconstruction step eit_obj = greit.GREIT(mesh_t[0], mesh_t[1], ex_mat=ex_mat, step=step, perm=0.8, parser='std') # prem default value eq = 1. eit_obj.setup(p=0.45, lamb=1e-3, n=96, s=10.0, ratio=0.05) # n - wielkość siatki, domyślna wartość 32 return eit_obj
ax.grid(True) ax.set_xlabel("Frames 1/20 (s)") ax.set_ylabel("Averaged Impedances") fig.subplots_adjust(top=0.95, bottom=0.15, left=0.175, right=0.95) """ 2. measurement protocol """ el_dist, step = 1, 1 ex_mat = eit_scan_lines(16, el_dist) """ 3. JAC solver """ # Note: if the jac and the real-problem are generated using the same mesh, # then, jac_normalized in JAC and data normalization in solve are not needed. # However, when you generate jac from a known mesh, but in real-problem # (mostly) the shape and the electrode positions are not exactly the same # as in mesh generating the jac, then both JAC and data must be normalized. eit = greit.GREIT(mesh_obj, el_pos, ex_mat=ex_mat, step=step, parser="fmmu", jac_normalized=True) eit.setup(p=0.50, lamb=0.01, n=32, s=20, ratio=0.05) ds = eit.solve(v1, v0, normalize=True) x, y, ds = eit.mask_value(ds, mask_value=np.NAN) # plot EIT imaging fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(np.real(ds), interpolation="none", cmap=plt.cm.viridis) fig.colorbar(im) ax.axis("equal") # fig.set_size_inches(6, 4) # fig.savefig('./figs/daeger_pulmovista_eit.png', dpi=200) plt.show()
# calculate simulated data fwd = Forward(ms, el_pos) f0 = fwd.solve(ex_mat, step=step, perm=ms0['alpha']) f1 = fwd.solve(ex_mat, step=step, perm=ms1['alpha']) """ ax2. BP """ eit = bp.BP(ms, el_pos, ex_mat=ex_mat, step=1, parser='std') ds = eit.solve(f1.v, f0.v, normalize=True) ds_bp = ds """ ax3. JAC """ eit = jac.JAC(ms, el_pos, ex_mat=ex_mat, step=step, perm=1., parser='std') eit.setup(p=0.2, lamb=0.001, method='kotre') # parameter tuning is needed for better display ds = eit.solve(f1.v, f0.v) ds_jac = pdeprtni(no2xy, el2no, ds) """ ax4. GREIT """ eit = greit.GREIT(ms, el_pos, ex_mat=ex_mat, step=step, parser='std') ds = eit.solve(f1.v, f0.v) x, y, ds_greit = eit.mask_value(ds, mask_value=np.NAN) """ build for EIT2016b (orig: 300p x 300p, 150dpi) """ size = (6, 6) axis_size = [-1.2, 1.2, -1.2, 1.2] fig = plt.figure(figsize=size) gs = gridspec.GridSpec(2, 2) # simulation ax1 = fig.add_subplot(gs[0, 0]) ax1.tripcolor(no2xy[:, 0], no2xy[:, 1], el2no, alpha, shading='flat') ax1.set_title(r'(a) $\Delta$ Conductivity') ax1.axis(axis_size) ax1.axis('off')
def simulate(self, el_dist, step, NN_path): reconstruction_ims = np.empty_like(self.truth_ims) output_ims = np.empty_like(self.truth_ims) loss = np.empty((self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4])) mean_deviation = np.empty((self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4])) predicted_mean = np.empty((self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4], 2)) el_pos = np.arange(self.n_el * self.num_per_el) forward = train.Forward(self.mesh_obj, el_pos, self.n_el) ex_mat = self.ex_mat_w_dist(el_dist) model = keras.models.load_model(NN_path, custom_objects={'loss_fn': UNet.loss_fn}) #print(ex_mat) for mean_index in range(self.truth_ims.shape[2]): for amp_index in range(self.truth_ims.shape[3]): for std_index in range(self.truth_ims.shape[4]): f_unp = forward.solve_eit(ex_mat=ex_mat, step=step, perm=np.ones(self.mesh_obj['element'].shape[0])) f_p = forward.solve_eit(ex_mat=ex_mat, step=step, perm=self.tri_perm[:, mean_index, amp_index, std_index] + np.ones(self.mesh_obj['element'].shape[0])) variance = 0.0009 * np.power(f_p.v, 2) volt_noise = train.sk.random_noise(f_p.v, mode='gaussian', clip=False, mean=0.0, var=variance) eit = greit.GREIT(self.mesh_obj, el_pos, f=f_unp, ex_mat=ex_mat, step=step, parser='std') eit.setup(p=0.1, lamb=0.01, n=self.npix, s=20., ratio=0.1) reconstruction_ims[:, :, mean_index, amp_index, std_index] = eit.solve(volt_noise, f_unp.v).reshape((self.npix, self.npix)) current_rec = reconstruction_ims[:, :, mean_index, amp_index, std_index].reshape((-1, self.npix, self.npix, 1)) output_ims[:, :, mean_index, amp_index, std_index] = model.predict(current_rec + 1.).reshape(64 ,64) - 1. ''' plt.figure(1) im2 = plt.imshow(self.truth_ims[:,:,mean_index, amp_index, std_index], origin='lower') plt.colorbar(im2) plt.figure(2) im = plt.imshow(reconstruction_ims[:,:,mean_index, amp_index, std_index], origin='lower') plt.colorbar(im) plt.figure(3) im3 = plt.imshow(output_ims[:, :, mean_index, amp_index, std_index], origin='lower') plt.colorbar(im3) plt.show()''' ''' t1 = time() error = 0.03 * np.ones(self.npix**2) max_value = np.argmax(reconstruction_ims[:, :, mean_index, amp_index, std_index]) max_coord = self.centresSq[max_value // self.npix, max_value % self.npix] initial_params = np.array([max_coord[0], max_coord[1], 1., 1.]) params_predicted, _ = curve_fit(gauss, self.centresSq.reshape(self.npix**2, 2), reconstruction_ims[:, :, mean_index, amp_index, std_index].reshape(self.npix**2), p0 = initial_params, sigma=error, method='trf') predicted_mean[mean_index, amp_index, std_index] = np.array([params_predicted[0], params_predicted[1]]) print(predicted_mean[mean_index, amp_index, std_index]) print(time()-t1)''' ''' #find mean without neural net processing max_indices = np.argmax(np.abs(reconstruction_ims[:, :, mean_index, amp_index, std_index])) max_coord = self.centresSq[max_indices // self.npix, max_indices % self.npix] pixels_of_interest = np.linalg.norm(max_coord[None, None] - self.centresSq[:, :], axis=2) < 0.1 * self.a predicted_mean[mean_index, amp_index, std_index] = np.sum(self.centresSq[pixels_of_interest] * np.abs(reconstruction_ims[pixels_of_interest][:, None, mean_index, amp_index, std_index]), axis=0) / np.sum(np.abs(reconstruction_ims[pixels_of_interest][:, None, mean_index, amp_index, std_index]), axis=0) mean_deviation[mean_index, amp_index, std_index] = (np.linalg.norm(predicted_mean[mean_index, amp_index, std_index] - self.mean_grid[mean_index])) ''' max_indices = np.argmax(np.abs(output_ims[:, :, mean_index, amp_index, std_index])) max_coord = self.centresSq[max_indices // self.npix, max_indices % self.npix] pixels_of_interest = np.linalg.norm(max_coord[None, None] - self.centresSq[:, :], axis=2) < 0.1 * self.a predicted_mean[mean_index, amp_index, std_index] = np.sum(self.centresSq[pixels_of_interest] * np.abs(output_ims[pixels_of_interest][:, None, mean_index, amp_index, std_index]), axis=0) / np.sum(np.abs(output_ims[pixels_of_interest][:, None, mean_index, amp_index, std_index]), axis=0) mean_deviation[mean_index, amp_index, std_index] = (np.linalg.norm(predicted_mean[mean_index, amp_index, std_index] - self.mean_grid[mean_index])) print(mean_deviation[mean_index, amp_index, std_index]) ''' max_indices = np.argmax(np.abs(reconstruction_ims).reshape(self.npix**2, reconstruction_ims.shape[2], reconstruction_ims.shape[3], reconstruction_ims.shape[4]), axis=0) max_coord = self.centresSq[max_indices // self.npix, max_indices % self.npix] pixels_of_interest = np.linalg.norm(max_coord[None, None] - self.centresSq[:, :, None, None, None], axis=6) < 0.05 * self.a self.centresSq[pixels_of_interest] ''' loss[:] = self.L2_loss(output_ims) save_file = h5py.File("./sensitivity data/sensitivity_060620_0,5_neural_net.h5", 'a') try: save_file.create_dataset('predicted_mean', data=predicted_mean, maxshape=(self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4], 2)) save_file.create_dataset('mean_deviation', data=mean_deviation, maxshape=(self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4])) save_file.create_dataset('loss', data=loss, maxshape=(self.truth_ims.shape[2], self.truth_ims.shape[3], self.truth_ims.shape[4])) save_file.create_dataset('reconstruction_ims', data=reconstruction_ims, maxshape=reconstruction_ims.shape) save_file.create_dataset('truth_ims', data=self.truth_ims, maxshape=self.truth_ims.shape) save_file.create_dataset('output_ims', data=output_ims, maxshape=output_ims.shape) print('files saved successfully!') # if not first, it returns an error, so the datasets in the hdf5 file are resized and filled except: save_file["predicted_mean"].resize((save_file["predicted_mean"].shape[0] + 1), axis = 0) save_file["mean_deviation"].resize((save_file["mean_deviation"].shape[0] + 1), axis = 0) save_file["loss"].resize((save_file["loss"].shape[0] + 1), axis = 0) save_file['predicted_mean'][mean_index] = predicted_mean[mean_index] save_file['mean_deviation'][mean_index] = mean_deviation[mean_index] save_file['loss'][mean_index] = loss[mean_index] save_file.close() return reconstruction_ims, loss
def greit_rec(p, t, el_pos, anomaly, fwd, continuous=False, step='random', n_pix=64, n_el=20, length=None, el_dist=None, num_per_el=3, continuousPerm=None): ''' function that generates forward solution and a GREIT reconstruction for a given conductivity distribution Takes: p - array of point coordinates created by meshing algorithm [number of points, 2] array[float] t - array of a triangles included in meshing [number of triangles , 3] array[int] el_pos - array of electrode positions [number of electrodes , 2] array[float] anomaly - list of all the anomalies for which reconstruction should be made array[dict] step - array storing the distance (in number of electrodes) for each source/sink pair [number of source/sink pairs , 1] array[int] (Default is 'random' == generates random step for each measurement) n_pix - number of pixels to be created in each dimension for GREIT algorithm [int] n_el - number of electrodes of the system that participate in reconstruction [int] Returns: ds - recreated conductivity map by GREIT algorithm [number of pixels,number of pixels] array[float] ''' #check order of points for each triangle and rearrange to ensure counter-clockwise arrangement (from pyEIT) t = checkOrder(p, t) #generate electrode indices el_pos = np.arange(n_el * num_per_el) #initialise unit uniform permitivity for the triangular mesh to be used perm = np.ones(t.shape[0], dtype=np.float) #build mesh structure given the input elements mesh_obj = {'element': t, 'node': p, 'perm': perm} # extract x, y coordinate of mesh vertices x, y = p[:, 0], p[:, 1] #check to see the state of the generated mesh (optional) #quality.stats(p, t) ex_mat = orderedExMat(n_el, length, el_dist) #if random step is invoked a random step is generated for each source/sink pair if step == 'random': step = np.array(rand.randint(1, n_el, size=ex_mat.shape[0])) #if the step is not an integer in the needed range, just randomize the same step for a source/sink pairs elif (step < 0 or step > n_el).any(): step = rand.randint(1, n_el) start_t = time() # calculate simulated data using FEM (for uniform conductivity) f = fwd.solve_eit(ex_mat=ex_mat, step=step, perm=mesh_obj['perm']) # creating forward dictionary with solution of forward problem pde_result = namedtuple("pde_result", ['jac', 'v', 'b_matrix']) f0 = pde_result(jac=f.jac, v=f.v, b_matrix=f.b_matrix) # adding anomalies with a overwritten anomaly function originally in pyEIT (pyEIT.mesh.wrapper) (heavily changed) unp_t = time() print("Unperturbed forward solution t", unp_t - start_t) if continuous == False: mesh_new = set_perm(mesh_obj, anomaly=anomaly, background=None) permUsed = mesh_new['perm'] elif continuous == True: permUsed = continuousPerm else: print('kurec') start_anom = time() # solving with anomalies f1 = fwd.solve_eit(ex_mat=ex_mat, step=step, perm=permUsed) # generate array for variance, 3% standard deviation for the voltage measurement variance = 0.0009 * np.power(f1.v, 2) # apply noise to voltage measurements v # here white Gaussian noise is assumed (since we don't have significant sources of systematic error like in medical applications, e.g. moving electrodes...) v = sk.random_noise(f1.v, mode='gaussian', clip=False, mean=0.0, var=variance) # create the Forward object used by GREIT the voltage map with the Gaussian noise f1 = pde_result(jac=np.vstack(f1.jac), v=np.hstack(v), b_matrix=np.vstack(f1.b_matrix)) end_anom = time() print("Anomaly forward t: ", end_anom - start_anom ) # (optional) draw anomalies only delta_perm = np.real(mesh_new['perm'] - mesh_obj['perm']) fig, ax = plt.subplots() im = ax.tripcolor(p[:, 0], p[:, 1], t, delta_perm, shading='flat', cmap=plt.cm.viridis) ax.set_title(r'$\Delta$ Conductivities') fig.colorbar(im) ax.axis('equal') fig.set_size_inches(6, 4) # fig.savefig('demo_bp_0.png', dpi=96) #plt.show() start_greit = time() # constructing GREIT object (from pyEIT) (classes changed singificantly for optimisation) eit = greit.GREIT(mesh_obj, el_pos, f=f, ex_mat=ex_mat, step=step, parser='std') # solving inverse problem with GREIT algorithm eit.setup(p=0.1, lamb=0.01, n=n_pix, s=15., ratio=0.1) ds = eit.solve(f1.v, f0.v) #reshaping output to the desired dimensions ds = ds.reshape((n_pix, n_pix)) print("Greit solution time ", time() - start_greit) # (optional) plot to check whether generated sensibly fig, ax = plt.subplots(figsize=(6, 4)) im = ax.imshow(np.real(ds), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1]) fig.colorbar(im) ax.axis('equal') plt.show() ''' gradConductivity = np.linalg.norm(np.gradient(ds), axis=0) figGrad, axGrad = plt.subplots(figsize=(6, 4)) imGrad = axGrad.imshow(np.real(gradConductivity), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1]) figGrad.colorbar(imGrad) axGrad.axis('equal') figGrad2, axGrad2 = plt.subplots(figsize=(6, 4)) imGrad2 = axGrad2.imshow(np.real(gradConductivity * ds), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1]) figGrad2.colorbar(imGrad2) axGrad2.axis('equal') v_pert = np.empty(shape=(len(f1.v), len(f1.v))) perturbing_mat = np.ones((len(f1.v), len(f1.v))) + 0.05 * np.identity(len(f1.v)) v_pert[:] = np.dot(perturbing_mat, np.diag(f1.v)) influence_mat = -np.dot(eit.H, v_pert).reshape(n_pix, n_pix, len(f1.v)) - ds[:, :, None] influence_mat = np.absolute(influence_mat) influence_mat = np.sum(influence_mat, axis=2) #mask = circleMask(npix, a) #influence_mat[~mask] = np.amax(influence_mat) figInfl, axInfl = plt.subplots(figsize=(6, 4)) imInfl = axInfl.imshow(np.real(influence_mat), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1]) figInfl.colorbar(imInfl) axInfl.axis('equal') totalMap = gradConductivity * ds * influence_mat figTotal, axTotal = plt.subplots(figsize=(6, 4)) imTotal = axTotal.imshow(np.real(totalMap), interpolation='none', cmap=plt.cm.viridis, origin='lower', extent=[-1,1,-1,1]) figTotal.colorbar(imTotal) axTotal.axis('equal') plt.show() ''' return ds
ax.set_ylim([-1.2, 1.2]) ax.set_title(r"$\Delta$ Conductivity") # fig.set_size_inches(6, 4) """ 2. FEM forward simulations """ # setup EIT scan conditions el_dist, step = 1, 1 ex_mat = eit_scan_lines(16, el_dist) # calculate simulated data fwd = Forward(mesh_obj, el_pos) f0 = fwd.solve_eit(ex_mat, step=step, perm=mesh_obj["perm"]) f1 = fwd.solve_eit(ex_mat, step=step, perm=mesh_new["perm"]) """ 3. Construct using GREIT """ eit = greit.GREIT(mesh_obj, el_pos, ex_mat=ex_mat, step=step, parser="std") eit.setup(p=0.50, lamb=0.001) ds = eit.solve(f1.v, f0.v) x, y, ds = eit.mask_value(ds, mask_value=np.NAN) # plot """ imshow will automatically set NaN (bad values) to 'w', if you want to manually do so import matplotlib.cm as cm cmap = cm.gray cmap.set_bad('w', 1.) plt.imshow(np.real(ds), interpolation='nearest', cmap=cmap) """ ax = axes[1]