예제 #1
0
def problem2():

    patient = LVTestPatient("benchmark")

    setup_general_parameters()
    params = setup_adjoint_contraction_parameters()
    params["base_bc"] = "fixed"
    material_model = "guccione"

    solver_parameters, pressure, paramvec = make_solver_params(params, patient)
    V_real = df.FunctionSpace(solver_parameters["mesh"], "R", 0)
    gamma = df.Function(V_real, name="gamma")

    matparams = setup_material_parameters(material_model)

    matparams["C"] = 10.0
    matparams["bf"] = 1.0
    matparams["bt"] = 1.0
    matparams["bfs"] = 1.0

    args = (patient.fiber, gamma, matparams, "active_stress", patient.sheet,
            patient.sheet_normal, params["T_ref"])

    material = Guccione(*args)
    solver_parameters["material"] = material

    solver = LVSolver(solver_parameters)
    solver.parameters["solve"]["snes_solver"]["report"] = True

    solver.solve()

    iterate_pressure(solver, 10.0, pressure)

    u, p = solver.get_state().split(deepcopy=True)

    f = df.XDMFFile(df.mpi_comm_world(), "benchmark_2.xdmf")
    f.write(u)
예제 #2
0
from pulse_adjoint.unloading import *
from pulse_adjoint.setup_parameters import setup_general_parameters
setup_general_parameters()

from pulse_adjoint import LVTestPatient
geo_lv = LVTestPatient()
p_lv = 2.0

from pulse_adjoint import BiVTestPatient
geo_biv = BiVTestPatient()
p_biv = (2.0, 1.0)


def test_fixed_point_lv():

    unloader = FixedPoint(geo_lv,
                          p_lv,
                          h5name="fixedpoint_lv.h5",
                          options={"maxiter": 15})
    unloader.unload()


def test_raghavan_lv():
    unloader = Raghavan(geo_lv,
                        p_lv,
                        h5name="raghavan_biv.h5",
                        options={"maxiter": 1})
    unloader.unload()


