Esempio n. 1
0
def get_baseconf_settings( baseconf_settings_filename = None ):
    """
    Returns the basic configuration settings as a parameter structure.

    :param baseconf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default settings from scratch.
    :return: parameter structure
    """

    # These are the parameters for the general I/O and example cases
    baseconf_params = pars.ParameterDict()
    baseconf_params[('baseconf',{},'determines if settings should be loaded from file and visualization options')]

    if baseconf_settings_filename is not None:
        print( 'Loading baseconf configuration from: ' + baseconf_settings_filename )
        baseconf_params.load_JSON( baseconf_settings_filename )
        return baseconf_params
    else:
        print( 'Using default baseconf settings from config_parser.py')

    baseconf_params['baseconf'][('load_default_settings_from_default_setting_files',False,'if set to True default configuration files (in settings directory) are first loaded')]
    baseconf_params['baseconf'][('load_settings_from_file',True,'if set to True configuration settings are loaded from file')]
    baseconf_params['baseconf'][('save_settings_to_file',True,'if set to True configuration settings are saved to file')]

    if not baseconf_params['baseconf']['load_default_settings_from_default_setting_files']:
        print('HINT: Only compute_settings.json and baseconf_settings.json will be read from file by default.')
        print('HINT: Set baseconf.load_default_settings_from_default_setting_files to True if you want to use the other setting files in directory settings.')
        print('HINT: Otherwise the defaults will be as defined in config_parser.py.')

    return baseconf_params
Esempio n. 2
0
def analyze_on_single_res(pair,pair_name, expr_folder=None, color_image=False,model_name='rdmm'):
    moving, target, spacing, moving_init_weight, phi,m = get_analysis_input(pair,expr_folder,pair_name,color_image=color_image,model_name=model_name)
    lmoving, ltarget =get_labeled_image(pair)
    params = pars.ParameterDict()
    params.load_JSON(os.path.join(expr_folder,'mermaid_setting.json'))
    individual_parameters = dict(m=m,local_weights=moving_init_weight)
    sz = np.array(moving.shape)
    saving_folder = os.path.join(expr_folder, 'analysis')
    saving_folder = os.path.join(saving_folder, pair_name)
    saving_folder = os.path.join(saving_folder,'res_analysis')
    os.makedirs(saving_folder,exist_ok=True)
    extra_info = None
    visual_param = None

    extra_info = {'fname':[pair_name],'saving_folder':[saving_folder]}
    visual_param = setting_visual_saving(expr_folder, pair_name,folder_name='color')

    res= evaluate_model(moving, target, sz, spacing,
                   use_map=True,
                   compute_inverse_map=False,
                   map_low_res_factor=0.5,
                   compute_similarity_measure_at_low_res=False,
                   spline_order=1,
                   individual_parameters=individual_parameters,
                   shared_parameters=None, params=params, extra_info=extra_info,visualize=False,visual_param=visual_param, given_weight=True)
    phi = res[1]
    lres = utils.compute_warped_image_multiNC(lmoving, phi, spacing, 0, zero_boundary=True)
    scores = get_multi_metric(lres,ltarget,rm_bg=True)
    avg_jacobi = compute_jacobi(phi,spacing)
    return scores['label_batch_avg_res']['dice'], avg_jacobi
Esempio n. 3
0
        def create_mermaid_model(mermaid_json_pth,
                                 img_sz,
                                 compute_inverse=True):
            import mermaid.model_factory as py_mf
            spacing = 1. / (np.array(img_sz[2:]) - 1)
            params = pars.ParameterDict()
            params.load_JSON(
                mermaid_json_pth)  # ''../easyreg/cur_settings_svf.json')
            model_name = params['model']['registration_model']['type']
            params.print_settings_off()
            mermaid_low_res_factor = 0.5
            lowResSize = get_res_size_from_size(img_sz, mermaid_low_res_factor)
            lowResSpacing = get_res_spacing_from_spacing(
                spacing, img_sz, lowResSize)
            ##
            mf = py_mf.ModelFactory(img_sz, spacing, lowResSize, lowResSpacing)
            model, criterion = mf.create_registration_model(
                model_name, params['model'], compute_inverse_map=True)
            lowres_id = identity_map_multiN(lowResSize, lowResSpacing)
            lowResIdentityMap = torch.from_numpy(lowres_id).cuda()

            _id = identity_map_multiN(img_sz, spacing)
            identityMap = torch.from_numpy(_id).cuda()
            mermaid_unit_st = model.cuda()
            mermaid_unit_st.associate_parameters_with_module()
            return mermaid_unit_st, criterion, lowResIdentityMap, lowResSize, lowResSpacing, identityMap, spacing
