Exemplo n.º 1
0
        fun=chi_star_func,method='TNC',x0=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'),
        bounds=None,
        options=dict(maxiter=500, disp=500))

    # print('Your results are: \n '+str(minimization))  # debug

    chi_arr = minimization['x'].reshape(shape)
    return chi_arr


# ======================================================================
# calling the function:
if __name__ == '__main__':
    begin_time = datetime.datetime.now()
    chi_arr = chi_star(
        f=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz') * 100)

    # saving the results here:
    i = 0
    template = '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs_TNC_nobound_{i}.nii.gz'
    filepath = template.format_map(locals())
    while os.path.isfile(filepath):
        i += 1
        filepath = template.format_map(locals())
    save(filepath ,chi_arr)

    end_time = datetime.datetime.now()
    time_elapsed = end_time - begin_time
    print('Time elapsed: {c} seconds!'.format(c=time_elapsed))

    # results for:
Exemplo n.º 2
0
def chi_star(
        f=None,
        shape=None,
        d=None,
        W=None,
        M_G=None,
        chi=None,
        lambda_=np.power(10.,-3)):

    """
    Minimization using scipy.optimize.minimize() and method='BFGS'.

    The function takes input data and a guess for chi to perform
    the minimization according to the scipy.optimize.minimize() function
    with the method='BFGS'.
    It calculates all necessary parameters if not provided for the input
    of the minimization to be of the form:

    .. math:
        0.5 * ((np.linalg.norm(
            W * (f - np.fft.ifftn(d * np.fft.fftn(chi))))) ** 2 +
                    lambda_ * np.sum(abs((M_G) * (np.gradient(chi)))))

    Args:
        f (np.ndarray): Input data that is to be minimized.
            If not specified, takes it as (3,3,3) array of ones.
        shape (tuple[int]): The shape of the input data.
            By default this is (3,3,3).
        d (np.ndarray): The kernel of the respective dipole field,
            by default the dipole kernel in Fourier space according to the
            'dipole_kernel' function.
        W (np.ndarray): Data weighting term.
            By default array of ones in shape of f.
        M_G (np.ndarray): Mask of the data.
            By default an array of ones in shape of f.
        chi (np.ndarray): Term that is actively fitted/guessed.
            By default an array of ones in the shape of f.
        lambda_ (float): Numerical parameter taken according to the situation.
            By default, it is 0.001.
        time_ (bool): Boolean, gives choice if time for run should be printed.
            By default it is printed (i.e. set to True).

    Returns:

    """
    # : setting the initial values:
    if f is None:
        f = np.ones((3,3,3))
    if shape is None:
        shape = f.shape
    ones = np.ones((shape))
    if chi is None:
        chi = ones
    if W is None:
        W = ones
    if M_G is None:
        M_G = ones
    if d is None:
        d = dipole_kernel(shape=shape, origin=0.)

    def chi_star_func(chi=chi, f=f, d=d, W=W, M_G=M_G, lambda_=lambda_):
        """Calculates the input for the minimazation."""
        chi = chi.reshape(shape)
        result = 0.5 * (np.linalg.norm(
            W * (f - np.fft.ifftn(d * np.fft.fftn(chi)))) ** 2 +
                    lambda_ * np.sum(abs((M_G) * (pmu.gradient(arr=chi)))))
        return result

    # performs the minimization
    minimization = scipy.optimize.minimize(
        fun=chi_star_func,method='TNC',x0=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'),
        bounds=None,
        options=dict(maxiter=500, disp=500))

    # print('Your results are: \n '+str(minimization))  # debug

    chi_arr = minimization['x'].reshape(shape)
    return chi_arr
Exemplo n.º 3
0
        fun=chi_star_func,
        method='TNC',
        x0=load(
            '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'
        ),
        bounds=None,
        options=dict(maxiter=1, disp=100))

    # print('Your results are: \n '+str(minimization))  # debug

    chi_arr = minimization['x'].reshape(shape)
    return chi_arr


