Example #1
0
def calc_surface_potential_fn(dipole_file, dipole_row, leadfield, mesh_file,
                              mesh_id):
    import os.path as op
    import numpy as np
    import h5py
    from forward.mesh import get_closest_element_to_point

    from nipype import logging
    iflogger = logging.getLogger('interface')

    dipole_data = np.loadtxt(dipole_file)
    if len(dipole_data.shape) == 1:
        dipole_data = [dipole_data]
    dip = dipole_data[int(dipole_row)]

    x, y, z = [float(i) for i in dip[2:5]]
    q_x, q_y, q_z = [float(j) for j in dip[6:9]]
    _, element_idx, centroid, element_data, lf_idx = get_closest_element_to_point(
        mesh_file, mesh_id, [[x, y, z]])

    lf_data_file = h5py.File(leadfield, "r")
    lf_data = lf_data_file.get("leadfield")
    leadfield_matrix = lf_data.value

    L = np.transpose(leadfield_matrix[lf_idx * 3:lf_idx * 3 + 3])
    J = np.array([q_x, q_y, q_z])
    potential = np.dot(L, J)
    out_potential = op.abspath("potential.npy")
    np.save(out_potential, potential)
    return out_potential
def calc_surface_potential_fn(dipole_file, dipole_row, leadfield, mesh_file, mesh_id):
    import os.path as op
    import numpy as np
    import h5py
    from forward.mesh import get_closest_element_to_point

    from nipype import logging
    iflogger = logging.getLogger('interface')

    dipole_data = np.loadtxt(dipole_file)
    if len(dipole_data.shape) == 1:
        dipole_data = [dipole_data]
    dip = dipole_data[int(dipole_row)]
    
    x, y, z = [float(i) for i in dip[2:5]]
    q_x, q_y, q_z = [float(j) for j in dip[6:9]]
    _, element_idx, centroid, element_data, lf_idx = get_closest_element_to_point(mesh_file, mesh_id, [[x, y, z]])

    lf_data_file = h5py.File(leadfield, "r")
    lf_data = lf_data_file.get("leadfield")
    leadfield_matrix = lf_data.value

    L = np.transpose(leadfield_matrix[lf_idx * 3:lf_idx * 3 + 3])
    J = np.array([q_x,q_y,q_z])
    potential = np.dot(L,J)
    out_potential = op.abspath("potential.npy")
    np.save(out_potential,potential)
    return out_potential
Example #3
0
def single_dipole_search(electrode_potential, leadfield, mesh_file, elements_to_consider=[1002]):
    from forward.mesh import read_mesh, get_closest_element_to_point
    from nipype import logging
    iflogger = logging.getLogger('interface')

    geo_file = op.abspath("search_points.geo")
    data_name = "leadfield"
    lf_data_file = h5py.File(leadfield, "r")
    lf_data = lf_data_file.get(data_name)
    leadfield_matrix = lf_data.value
    _, lf_name, _ = split_filename(leadfield)

    bounds = (0,leadfield_matrix.shape[0]/3)
    mesh_data, _, _, _ = read_mesh(mesh_file, elements_to_consider)

    centroids = []
    element_ids = []
    for poly in mesh_data:
        element_ids.append(poly["element_id"])
        centroids.append(poly["centroid"])
    

    p0, bounds = random_initial_guess(centroids)
    #p0 = np.array([0,0,60])

    mw = {}
    args = (leadfield_matrix, electrode_potential, centroids, element_ids)
    mw['args'] = args
    #mw['bounds'] = bounds

    #res = so.basinhopping(calculate_element_cost, p0, T=0.01, stepsize = 3, minimizer_kwargs=mw, disp=True, niter_success=20)

    # Perform downhill search, minimizing cost function
    xopt, fopt, n_iter, funcalls, _, allvecs = so.fmin(calculate_element_cost, p0, ftol=0.00000001, args=(leadfield_matrix, electrode_potential, centroids, element_ids), xtol = 1, disp=True, full_output=True, retall=True)

    write_search_points(allvecs, geo_file) 

    # Need to minimize cost by changing values of orientation and magnitude:
    _, element_idx, centroid, element_data, lf_idx = get_closest_element_to_point(mesh_file, elements_to_consider, np.array([xopt]))

    L = np.transpose(leadfield_matrix[lf_idx * 3:lf_idx * 3 + 3])
    V = electrode_potential
    qopt, _, _, _ = np.linalg.lstsq(L, V)
    return xopt, qopt, element_data, geo_file