Esempio n. 4
0
def add_texture_on_img(im_orig,
                       texture_gaussian_smoothness=0.1,
                       texture_magnitude=0.3):

    # do this separately for each integer intensity level
    levels = np.unique((np.floor(im_orig)).astype('int'))

    im = np.zeros_like(im_orig)

    for current_level in levels:

        sz = im_orig.shape
        rand_noise = np.random.random(sz[2:]).astype('float32') - 0.5
        rand_noise = rand_noise.view().reshape(sz)
        r_params = pars.ParameterDict()
        r_params['smoother']['type'] = 'gaussian'
        r_params['smoother']['gaussian_std'] = texture_gaussian_smoothness
        spacing = 1.0 / (np.array(sz[2:]).astype('float32') - 1)
        s_r = sf.SmootherFactory(sz[2::], spacing).create_smoother(r_params)

        rand_noise_smoothed = s_r.smooth(AdaptVal(
            torch.from_numpy(rand_noise))).detach().cpu().numpy()
        rand_noise_smoothed /= rand_noise_smoothed.max()
        rand_noise_smoothed *= texture_magnitude

        c_indx = (im_orig >= current_level - 0.5)
        im[c_indx] = im_orig[c_indx] + rand_noise_smoothed[c_indx]

    return torch.Tensor(im)
Esempio n. 5
0
def _none_if_empty(par):
    if type(par) == type(pars.ParameterDict()):
        if par.isempty():
            return None
        else:
            return par
    else:
        return par
Esempio n. 6
0
def get_setting(path, output_path, setting_name="mermaid"):
    params = pars.ParameterDict()
    params.load_JSON(path)
    os.makedirs(output_path, exist_ok=True)
    output_path = os.path.join(output_path,
                               '{}_setting.json'.format(setting_name))
    params.write_JSON(output_path, save_int=False)
    return params
Esempio n. 7
0
def setting_visual_saving(expr_folder,pair_name,expr_name='',folder_name='intermid'):
    extra_info = pars.ParameterDict()
    extra_info['expr_name'] = expr_name
    extra_info['visualize']=False
    extra_info['save_fig']=True
    extra_info['save_fig_path']=os.path.join(expr_folder,folder_name)
    extra_info['save_fig_num'] = -1
    extra_info['save_excel'] =False
    extra_info['pair_name'] = [pair_name]
    return  extra_info
Esempio n. 8
0
    def test_lddmm_shooting_scalar_momentum_image_multi_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_scalar_momentum_image_multi_scale_config.json')

        self.createImage()

        mo = MO.SimpleMultiScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        mo.get_optimizer().set_visualization(False)
        mo.register()

        # E=[ 0.03197587], similarityE=[ 0.02087387], regE=[ 0.01110199], relF=[ 0.00138645]
        energy = mo.get_energy()

        npt.assert_almost_equal(energy[0], 0.03184246, decimal=4 )
        npt.assert_almost_equal(energy[1], 0.0207199, decimal=4 )
        npt.assert_almost_equal(energy[2], 0.01112256, decimal=4 )
Esempio n. 9
0
    def test_lddmm_shooting_scalar_momentum_image_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_scalar_momentum_image_single_scale_config.json')

        self.createImage()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E = [0.03198373], similarityE = [0.0210261], regE = [0.01095762], relF = [0.]
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.03198373, decimal=4 )
        npt.assert_almost_equal(energy[1], 0.0210261, decimal=4 )
        npt.assert_almost_equal(energy[2], 0.01095762, decimal=4 )
Esempio n. 10
0
    def test_lddmm_shooting_scalar_momentum_map_multi_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_scalar_momentum_map_multi_scale_config.json')

        self.createImage()

        mo = MO.SimpleMultiScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        mo.get_optimizer().set_visualization(False)
        mo.register()

        # E = [0.08930502], simE = [0.08034889], regE = [0.00895613], optParE = [0.], relF = [0.03883468]
        energy = mo.get_energy()

        npt.assert_almost_equal(energy[0], 0.04333755, decimal=4 )
        npt.assert_almost_equal(energy[1], 0.03237363, decimal=4 )
        npt.assert_almost_equal(energy[2], 0.010963925, decimal=4 )
