Пример #1
0
 def sigma_e(u):
     return lambda_ * ufl.nabla_div(u) * fenics.Identity(
         2) + 2 * mu * epsilon(u)
Пример #2
0
 def sigma_d(u):
     return eta_b * ufl.nabla_div(u) * fenics.Identity(
         2) + 2 * eta_s * epsilon(u)
Пример #3
0
def sigma(u):
    return lmbda * nabla_div(u) * Identity(d) + 2 * mu * eps(u)
Пример #4
0
    def xest_implement_2d_myosin(self):
        #Parameters
        total_time = 1.0
        number_of_time_steps = 100
        delta_t = total_time / number_of_time_steps
        nx = ny = 100
        domain_size = 1.0
        lambda_ = 5.0
        mu = 2.0
        gamma = 1.0
        eta_b = 0.0
        eta_s = 1.0
        k_b = 1.0
        k_u = 1.0
        #         zeta_1 = -0.5
        zeta_1 = 0.0
        zeta_2 = 1.0
        mu_a = 1.0
        K_0 = 1.0
        K_1 = 0.0
        K_2 = 0.0
        K_3 = 0.0
        D = 0.25
        alpha = 3
        c = 0.1

        # Sub domain for Periodic boundary condition
        class PeriodicBoundary(fenics.SubDomain):
            # Left boundary is "target domain" G
            def inside(self, x, on_boundary):
                # return True if on left or bottom boundary AND NOT on one of the two corners (0, 1) and (1, 0)
                return bool(
                    (fenics.near(x[0], 0) or fenics.near(x[1], 0)) and
                    (not ((fenics.near(x[0], 0) and fenics.near(x[1], 1)) or
                          (fenics.near(x[0], 1) and fenics.near(x[1], 0))))
                    and on_boundary)

            def map(self, x, y):
                if fenics.near(x[0], 1) and fenics.near(x[1], 1):
                    y[0] = x[0] - 1.
                    y[1] = x[1] - 1.
                elif fenics.near(x[0], 1):
                    y[0] = x[0] - 1.
                    y[1] = x[1]
                else:  # near(x[1], 1)
                    y[0] = x[0]
                    y[1] = x[1] - 1.

        periodic_boundary_condition = PeriodicBoundary()

        #Set up finite elements
        mesh = fenics.RectangleMesh(fenics.Point(0, 0),
                                    fenics.Point(domain_size, domain_size), nx,
                                    ny)
        vector_element = fenics.VectorElement('P', fenics.triangle, 2, dim=2)
        single_element = fenics.FiniteElement('P', fenics.triangle, 2)
        mixed_element = fenics.MixedElement(vector_element, single_element)
        V = fenics.FunctionSpace(
            mesh,
            mixed_element,
            constrained_domain=periodic_boundary_condition)
        v, r = fenics.TestFunctions(V)
        full_trial_function = fenics.Function(V)
        u, rho = fenics.split(full_trial_function)
        full_trial_function_n = fenics.Function(V)
        u_n, rho_n = fenics.split(full_trial_function_n)

        #Define non-linear weak formulation
        def epsilon(u):
            return 0.5 * (fenics.nabla_grad(u) + fenics.nabla_grad(u).T
                          )  #return sym(nabla_grad(u))

        def sigma_e(u):
            return lambda_ * ufl.nabla_div(u) * fenics.Identity(
                2) + 2 * mu * epsilon(u)

        def sigma_d(u):
            return eta_b * ufl.nabla_div(u) * fenics.Identity(
                2) + 2 * eta_s * epsilon(u)
