コード例 #1
0
 def get_all_voltages(self, anomaly):
     mesh_new = set_perm(self.all_meas.mesh_obj,
                         anomaly=anomaly,
                         background=None)
     voltage_readings, measurements, new_ind = self.fwd.solveAnomaly(
         ex_mat=self.ex_mat_all, step=1, perm=mesh_new['perm'], parser=None)
     ind = np.lexsort((measurements[:, 3], measurements[:, 2],
                       measurements[:, 1], measurements[:, 0]))
     return voltage_readings[ind], measurements[ind]
コード例 #2
0
def demo():
    """demo shows how to interpolate on regular/irregular grids"""
    # 1. create mesh
    mesh_obj, _ = layer_circle(n_layer=8, n_fan=6)
    pts = mesh_obj['node']
    tri = mesh_obj['element']

    # set anomaly
    anomaly = [{'x': 0.5, 'y': 0.5, 'd': 0.2, 'perm': 100.0}]
    mesh_new = set_perm(mesh_obj, anomaly=anomaly)

    # 2. interpolate using averaged neighbor triangle area
    perm_node = sim2pts(pts, tri, mesh_new['perm'])

    # plot mesh and interpolated mesh (tri2pts)
    fig_size = (6, 4)
    fig = plt.figure(figsize=fig_size)
    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.triplot(pts[:, 0], pts[:, 1], tri)
    im1 = ax.tripcolor(pts[:, 0], pts[:, 1], tri, mesh_new['perm'])
    fig.colorbar(im1, orientation='vertical')

    fig = plt.figure(figsize=fig_size)
    ax2 = fig.add_subplot(111)
    ax2.set_aspect('equal')
    ax2.triplot(pts[:, 0], pts[:, 1], tri)
    im2 = ax2.tripcolor(pts[:, 0], pts[:, 1], tri, perm_node, shading='flat')
    fig.colorbar(im2, orientation='vertical')

    # 3. interpolate on grids (irregular or regular) using IDW, sigmod
    xg, yg, mask = meshgrid(pts)
    im = np.ones_like(mask)
    # mapping from values on xy to values on xyi
    xy = np.mean(pts[tri], axis=1)
    xyi = np.vstack((xg.flatten(), yg.flatten())).T
    # w_mat = weight_idw(xy, xyi)
    w_mat = weight_sigmod(xy, xyi)
    im = np.dot(w_mat.T, mesh_new['perm'])
    # im = weight_linear_rbf(xy, xyi, mesh_new['perm'])
    im[mask] = 0.
    # reshape to grid size
    im = im.reshape(xg.shape)

    # plot interpolated values
    fig, ax = plt.subplots(figsize=fig_size)
    ax.set_aspect('equal')
    ax.triplot(pts[:, 0], pts[:, 1], tri, alpha=0.5)
    im3 = ax.pcolor(xg, yg, im, edgecolors=None, linewidth=0, alpha=0.8)
    fig.colorbar(im3, orientation='vertical')
    plt.show()
コード例 #3
0
ファイル: interp2d.py プロジェクト: fzouari/pyEIT
def demo():
    """demo shows how to interpolate on regular/irregular grids"""
    # 1. create mesh
    mesh_obj, _ = layer_circle(n_layer=8, n_fan=6)
    pts = mesh_obj["node"]
    tri = mesh_obj["element"]

    # set anomaly
    anomaly = [{"x": 0.5, "y": 0.5, "d": 0.2, "perm": 100.0}]
    mesh_new = set_perm(mesh_obj, anomaly=anomaly)

    # 2. interpolate using averaged neighbor triangle area
    perm_node = sim2pts(pts, tri, mesh_new["perm"])

    # 3. interpolate on grids (irregular or regular) using IDW, sigmod
    xg, yg, mask = meshgrid(pts)
    im = np.ones_like(mask)
    # mapping from values on xy to values on xyi
    xy = np.mean(pts[tri], axis=1)
    xyi = np.vstack((xg.flatten(), yg.flatten())).T
    # w_mat = weight_idw(xy, xyi)
    w_mat = weight_sigmod(xy, xyi)
    im = np.dot(w_mat.T, mesh_new["perm"])
    # im = weight_linear_rbf(xy, xyi, mesh_new['perm'])
    im[mask] = 0.0
    # reshape to grid size
    im = im.reshape(xg.shape)
    # Inverse mapping
    # w_mat_T_inv = np.linalg.pinv(w_mat.T)
    w_mat_T_inv = w_mat
    mesh_new_r = np.dot(w_mat_T_inv, im)

    # plot mesh and interpolated mesh (tri2pts)
    fig, axs = plt.subplots(1, 3)
    ax1, ax2, ax3 = axs[0], axs[1], axs[2]

    ax1.set_aspect('equal')
    ax1.triplot(pts[:, 0], pts[:, 1], tri)
    im1 = ax1.tripcolor(pts[:, 0], pts[:, 1], tri, mesh_new['perm'])

    ax2.set_aspect('equal')
    ax2.triplot(pts[:, 0], pts[:, 1], tri)
    im2 = ax2.tripcolor(pts[:, 0], pts[:, 1], tri, perm_node, shading='flat')

    # plot interpolated values
    fig, ax = plt.subplots(figsize=fig_size)
    ax.set_aspect("equal")
    ax.triplot(pts[:, 0], pts[:, 1], tri, alpha=0.5)
    im3 = ax.pcolor(xg, yg, im, edgecolors=None, linewidth=0, alpha=0.8)
    fig.colorbar(im3, orientation="vertical")
    plt.show()