Esempio n. 11
0
    def test_svf_image_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_svf_image_single_scale_config.json')

        self.createImage( 32 )

        so = MO.SimpleSingleScaleRegistration( self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E=[ 1.80229616], similarityE=[ 0.71648604], regE=[ 1.08581007], relF=[ 0.0083105]
        energy = so.get_energy()

        npt.assert_almost_equal( energy[0], 1.7918575, decimal=1 )
        npt.assert_almost_equal( energy[1], 0.5308577, decimal=1 )
        npt.assert_almost_equal( energy[2], 1.2609998, decimal=1 )
Esempio n. 12
0
    def test_lddmm_shooting_map_multi_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_map_multi_scale_config.json')

        self.createImage()

        mo = MO.SimpleMultiScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        mo.get_optimizer().set_visualization(False)
        mo.register()

        # E = [0.07970674], simE = [0.06657108], regE = [0.01313565], optParE = [0.], relF = [0.02088663]
        energy = mo.get_energy()

        npt.assert_almost_equal(energy[0], 0.07360865, decimal=4 )
        npt.assert_almost_equal(energy[1], 0.06016802, decimal=4 )
        npt.assert_almost_equal(energy[2], 0.01344063, decimal=4 )
Esempio n. 13
0
    def test_svf_map_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_svf_map_single_scale_config.json')

        self.createImage( 32 )

        so = MO.SimpleSingleScaleRegistration( self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E = [36.42594528], similarityE = [16.22630882], regE = [20.19963646], relF = [0.0422723]
        energy = so.get_energy()

        npt.assert_almost_equal( energy[0], 16.957407, decimal=0 )
        npt.assert_almost_equal( energy[1], 6.718715, decimal=0 )
        npt.assert_almost_equal( energy[2], 10.238692, decimal=0 )
Esempio n. 14
0
    def test_lddmm_shooting_map_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_map_single_scale_config.json')

        self.createImage()

        so = MO.SimpleSingleScaleRegistration( self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E = [0.05674197], similarityE = [0.04364978], regE = [0.01309219], relF = [0.01391943]
        energy = so.get_energy()

        npt.assert_almost_equal( energy[0], 0.05927172, decimal=3 )
        npt.assert_almost_equal( energy[1], 0.04580842, decimal=3 )
        npt.assert_almost_equal( energy[2], 0.013463295, decimal=3 )
Esempio n. 15
0
    def test_lddmm_shooting_image_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_image_single_scale_config.json')

        self.createImage()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E=[ 0.02896098], similarityE=[ 0.0170299], regE=[ 0.01193108], relF=[ 0.00193194]
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.02896098, decimal=2 )
        npt.assert_almost_equal(energy[1], 0.0170299, decimal=2 )
        npt.assert_almost_equal(energy[2], 0.01193108, decimal=2 )
Esempio n. 16
0
    def test_lddmm_shooting_image_multi_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/test_lddmm_shooting_image_multi_scale_config.json')

        self.createImage()

        mo = MO.SimpleMultiScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        mo.get_optimizer().set_visualization(False)
        mo.register()

        # E = [0.04338037], similarityE = [0.03070126], regE = [0.01267911], relF = [0.01936091]
        energy = mo.get_energy()

        npt.assert_almost_equal(energy[0], 0.04338037, decimal=4 )
        npt.assert_almost_equal(energy[1], 0.03070126, decimal=4 )
        npt.assert_almost_equal(energy[2], 0.01267911, decimal=4 )
Esempio n. 17
0
    def test_svf_vector_momentum_map_single_scale(self):
        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/svf_momentum_base_config.json')

        self.params['model']['deformation']['use_map'] = True
        self.params['model']['registration_model']['type'] = 'svf_vector_momentum_map'

        self.createImage()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E=[0.03567663], simE=[0.02147915], regE=0.01419747807085514
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.03706806, decimal = 4)
        npt.assert_almost_equal(energy[1], 0.02302469, decimal = 4)
        npt.assert_almost_equal(energy[2], 0.014043369330, decimal = 4)
Esempio n. 18
0
    def test_svf_scalar_momentum_image_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/svf_momentum_base_config.json')

        self.params['model']['deformation']['use_map'] = False
        self.params['model']['registration_model']['type'] = 'svf_scalar_momentum_image'

        self.createImage()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()
        # E=[0.12413108], simE=[0.11151054], regE=0.012620546855032444
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.12428085, decimal=4)
        npt.assert_almost_equal(energy[1], 0.11166441, decimal=4)
        npt.assert_almost_equal(energy[2], 0.012616440653800964, decimal=4)