def get_rdm_and_mags(mesh_file, mesh_id, probe_dipole, probe_dipole_orientation, radii, cond, n=42, nMax=60):
    four = pe.Node(interface=FourShellAnalyticalModel(), name="four")
    name = str(probe_dipole[0]).replace(" ", "")
    name = name.replace("[", "")
    name = name.replace("]", "")
    out_directory = op.abspath("dipole" + name)
    if not op.exists(out_directory):
        os.makedirs(out_directory)
    four.base_dir = out_directory
    four.inputs.probe_dipole_location = probe_dipole[0].tolist()
    four.inputs.probe_dipole_orientation = probe_dipole_orientation[0].tolist()
    four.inputs.script = "pyscript.m"
    four.inputs.sphere_radii = radii
    four.inputs.shell_conductivity = cond
    four.inputs.icosahedron_sides = n
    four.inputs.number_of_analytical_terms = nMax
    four.inputs.fieldtrip_path = "/Developer/fieldtrip"

    analytical_solution = op.join(out_directory, "four", "analytical.txt")
    if not op.exists(analytical_solution):
        four.run()

    # Re-reference to ground electrode
    lf_sphere = np.loadtxt(analytical_solution, delimiter=",")
    lf_sphere = lf_sphere - lf_sphere[ground_idx]
    lf_sphere = np.delete(lf_sphere, (ground_idx), axis=0)
    lf_sphere = lf_sphere * probe_dipole_orientation

    mesh_data, closest_element_idx, centroid, closest_element_data, lf_idx = get_closest_element_to_point(
        mesh_file, mesh_id, probe_dipole
    )
    lf_getdp = np.transpose(leadfield_matrix[lf_idx * 3 : lf_idx * 3 + 3])

    lf_getdp = lf_getdp * probe_dipole_orientation

    rdms = np.empty((np.shape(lf_getdp)[1], 1))
    rows = np.shape(lf_getdp)[1]
    for idx in xrange(0, rows):
        rdms[idx, :] = norm(lf_getdp[:, idx] / norm(lf_getdp[:, idx]) - lf_sphere[:, idx] / norm(lf_sphere[:, idx]))

    mags = np.divide(np.sqrt(np.sum(lf_getdp ** 2, 0)), np.sqrt(np.sum(lf_sphere ** 2, 0)))

    rdm_singlevalue = norm(lf_getdp / norm(lf_getdp) - lf_sphere / norm(lf_sphere))
    mag_singlevalue = np.divide(norm(lf_getdp), norm(lf_sphere))

    print ("RDMs %s" % str(rdms))
    print rdm_singlevalue
    print ("MAGs %s" % str(mags))
    print mag_singlevalue

    openmeeg_solution = op.join(out_directory, "four", "openmeeg.txt")
    lf_openmeeg = np.loadtxt(openmeeg_solution, delimiter=",")
    lf_openmeeg = lf_openmeeg * probe_dipole_orientation

    try:
        lf_openmeeg = lf_openmeeg - lf_openmeeg[ground_idx]
        lf_openmeeg = np.delete(lf_openmeeg, (ground_idx), axis=0)

        rdm_openmeeg = norm(lf_openmeeg / norm(lf_openmeeg) - lf_sphere / norm(lf_sphere))
        mag_openmeeg = np.divide(norm(lf_openmeeg), norm(lf_sphere))
    except IndexError:
        rdm_openmeeg = None
        mag_openmeeg = None

    return (rdms, mags, rdm_singlevalue, mag_singlevalue, rdm_openmeeg, mag_openmeeg, lf_getdp, lf_sphere)