コード例 #4
0
    def get_obs(self,**kwargs):
        folder=kwargs.pop('folder','./result')
        fname=str(self.gdim)+'d_EIT_dim'+str(self.dim)
        try:
            with open(os.path.join(folder,fname+'.pckl'),'rb') as f:
                [self.true_perm,obs]=pickle.load(f)[:2]
            print('Data '+fname+' loaded!')
        except:
            print('No data found. Generate new data...')
            mesh_new=mesh.set_perm(self.mesh_obj, anomaly=self.anomaly, background=1.0)
            self.true_perm=mesh_new['perm']
            fs=self.solve(self.true_perm,skip_jac=True,**kwargs)
            obs=fs.v
#             if np.size(self.nz_var)<np.size(obs): self.nz_var=np.resize(self.nz_var,np.size(obs))
#             obs+=np.sqrt(self.nz_var)*np.random.randn(np.size(obs)) # voltage must be positive!
            if not os.path.exists(folder): os.makedirs(folder)
            with open(os.path.join(folder,fname+'.pckl'),'wb') as f:
                pickle.dump([self.true_perm,obs,self.n_el,self.bbox,self.meshsz,self.el_dist,self.step,self.anomaly,self.lamb],f)
        return obs
コード例 #5
0
ファイル: demo_dynamic_bp.py プロジェクト: zhould1990/pyEIT
import numpy as np
import matplotlib.pyplot as plt

import pyeit.mesh as mesh
from pyeit.eit.fem import Forward
from pyeit.eit.utils import eit_scan_lines
import pyeit.eit.bp as bp
""" 0. build mesh """
mesh_obj, el_pos = mesh.create(16, h0=0.1)

# extract node, element, alpha
pts = mesh_obj['node']
tri = mesh_obj['element']
""" 1. problem setup """
anomaly = [{'x': 0.5, 'y': 0.5, 'd': 0.1, 'perm': 10.0}]
mesh_new = mesh.set_perm(mesh_obj, anomaly=anomaly, background=1.0)

# draw
delta_perm = np.real(mesh_new['perm'] - mesh_obj['perm'])
fig, ax = plt.subplots()
im = ax.tripcolor(pts[:, 0],
                  pts[:, 1],
                  tri,
                  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)
コード例 #6
0
anomaly = [
    {
        "x": 0.4,
        "y": 0.4,
        "d": 0.2,
        "perm": 10
    },
    {
        "x": -0.4,
        "y": -0.4,
        "d": 0.2,
        "perm": 0.1
    },
]
# background changed to values other than 1.0 requires more iterations
mesh_new = set_perm(mesh_obj, anomaly=anomaly, background=2.0)

# extract node, element, perm
pts = mesh_obj["node"]
tri = mesh_obj["element"]
perm = mesh_new["perm"]

# show
fig, ax = plt.subplots(figsize=(6, 4))
im = ax.tripcolor(pts[:, 0],
                  pts[:, 1],
                  tri,
                  np.real(perm),
                  shading="flat",
                  cmap=plt.cm.viridis)
fig.colorbar(im)
コード例 #7
0
ファイル: eit_dynamic_jac.py プロジェクト: fzouari/pyEIT
from pyeit.eit.interp2d import sim2pts
import pyeit.eit.jac_reg as jac_reg

""" 0. construct mesh """
mesh_obj, el_pos = mesh.create(16, h0=0.1)
# mesh_obj, el_pos = mesh.layer_circle()

# extract node, element, alpha
pts = mesh_obj["node"]
tri = mesh_obj["element"]
x, y = pts[:, 0], pts[:, 1]

""" 1. problem setup """
mesh_obj["alpha"] = np.random.rand(tri.shape[0]) * 200 + 100
anomaly = [{"x": 0.5, "y": 0.5, "d": 0.1, "perm": 1000.0}]
mesh_new = mesh.set_perm(mesh_obj, anomaly=anomaly)

""" 2. FEM simulation """
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. JAC solver """
# Note: if the jac and the real-problem are generated using the same mesh,
# then, 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
コード例 #8
0
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