Пример #1
0
def run_makespec_bothhemis(config, env):
    refdir = config['refdir']
    overwrite = config['overwrite']
    icolds, hemis = _get_hemis_icolds(config)

    if hemis != ['l', 'r']:
        raise ValueError("Cannot run without left and right hemisphere")

    for icold in icolds:
        specs = []
        for hemi in hemis:
            #surfprefix = '%s%sh' % (config['mi_icopat'] % icold, hemi)
            specfn = afni_suma_spec.canonical_filename(icold, hemi,
                                                       config['alsuffix'])
            specpathfn = os.path.join(refdir, specfn)
            specs.append(afni_suma_spec.read(specpathfn))

        specs = afni_suma_spec.hemi_pairs_add_views(specs,
                                                    'inflated',
                                                    refdir,
                                                    overwrite=overwrite)
        specs = afni_suma_spec.hemi_pairs_add_views(specs,
                                                    'sphere.reg',
                                                    refdir,
                                                    overwrite=overwrite)

        spec_both = afni_suma_spec.combine_left_right(specs)

        # generate spec files for both hemispheres
        hemiboth = 'b'
        specfn = afni_suma_spec.canonical_filename(icold, hemiboth,
                                                   config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)
        spec_both.write(specpathfn, overwrite=overwrite)

        # merge left and right into one surface
        # and generate the spec files as well
        hemimerged = 'm'
        specfn = afni_suma_spec.canonical_filename(icold, hemimerged,
                                                   config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)

        if config['overwrite'] or not os.path.exists(specpathfn):
            spec_merged, surfs_to_join = afni_suma_spec.merge_left_right(
                spec_both)
            spec_merged.write(specpathfn, overwrite=overwrite)

            full_path = lambda x: os.path.join(refdir, x)
            for fn_out, fns_in in surfs_to_join.iteritems():
                surfs_in = [surf_fs_asc.read(full_path(fn)) for fn in fns_in]
                surf_merged = surf.merge(*surfs_in)
                if config['overwrite'] or not os.path.exists(
                        full_path(fn_out)):
                    surf_fs_asc.write(surf_merged,
                                      full_path(fn_out),
                                      overwrite=overwrite)
                    print "Merged surfaces written to %s" % fn_out
Пример #2
0
def run_makespec_bothhemis(config, env):
    refdir = config['refdir']
    overwrite = config['overwrite']
    icolds, hemis = _get_hemis_icolds(config)

    if hemis != ['l', 'r']:
        raise ValueError("Cannot run without left and right hemisphere")

    for icold in icolds:
        specs = []
        for hemi in hemis:
            #surfprefix = '%s%sh' % (config['mi_icopat'] % icold, hemi)
            specfn = afni_suma_spec.canonical_filename(icold, hemi,
                                                       config['alsuffix'])
            specpathfn = os.path.join(refdir, specfn)
            specs.append(afni_suma_spec.read(specpathfn))

        specs = afni_suma_spec.hemi_pairs_add_views(specs,
                            'inflated', refdir, overwrite=overwrite)
        specs = afni_suma_spec.hemi_pairs_add_views(specs,
                            'sphere.reg', refdir, overwrite=overwrite)


        spec_both = afni_suma_spec.combine_left_right(specs)


        # generate spec files for both hemispheres
        hemiboth = 'b'
        specfn = afni_suma_spec.canonical_filename(icold, hemiboth, config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)
        spec_both.write(specpathfn, overwrite=overwrite)

        # merge left and right into one surface
        # and generate the spec files as well
        hemimerged = 'm'
        specfn = afni_suma_spec.canonical_filename(icold, hemimerged, config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)

        if config['overwrite'] or not os.path.exists(specpathfn):
            spec_merged, surfs_to_join = afni_suma_spec.merge_left_right(spec_both)
            spec_merged.write(specpathfn, overwrite=overwrite)

            full_path = lambda x:os.path.join(refdir, x)
            for fn_out, fns_in in surfs_to_join.iteritems():
                surfs_in = [surf_fs_asc.read(full_path(fn)) for fn in fns_in]
                surf_merged = surf.merge(*surfs_in)
                if config['overwrite'] or not os.path.exists(full_path(fn_out)):
                    surf_fs_asc.write(surf_merged, full_path(fn_out),
                                                overwrite=overwrite)
                    print "Merged surfaces written to %s" % fn_out