def get_rdm_and_mags(mesh_file, mesh_id, probe_dipole, probe_dipole_orientation, radii, cond, n=42, nMax=60):
    four = pe.Node(interface=FourShellAnalyticalModel(), name="four")
    name = str(probe_dipole[0]).replace(" ","")
    name = name.replace('[','')
    name = name.replace(']','')
    out_directory = op.abspath("dipole" + name)
    if not op.exists(out_directory):
        os.makedirs(out_directory)
    four.base_dir = out_directory
    four.inputs.probe_dipole_location = probe_dipole[0].tolist()
    four.inputs.probe_dipole_orientation = probe_dipole_orientation[0].tolist()
    four.inputs.script = "pyscript.m"
    four.inputs.sphere_radii = radii
    four.inputs.shell_conductivity = cond
    four.inputs.icosahedron_sides = n
    four.inputs.number_of_analytical_terms = nMax
    four.inputs.fieldtrip_path = "/Developer/fieldtrip"
    
    analytical_solution = op.join(out_directory, "four", "analytical.txt")
    if not op.exists(analytical_solution):
        four.run()
        
    # Re-reference to ground electrode
    lf_sphere = np.loadtxt(analytical_solution, delimiter=",")
    lf_sphere = lf_sphere - lf_sphere[ground_idx]
    lf_sphere = np.delete(lf_sphere, (ground_idx), axis=0)
    lf_sphere = lf_sphere * probe_dipole_orientation

    mesh_data, closest_element_idx, centroid, closest_element_data, lf_idx = get_closest_element_to_point(mesh_file, mesh_id, probe_dipole)
    lf_getdp = np.transpose(leadfield_matrix[lf_idx * 3:lf_idx * 3 + 3])

    lf_getdp = lf_getdp * probe_dipole_orientation

    rdms = np.empty((np.shape(lf_getdp)[1], 1))
    rows = np.shape(lf_getdp)[1]
    for idx in xrange(0, rows):
        rdms[idx, :] = norm(lf_getdp[:, idx] / norm(lf_getdp[:, idx]) -
                            lf_sphere[:, idx] / norm(lf_sphere[:, idx]))

    mags = np.divide(np.sqrt(np.sum(lf_getdp ** 2, 0)),
                     np.sqrt(np.sum(lf_sphere ** 2, 0)) )


    rdm_singlevalue = norm( lf_getdp / norm(lf_getdp) - lf_sphere / norm(lf_sphere) )
    mag_singlevalue = np.divide(norm(lf_getdp),norm(lf_sphere))

    print("RDMs %s" % str(rdms))
    print rdm_singlevalue
    print("MAGs %s" % str(mags))
    print mag_singlevalue

    openmeeg_solution = op.join(out_directory, "four", "openmeeg.txt")
    lf_openmeeg = np.loadtxt(openmeeg_solution, delimiter=",")
    lf_openmeeg = lf_openmeeg * probe_dipole_orientation

    try:
        lf_openmeeg = lf_openmeeg - lf_openmeeg[ground_idx]
        lf_openmeeg = np.delete(lf_openmeeg, (ground_idx), axis=0)

        rdm_openmeeg = norm( lf_openmeeg / norm(lf_openmeeg) - lf_sphere / norm(lf_sphere) )
        mag_openmeeg = np.divide(norm(lf_openmeeg),norm(lf_sphere))
    except IndexError:
        rdm_openmeeg = None
        mag_openmeeg = None

    return (rdms, mags, rdm_singlevalue, mag_singlevalue, rdm_openmeeg,
        mag_openmeeg, lf_getdp, lf_sphere)