def test_hybrid_lv():
예제 #3
0
def general_solver(parameters, advanced_parameters):
    print 'TESTING THREAD1'
    setup_general_parameters()
    patient = parameters['patient']
    mesh = patient.mesh
    mesh_name = parameters['mesh_name']
    marked_mesh = patient.ffun
    N = df.FacetNormal(mesh)
    fibers = patient.fiber

    # Getting BC
    BC_type = parameters['BC_type']

    def make_dirichlet_bcs(W):
        V = W if W.sub(0).num_sub_spaces() == 0 else W.sub(0)
        if BC_type == 'fix_x':
            no_base_x_tran_bc = df.DirichletBC(V.sub(0), df.Constant(0.0),
                                               marked_mesh,
                                               patient.markers["BASE"][0])
        elif BC_type == 'fixed':
            no_base_x_tran_bc = df.DirichletBC(V, df.Constant(
                (0.0, 0.0, 0.0)), marked_mesh, patient.markers["BASE"][0])
        return no_base_x_tran_bc

    # Contraction parameter
    # gamma = Constant(0.0)
    #gamma = df.Function(df.FunctionSpace(mesh, "R", 0))
    gamma = RegionalParameter(patient.sfun)

    gamma_values = parameters['gamma']
    gamma_base = gamma_values['gamma_base']
    gamma_mid = gamma_values['gamma_mid']
    gamma_apical = gamma_values['gamma_apical']
    gamma_apex = gamma_values['gamma_apex']

    gamma_arr = np.array(gamma_base + gamma_mid + gamma_apical + gamma_apex)

    G = RegionalParameter(patient.sfun)
    G.vector()[:] = gamma_arr
    G_ = df.project(G.get_function(), G.get_ind_space())

    f_gamma = df.XDMFFile(df.mpi_comm_world(), "activation.xdmf")
    f_gamma.write(G_)

    # Pressure
    pressure = df.Constant(0.0)
    lv_pressure = df.Constant(0.0)
    rv_pressure = df.Constant(0.0)
    #lv_pressure = df.Constant(0.0)
    #rv_pressure = df.Constant(0.0)

    # Spring
    spring_constant = advanced_parameters['spring_constant']
    spring = df.Constant(spring_constant)
    spring_area = advanced_parameters['spring_area']

    # Set up material model
    material_model = advanced_parameters['material_model']
    active_model = advanced_parameters['active_model']
    T_ref = advanced_parameters['T_ref']
    matparams = advanced_parameters['mat_params']
    #matparams=setup_material_parameters(material_model)
    if material_model == 'guccione':
        try:
            args = (fibers, gamma, matparams, active_model, patient.sheet,
                    patient.sheet_normal, T_ref)

        except AttributeError:
            print 'Mesh does not have "sheet" attribute, choose another material model.'
            return

    else:
        args = (
            fibers,
            gamma,
            matparams,
            active_model,
            #patient.sheet,
            #patient.sheet_normal,
            T_ref)

    if material_model == 'holzapfel_ogden':
        material = mat.HolzapfelOgden(*args)

    elif material_model == 'guccione':
        material = mat.Guccione(*args)

    elif material_model == 'neo_hookean':
        material = mat.NeoHookean(*args)

    # Create parameters for the solver
    if mesh_name == 'biv_ellipsoid.h5':
        params = {
            "mesh": mesh,
            "facet_function": marked_mesh,
            "facet_normal": N,
            "state_space": "P_2:P_1",
            "compressibility": {
                "type": "incompressible",
                "lambda": 0.0
            },
            "material": material,
            "bc": {
                "dirichlet":
                make_dirichlet_bcs,
                "neumann": [[lv_pressure, patient.markers["ENDO_LV"][0]],
                            [rv_pressure, patient.markers["ENDO_RV"][0]]],
                "robin": [[spring, patient.markers[spring_area][0]]]
            }
        }
    else:
        params = {
            "mesh": mesh,
            "facet_function": marked_mesh,
            "facet_normal": N,
            "state_space": "P_2:P_1",
            "compressibility": {
                "type": "incompressible",
                "lambda": 0.0
            },
            "material": material,
            "bc": {
                "dirichlet": make_dirichlet_bcs,
                "neumann": [[pressure, patient.markers["ENDO"][0]]],
                "robin": [[spring, patient.markers[spring_area][0]]]
            }
        }

    df.parameters["adjoint"]["stop_annotating"] = True

    # Initialize solver
    solver = LVSolver(params)
    print 'TESTING THREAD2'
    # Solve for the initial state
    folder_path = parameters['folder_path']
    u, p = solver.get_state().split(deepcopy=True)
    U = df.Function(u.function_space(), name="displacement")
    f = df.XDMFFile(df.mpi_comm_world(), folder_path + "/displacement.xdmf")

    sigma_f = solver.postprocess().cauchy_stress_component(fibers)
    V = df.FunctionSpace(mesh, 'DG', 1)
    sf = df.project(sigma_f, V)
    SF = df.Function(sf.function_space(), name='stress')
    g = df.XDMFFile(df.mpi_comm_world(), folder_path + "/stress.xdmf")

    solver.solve()

    u1, p1 = solver.get_state().split(deepcopy=True)
    U.assign(u1)
    f.write(U)

    sigma_f1 = solver.postprocess().cauchy_stress_component(fibers)
    sf1 = df.project(sigma_f1, V)
    SF.assign(sf1)
    g.write(SF)

    # Put on some pressure and solve
    plv = parameters['lv_pressure']
    prv = parameters['rv_pressure']

    if mesh_name == 'biv_ellipsoid.h5':
        iterate("pressure", solver, (plv, prv), {
            "p_lv": lv_pressure,
            "p_rv": rv_pressure
        })
    else:
        iterate("pressure", solver, plv, {"p_lv": pressure})

    u2, p2 = solver.get_state().split(deepcopy=True)
    U.assign(u2)
    f.write(U)

    sigma_f2 = solver.postprocess().cauchy_stress_component(fibers)
    sf2 = df.project(sigma_f2, V)
    SF.assign(sf2)
    g.write(SF)

    # Put on some active contraction and solve
    cont_mult = parameters['contraction_multiplier']
    g_ = cont_mult * gamma_arr

    iterate("gamma", solver, g_, gamma, max_nr_crash=100, max_iters=100)
    u3, p3 = solver.get_state().split(deepcopy=True)
    U.assign(u3)
    f.write(U)

    sigma_f3 = solver.postprocess().cauchy_stress_component(fibers)
    sf3 = df.project(sigma_f3, V)
    SF.assign(sf3)
    g.write(SF)

    fname_u = "output_u.h5"
    if os.path.isfile(fname_u): os.remove(fname_u)
    u1.rename("u1", "displacement")
    u2.rename("u2", "displacement")
    u3.rename("u3", "displacement")

    fname_sf = "output_sf.h5"
    if os.path.isfile(fname_sf): os.remove(fname_sf)
    sf1.rename("sf1", "stress")
    sf2.rename("sf2", "stress")
    sf3.rename("sf3", "stress")

    save_to_h5(fname_u, mesh, u1, u2, u3)
    save_to_h5(fname_sf, mesh, sf1, sf2, sf3)

    return u1, u2, u3, sf1, sf2, sf3