#         def sigma_a(u,rho):
#             return ( -zeta_1*rho/(1+zeta_2*rho)*mu_a*fenics.Identity(2)*(K_0+K_1*ufl.nabla_div(u)+
#                                                                          K_2*ufl.nabla_div(u)*ufl.nabla_div(u)+K_3*ufl.nabla_div(u)*ufl.nabla_div(u)*ufl.nabla_div(u)))

        def sigma_a(u, rho):
            return -zeta_1 * rho / (
                1 + zeta_2 * rho) * mu_a * fenics.Identity(2) * (K_0)

        F = (gamma * fenics.dot(u, v) * fenics.dx -
             gamma * fenics.dot(u_n, v) * fenics.dx +
             fenics.inner(sigma_d(u), fenics.nabla_grad(v)) * fenics.dx -
             fenics.inner(sigma_d(u_n), fenics.nabla_grad(v)) * fenics.dx -
             delta_t *
             fenics.inner(sigma_e(u) + sigma_a(u, rho), fenics.nabla_grad(v)) *
             fenics.dx + rho * r * fenics.dx - rho_n * r * fenics.dx +
             ufl.nabla_div(rho * u) * r * fenics.dx -
             ufl.nabla_div(rho * u_n) * r * fenics.dx - D * delta_t *
             fenics.dot(fenics.nabla_grad(rho), fenics.nabla_grad(r)) *
             fenics.dx + delta_t *
             (-k_u * rho * fenics.exp(alpha * ufl.nabla_div(u)) + k_b *
              (1 - c * ufl.nabla_div(u))) * r * fenics.dx)

        #         F = ( gamma*fenics.dot(u,v)*fenics.dx - gamma*fenics.dot(u_n,v)*fenics.dx + fenics.inner(sigma_d(u),fenics.nabla_grad(v))*fenics.dx -
        #               fenics.inner(sigma_d(u_n),fenics.nabla_grad(v))*fenics.dx - delta_t*fenics.inner(sigma_e(u)+sigma_a(u,rho),fenics.nabla_grad(v))*fenics.dx
        #               +rho*r*fenics.dx-rho_n*r*fenics.dx + ufl.nabla_div(rho*u)*r*fenics.dx - ufl.nabla_div(rho*u_n)*r*fenics.dx -
        #               D*delta_t*fenics.dot(fenics.nabla_grad(rho),fenics.nabla_grad(r))*fenics.dx +delta_t*(-k_u*rho*fenics.exp(alpha*ufl.nabla_div(u))+k_b*(1-c*ufl.nabla_div(u))))

        vtkfile_rho = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_rho.pvd'))
        vtkfile_u = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_u.pvd'))

        #         rho_0 = fenics.Expression(((('0.0'),('0.0'),('0.0')),('sin(x[0])')), degree=1 )
        #         full_trial_function_n = fenics.project(rho_0, V)
        time = 0.0
        for time_index in range(number_of_time_steps):
            # Update current time
            time += delta_t
            # Compute solution
            fenics.solve(F == 0, full_trial_function)
            # Save to file and plot solution
            vis_u, vis_rho = full_trial_function.split()
            vtkfile_rho << (vis_rho, time)
            vtkfile_u << (vis_u, time)
            full_trial_function_n.assign(full_trial_function)
Пример #5
0
def sigma1(u):
    return lmbda * nabla_div(u) * Identity(d) + 2.0 * mu * eps1(u)
Пример #6
0
def sigma(u):
    return lambda_*nabla_div(u)*Identity(d) + 2*mu*epsilon(u)
Пример #7
0
def sigma(u):
    return lmbda * nabla_div(u) * Identity(2) + 2 * mu * epsilon(u)
