Beispiel #1
0
def _tau_to_kappa(tau):
    """Using non-linear optimization, convert the NODDI-DTI Tau variables to NODDI kappa's.

    Args:
        tau (ndarray): the list of tau's per voxel.

    Returns:
        ndarray: the list of corresponding kappa's
    """
    tau_func = SimpleCLFunction.from_string('''
        double tau(double kappa){
            if(kappa < 1e-12){
                return 1/3.0;
            }
            return 0.5 * ( 1 / ( sqrt(kappa) * dawson(sqrt(kappa) ) ) - 1/kappa);
        }''',
                                            dependencies=[dawson()])

    objective_func = SimpleCLFunction.from_string('''
        double tau_to_kappa(local const mot_float_type* const x, void* data, local mot_float_type* objective_list){
            return pown(tau(x[0]) - ((_tau_to_kappa_data*)data)->tau, 2); 
        }
    ''',
                                                  dependencies=[tau_func])

    kappa = minimize(objective_func,
                     np.ones_like(tau),
                     data=Struct(
                         {'tau': Array(tau, 'mot_float_type', as_scalar=True)},
                         '_tau_to_kappa_data')).x
    kappa[kappa > 64] = 1
    kappa[kappa < 0] = 1
    return kappa
    def _single_optimization_run(self, y_star, x0, roi_indices):
        """Generate one new sample using a single run of the optimization routine."""
        self._roi_input_data.observations[roi_indices] = y_star
        self._model.set_input_data(self._roi_input_data,
                                   suppress_warnings=True)

        kernel_data_subset = self._model.get_kernel_data().get_subset(
            roi_indices)

        results = minimize(
            self._objective_func,
            x0,
            method=self._optimization_method,
            nmr_observations=self._model.get_nmr_observations(),
            cl_runtime_info=self._cl_runtime_info,
            data=self._wrapper.wrap_input_data(kernel_data_subset),
            lower_bounds=self._get_bounds(self._lower_bounds, roi_indices),
            upper_bounds=self._get_bounds(self._upper_bounds, roi_indices),
            constraints_func=self._constraints_func,
            options=self._optimizer_options)

        x_final_array = self._codec.decode(results['x'], kernel_data_subset)

        x_dict = split_array_to_dict(x_final_array,
                                     self._model.get_free_param_names())
        x_dict.update(
            self._model.get_post_optimization_output(x_final_array,
                                                     roi_indices=roi_indices,
                                                     parameters_dict=x_dict))
        return x_dict
Beispiel #3
0
def _tau_to_kappa(tau):
    """Using non-linear optimization, convert the NODDI-DTI Tau variables to NODDI kappa's.

    Args:
        tau (ndarray): the list of tau's per voxel.

    Returns:
        ndarray: the list of corresponding kappa's
    """
    tau_func = SimpleCLFunction.from_string('''
        mot_float_type tau(mot_float_type kappa){
            if(kappa < 1e-12){
                return 1/3.0;
            }
            return 0.5 * ( 1 / ( sqrt(kappa) * dawson(sqrt(kappa) ) ) - 1/kappa);
        }''',
                                            dependencies=[dawson()])

    objective_func = SimpleCLFunction.from_string('''
        double tau_to_kappa(local const mot_float_type* const x, void* data, local mot_float_type* objective_list){
            return pown(tau(x[0]) - *((mot_float_type*)data), 2); 
        }
    ''',
                                                  dependencies=[tau_func])

    kappa = minimize(objective_func,
                     np.ones_like(tau),
                     data=Array(tau, 'mot_float_type')).x
    return np.clip(kappa, 0, 64)
Beispiel #4
0
 def test_model(self):
     for method in self.methods:
         output = minimize(self._objective_func, np.array([[0.3, 0.4]]), method=method,
                           nmr_observations=self._nmr_observations)
         v = output['x']
         for ind in range(2):
             self.assertAlmostEqual(v[0, ind], 0.2578, places=3, msg=method)