예제 #4
0
def closed_loop(parameters, advanced_parameters, CL_parameters):
    
    
    ####################
    ### Gernal setup ###
    ####################
    setup_general_parameters()
    
    df.PETScOptions.set('ksp_type', 'preonly')
    df.PETScOptions.set('pc_factor_mat_solver_package', 'mumps')
    df.PETScOptions.set("mat_mumps_icntl_7", 6)    
    
    
    ############
    ### MESH ###
    ############
    patient = parameters['patient']
    meshname = parameters['mesh_name']
    mesh = parameters['mesh']
    mesh = patient.mesh
    X = df.SpatialCoordinate(mesh)
    N = df.FacetNormal(mesh)
    
    
    
    # Cycle lenght
    BCL = CL_parameters['BCL']
    t = CL_parameters['t']
    # Time increment
    dt = CL_parameters['dt']
    
    # End-Diastolic volume
    ED_vol = CL_parameters['ED_vol']
    
    #####################################
    # Parameters for Windkessel model ###
    #####################################
    
    # Aorta compliance (reduce)
    Cao = CL_parameters['Cao']
    # Venous compliace
    Cven = CL_parameters['Cven']
    # Dead volume
    Vart0 = CL_parameters['Vart0']
    Vven0 = CL_parameters['Vven0']
    # Aortic resistance
    Rao = CL_parameters['Rao']
    Rven = CL_parameters['Rven']
    # Peripheral resistance (increase)
    Rper = CL_parameters['Rper']
    
    V_ven = CL_parameters['V_ven']
    V_art = CL_parameters['V_art']
    
    # scale geometry to match hemodynamics parameters
    mesh.coordinates()[:] *= CL_parameters['mesh_scaler']
    
    
    ######################
    ### Material model ###
    ######################
    material_model =  advanced_parameters['material_model']
    
    ####################
    ### Active model ###
    ####################
    active_model = advanced_parameters['active_model']
    T_ref = advanced_parameters['T_ref']
    
    # These can be used to adjust the contractility
    gamma_base = parameters['gamma']['gamma_base']
    gamma_mid =  parameters['gamma']['gamma_mid']
    gamma_apical =  parameters['gamma']['gamma_apical']
    gamma_apex = parameters['gamma']['gamma_apex']
    gamma_arr = np.array(gamma_base + gamma_mid + gamma_apical + gamma_apex)
    # gamma_arr = np.ones(17)
    
    
    ##############
    ### OUTPUT ###
    ##############
    dir_results = "results"
    if not os.path.exists(dir_results):
        os.makedirs(dir_results)
    
    disp_file = df.XDMFFile(df.mpi_comm_world(), "{}/displacement.xdmf".format(dir_results))

    pv_data  = {"pressure":[], "volume":[]}
    output = "/".join([dir_results, "output_{}_ed{}.h5".format(meshname, ED_vol)])
    
    
    G = RegionalParameter(patient.sfun)
    G.vector()[:] = gamma_arr
    G_ = df.project(G.get_function(), G.get_ind_space())
    f_gamma = df.XDMFFile(df.mpi_comm_world(), "{}/activation.xdmf".format(dir_results))
    f_gamma.write(G_)
    
    
    
    ########################
    ### Setup Parameters ###
    ########################
    params = setup_application_parameters(material_model)
    params.remove("Material_parameters")
    matparams = df.Parameters("Material_parameters")
    for k, v in  advanced_parameters['mat_params'].iteritems():
        matparams.add(k,v)
    params.add(matparams)
   
   
   
    params["base_bc"] = parameters['BC_type']
    params["base_spring_k"] = advanced_parameters['spring_constant']
    # params["base_bc"] = "fixed"
    params["active_model"] = active_model
    params["T_ref"] = T_ref
    params["gamma_space"] = "regional"
    
    
    ######################
    ### Initialization ###
    ######################
    
    # Solver paramters
    check_patient_attributes(patient)
    solver_parameters, _, _ = make_solver_params(params, patient)
    
    # Cavity volume
    V0 = df.Expression("vol",vol = 0, name = "Vtarget", degree=1)
    solver_parameters["volume"] = V0
    
    # Solver
    solver = LVSolver3Field(solver_parameters, use_snes=True)
    df.set_log_active(True)
    solver.parameters["solve"]["snes_solver"]["report"] =True
    solver.parameters["solve"]["snes_solver"]['maximum_iterations'] = 50
    
    # Surface measure
    ds = df.Measure("exterior_facet", domain = solver.parameters["mesh"],
                 subdomain_data = solver.parameters["facet_function"])
    dsendo = ds(solver.parameters["markers"]["ENDO"][0])
    
    # Set cavity volume
    V0.vol = df.assemble(solver._V_u*dsendo)
    
    print V0.vol
    
    # Initial solve
    solver.solve()
    
    # Save initial state
    w = solver.get_state()
    u, p, pinn = w.split(deepcopy=True)
    U_save = df.Function(u.function_space(), name = "displacement")
    U_save.assign(u)
    disp_file.write(U_save)      
    
    file_format = "a" if os.path.isfile('pv_data_plot.txt') else "w"
    pv_data_plot = open('pv_data_plot.txt', file_format)
    pv_data_plot.write('{},'.format(float(pinn)/1000.0))
    pv_data_plot.write('{}\n'.format(V0.vol))

    pv_data["pressure"].append(float(pinn)/1000.0)
    pv_data["volume"].append(V0.vol)
    
    
    
    # Active contraction
    from force import ca_transient
    V_real = df.FunctionSpace(mesh, "R", 0)
    gamma = solver.parameters["material"].get_gamma()
    
    # times = np.linspace(0,200,200)
    # target_gamma = ca_transient(times)
    # plt.plot(target_gamma)
    # plt.show()
    # exit()g
    
    #######################
    ### Inflation Phase ###
    #######################
    inflate = True
    # Check if inflation allready exist
    if os.path.isfile(output):
        
        with df.HDF5File(df.mpi_comm_world(), output, "r") as h5file:
            if h5file.has_dataset("inflation"):
                h5file.read(solver.get_state(), "inflation")
                print ("\nInflation phase fetched from output file.")
                inflate = False
    
    if inflate:
        print ("\nInflate geometry to volume : {}\n".format(ED_vol))
        initial_step =  int((ED_vol - V0.vol) / 10.0) +1
        control_values, prev_states = iterate("expression", solver, V0, "vol",
                                              ED_vol, continuation=False,
                                              initial_number_of_steps=initial_step,
                                              log_level=10)
    
        # Store outout
        for i, wi in enumerate(prev_states):
            ui, pi, pinni = wi.split(deepcopy=True)
            U_save.assign(ui)
            disp_file.write(U_save)
    
            print ("V = {}".format(control_values[i]))
            print ("P = {}".format(float(pinni)/1000.0))
            
            pv_data_plot.write('{},'.format(float(pinni)/1000.0))
            pv_data_plot.write('{}\n'.format(control_values[i]))
            pv_data["pressure"].append(float(pinni)/1000.0)
            pv_data["volume"].append(control_values[i])
    
        
        with df.HDF5File(df.mpi_comm_world(), output, "w") as h5file:
            h5file.write(solver.get_state(), "inflation")
            
    
    # Store ED solution
    w = solver.get_state()
    u, p, pinn = w.split(deepcopy=True)
    U_save.assign(u)
    disp_file.write(U_save)
    
    pv_data_plot.write('{},'.format(float(pinn)/1000.0))
    pv_data_plot.write('{}\n'.format(ED_vol))
    pv_data["pressure"].append(float(pinn)/1000.0)
    pv_data["volume"].append(ED_vol)
      
    print ("\nInflation succeded! Current pressure: {} kPa\n\n".format(float(pinn)/1000.0))
    
    pv_data_plot.close()
        
    #########################
    ### Closed loop cycle ###
    #########################
    
    while (t < BCL):
    
        w = solver.get_state()
        u, p, pinn = w.split(deepcopy=True)
        
        p_cav = float(pinn)
        V_cav = df.assemble(solver._V_u*dsendo)
        if t + dt > BCL:
            dt = BCL - t
        t = t + dt
    
        target_gamma = ca_transient(t)
    
    
        # Update windkessel model
        Part = 1.0/Cao*(V_art - Vart0);
        Pven = 1.0/Cven*(V_ven - Vven0);
        PLV = float(p_cav);
    
        print ("PLV = {}".format(PLV))
        print ("Part = {}".format(Part))
        # Flux trough aortic valve
        if(PLV <= Part):
             Qao = 0.0;
        else:
             Qao = 1.0/Rao*(PLV - Part);
        
        # Flux trough mitral valve
        if(PLV >= Pven):
            Qmv = 0.0;
        else: 
            Qmv = 1.0/Rven*(Pven - PLV);
        
    
        Qper = 1.0/Rper*(Part - Pven);
    
        V_cav = V_cav + dt*(Qmv - Qao);
        V_art = V_art + dt*(Qao - Qper);
        V_ven = V_ven + dt*(Qper - Qmv);
    
        
    
        # Update cavity volume
        V0.vol = V_cav 
    
    
        # Iterate active contraction
        if t <= 150:
            target_gamma_ = target_gamma * gamma_arr
            _, states = iterate("gamma", solver, target_gamma_, gamma, initial_number_of_steps = 1)
        else:
            solver.solve()
        
    
        # Adapt time step
        if len(states) == 1:
            dt *= 1.7
        else:
            dt *= 0.5
              
        dt = min(dt, 10)
    
        # Store data 
        ui, pi, pinni = solver.get_state().split(deepcopy=True)
        U_save.assign(ui)
        disp_file.write(U_save)
    
        Pcav = float(pinni)/1000.0
        pv_data_plot = open('pv_data_plot.txt', 'a')
        pv_data_plot.write('{},'.format(Pcav))
        pv_data_plot.write('{}\n'.format(V_cav))
        pv_data_plot.close()
        pv_data["pressure"].append(Pcav)
        pv_data["volume"].append(V_cav)
        
        msg = ("\n\nTime:\t{}".format(t) + \
               "\ndt:\t{}".format(dt) +\
               "\ngamma:\t{}".format(target_gamma) +\
               "\nV_cav:\t{}".format(V_cav) + \
               "\nV_art:\t{}".format(V_art) + \
               "\nV_ven:\t{}".format(V_ven) + \
               "\nPart:\t{}".format(Part) + \
               "\nPven:\t{}".format(Pven) + \
               "\nPLV:\t{}".format(Pcav) + \
               "\nQper:\t{}".format(Qper) + \
               "\nQao:\t{}".format(Qao) + \
               "\nQmv:\t{}\n\n".format(Qmv))
        print ((msg))        
    