Пример #8
0
def solve_Laplace(Sim_setup,Solver_type,Vertices_array,Domains,core,VTA_IFFT,output):
    set_log_active(False)   #turns off debugging info

    Sim_setup.mesh.coordinates()
    Sim_setup.mesh.init()

    # to get conductivity (and permittivity if EQS formulation) mapped accrodingly to the subdomains. k_val_r is just a list of conductivities (S/mm!) in a specific order to scale the cond. tensor
    kappa,k_val_r=get_dielectric_properties_from_subdomains(Sim_setup.mesh,Sim_setup.subdomains,Sim_setup.Laplace_eq,Domains.Float_contacts,Sim_setup.conductivities,Sim_setup.rel_permittivities,Sim_setup.sine_freq)
    if int(Sim_setup.sine_freq)==int(Sim_setup.signal_freq):
        file=File('/opt/Patient/Field_solutions/Conductivity_map_'+str(Sim_setup.signal_freq)+'Hz.pvd')
        file<<kappa[0]
        if Sim_setup.Laplace_eq == 'EQS':
            file=File('/opt/Patient/Field_solutions/Permittivity_map_'+str(Sim_setup.signal_freq)+'Hz.pvd')
            file<<kappa[1]

    # to get tensor scaled by the conductivity map
    if Sim_setup.anisotropy==1:
        Cond_tensor=get_scaled_cond_tensor(Sim_setup.mesh,Sim_setup.subdomains,Sim_setup.sine_freq,Sim_setup.signal_freq,Sim_setup.unscaled_tensor,k_val_r)
    else:
        Cond_tensor=False  #just to initialize


    #In case of current-controlled stimulation, Dirichlet_bc or the whole potential distribution will be scaled afterwards (due to the system's linearity)
    V_space,Dirichlet_bc,ground_index,facets=get_solution_space_and_Dirichlet_BC(Sim_setup.external_grounding,Sim_setup.c_c,Sim_setup.mesh,Sim_setup.subdomains,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,Domains.fi)
    #ground index refers to the ground in .med/.msh file

    # to solve the Laplace equation div(kappa*grad(phi))=0   (variational form: a(u,v)=L(v))
    phi_sol=define_variational_form_and_solve(V_space,Dirichlet_bc,kappa,Sim_setup.Laplace_eq,Cond_tensor,Solver_type)

    if Sim_setup.Laplace_eq=='EQS':
        (phi_r,phi_i)=phi_sol.split(deepcopy=True)
    else:
        phi_r=phi_sol
        phi_i=Function(V_space)
        phi_i.vector()[:] = 0.0

    #save unscaled real solution for plotting
    if int(Sim_setup.sine_freq)==int(Sim_setup.signal_freq):
        file=File('/opt/Patient/Field_solutions/Phi_real_unscaled_'+str(Sim_setup.signal_freq)+'Hz.pvd')
        file<<phi_r,Sim_setup.mesh
        if Sim_setup.external_grounding==True:
            file=File('/opt/Patient/Field_solutions/ground_facets'+str(Sim_setup.signal_freq)+'Hz.pvd')
            file<<facets
        print("DoFs on the mesh for "+Sim_setup.Laplace_eq+" : ", (max(V_space.dofmap().dofs())+1))


    if Sim_setup.c_c==1 or Sim_setup.CPE_status==1:     #we compute E-field, currents and impedances only for current-controlled or if CPE is used
        J_ground=get_current(Sim_setup.mesh,facets,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,kappa,Cond_tensor,phi_r,phi_i,ground_index)
        #If EQS, J_ground is a complex number

        #V_across=max(Domains.fi[:], key=abs)        # voltage drop in the system
        #V_across=abs(max(Domains.fi[:])-min(Domains.fi[:]))        # voltage drop in the system

        if Sim_setup.external_grounding==True and (Sim_setup.c_c==1 or len(Domains.fi)==1):
            V_max=max(Domains.fi[:], key=abs)
            V_min=0.0
        elif -1*Domains.fi[0]==Domains.fi[1]:     # V_across is needed only for 2 active contact systems
            V_min=-1*abs(Domains.fi[0])
            V_max=abs(Domains.fi[0])
        else:
            V_min=min(Domains.fi[:], key=abs)
            V_max=max(Domains.fi[:], key=abs)
        V_across=V_max-V_min   # this can be negative

        Z_tissue = V_across/J_ground                   # Tissue impedance
        if int(Sim_setup.sine_freq)==int(Sim_setup.signal_freq):
            print("Tissue impedance at the signal freq.: ",Z_tissue)

        if Sim_setup.CPE_status==1:   # in this case we need to estimate the voltage drop over the CPE and adjust the Derichlet BC accordingly

            if len(Domains.fi)>2:
                print("Currently, CPE can be used only for simulations with two contacts. Please, assign the rest to 'None'")
                raise SystemExit

            Dirichlet_bc_with_CPE,total_impedance=get_CPE_corrected_Dirichlet_BC(Sim_setup.external_grounding,facets,Sim_setup.boundaries,Sim_setup.CPE_param,Sim_setup.Laplace_eq,Sim_setup.sine_freq,Sim_setup.signal_freq,Domains.Contacts,Domains.fi,V_across,Z_tissue,V_space)

            f=open('/opt/Patient/Field_solutions/Impedance'+str(core)+'.csv','ab')
            np.savetxt(f, total_impedance, delimiter=" ")
            f.close()

            # to solve the Laplace equation for the adjusted Dirichlet
            phi_sol_CPE=define_variational_form_and_solve(V_space,Dirichlet_bc_with_CPE,kappa,Sim_setup.Laplace_eq,Cond_tensor,Solver_type)
            if Sim_setup.Laplace_eq=='EQS':
                (phi_r_CPE,phi_i_CPE)=phi_sol_CPE.split(deepcopy=True)
            else:
                phi_r_CPE=phi_sol_CPE
                phi_i_CPE=Function(V_space)
                phi_i_CPE.vector()[:] = 0.0

            J_ground_CPE=get_current(Sim_setup.mesh,facets,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,kappa,Cond_tensor,phi_r_CPE,phi_i_CPE,ground_index)

            # just resaving
            phi_sol,phi_r,phi_i,J_ground=(phi_sol_CPE,phi_r_CPE,phi_i_CPE,J_ground_CPE)

    # if Full_IFFT==1:
    #     Hdf=HDF5File(Sim_setup.mesh.mpi_comm(), "/opt/Patient/Field_solutions_functions/solution"+str(np.round(Sim_setup.sine_freq,6))+".h5", "w")
    #     Hdf.write(Sim_setup.mesh, "mesh")
    #     if Sim_setup.CPE_status!=1:
    #         Hdf.write(phi_sol, "solution_full")

    #     if Sim_setup.c_c==1:
    #         with open('/opt/Patient/Field_solutions_functions/current_scale'+str(np.round(Sim_setup.sine_freq,6))+'.file', 'wb') as f:
    #             pickle.dump(np.array([np.real(J_ground),np.imag(J_ground)]), f)
    #     Hdf.close()

    #else:
    if VTA_IFFT==1:
        Sim_type='Astrom' #   fixed for now
        if Sim_type=='Astrom' or Sim_type=='Butson':
            # Solve for rescaled
            Dirichlet_bc_scaled=[]
            for bc_i in range(len(Domains.Contacts)):          #CPE estimation is valid only for one activa and one ground contact configuration
                if Sim_setup.Laplace_eq == 'EQS':
                    if Domains.fi[bc_i]==0.0:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                    else:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), np.imag((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
                else:
                    if Domains.fi[bc_i]==0.0:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space, 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                    else:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space, np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))


            if Sim_setup.external_grounding==True:
                if Sim_setup.Laplace_eq == 'EQS':
                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0),0.0,facets,1))
                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1),0.0,facets,1))
                else:
                    Dirichlet_bc_scaled.append(DirichletBC(V_space,0.0,facets,1))

            phi_sol_check=define_variational_form_and_solve(V_space,Dirichlet_bc_scaled,kappa,Sim_setup.Laplace_eq,Cond_tensor,Solver_type)

            if Sim_setup.Laplace_eq=='EQS':
                (phi_r_check,phi_i_check)=phi_sol_check.split(deepcopy=True)
            else:
                phi_r_check=phi_sol_check
                phi_i_check=Function(V_space)
                phi_i_check.vector()[:] = 0.0

            J_ground,E_field_r,E_field_im=get_current(Sim_setup.mesh,facets,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,kappa,Cond_tensor,phi_r_check,phi_i_check,ground_index,get_E_field=True)

            if Sim_type=='Astrom':
                W_amp=FunctionSpace(Sim_setup.mesh,'DG',Sim_setup.element_order-1)
                w_amp = TestFunction(W_amp)
                Pv_amp = TrialFunction(W_amp)
                E_amp_real = Function(W_amp)
                a_local = inner(w_amp, Pv_amp) * dx
                L_local = inner(w_amp, sqrt(dot(E_field_r,E_field_r))) * dx
                A_local, b_local = assemble_system(a_local, L_local, bcs=[])

                local_solver = PETScKrylovSolver('bicgstab')
                local_solver.solve(A_local,E_amp_real.vector(),b_local)

                #E_amp_real.vector()[:]=E_amp_real.vector()

                E_amp_imag = Function(W_amp)
                a_local = inner(w_amp, Pv_amp) * dx
                L_local = inner(w_amp, sqrt(dot(E_field_im,E_field_im))) * dx
                A_local, b_local = assemble_system(a_local, L_local, bcs=[])

                local_solver = PETScKrylovSolver('bicgstab')
                local_solver.solve(A_local,E_amp_imag.vector(),b_local)
            elif Sim_type=='Butson':
                from ufl import nabla_div

                W_amp=FunctionSpace(Sim_setup.mesh,'DG',Sim_setup.element_order-1)
                w_amp = TestFunction(W_amp)
                Pv_amp = TrialFunction(W_amp)
                Second_deriv= Function(W_amp)
                a_local = inner(w_amp, Pv_amp) * dx
                L_local = inner(w_amp, nabla_div(E_field_r)) * dx
                A_local, b_local = assemble_system(a_local, L_local, bcs=[])

                local_solver = PETScKrylovSolver('bicgstab')
                local_solver.solve(A_local,Second_deriv.vector(),b_local)

                W_amp=FunctionSpace(Sim_setup.mesh,'DG',Sim_setup.element_order-1)
                w_amp = TestFunction(W_amp)
                Pv_amp = TrialFunction(W_amp)
                Second_deriv_imag= Function(W_amp)
                a_local = inner(w_amp, Pv_amp) * dx
                L_local = inner(w_amp, nabla_div(E_field_im)) * dx
                A_local, b_local = assemble_system(a_local, L_local, bcs=[])

                local_solver = PETScKrylovSolver('bicgstab')
                local_solver.solve(A_local,Second_deriv_imag.vector(),b_local)


            Phi_ROI=np.zeros((Vertices_array.shape[0],5),float)

            #VTA=0.0

            for inx in range(Vertices_array.shape[0]):
                pnt=Point(Vertices_array[inx,0],Vertices_array[inx,1],Vertices_array[inx,2])
                if Sim_setup.mesh.bounding_box_tree().compute_first_entity_collision(pnt)<Sim_setup.mesh.num_cells()*100:

                    Phi_ROI[inx,0]=Vertices_array[inx,0]
                    Phi_ROI[inx,1]=Vertices_array[inx,1]
                    Phi_ROI[inx,2]=Vertices_array[inx,2]

                    #if Sim_setup.c_c==1:
                    if Sim_type=='Butson':
                        Phi_ROI[inx,3]=Second_deriv(pnt)   # already scaled
                        Phi_ROI[inx,4]=Second_deriv_imag(pnt)    # already scaled
                    elif Sim_type=='Astrom':
                        Phi_ROI[inx,3]=E_amp_real(pnt)   # already scaled
                        Phi_ROI[inx,4]=E_amp_imag(pnt)    # already scaled

                    #if Sim_setup.sine_freq==Sim_setup.signal_freq and abs(Phi_ROI[inx,3])>=0.3:
                    #    VTA+=0.1**3

                else:       # we assign 0.0 here
                    Phi_ROI[inx,3]=0.0
                    Phi_ROI[inx,4]=0.0

                    #print("Couldn't probe the potential at the point ",Vertices_array[inx,0],Vertices_array[inx,1],Vertices_array[inx,2])
                    #print("check the neuron array, exiting....")
                    #raise SystemExit

            fre_vector=[Sim_setup.sine_freq]*Phi_ROI.shape[0]
            comb=np.vstack((Phi_ROI[:,0],Phi_ROI[:,1],Phi_ROI[:,2],Phi_ROI[:,3],Phi_ROI[:,4],fre_vector)).T

            f = h5py.File('/opt/Patient/Field_solutions/sol_cor'+str(core)+'.h5','a')
            f.create_dataset(str(Sim_setup.sine_freq), data=comb)
            f.close()



        if Sim_setup.c_c==1:
            comb_Z=np.vstack((np.real(Z_tissue),np.imag(Z_tissue),Sim_setup.sine_freq)).T
            f=open('/opt/Patient/Field_solutions/Impedance'+str(core)+'.csv','ab')
            np.savetxt(f, comb_Z, delimiter=" ")
            f.close()


