Beispiel #1
0
def main():
    args = parseArguments(sys.argv[1:])
    if not os.path.isfile(args.fn_nifti):
        raise IOError('Could not find file: {0}'.format(args.fn_nifti))
    if not os.path.isfile(args.fn_mesh):
        raise IOError('Could not find file: {0}'.format(args.fn_mesh))
    image = nibabel.load(args.fn_nifti)
    mesh = mesh_io.read_msh(args.fn_mesh)
    vol = image.dataobj
    affine = image.affine
    if args.ev:
        logger.info('Creating tensor visualization')
        mesh = mesh.crop_mesh([1, 2, 1001, 1002])
        cond_list = [c.value for c in cond.standard_cond()]
        sigma = cond.cond2elmdata(mesh,
                                  cond_list,
                                  anisotropy_volume=vol,
                                  affine=affine,
                                  aniso_tissues=[1, 2])
        views = cond.TensorVisualization(sigma, mesh)
        mesh.nodedata = []
        mesh.elmdata = views
        mesh_io.write_msh(mesh, args.fn_out)
    else:
        logger.info('Interpolating data in NifTI file to mesh')
        if args.type == 'elements':
            ed = mesh_io.ElementData.from_data_grid(mesh, vol, affine,
                                                    'from_volume')
            mesh.elmdata.append(ed)
        if args.type == 'nodes':
            nd = mesh_io.NodeData.from_data_grid(mesh, vol, affine,
                                                 'from_volume')
            mesh.nodedata.append(nd)
        mesh_io.write_msh(mesh, args.fn_out)
Beispiel #2
0
def main():
    args = parseArguments(sys.argv[1:])
    if not os.path.isfile(args.fn_mask):
        raise IOError('Could not find file: {0}'.format(args.fn_mask))
    if not os.path.isfile(args.fn_mesh):
        raise IOError('Could not find file: {0}'.format(args.fn_mesh))
    image = nibabel.load(args.fn_mask)
    mesh = mesh_io.read_msh(args.fn_mesh)
    vol = image.dataobj
    if not np.issubdtype(vol.dtype, np.integer):
        logger.warn('Volume is not an integer type, masking may fail')

    affine = image.affine

    logger.info('Applying Mask')
    ed = mesh_io.ElementData.from_data_grid(mesh, vol, affine, 'from_volume')
    # Re-label tetrahedra
    mesh.elm.tag1[(ed.value > 0) * mesh.elm.elm_type == 4] = args.tag
    mesh.elm.tag2[(ed.value > 0) * mesh.elm.elm_type == 4] = args.tag
    # Remove triangles
    mesh.elm.tag1[(ed.value > 0) * mesh.elm.elm_type == 2] = 99999
    mesh.elm.tag2[(ed.value > 0) * mesh.elm.elm_type == 2] = 99999
    mesh = mesh.remove_from_mesh(99999)

    logger.info(f'Writing {args.fn_out}')
    mesh_io.write_msh(mesh, args.fn_out)
def main():
    args = parse_arguments(sys.argv[1:])
    msh = mesh_io.read_msh(os.path.abspath(os.path.realpath(os.path.expanduser(args.mesh))))
    fn_csv = os.path.expanduser(args.csv)
    if args.l is not None:
        labels = [int(n) for n in args.l[0].split(',')]
        msh = msh.crop_mesh(tags=labels)

    points = np.atleast_2d(np.loadtxt(fn_csv, delimiter=',', dtype=float))
    if points.shape[1] != 3:
        raise IOError('CSV file should have 3 columns')

    csv_basename, _ = os.path.splitext(fn_csv)
    for ed in msh.elmdata:
        fn_out = '{0}_{1}.csv'.format(csv_basename, ed.field_name)
        logger.info('Interpolating field: {0} and writing to file: {1}'.format(
            ed.field_name, fn_out))
        f = ed.interpolate_scattered(
                points, out_fill=args.out_fill,
                method=args.method, continuous=False, squeeze=False)
        if f.ndim == 1:
            f = f[:, None]
        np.savetxt(fn_out, f, delimiter=',')

    for nd in msh.nodedata:
        fn_out = '{0}_{1}.csv'.format(csv_basename, nd.field_name)
        logger.info('Interpolating field: {0} and writing to file: {1}'.format(
            nd.field_name, fn_out))
        f = nd.interpolate_scattered(
            points, out_fill=args.out_fill, squeeze=False)
        if f.ndim == 1:
            f = f[:, None]
        np.savetxt(fn_out, f, delimiter=',')