#==============================================================================
#     fig = plt.figure()
#     ax = fig.gca()
#     ax.plot(pv_data["volume"], pv_data["pressure"])
#     ax.set_ylabel("Pressure (kPa)")
#     ax.set_xlabel("Volume (ml)")
#     
#     
#     fig.savefig("/".join([dir_results, "pv_loop.png"]))
#     plt.show()
#==============================================================================
    return
#import threading
#thread1 = threading.Thread(target = closed_loop)
#thread1.start()

    
예제 #5
0
def problem3():

    patient = LVTestPatient("benchmark")

    setup_general_parameters()
    params = setup_adjoint_contraction_parameters()
    params["phase"] == "all"
    active_model = "active_stress"
    params["active_model"] = active_model
    params["T_ref"] = 60.0
    params["base_bc"] = "fixed"

    # material_model = "guccione"
    material_model = "holzapfel_ogden"
    # material_model = "neo_hookean"

    solver_parameters, pressure, paramvec = make_solver_params(params, patient)
    V_real = df.FunctionSpace(solver_parameters["mesh"], "R", 0)
    gamma = df.Function(V_real, name="gamma")
    target_gamma = df.Function(V_real, name="target gamma")

    matparams = setup_material_parameters(material_model)

    if material_model == "guccione":
        matparams["C"] = 2.0
        matparams["bf"] = 8.0
        matparams["bt"] = 2.0
        matparams["bfs"] = 4.0

    args = (patient.fiber, gamma, matparams, active_model, patient.sheet,
            patient.sheet_normal, params["T_ref"])

    if material_model == "guccione":
        material = Guccione(*args)
    else:
        material = HolzapfelOgden(*args)

    solver_parameters["material"] = material

    solver = LVSolver(solver_parameters)
    solver.parameters["solve"]["snes_solver"]["report"] = True

    solver.solve()

    p_end = 15.0
    g_end = 1.0

    N = 5
    df.set_log_active(True)
    df.set_log_level(df.INFO)
    f = df.XDMFFile(df.mpi_comm_world(), "benchmark_3.xdmf")
    u, p = solver.get_state().split(deepcopy=True)
    U = df.Function(u.function_space(), name="displacement")

    for (plv, g) in zip(np.linspace(0, p_end, N), np.linspace(0, g_end, N)):

        t = df.Timer("Test Material Model")
        t.start()
        iterate_pressure(solver, plv, pressure)

        u, p = solver.get_state().split(deepcopy=True)
        U.assign(u)
        f.write(U)

        target_gamma.assign(df.Constant(g))

        iterate_gamma(solver, target_gamma, gamma)

        u, p = solver.get_state().split(deepcopy=True)
        U.assign(u)
        f.write(U)