Esempio n. 19
0
    def test_svf_scalar_momentum_map_single_scale(self):
        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/svf_momentum_base_config.json')

        self.params['model']['deformation']['use_map'] = True
        self.params['model']['registration_model']['type'] = 'svf_scalar_momentum_map'

        self.createImage()
        self.setUp()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E=[0.16388921], simE=[0.15010326], regE=0.013785961084067822
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.16180025, decimal = 4)
        npt.assert_almost_equal(energy[1], 0.14811447, decimal = 4)
        npt.assert_almost_equal(energy[2], 0.01368578, decimal = 4)
Esempio n. 20
0
    def test_svf_vector_momentum_image_single_scale(self):

        self.params = pars.ParameterDict()
        self.params.load_JSON('./json/svf_momentum_base_config.json')

        self.params['model']['deformation']['use_map'] = False
        self.params['model']['registration_model']['type'] = 'svf_vector_momentum_image'

        self.createImage()
        self.setUp()

        so = MO.SimpleSingleScaleRegistration(self.ISource, self.ITarget, self.spacing, self.sz, self.params)
        so.get_optimizer().set_visualization(False)
        so.register()

        # E=[ 0.02504558], similarityE=[ 0.01045385], regE=[ 0.01459173], relF=[ 0.00203472]
        energy = so.get_energy()

        npt.assert_almost_equal(energy[0], 0.02504558, decimal = 2)
        npt.assert_almost_equal(energy[1], 0.01045385, decimal = 2)
        npt.assert_almost_equal(energy[2], 0.01459173, decimal = 2)
Esempio n. 21
0
def get_respro_settings(respro_settings_filename = None):

    respro_params = pars.ParameterDict()
    respro_params[('respro', {}, 'settings for the results process')]

    if respro_settings_filename is not None:
        print( 'Loading respro configuration from: ' + respro_settings_filename )
        respro_params.load_JSON(respro_settings_filename)
        return respro_params
    else:
        print( 'Using default respro settings from config_parser.py')

    respro_params['respro'][('expr_name', 'reg', 'name of experiment')]
    respro_params['respro'][('visualize', True, 'if set to true intermediate results are visualized')]
    respro_params['respro'][('visualize_step', 5, 'Number of iterations between visualization output')]

    respro_params['respro'][('save_fig', False, 'save visualized results')]
    respro_params['respro'][('save_fig_path', '../data/saved_results', 'path of saved figures')]
    respro_params['respro'][('save_excel', True, 'save results in excel')]

    return respro_params
Esempio n. 22
0
def get_democonf_settings( democonf_settings_filename = None ):
    """
    Returns the configuration settings for the demo data as a parameter structure.

    :param democonf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default settings from scratch.
    :return: parameter structure
    """

    # These are the parameters for the general I/O and example cases
    democonf_params = pars.ParameterDict()
    democonf_params[('democonf', {}, 'settings for demo images/examples')]

    if democonf_settings_filename is not None:
        print( 'Loading democonf configuration from: ' + democonf_settings_filename )
        democonf_params.load_JSON( democonf_settings_filename )
        return democonf_params
    else:
        print( 'Using default democonf settings from config_parser.py' )

    democonf_params['democonf'][('dim', 2, 'Spatial dimension for demo examples 1/2/3')]
    democonf_params['democonf'][('example_img_len', 128, 'side length of image cube for example')]
    democonf_params['democonf'][('use_real_images', False, 'if set to true using real and otherwise synthetic images')]

    return democonf_params
Esempio n. 23
0
def get_mermaid_setting(path, output_path):
    params = pars.ParameterDict()
    params.load_JSON(path)
    os.makedirs(output_path, exist_ok=True)
    output_path = os.path.join(output_path, 'mermaid_setting.json')
    params.write_JSON(output_path, save_int=False)