Пример #3
0
    def test_afni_suma_spec(self, temp_dir):

        # XXX this function generates quite a few temporary files,
        #     which are removed at the end.
        #     the decorator @with_tempfile seems unsuitable as it only
        #     supports a single temporary file

        # make temporary directory
        os.mkdir(temp_dir)

        # generate surfaces
        inflated_surf = surf.generate_plane((0, 0, 0), (0, 1, 0), (0, 0, 1),
                                                    10, 10)
        white_surf = inflated_surf + 1.

        # helper function
        _tmp = lambda x:pathjoin(temp_dir, x)


        # filenames for surfaces and spec file
        inflated_fn = _tmp('_lh_inflated.asc')
        white_fn = _tmp('_lh_white.asc')
        spec_fn = _tmp('lh.spec')

        spec_dir = os.path.split(spec_fn)[0]

        # generate SUMA-like spec dictionary
        white = dict(SurfaceFormat='ASCII',
            EmbedDimension='3',
            SurfaceType='FreeSurfer',
            SurfaceName=white_fn,
            Anatomical='Y',
            LocalCurvatureParent='SAME',
            LocalDomainParent='SAME',
            SurfaceState='smoothwm')

        inflated = dict(SurfaceFormat='ASCII',
            EmbedDimension='3',
            SurfaceType='FreeSurfer',
            SurfaceName=inflated_fn,
            Anatomical='N',
            LocalCurvatureParent=white_fn,
            LocalDomainParent=white_fn,
            SurfaceState='inflated')

        # make SurfaceSpec object
        spec = afni_suma_spec.SurfaceSpec([white], directory=spec_dir)
        spec.add_surface(inflated)

        # test __str__ and __repr__
        assert_true('SurfaceSpec instance with 2 surfaces'
                        ', 2 states ' in '%s' % spec)
        assert_true(('%r' % spec).startswith('SurfaceSpec'))

        # test finding surfaces
        inflated_ = spec.find_surface_from_state('inflated')
        assert_equal([(1, inflated)], inflated_)

        empty = spec.find_surface_from_state('unknown')
        assert_equal(empty, [])

        # test .same_states
        minimal = afni_suma_spec.SurfaceSpec([dict(SurfaceState=s)
                                            for s in ('smoothwm', 'inflated')])
        assert_true(spec.same_states(minimal))
        assert_false(spec.same_states(afni_suma_spec.SurfaceSpec(dict())))

        # test 'smart' surface file matching
        assert_equal(spec.get_surface_file('smo'), white_fn)
        assert_equal(spec.get_surface_file('inflated'), inflated_fn)
        assert_equal(spec.get_surface_file('this should be None'), None)

        # test i/o
        spec.write(spec_fn)
        spec_ = afni_suma_spec.from_any(spec_fn)

        # prepare for another (right-hemisphere) spec file
        lh_spec = spec
        rh_spec_fn = spec_fn.replace('lh', 'rh')

        rh_inflated_fn = _tmp(os.path.split(inflated_fn)[1].replace('_lh',
                                                                    '_rh'))
        rh_white_fn = _tmp(os.path.split(white_fn)[1].replace('_lh',
                                                              '_rh'))
        rh_spec_fn = _tmp('rh.spec')

        rh_white = dict(SurfaceFormat='ASCII',
            EmbedDimension='3',
            SurfaceType='FreeSurfer',
            SurfaceName=rh_white_fn,
            Anatomical='Y',
            LocalCurvatureParent='SAME',
            LocalDomainParent='SAME',
            SurfaceState='smoothwm')

        rh_inflated = dict(SurfaceFormat='ASCII',
            EmbedDimension='3',
            SurfaceType='FreeSurfer',
            SurfaceName=rh_inflated_fn,
            Anatomical='N',
            LocalCurvatureParent=rh_white_fn,
            LocalDomainParent=rh_white_fn,
            SurfaceState='inflated')

        rh_spec = afni_suma_spec.SurfaceSpec([rh_white], directory=spec_dir)
        rh_spec.add_surface(rh_inflated)

        # write files
        all_temp_fns = [spec_fn, rh_spec_fn]
        for fn, s in [(rh_inflated_fn, inflated_surf),
                      (rh_white_fn, white_surf),
                      (inflated_fn, inflated_surf),
                      (white_fn, white_surf)]:
            surf.write(fn, s)
            all_temp_fns.append(fn)

        # test adding views
        added_specs = afni_suma_spec.hemi_pairs_add_views((lh_spec, rh_spec),
                                                          'inflated', '.asc')

        for hemi, added_spec in zip(('l', 'r'), added_specs):
            states = ['smoothwm', 'inflated'] + ['CoM%sinflated' % i
                                                    for i in 'msiap']
            assert_equal(states, [s['SurfaceState']
                                  for s in added_specs[0].surfaces])
            all_temp_fns.extend([s['SurfaceName']
                                 for s in added_spec.surfaces])

        # test combining specs (bh=both hemispheres)
        bh_spec = afni_suma_spec.combine_left_right(added_specs)

        # test merging specs (mh=merged hemispheres)
        mh_spec, mh_surfs = afni_suma_spec.merge_left_right(bh_spec)

        assert_equal([s['SurfaceState'] for s in mh_spec.surfaces],
                    ['smoothwm'] + ['CoM%sinflated' % i for i in 'msiap'])