#    if Sim_setup.sine_freq==Sim_setup.signal_freq and Sim_setup.c_c==1:  # re-solve with the scaled potential just to check (to match 1 A)
#        Dirichlet_bc_scaled=[]
#        for bc_i in range(len(Domains.Contacts)):          #CPE estimation is valid only for one activa and one ground contact configuration
#            if Sim_setup.Laplace_eq == 'EQS':
#                if Domains.fi[bc_i]==0.0:
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
#                else:
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), np.imag((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
#            else:
#                if Domains.fi[bc_i]==0.0:
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space, 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
#                else:
#                    Dirichlet_bc_scaled.append(DirichletBC(V_space, np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
#
#        phi_sol_check=define_variational_form_and_solve(V_space,Dirichlet_bc_scaled,kappa,Sim_setup.Laplace_eq,Cond_tensor,Solver_type)
#
#        if Sim_setup.Laplace_eq=='EQS':
#            (phi_r_check,phi_i_check)=phi_sol_check.split(deepcopy=True)
#        else:
#            phi_r_check=phi_sol_check
#            phi_i_check=Function(V_space)
#            phi_i_check.vector()[:] = 0.0

        #J_ground=get_current(Sim_setup.mesh,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,kappa,Cond_tensor,phi_r_check,phi_i_check,ground_index)
        if Sim_setup.sine_freq==Sim_setup.signal_freq:
            print("Current through the ground after normalizing to 1 A at the signal freq.: ",J_ground)

            file=File('/opt/Patient/Field_solutions/'+str(Sim_setup.Laplace_eq)+str(Sim_setup.signal_freq)+'_phi_r_1A.pvd')
            file<<phi_r_check

        output.put(1)

    else:

        Phi_ROI=np.zeros((Vertices_array.shape[0],5),float)

        for inx in range(Vertices_array.shape[0]):
            pnt=Point(Vertices_array[inx,0],Vertices_array[inx,1],Vertices_array[inx,2])
            if Sim_setup.mesh.bounding_box_tree().compute_first_entity_collision(pnt)<Sim_setup.mesh.num_cells()*100:

                Phi_ROI[inx,0]=Vertices_array[inx,0]
                Phi_ROI[inx,1]=Vertices_array[inx,1]
                Phi_ROI[inx,2]=Vertices_array[inx,2]

                if Sim_setup.c_c==1:
                    Phi_ROI[inx,3]=np.real((phi_r(pnt)+1j*phi_i(pnt))/J_ground)    #*1A is left out here
                    Phi_ROI[inx,4]=np.imag((phi_r(pnt)+1j*phi_i(pnt))/J_ground)    #*1A is left out here
                else:
                    Phi_ROI[inx,3]=phi_r(pnt)
                    Phi_ROI[inx,4]=phi_i(pnt)
            else:
                print("Couldn't probe the potential at the point ",Vertices_array[inx,0],Vertices_array[inx,1],Vertices_array[inx,2])
                print("check the neuron array, exiting....")
                raise SystemExit

        fre_vector=[Sim_setup.sine_freq]*Phi_ROI.shape[0]
        comb=np.vstack((Phi_ROI[:,0],Phi_ROI[:,1],Phi_ROI[:,2],Phi_ROI[:,3],Phi_ROI[:,4],fre_vector)).T

        f = h5py.File('/opt/Patient/Field_solutions/sol_cor'+str(core)+'.h5','a')
        f.create_dataset(str(Sim_setup.sine_freq), data=comb)
        f.close()

        if Sim_setup.c_c==1:
            comb_Z=np.vstack((np.real(Z_tissue),np.imag(Z_tissue),Sim_setup.sine_freq)).T
            f=open('/opt/Patient/Field_solutions/Impedance'+str(core)+'.csv','ab')
            np.savetxt(f, comb_Z, delimiter=" ")
            f.close()


        if Sim_setup.sine_freq==Sim_setup.signal_freq and Sim_setup.c_c==1:  # re-solve with the scaled potential just to check (to match 1 A)
            Dirichlet_bc_scaled=[]
            for bc_i in range(len(Domains.Contacts)):          #CPE estimation is valid only for one activa and one ground contact configuration
                if Sim_setup.Laplace_eq == 'EQS':
                    if Domains.fi[bc_i]==0.0:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                    else:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0), np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
                        Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1), np.imag((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))
                else:
                    if Domains.fi[bc_i]==0.0:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space, 0.0, Sim_setup.boundaries,Domains.Contacts[bc_i]))
                    else:
                        Dirichlet_bc_scaled.append(DirichletBC(V_space, np.real((Domains.fi[bc_i])/J_ground),Sim_setup.boundaries,Domains.Contacts[bc_i]))

            if Sim_setup.external_grounding==True:
                if Sim_setup.Laplace_eq == 'EQS':
                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(0),0.0,facets,1))
                    Dirichlet_bc_scaled.append(DirichletBC(V_space.sub(1),0.0,facets,1))
                else:
                    Dirichlet_bc_scaled.append(DirichletBC(V_space,0.0,facets,1))

            phi_sol_check=define_variational_form_and_solve(V_space,Dirichlet_bc_scaled,kappa,Sim_setup.Laplace_eq,Cond_tensor,Solver_type)

            if Sim_setup.Laplace_eq=='EQS':
                (phi_r_check,phi_i_check)=phi_sol_check.split(deepcopy=True)
            else:
                phi_r_check=phi_sol_check
                phi_i_check=Function(V_space)
                phi_i_check.vector()[:] = 0.0

            J_ground=get_current(Sim_setup.mesh,facets,Sim_setup.boundaries,Sim_setup.element_order,Sim_setup.Laplace_eq,Domains.Contacts,kappa,Cond_tensor,phi_r_check,phi_i_check,ground_index)
            print("Current through the ground after normalizing to 1 A at the signal freq.: ",J_ground)

            file=File('/opt/Patient/Field_solutions/'+str(Sim_setup.Laplace_eq)+str(Sim_setup.signal_freq)+'_phi_r_1A.pvd')
            file<<phi_r_check

        output.put(1)
Пример #9
0
    bc_R = DirichletBC(V, p_R, boundary_R)

    bcs = [bc_L, bc_R]

    # Defining variational problem
    p = TrialFunction(V)
    v = TestFunction(V)
    d = 2
    I = Identity(d)
    x, y = SpatialCoordinate(mesh)
    M = max_value(Constant(0.10), exp(-(10 * y - 1.0 * sin(10 * x) - 5.0)**2))
    K = M * I
    #K = Constant(1.0)
    a = dot(K * grad(p), grad(v)) * dx
    f1 = as_vector((-2 * x, 0))
    f = nabla_div(dot(-K, f1))
    L = inner(f, v) * dx

    # Computing solutions
    p = Function(V)
    solve(a == L, p, bcs)
    u_bar = -K * grad(p)

    # Projecting the Velocity profile
    W = VectorFunctionSpace(mesh, 'P', 1)
    u_bar1 = project(u_bar, W)

    # Evaluating difference between Numerical pressure, p and Exact pressure, p_e
    p_e_f = interpolate(p_e, V)
    diff_p = Function(V)
    diff_p.vector()[:] = p.vector() - p_e_f.vector()