# ======================================================================
# calling the function:
if __name__ == '__main__':
    begin_time = datetime.datetime.now()
    chi_arr = chi_star(f=load(
        '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'
    ))

    # saving the results here:
    save(
        '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs_TNC_one_iter.nii.gz',
        chi_arr)

    end_time = datetime.datetime.now()
    time_elapsed = end_time - begin_time
    print('Time elapsed: {c} seconds!'.format(c=time_elapsed))
def abcd():
    abcd = load(
        '/home/raid3/vonhof/Documents/Riccardo Data/1703_phantomStuff/dipole_kernel_128.nii.gz'
    )
    return abcd
#aaddfda = scipy.optimize.minimize(fun=input_Gauss, x0=0.,method='Nelder-Mead')

import nibabel as nib
from pymrt.input_output import load, save


# put thtis into the equation to actually make up the function for input f
def abcd():
    abcd = load(
        '/home/raid3/vonhof/Documents/Riccardo Data/1703_phantomStuff/dipole_kernel_128.nii.gz'
    )
    return abcd


db_zero = load(
    '/home/raid3/vonhof/Documents/Riccardo Data/1703_phantomStuff/phantom_db0.nii.gz'
)


def data_input(db_zero):
    return


#other_adfaother_test = scipy.optimize.minimize(fun=abcd,method='BFGS',x0=0.)

#print(abcd.shape)