Пример #4
0
def run_makespec_bothhemis(config, env):
    refdir = config['refdir']
    overwrite = config['overwrite']
    icolds, hemis = _get_hemis_icolds(config)

    ext = format2extension(config)

    if hemis != ['l', 'r']:
        raise ValueError("Cannot run without left and right hemisphere")

    for icold in icolds:
        specs = []
        for hemi in hemis:
            #surfprefix = '%s%sh' % (config['mi_icopat'] % icold, hemi)
            specfn = afni_suma_spec.canonical_filename(icold, hemi,
                                                       config['alsuffix'])
            specpathfn = os.path.join(refdir, specfn)
            s = afni_suma_spec.read(specpathfn)

            specs.append(afni_suma_spec.read(specpathfn))

        add_states = ['inflated', 'full.patch.flat', 'sphere.reg']
        add_states_required = [True, False, True]  # flat surface is optional
        for add_state, is_req in zip(add_states, add_states_required):
            has_state = all([
                len(spec.find_surface_from_state(add_state)) == 1
                for spec in specs
            ])

            if not has_state:
                if is_req:
                    error('cannot find state %s' % add_state)
                else:
                    # skip this state
                    print "Optional state %s not found - skipping" % add_state
                    continue

            specs = afni_suma_spec.hemi_pairs_add_views(specs,
                                                        add_state,
                                                        ext,
                                                        refdir,
                                                        overwrite=overwrite)

        spec_both = afni_suma_spec.combine_left_right(specs)

        # generate spec files for both hemispheres
        hemiboth = 'b'
        specfn = afni_suma_spec.canonical_filename(icold, hemiboth,
                                                   config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)
        spec_both.write(specpathfn, overwrite=overwrite)

        # merge left and right into one surface
        # and generate the spec files as well
        hemimerged = 'm'
        specfn = afni_suma_spec.canonical_filename(icold, hemimerged,
                                                   config['alsuffix'])
        specpathfn = os.path.join(refdir, specfn)

        if config['overwrite'] or not os.path.exists(specpathfn):
            spec_merged, surfs_to_join = afni_suma_spec.merge_left_right(
                spec_both)
            spec_merged.write(specpathfn, overwrite=overwrite)

            full_path = lambda x: os.path.join(refdir, x)
            for fn_out, fns_in in surfs_to_join.iteritems():
                surfs_in = [surf.read(full_path(fn)) for fn in fns_in]

                if all(['full.patch.flat' in fn for fn in fns_in]):
                    # left hemi of flat; rotate 180 degrees, reposition again
                    surfs_in[0] = surfs_in[0] * [-1, -1, 1]
                    surfs_in = surf.reposition_hemisphere_pairs(
                        surfs_in[0], surfs_in[1], 'm')

                surf_merged = surf.merge(*surfs_in)

                if config['overwrite'] or not os.path.exists(
                        full_path(fn_out)):
                    surf.write(full_path(fn_out), surf_merged)
                    print "Merged surfaces written to %s" % fn_out
