def solveGREIT(n_el=20, n_pix=64, a=2.): # number electrodes because these are their indices in pts array (due to pyEIT meshing) el_pos = np.arange(n_el) # create an object with the meshing to initialise a Forward object mesh_obj = mesh(n_el) fwd = Forward(mesh_obj, el_pos) ex_mat = train.generateExMat(ne=n_el) f = fwd.solve_eit(ex_mat=ex_mat, perm=fwd.tri_perm) # generate anomalies in a random manner to simulate real samples anomaly = train.generate_anoms(a, a) # generate new meshing with anomaly new_mesh = train.set_perm(mesh_obj, anomaly=anomaly, background=None) # solve forward problem with anomaly f_anom = fwd.solve_eit(ex_mat=ex_mat, perm=new_mesh['perm']) greit = train.greit.GREIT(mesh_obj, el_pos, f=f, ex_mat=ex_mat, step=None) greit.setup(p=0.2, lamb=0.01, n=n_pix) rel_perm = greit.solve(f_anom.v, f.v) rel_perm = rel_perm.reshape( (n_pix, n_pix)) # from (n_pix, n_pix, 1) to (n_pix, n_pix) return rel_perm
print("Overriding plots in folder set_"+str(plot_set)) # Initialise current voltage excitation matrix to simulate some voltages measurements to kick start the ESA ex_volt_mat, ex_mat, volt_mat, ind = initialise_ex_volt_mat(current_mode=current_mode, volt_mode=volt_mode,n_el=n_el, ex_mat_length=ex_mat_length) mesh_obj = mesh(n_el=n_el,start_pos='mid') # Making an empty mesh el_pos = np.arange(n_el * n_per_el).astype(np.int16) #el_pos = np.arange(n_el).astype(np.int16) fwd = Forward_given(mesh_obj, el_pos, n_el) empty_mesh_f, empty_meas, empty_ind = fwd.solve_eit(volt_mat=volt_mat, new_ind=ind, ex_mat=ex_mat) # forward solve on the empty mesh # Either simulate data or modify code to read in some real data if simulate_anomalies is True: print("Simulating anomalies and voltage data") a = 2.0 anomaly = train.generate_anoms(a, a) true = train.generate_examplary_output(a, int(n_pix), anomaly) # true conductivty map mesh_new = train.set_perm(mesh_obj, anomaly=anomaly, background=1) # New mesh with anomalies f_sim, dummy_meas, dummy_ind = fwd.solve_eit(volt_mat=volt_mat, new_ind=ind, ex_mat=ex_mat, perm=mesh_new['perm'].astype('f8')) greit = train.greit.GREIT(mesh_obj, el_pos, f=empty_mesh_f, ex_mat=ex_mat) greit.setup(p=0.2, lamb=0.01, n=n_pix) voltages = f_sim.v # assigning simulated voltages reconstruction_initial = greit.solve(voltages, empty_mesh_f.v).reshape(n_pix, n_pix) plt.figure() im1 = plt.imshow(true, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1]) plt.colorbar(im1) plt.title("True Image") if demo_no == 2 and save_plots==True: plt.savefig(filepath+"True image")
def simulateMeasurements(fileJac, anomaly=0, measurements=None, v_meas=None, n_el=20, n_per_el=3, n_pix=64, a=2.): # extract const permittivity jacobian and voltage (& other) file = h5.File(fileJac, 'r') meas = file['meas'][()] new_ind = file['new_ind'][()] p = file['p'][()] t = file['t'][()] file.close() # initialise const permitivity and el_pos variables perm = np.ones(t.shape[0], dtype=np.float32) el_pos = np.arange(n_el * n_per_el).astype(np.int16) mesh_obj = {'element': t, 'node': p, 'perm': perm} #for testing if measurements is None: el_dist = np.random.randint(1, 20) ex_mat = (cp.concatenate((cp.arange(20)[None], (cp.arange(20) + el_dist)[None])) % 20).T #print(ex_mat.shape) fem_all = Forward(mesh_obj, el_pos) measurements = fem_all.voltMeter(ex_mat) #ex_mat = mesurements[1] measurements = cp.concatenate((measurements[1], measurements[0]), axis=1) #print(measurements.shape) # list all possible active/measuring electrode permutations of this measurement meas = cp.array(meas) # find their indices in the already calculated const. permitivity Jacobian (CPJ) measurements = cp.array(measurements) measurements_0 = cp.amin(measurements[:, :2], axis=1) measurements_1 = cp.amax(measurements[:, :2], axis=1) measurements_2 = cp.amin(measurements[:, 2:], axis=1) measurements_3 = cp.amax(measurements[:, 2:], axis=1) measurements = cp.empty((len(measurements), 4)) measurements[:, 0] = measurements_0 measurements[:, 1] = measurements_1 measurements[:, 2] = measurements_2 measurements[:, 3] = measurements_3 index = (cp.sum(cp.equal(measurements[:, None, :], meas[None, :, :]), axis=2) == 4) index = cp.where(index) ind = cp.unique(index[1]) i = cp.asnumpy(ind) j = index[0] mask = np.zeros(len(meas), dtype=int) mask[i] = 1 mask = mask.astype(bool) # take a slice of Jacobian, voltage readings and B matrix file = h5.File(fileJac, 'r') jac = file['jac'][mask, :][()] v = file['v'][mask][()] b = file['b'][mask, :][()] file.close() pde_result = train.namedtuple("pde_result", ['jac', 'v', 'b_matrix']) f = pde_result(jac=jac, v=v, b_matrix=b) # simulate voltage readings if not given if v_meas is None: if np.isscalar(anomaly): print("generating new anomaly") anomaly = train.generate_anoms(a, a) true = train.generate_examplary_output(a, int(n_pix), anomaly) mesh_new = train.set_perm(mesh_obj, anomaly=anomaly, background=1) fem = FEM(mesh_obj, el_pos, n_el) new_ind = cp.array(new_ind) f2, raw = fem.solve_eit(volt_mat_all=meas[ind, 2:], new_ind=new_ind[ind], ex_mat=meas[ind, :2], parser=None, perm=mesh_new['perm'].astype('f8')) v_meas = f2.v ''' #plot fig = plt.figure(3) x, y = p[:, 0], p[:, 1] ax1 = fig.add_subplot(111) # draw equi-potential lines print(raw.shape) raw = cp.asnumpy(raw[5]).ravel() vf = np.linspace(min(raw), max(raw), 32) ax1.tricontour(x, y, t, raw, vf, cmap=plt.cm.viridis) # draw mesh structure ax1.tripcolor(x, y, t, np.real(perm), edgecolors='k', shading='flat', alpha=0.5, cmap=plt.cm.Greys) ax1.plot(x[el_pos], y[el_pos], 'ro') for i, e in enumerate(el_pos): ax1.text(x[e], y[e], str(i+1), size=12) ax1.set_title('Equipotential Lines of Uniform Permittivity') # clean up ax1.set_aspect('equal') ax1.set_ylim([-1.2, 1.2]) ax1.set_xlim([-1.2, 1.2]) fig.set_size_inches(6, 6) #plt.show()''' elif len(measurements) == len(v_meas): measurements = np.array(measurements) v_meas = np.array(v_meas[j[:len(ind)]]) else: raise ValueError('Sizes of arrays do not match (have to have voltage reading for each measurement). If you don\'t have readings, leave empty for simulation.') print('Number of measurements:', len(v_meas), len(f.v)) # now we can use the real voltage readings and the GREIT algorithm to reconstruct greit = train.greit.GREIT(mesh_obj, el_pos, f=f, ex_mat=(meas[index[1], :2]), step=None) greit.setup(p=0.2, lamb=0.01, n=n_pix) h_mat = greit.H reconstruction = greit.solve(v_meas, f.v).reshape(n_pix, n_pix) # optional: see reconstruction ''' plt.figure(1) im1 = plt.imshow(reconstruction, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1]) plt.title("Reconstruction") plt.colorbar(im1) plt.figure(2) im2 = plt.imshow(true, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1]) plt.colorbar(im2) plt.title("True Image") plt.show() ''' return reconstruction, h_mat, v_meas, f.v, true, len(v_meas)
def testAlgorithm(fileJac, n=4, a=2., ne=20, pert=0.5, cutoff=0.97, p_influence=-10., p_rec=10.): file = h5.File(fileJac, 'r') meas = file['meas'][()] new_ind = file['new_ind'][()] p = file['p'][()] t = file['t'][()] '''jac = file['jac'][()] b = file['b'][()] v = file['v'][()]''' file.close() #make anomaly anomaly = None while anomaly is None: anomaly = train.generate_anoms(a, a) print(anomaly) index_stand = ((np.absolute(meas[:, 1] - meas[:, 0]) == 10) ) # + (np.absolute(meas[:,1] - meas[:,0]) == 19)) index_stand *= ((np.absolute(meas[:, 3] - meas[:, 2]) == 1) + (np.absolute(meas[:, 3] - meas[:, 2]) == 19)) ex_mat_all = train.generateExMat(ne=ne) volt_mat_all = train.generateExMat(ne=ne) index_1 = ((np.absolute(volt_mat_all[:, 1] - volt_mat_all[:, 0]) == 1) + (np.absolute(volt_mat_all[:, 1] - volt_mat_all[:, 0]) == 19)) volt_mat_1 = volt_mat_all[index_1] volt_mat_1 = volt_mat_1[np.argsort(volt_mat_1[:, 1], axis=0)] volt_mat_1 = volt_mat_1[np.argsort(volt_mat_1[:, 0] % 5, axis=0)] #print(np.sum(index_stand)) meas_11 = meas[index_stand] ind = np.argsort(meas_11[:, 1], axis=0) meas_11 = meas_11[ind] ordered = meas_11[:10] suggested = ordered[:] counter = np.zeros(190) print(ordered) numS = [] numO = [] lossS = [] lossO = [] for i in range(int((len(meas_11) - 10) // n)): ex_pred, recSugg, trSugg, numSugg, total_map = findNextPair( fileJac, ne, anomaly=anomaly, meas=suggested, a=2., npix=64, pert=pert, p_influence=p_influence, p_rec=p_rec) recOrd, _, _, _, trOrd, numOrd = simulateMeasurements( fileJac, anomaly=anomaly, measurements=ordered, n_el=ne, n_pix=64, a=a) lossSugg = lossL2(recSugg, trSugg) lossOrd = lossL2(recOrd, trOrd) numS.append(numSugg) numO.append(numOrd) lossS.append(lossSugg) lossO.append(lossOrd) print('Reconsructing with', 10 + i * n, 'measurements:') print('Loss Optimised =', lossSugg) print('Loss Ordinary =', lossOrd) rem_r = (np.sum( (volt_mat_1 != ex_pred[0]) + (volt_mat_1 != ex_pred[1]), axis=1)).astype(bool) volt_mat = volt_mat_1[rem_r] j = 0 while True: loc = (np.sum((ex_mat_all == ex_pred[None, j]), axis=1) == 2).astype(bool) if counter[loc] == 0 or counter[loc] < (ne - 2) * (ne - 3) // (5 * n): counter[loc] += 1 ex_pred = ex_pred[j] new_volt_meas = findNextVoltagePair(ex_pred, fileJac, total_map, n, counter[loc], npix=64, cutoff=cutoff) break else: j += 1 #x = volt_mat[int(n * (counter[loc] - 1)):int(n * counter[loc])] #x = np.hstack([np.tile(ex_pred, (n, 1)), x]) x = np.empty((new_volt_meas.shape[0], 4)) x[:, :2] = ex_pred x[:, 2:] = new_volt_meas print(x) ordered = meas_11[:int(10 + n * (i + 1))] suggested = np.concatenate((suggested, x), axis=0) ''' fig1, ax1 = plt.subplots() ax1.plot(numS, lossS, 'rx') ax1.set_title('L2 Loss Function of Algorithm Selected Measurements') ax1.set_xlabel('Num. of Measurements') ax1.set_ylabel('L2 Loss Squared') fig2, ax2 = plt.subplots() ax2.plot(numO, lossO, 'bx') ax2.set_title('L2 Loss Function of a Commonly Used Measurement Technique') ax2.set_xlabel('Num. of Test Sample') ax2.set_ylabel('L2 Loss Squared') plt.show()''' parameterS = np.gradient(lossS) / np.gradient(numS) parameterS /= np.array(numS)**1. parameterS = np.mean(parameterS) parameterO = np.gradient(lossO) / np.gradient(numO) parameterO /= np.array(numO)**1. parameterO = np.mean(parameterO) return np.array(lossS), np.array(numS), np.array(lossO), np.array( numO), parameterS / parameterO