# correct dipole kernel function without error message:
def dipole_kernel(shape, origin=0.5, theta=0.0, phi=0.0):
    """
Exemplo n.º 6
0
def compute_generic(sources,
                    out_dirpath,
                    params=None,
                    opts=None,
                    force=False,
                    verbose=D_VERB_LVL):
    """
    Perform the specified computation on source files.

    Args:
        sources (list[str]): Directory containing data files.
        out_dirpath (str): Directory containing metadata files.
        params (dict): Parameters associated with the sources.
        opts (dict):
            Accepted options:
                - types (list[str]): List of image types to use for results.
                - mask: (tuple[tuple[int]): Slicing for each dimension.
                - adapt_mask (bool): adapt over- or under-sized mask.
                - dtype (str): data type to be used for the target images.
                - compute_func (str): function used for the computation.

                  compute_func(images, params, compute_args, compute_kwargs)
                  -> img_list, img_type_list
                - compute_args (list): additional positional parameters for
                  compute_func
                - compute_kwargs (dict): additional keyword parameters for
                  compute_func
                - affine_func (str): name of the function for affine
                  computation: affine_func(affines, affine_args...) -> affine
                - affine_args (list): additional parameters for affine_func
        force (bool): Force calculation of output
        verbose (int): Set level of verbosity.

    Returns:
        targets ():

    See Also:
        pymrt.computation.sources_generic,
        pymrt.computation.compute,
        pymrt.computation.D_OPTS
    """
    # TODO: implement affine_func, affine_args, affine_kwargs?
    # get the num, name and seq from first source file
    opts = pmu.merge_dicts(D_OPTS, opts)

    if params is None:
        params = {}
    if opts is None:
        opts = {}

    targets = []
    info = pmn.parse_filename(sources[0])
    if 'ProtocolName' in params:
        info['name'] = params['ProtocolName']
    for image_type in opts['types']:
        info['type'] = image_type
        targets.append(os.path.join(out_dirpath, pmn.to_filename(info)))

    # perform the calculation
    if pmu.check_redo(sources, targets, force):
        if verbose > VERB_LVL['none']:
            print('{}:\t{}'.format('Object', os.path.basename(info['name'])))
        if verbose >= VERB_LVL['medium']:
            print('Opts:\t{}'.format(json.dumps(opts)))
        images, affines = [], []
        mask = [(slice(*dim) if dim is not None else slice(None))
                for dim in opts['mask']]
        for source in sources:
            if verbose > VERB_LVL['none']:
                print('Source:\t{}'.format(os.path.basename(source)))
            if verbose > VERB_LVL['none']:
                print('Params:\t{}'.format(params))
            image, affine, header = pmio.load(source, full=True)
            # fix mask if shapes are different
            if opts['adapt_mask']:
                mask = [(mask[i] if i < len(mask) else slice(None))
                        for i in range(len(image.shape))]
            images.append(image[mask])
            affines.append(affine)
        if 'compute_func' in opts:
            compute_func = eval(opts['compute_func'])
            if 'compute_args' not in opts:
                opts['compute_args'] = []
            if 'compute_kwargs' not in opts:
                opts['compute_kwargs'] = {}
            img_list, aff_list, img_type_list, params_list = compute_func(
                images, affines, params, *opts['compute_args'],
                **opts['compute_kwargs'])
        else:
            img_list, aff_list, img_type_list = zip(
                *[(img, aff, img_type) for img, aff, img_type in zip(
                    images, affines, itertools.cycle(opts['types']))])
            params_list = ({}, ) * len(img_list)

        for target, target_type in zip(targets, opts['types']):
            for img, aff, img_type, params in \
                    zip(img_list, aff_list, img_type_list, params_list):
                if img_type == target_type:
                    if 'dtype' in opts:
                        img = img.astype(opts['dtype'])
                    if params:
                        for key, val in params.items():
                            target = pmn.change_param_val(target, key, val)
                    if verbose > VERB_LVL['none']:
                        print('Target:\t{}'.format(os.path.basename(target)))
                    pmio.save(target, img, aff)
                    break
    return targets
Exemplo n.º 7
0
def ext_qsm_as_legacy(
        images,
        affines,
        params,
        te_label,
        # b0_label,
        # th_label,
        img_types):
    """

    Args:
        images ():
        affines ():
        params ():
        te_label ():
        img_types ():

    Returns:

    """
    # determine correct TE
    max_te = 25.0  # ms
    selected = len(params[te_label])
    for i, te in enumerate(params[te_label]):
        if te < max_te:
            selected = i
    tmp_dirpath = '/tmp/{}'.format(hashlib.md5(str(params)).hexdigest())
    if not os.path.isdir(tmp_dirpath):
        os.makedirs(tmp_dirpath)
    tmp_filenames = ('magnitude.nii.gz', 'phase.nii.gz', 'qsm.nii.gz',
                     'mask.nii.gz')
    tmp_filepaths = tuple(
        os.path.join(tmp_dirpath, tmp_filename)
        for tmp_filename in tmp_filenames)
    # export temp input
    if len(images) > 2:
        images = images[-2:]
        affines = affines[-2:]
    for image, affine, tmp_filepath in zip(images, affines, tmp_filepaths):
        pmio.save(tmp_filepath, image[..., selected], affine)
    # execute script on temp input
    cmd = [
        'qsm_as_legacy.py',
        '--magnitude_input',
        tmp_filepaths[0],
        '--phase_input',
        tmp_filepaths[1],
        '--qsm_output',
        tmp_filepaths[2],
        '--mask_output',
        tmp_filepaths[3],
        '--echo_time',
        str(params[te_label][selected]),
        # '--field_strength', str(params[b0_label][selected]),
        # '--angles', str(params[th_label][selected]),
        '--units',
        'ppb'
    ]
    pmu.execute(str(' '.join(cmd)))
    # import temp output
    img_list, aff_list = [], []
    for tmp_filepath in tmp_filepaths[2:]:
        img, aff, hdr = pmio.load(tmp_filepath, full=True)
        img_list.append(img)
        aff_list.append(aff)
    # clean up tmp files
    if os.path.isdir(tmp_dirpath):
        shutil.rmtree(tmp_dirpath)
    # prepare output
    type_list = ('qsm', 'mask')
    params_list = ({'te': params[te_label][selected]}, {})
    img_type_list = tuple(img_types[key] for key in type_list)
    return img_list, aff_list, img_type_list, params_list