Пример #5
0
def run_makespec_bothhemis(config, env):
    refdir = config['refdir']
    overwrite = config['overwrite']
    icolds, hemis = _get_hemis_icolds(config)

    ext = format2extension(config)

    if hemis != ['l', 'r']:
        raise ValueError("Cannot run without left and right hemisphere")

    for icold in icolds:
        specs = []
        for hemi in hemis:
            #surfprefix = '%s%sh' % (config['mi_icopat'] % icold, hemi)
            specfn = afni_suma_spec.canonical_filename(icold, hemi,
                                                       config['alsuffix'])
            specpathfn = pathjoin(refdir, specfn)
            s = afni_suma_spec.read(specpathfn)

            specs.append(afni_suma_spec.read(specpathfn))

        add_states = ['inflated', 'full.patch.flat', 'sphere.reg']
        add_states_required = [True, False, True] # flat surface is optional
        for add_state, is_req in zip(add_states, add_states_required):
            has_state = all([len(spec.find_surface_from_state(add_state)) == 1
                                    for spec in specs])

            if not has_state:
                if is_req:
                    error('cannot find state %s' % add_state)
                else:
                    # skip this state
                    print "Optional state %s not found - skipping" % add_state
                    continue

            specs = afni_suma_spec.hemi_pairs_add_views(specs,
                            add_state, ext, refdir, overwrite=overwrite)


        spec_both = afni_suma_spec.combine_left_right(specs)


        # generate spec files for both hemispheres
        hemiboth = 'b'
        specfn = afni_suma_spec.canonical_filename(icold, hemiboth, config['alsuffix'])
        specpathfn = pathjoin(refdir, specfn)
        spec_both.write(specpathfn, overwrite=overwrite)

        # merge left and right into one surface
        # and generate the spec files as well
        hemimerged = 'm'
        specfn = afni_suma_spec.canonical_filename(icold, hemimerged, config['alsuffix'])
        specpathfn = pathjoin(refdir, specfn)

        if config['overwrite'] or not os.path.exists(specpathfn):
            spec_merged, surfs_to_join = afni_suma_spec.merge_left_right(spec_both)
            spec_merged.write(specpathfn, overwrite=overwrite)

            full_path = lambda x:pathjoin(refdir, x)
            for fn_out, fns_in in surfs_to_join.iteritems():
                surfs_in = [surf.read(full_path(fn)) for fn in fns_in]

                if all(['full.patch.flat' in fn for fn in fns_in]):
                    # left hemi of flat; rotate 180 degrees, reposition again
                    surfs_in[0] = surfs_in[0] * [-1, -1, 1]
                    surfs_in = surf.reposition_hemisphere_pairs(surfs_in[0], surfs_in[1], 'm')

                surf_merged = surf.merge(*surfs_in)

                if config['overwrite'] or not os.path.exists(full_path(fn_out)):
                    surf.write(full_path(fn_out), surf_merged)
                    print "Merged surfaces written to %s" % fn_out