Esempio n. 24
0
def get_algconf_settings( algconf_settings_filename = None ):
    """
    Returns the registration algorithm configuration settings as a parameter structure.

    :param algconf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default settings from scratch.
    :return: parameter structure
    """

    # These are the parameters for the general I/O and example cases
    algconf_params = pars.ParameterDict()
    algconf_params[('algconf',{},'settings for the registration algorithms')]

    if algconf_settings_filename is not None:
        print( 'Loading algconf configuration from: ' + algconf_settings_filename )
        algconf_params.load_JSON( algconf_settings_filename )
        return algconf_params
    else:
        print( 'Using default algconf settings from config_parser.py')

    algconf_params['algconf'][('optimizer', {}, 'optimizer settings')]
    algconf_params['algconf']['optimizer'][('name', 'lbfgs_ls', 'name of the optimizer: [lbfgs_ls|adam]')]
    algconf_params['algconf']['optimizer'][('single_scale', {}, 'single scale settings')]
    algconf_params['algconf']['optimizer']['single_scale'][('nr_of_iterations', 20, 'number of iterations')]
    algconf_params['algconf']['optimizer'][('multi_scale', {}, 'multi scale settings')]
    algconf_params['algconf']['optimizer']['multi_scale'][('use_multiscale', False, 'use multi-scale optimizer')]
    algconf_params['algconf']['optimizer']['multi_scale'][('scale_factors', [1.0, 0.5, 0.25], 'how images are scaled')]
    algconf_params['algconf']['optimizer']['multi_scale'][('scale_iterations', [10, 20, 20], 'number of iterations per scale')]

    algconf_params['algconf'][('model', {}, 'general model settings')]
    algconf_params['algconf']['model'][('deformation', {}, 'model describing the desired deformation model')]
    algconf_params['algconf']['model']['deformation'][('name', 'lddmm_shooting', "['svf'|'svf_quasi_momentum'|'lddmm_shooting'|'lddmm_shooting_scalar_momentum'] all with '_map' or '_image' suffix")]

    algconf_params['algconf']['model']['deformation'][('use_map', True, '[True|False] either do computations via a map or directly using the image')]
    algconf_params['algconf']['model']['deformation'][('map_low_res_factor',1.0,'Set to a value in (0,1) if a map-based solution should be computed at a lower internal resolution (image matching is still at full resolution')]

    algconf_params['algconf']['model'][('registration_model', {}, 'general settings for the registration model')]
    algconf_params['algconf']['model']['registration_model'][('forward_model', {}, 'Holds the parameters for the forward model')]
    algconf_params['algconf']['model']['registration_model']['forward_model'][('number_of_time_steps', 10, 'Number of time steps for integration (if applicable)')]
    algconf_params['algconf']['model']['registration_model']['forward_model'][('smoother', {}, 'how the smoothing of velocity fields is done')]
    #algconf_params['algconf']['model']['registration_model']['forward_model']['smoother'][('type', 'multiGaussian', 'type of smoothing')]
    #algconf_params['algconf']['model']['registration_model']['forward_model']['smoother'][('multi_gaussian_stds', [0.05,0.1,0.15,0.2,0.25], 'standard deviations for smoothing')]

    algconf_params['algconf']['model']['registration_model']['forward_model']['smoother'][
        ('type', 'gaussian', 'type of smoothing')]
    algconf_params['algconf']['model']['registration_model']['forward_model']['smoother'][
        ('gaussian_std', 0.15, 'standard deviations for smoothing')]

    algconf_params['algconf']['model']['registration_model'][('similarity_measure', {}, 'model describing the similarity measure')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure'][('sigma', 0.1, '1/sigma^2 weighting')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure'][('type', 'ssd', '[ssd|ncc]')]

    algconf_params['algconf']['model']['registration_model']['similarity_measure'][('develop_mod_on', False, 'if true would allow develop settings ')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure'][('develop_mod', {}, 'developing mode ')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure']['develop_mod'][('smoother', {}, 'how the smoothing of velocity fields is done ')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure']['develop_mod']['smoother'][('type', 'gaussian', 'type of smoothing')]
    algconf_params['algconf']['model']['registration_model']['similarity_measure']['develop_mod']['smoother'][('gaussian_std', 0.1, 'standard deviation for smoothing')]
    algconf_params['algconf'][('image_smoothing', {}, 'image smoothing settings')]
    algconf_params['algconf']['image_smoothing'][('smooth_images', True, '[True|False]; smoothes the images before registration')]
    algconf_params['algconf']['image_smoothing'][('smoother',{},'settings for the image smoothing')]
    algconf_params['algconf']['image_smoothing']['smoother'][('gaussian_std', 0.01, 'how much smoothing is done')]
    algconf_params['algconf']['image_smoothing']['smoother'][('type', 'gaussian', "['gaussianSpatial'|'gaussian'|'diffusion']")]

    return algconf_params
Esempio n. 25
0
def get_single_gaussian_smoother(gaussian_std, sz, spacing):
    s_m_params = pars.ParameterDict()
    s_m_params['smoother']['type'] = 'gaussian'
    s_m_params['smoother']['gaussian_std'] = gaussian_std
    s_m = sf.SmootherFactory(sz, spacing).create_smoother(s_m_params)
    return s_m
Esempio n. 26
0
        print('Specifying directories based on SYNTH main directory: {:s}'.
              format(args.main_synth_directory))

        validation_dataset_name = 'SYNTH'

        input_image_directory = os.path.join(args.main_synth_directory,
                                             'brain_affine_icbm')
        image_pair_config_pt = os.path.join(args.main_synth_directory,
                                            'used_image_pairs.pt')
        validation_dataset_directory = args.main_synth_directory

    # if this is not synth data, we first check if a JSON file was used to specify the directories
    elif args.dataset_config is not None:
        print('Reading dataset configuration from: {:s}'.format(
            args.dataset_config))
        data_params = pars.ParameterDict()
        save_dataset_config = False

        if not os.path.exists(args.dataset_config):
            print(
                'INFO: config file {:s} does not exist. Creating a generic one.'
                .format(args.dataset_config))
            input_image_directory_default = 'synthetic_example_out/brain_affine_icbm'
            image_pair_config_pt_default = 'synthetic_example_out/used_image_pairs.pt'
            output_base_directory_default = 'experimental_results_synth_2d'
            validation_dataset_directory_default = 'synthetic_example_out'
            validation_dataset_name_default = 'SYNTH'
            save_dataset_config = True
        else:
            input_image_directory_default = None
            image_pair_config_pt_default = None
Esempio n. 27
0
# first do the torch imports
import set_pyreg_paths

import torch
from torch.autograd import Variable
from mermaid.data_wrapper import AdaptVal
import numpy as np
import mermaid.module_parameters as MP
import mermaid.example_generation as eg
import mermaid.utils as utils

import mermaid.smoother_factory as SF

import matplotlib.pyplot as plt

params = MP.ParameterDict()

dim = 2

szEx = np.tile(64, dim)
I0, I1, spacing = eg.CreateSquares(dim).create_image_pair(
    szEx, params)  # create a default image size with two sample squares
sz = np.array(I0.shape)

# create the source and target image as pyTorch variables
ISource = AdaptVal(torch.from_numpy(I0.copy()))

smoother = SF.MySingleGaussianFourierSmoother(sz[2:], spacing, params)

g_std = smoother.get_gaussian_std()
Esempio n. 28
0
import numpy as np
import matplotlib.pyplot as plt

import mermaid.simple_interface as SI
import mermaid.example_generation as EG
import mermaid.module_parameters as pars

################################
# Creating some example data
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# We can use ``mermaid.example_generation`` to create some test data as follows:
#

# We first generate a parameter object to hold settings
params = pars.ParameterDict()

# We select if we want to create synthetic image pairs or would prefer a real image pair
use_synthetic_test_case = True

# Desired dimension (mermaid supports 1D, 2D, and 3D registration)
dim = 2

# If we want to add some noise to the background (for synthetic examples)
add_noise_to_bg = True

# and now create it
if use_synthetic_test_case:
    length = 64
    # size of the desired images: (sz)^dim
    szEx = np.tile(length, dim )
Esempio n. 29
0
    def init_mermaid_env(self):
        """
        setup the mermaid environemnt
        * saving the settings into record folder
        * initialize model from model, criterion and related variables

        """
        spacing = self.spacing
        params = pars.ParameterDict()
        params.load_JSON(
            self.mermaid_net_json_pth)  #''../easyreg/cur_settings_svf.json')
        print(" The mermaid setting from {} included:".format(
            self.mermaid_net_json_pth))
        print(params)
        model_name = params['model']['registration_model']['type']
        use_map = params['model']['deformation']['use_map']
        compute_similarity_measure_at_low_res = params['model']['deformation'][
            ('compute_similarity_measure_at_low_res', False,
             'to compute Sim at lower resolution')]
        params['model']['registration_model']['similarity_measure'][
            'type'] = self.loss_type
        params.print_settings_off()
        self.mermaid_low_res_factor = self.low_res_factor
        smoother_type = params['model']['registration_model']['forward_model'][
            'smoother']['type']
        self.use_adaptive_smoother = smoother_type == 'learned_multiGaussianCombination'

        lowResSize = None
        lowResSpacing = None
        ##
        if self.mermaid_low_res_factor == 1.0 or self.mermaid_low_res_factor == [
                1., 1., 1.
        ]:
            self.mermaid_low_res_factor = None

        self.lowResSize = self.img_sz
        self.lowResSpacing = spacing
        ##
        if self.mermaid_low_res_factor is not None:
            lowResSize = get_res_size_from_size(self.img_sz,
                                                self.mermaid_low_res_factor)
            lowResSpacing = get_res_spacing_from_spacing(
                spacing, self.img_sz, lowResSize)
            self.lowResSize = lowResSize
            self.lowResSpacing = lowResSpacing

        if self.mermaid_low_res_factor is not None:
            # computes model at a lower resolution than the image similarity
            if compute_similarity_measure_at_low_res:
                mf = py_mf.ModelFactory(lowResSize, lowResSpacing, lowResSize,
                                        lowResSpacing)
            else:
                mf = py_mf.ModelFactory(self.img_sz, spacing, lowResSize,
                                        lowResSpacing)
        else:
            # computes model and similarity at the same resolution
            mf = py_mf.ModelFactory(self.img_sz, spacing, self.img_sz, spacing)
        model, criterion = mf.create_registration_model(
            model_name,
            params['model'],
            compute_inverse_map=self.compute_inverse_map)

        if use_map:
            # create the identity map [0,1]^d, since we will use a map-based implementation
            _id = py_utils.identity_map_multiN(self.img_sz, spacing)
            self.identityMap = torch.from_numpy(_id).cuda()
            if self.mermaid_low_res_factor is not None:
                # create a lower resolution map for the computations
                lowres_id = py_utils.identity_map_multiN(
                    lowResSize, lowResSpacing)
                self.lowResIdentityMap = torch.from_numpy(lowres_id).cuda()
                print(torch.min(self.lowResIdentityMap))
        self.lowRes_fn = partial(get_resampled_image,
                                 spacing=spacing,
                                 desiredSize=lowResSize,
                                 zero_boundary=False,
                                 identity_map=self.lowResIdentityMap)
        self.mermaid_unit_st = model.cuda()
        self.criterion = criterion
        self.mermaid_unit_st.associate_parameters_with_module()
        self.save_cur_mermaid_settings(params)
Esempio n. 30
0
def get_default_algconf_settings_filenames():
    """Returns the filename string where the configuration for the registration algorithm will be read from.

    :return: filename string
    """
    return (_algconf_settings_filename,_algconf_settings_filename_comments)




def get_default_respro_settings_filenames():
    return (_respro_settings_filename,_respro_settings_filename_comments)

# First get the computational settings that will be used in various parts of the library
compute_params = pars.ParameterDict()
compute_params.print_settings_off()
compute_params.load_JSON(get_default_compute_settings_filenames()[0])

compute_params[('compute',{},'how computations are done')]
CUDA_ON = compute_params['compute'][('CUDA_ON',False,'Determines if the code should be run on the GPU')]
"""If set to True CUDA will be used, otherwise it will not be used"""

USE_FLOAT16 = compute_params['compute'][('USE_FLOAT16',False,'if set to True uses half-precision - not recommended')]
"""If set to True 16 bit computations will be used -- not recommended and not actively supported"""

nr_of_threads = compute_params['compute'][('nr_of_threads',mp.cpu_count(),'set the maximal number of threads')]
"""Specifies the number of threads"""

MATPLOTLIB_AGG = compute_params['compute'][('MATPLOTLIB_AGG',False,'Determines how matplotlib plots images. Set to True for remote debugging')]
"""If set to True matplotlib's AGG graphics renderer will be used; this should be set to True if run on a server and to False if visualization are desired as part of an interactive compute session"""