Beispiel #5
0
 def test_model(self):
     for method, options in self.methods.items():
         output = minimize(self._objective_func, np.array([[3] * 5]), method=method,
                           nmr_observations=self._nmr_observations, options=options)
         v = output['x']
         for ind in range(2):
             self.assertAlmostEqual(v[0, ind], 1, places=3, msg=method)
Beispiel #6
0
    def _reconstruct_slice(self, slice_data, slice_index):
        nmr_timeseries = slice_data.shape[-2]
        nmr_channels = slice_data.shape[-1]

        batch = np.reshape(slice_data, (-1, nmr_timeseries, nmr_channels))

        codec = STARCOptimizationCodec(nmr_channels)

        data = Struct({'observations': Array(batch.reshape((batch.shape[0], -1))),
                       'scratch': LocalMemory('double', nmr_items=batch.shape[1] + 4)},
                      'starc_data')

        wrapper = ParameterDecodingWrapper(nmr_channels)

        result = minimize(wrapper.wrap_objective_function(get_starc_objective_func(batch), codec.get_decode_function()),
                          codec.encode(self._get_starting_weights(slice_index, batch)),
                          data=wrapper.wrap_input_data(data),
                          cl_runtime_info=self.cl_runtime_info)

        weights = codec.decode(result['x'])
        reconstruction = np.sum(batch * weights[:, None, :], axis=2)

        sos = np.sqrt(np.sum(np.abs(slice_data).astype(np.float64) ** 2, axis=-1))
        reconstruction = np.reshape(reconstruction, slice_data.shape[:-2] + (nmr_timeseries,))
        reconstruction *= (np.mean(sos, axis=2) / np.mean(reconstruction, axis=2))[:, :, None]

        return {
            'weights': np.reshape(weights, slice_data.shape[:-2] + (nmr_channels,)),
            'reconstruction': reconstruction,
        }
Beispiel #7
0
    def _process(self, roi_indices, next_indices=None):
        self._logger.info('Starting optimization')
        self._logger.info('Using MOT version {}'.format(mot.__version__))
        self._logger.info(
            'We will use a {} precision float type for the calculations.'.
            format('double' if self._cl_runtime_info.
                   double_precision else 'single'))
        for env in self._cl_runtime_info.cl_environments:
            self._logger.info('Using device \'{}\'.'.format(str(env)))
        self._logger.info('Using compile flags: {}'.format(
            self._cl_runtime_info.compile_flags))

        if self._optimizer_options:
            self._logger.info('We will use the optimizer {} '
                              'with optimizer settings {}'.format(
                                  self._method, self._optimizer_options))
        else:
            self._logger.info(
                'We will use the optimizer {} with default settings.'.format(
                    self._method))

        kernel_data_subset = self._kernel_data.get_subset(roi_indices)
        x0 = self._codec.encode(self._initial_params[roi_indices],
                                kernel_data_subset)

        results = minimize(
            self._objective_func,
            x0,
            method=self._method,
            nmr_observations=self._model.get_nmr_observations(),
            cl_runtime_info=self._cl_runtime_info,
            data=self._wrapper.wrap_input_data(kernel_data_subset),
            lower_bounds=self._get_bounds(self._lower_bounds, roi_indices),
            upper_bounds=self._get_bounds(self._upper_bounds, roi_indices),
            constraints_func=self._constraints_func,
            options=self._optimizer_options)

        self._logger.info('Finished optimization')
        self._logger.info('Starting post-processing')

        x_final_array = self._codec.decode(results['x'], kernel_data_subset)

        x_dict = split_array_to_dict(x_final_array,
                                     self._model.get_free_param_names())
        x_dict.update({'ReturnCodes': results['status']})
        x_dict.update(
            self._model.get_post_optimization_output(x_final_array,
                                                     roi_indices=roi_indices,
                                                     parameters_dict=x_dict))
        x_dict.update({
            self._used_mask_name:
            np.ones(roi_indices.shape[0], dtype=np.bool)
        })

        self._logger.info('Finished post-processing')
        self._write_output_recursive(x_dict, roi_indices)