Beispiel #4
0
def main():
    if len(sys.argv) not in [3, 5]:
        print("Incorrect number of arguments")
        usage()
        sys.exit(1)

    # check extension
    if os.path.splitext(sys.argv[1])[1] != '.msh':
        print('1st argument must have a .msh extension')
        sys.exit(1)

    if os.path.splitext(sys.argv[2])[1] != '.msh':
        print('2nd argument must have a .msh extension')
        sys.exit(1)

    m = mesh_io.read_msh(sys.argv[1])

    m.fn = sys.argv[2]
    logger.info(
        "Relabeled ventricle regions to CSF and cerebellum regions to WM")
    m.elm.tag1[m.elm.tag1 == 6] = 1
    m.elm.tag1[m.elm.tag1 == 7] = 3
    m.elm.tag2[m.elm.tag2 == 6] = 1
    m.elm.tag2[m.elm.tag2 == 7] = 3

    logger.info("Fixing surface labeling")
    m.fix_surface_labels()
    logger.info("Fixing thin tetrahedra")
    m.fix_thin_tetrahedra()
    logger.info("Fixing tetrahedra node ordering")
    m.fix_th_node_ordering()
    logger.info("Fixing triangle node ordering")
    m.fix_tr_node_ordering()

    mesh_io.write_msh(m, mode='binary')
Beispiel #5
0
    def _factorize(self, A):
        """
        Factorize the matrix A, the factorization will automatically be used if the same
        matrix A is passed to the solve method.

        Parameters
        -------------
        A: scipy.sparse csr or csc
            Spase square matrix
        """

        self._check_A(A)
        self._A = A.copy()
        logger.info('Factorizing matrix using MKL PARDISO')
        start = time.time()
        b = np.zeros((A.shape[0], 1))
        self._call_pardiso(b, 12)
        logger.info(f'{time.time()-start:.2f} seconds to factorize matrix')
Beispiel #6
0
    def solve(self, b):
        """ solve Ax=b for x

        Parameters
        ----------
        b: numpy ndarray
           right-hand side(s), b.shape[0] needs to be the same as A.shape[0]

        Returns
        --------
        x: numpy ndarray
           solution of the system of linear equations, same shape as input b
        """

        logger.info('Solving system using MKL PARDISO')
        start = time.time()
        b = self._check_b(b)
        x = self._call_pardiso(b, 33)
        logger.info(f'{time.time()-start:.2f} seconds to solve system')
        return x
Beispiel #7
0
def main():
    args = parse_arguments(sys.argv[1:])
    m2m_dir = os.path.abspath(os.path.realpath(os.path.expanduser(args.m2mpath)))
    if not os.path.isdir(m2m_dir):
        raise IOError('Could not find directory: {0}'.format(args.m2mpath))
    subject_files = file_finder.SubjectFiles(subpath=m2m_dir)
    os.makedirs(args.out_folder, exist_ok=True)
    for hemi in ['lh', 'rh']:
        # I have a parallel implementation here
        fn_atlas = os.path.join(
            file_finder.templates.cat_atlases_surfaces,
            f'{hemi}.aparc_{args.atlas}.freesurfer.annot'
        )
        labels, colors, names = nibabel.freesurfer.io.read_annot(fn_atlas)
        if subject_files.seg_type == 'headreco':
            read_fun = read_gifti_surface
        elif subject_files.seg_type == 'mri2mesh':
            read_fun = read_freesurfer_surface

        if hemi == 'lh':
            ref_surf = read_gifti_surface(file_finder.templates.cat_lh_sphere_ref)
            sub_surf = read_fun(subject_files.lh_reg)
        if hemi == 'rh':
            ref_surf = read_gifti_surface(file_finder.templates.cat_rh_sphere_ref)
            sub_surf = read_fun(subject_files.rh_reg)

        labels_sub, _ = transformations._surf2surf(labels, ref_surf, sub_surf)
        fn_out = os.path.join(
            args.out_folder,
            f'{hemi}.{subject_files.subid}_{args.atlas}.annot'
        )
        logger.info('Writing: ' + fn_out)
        nibabel.freesurfer.io.write_annot(
            fn_out,
            labels_sub,
            colors,
            names,
            fill_ctab=True
        )