Пример #6
0
    def test_afni_suma_spec(self, temp_dir):

        # XXX this function generates quite a few temporary files,
        #     which are removed at the end.
        #     the decorator @with_tempfile seems unsuitable as it only
        #     supports a single temporary file

        # make temporary directory
        os.mkdir(temp_dir)

        # generate surfaces
        inflated_surf = surf.generate_plane((0, 0, 0), (0, 1, 0), (0, 0, 1),
                                            10, 10)
        white_surf = inflated_surf + 1.

        # helper function
        _tmp = lambda x: os.path.join(temp_dir, x)

        # filenames for surfaces and spec file
        inflated_fn = _tmp('_lh_inflated.asc')
        white_fn = _tmp('_lh_white.asc')
        spec_fn = _tmp('lh.spec')

        spec_dir = os.path.split(spec_fn)[0]

        # generate SUMA-like spec dictionary
        white = dict(SurfaceFormat='ASCII',
                     EmbedDimension='3',
                     SurfaceType='FreeSurfer',
                     SurfaceName=white_fn,
                     Anatomical='Y',
                     LocalCurvatureParent='SAME',
                     LocalDomainParent='SAME',
                     SurfaceState='smoothwm')

        inflated = dict(SurfaceFormat='ASCII',
                        EmbedDimension='3',
                        SurfaceType='FreeSurfer',
                        SurfaceName=inflated_fn,
                        Anatomical='N',
                        LocalCurvatureParent=white_fn,
                        LocalDomainParent=white_fn,
                        SurfaceState='inflated')

        # make SurfaceSpec object
        spec = afni_suma_spec.SurfaceSpec([white], directory=spec_dir)
        spec.add_surface(inflated)

        # test __str__ and __repr__
        assert_true('SurfaceSpec instance with 2 surfaces'
                    ', 2 states ' in '%s' % spec)
        assert_true(('%r' % spec).startswith('SurfaceSpec'))

        # test finding surfaces
        inflated_ = spec.find_surface_from_state('inflated')
        assert_equal([(1, inflated)], inflated_)

        empty = spec.find_surface_from_state('unknown')
        assert_equal(empty, [])

        # test .same_states
        minimal = afni_suma_spec.SurfaceSpec(
            [dict(SurfaceState=s) for s in ('smoothwm', 'inflated')])
        assert_true(spec.same_states(minimal))
        assert_false(spec.same_states(afni_suma_spec.SurfaceSpec(dict())))

        # test 'smart' surface file matching
        assert_equal(spec.get_surface_file('smo'), white_fn)
        assert_equal(spec.get_surface_file('inflated'), inflated_fn)
        assert_equal(spec.get_surface_file('this should be None'), None)

        # test i/o
        spec.write(spec_fn)
        spec_ = afni_suma_spec.from_any(spec_fn)

        # prepare for another (right-hemisphere) spec file
        lh_spec = spec
        rh_spec_fn = spec_fn.replace('lh', 'rh')

        rh_inflated_fn = _tmp(
            os.path.split(inflated_fn)[1].replace('_lh', '_rh'))
        rh_white_fn = _tmp(os.path.split(white_fn)[1].replace('_lh', '_rh'))
        rh_spec_fn = _tmp('rh.spec')

        rh_white = dict(SurfaceFormat='ASCII',
                        EmbedDimension='3',
                        SurfaceType='FreeSurfer',
                        SurfaceName=rh_white_fn,
                        Anatomical='Y',
                        LocalCurvatureParent='SAME',
                        LocalDomainParent='SAME',
                        SurfaceState='smoothwm')

        rh_inflated = dict(SurfaceFormat='ASCII',
                           EmbedDimension='3',
                           SurfaceType='FreeSurfer',
                           SurfaceName=rh_inflated_fn,
                           Anatomical='N',
                           LocalCurvatureParent=rh_white_fn,
                           LocalDomainParent=rh_white_fn,
                           SurfaceState='inflated')

        rh_spec = afni_suma_spec.SurfaceSpec([rh_white], directory=spec_dir)
        rh_spec.add_surface(rh_inflated)

        # write files
        all_temp_fns = [spec_fn, rh_spec_fn]
        for fn, s in [(rh_inflated_fn, inflated_surf),
                      (rh_white_fn, white_surf), (inflated_fn, inflated_surf),
                      (white_fn, white_surf)]:
            surf.write(fn, s)
            all_temp_fns.append(fn)

        # test adding views
        added_specs = afni_suma_spec.hemi_pairs_add_views((lh_spec, rh_spec),
                                                          'inflated', '.asc')

        for hemi, added_spec in zip(('l', 'r'), added_specs):
            states = ['smoothwm', 'inflated'
                      ] + ['CoM%sinflated' % i for i in 'msiap']
            assert_equal(states,
                         [s['SurfaceState'] for s in added_specs[0].surfaces])
            all_temp_fns.extend(
                [s['SurfaceName'] for s in added_spec.surfaces])

        # test combining specs (bh=both hemispheres)
        bh_spec = afni_suma_spec.combine_left_right(added_specs)

        # test merging specs (mh=merged hemispheres)
        mh_spec, mh_surfs = afni_suma_spec.merge_left_right(bh_spec)

        assert_equal([s['SurfaceState'] for s in mh_spec.surfaces],
                     ['smoothwm'] + ['CoM%sinflated' % i for i in 'msiap'])