Beispiel #8
0
    parser.add_argument('--version', action='version', version=simnibs_version)
    return parser.parse_args(argv)


if __name__ == '__main__':
    args = parseArguments(sys.argv[1:])
    if not os.path.isfile(args.fn_nifti):
        raise IOError('Could not find file: {0}'.format(args.fn_nifti))
    if not os.path.isfile(args.fn_mesh):
        raise IOError('Could not find file: {0}'.format(args.fn_mesh))
    image = nibabel.load(args.fn_nifti)
    mesh = gmsh.read_msh(args.fn_mesh)
    vol = image.dataobj
    affine = image.affine
    if args.ev:
        logger.info('Creating tensor visualization')
        mesh = mesh.crop_mesh([1, 2, 1001, 1002])
        cond_list = [c.value for c in cond.standard_cond()]
        sigma = cond.cond2elmdata(mesh,
                                  cond_list,
                                  anisotropy_volume=vol,
                                  affine=affine,
                                  aniso_tissues=[1, 2])
        views = cond.TensorVisualization(sigma)
        mesh.nodedata = []
        mesh.elmdata = views
        gmsh.write_msh(mesh, args.fn_out)
    else:
        logger.info('Interpolating data in NifTI file to mesh')
        ed = gmsh.ElementData.from_data_grid(mesh,
                                             vol,
Beispiel #9
0
    usage()
    sys.exit(1)

# check extension
if os.path.splitext(sys.argv[1])[1] != '.msh':
    print('1st argument must have a .msh extension')
    sys.exit(1)

if os.path.splitext(sys.argv[2])[1] != '.msh':
    print('2nd argument must have a .msh extension')
    sys.exit(1)

m = gmsh.read_msh(sys.argv[1])

m.fn = sys.argv[2]
logger.info("Relabeled ventricle regions to CSF and cerebellum regions to WM")
m.elm.tag1[m.elm.tag1 == 6] = 1
m.elm.tag1[m.elm.tag1 == 7] = 3
m.elm.tag2[m.elm.tag2 == 6] = 1
m.elm.tag2[m.elm.tag2 == 7] = 3

logger.info("Fixing surface labeling")
m.fix_surface_labels()
logger.info("Fixing thin tetrahedra")
m.fix_thin_tetrahedra()
logger.info("Fixing tetrahedra node ordering")
m.fix_th_node_ordering()
logger.info("Fixing triangle node ordering")
m.fix_tr_node_ordering()

gmsh.write_msh(m, mode='binary')
Beispiel #10
0
    msh = gmsh.read_msh(
        os.path.abspath(os.path.realpath(os.path.expanduser(args.mesh))))
    fn_csv = os.path.expanduser(args.csv)
    if args.l is not None:
        labels = [int(n) for n in args.l[0].split(',')]
        msh = msh.crop_mesh(tags=labels)

    points = np.atleast_2d(np.loadtxt(fn_csv, delimiter=',', dtype=float))
    if points.shape[1] != 3:
        raise IOError('CSV file should have 3 columns')

    csv_basename, _ = os.path.splitext(fn_csv)
    for ed in msh.elmdata:
        c = ed.field_name in ['normJ', 'J']
        fn_out = '{0}_{1}.csv'.format(csv_basename, ed.field_name)
        logger.info('Interpolating field: {0} and writing to file: {1}'.format(
            ed.field_name, fn_out))
        f = ed.interpolate_scattered(points,
                                     out_fill=args.out_fill,
                                     method=args.method,
                                     continuous=c,
                                     squeeze=False)
        if f.ndim == 1:
            f = f[:, None]
        np.savetxt(fn_out, f, delimiter=',')

    for nd in msh.nodedata:
        fn_out = '{0}_{1}.csv'.format(csv_basename, nd.field_name)
        logger.info('Interpolating field: {0} and writing to file: {1}'.format(
            nd.field_name, fn_out))
        f = nd.interpolate_scattered(points,
                                     out_fill=args.out_fill,