code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
(next_id, record_data) = \ get_sdr_data_helper(self.reserve_device_sdr_repository, self._get_device_sdr_chunk, record_id, reservation_id) return sdr.SdrCommon.from_data(record_data, next_id)
def get_device_sdr(self, record_id, reservation_id=None)
Collects all data from the sensor device to get the SDR specified by record id. `record_id` the Record ID. `reservation_id=None` can be set. if None the reservation ID will be determined.
6.201234
7.363074
0.842207
reservation_id = self.reserve_device_sdr_repository() record_id = 0 while True: record = self.get_device_sdr(record_id, reservation_id) yield record if record.next_id == 0xffff: break record_id = record.next_id
def device_sdr_entries(self)
A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0xffff is returned.
4.471037
3.50269
1.276458
rsp = self.send_message_with_name('GetSensorReading', sensor_number=sensor_number, lun=lun) reading = rsp.sensor_reading if rsp.config.initial_update_in_progress: reading = None sta...
def get_sensor_reading(self, sensor_number, lun=0)
Returns the sensor reading at the assertion states for the given sensor number. `sensor_number` Returns a tuple with `raw reading`and `assertion states`.
4.891916
5.026258
0.973272
req = create_request_by_name('SetSensorThresholds') req.sensor_number = sensor_number req.lun = lun thresholds = dict(unr=unr, ucr=ucr, unc=unc, lnc=lnc, lcr=lcr, lnr=lnr) for key, value in thresholds.items(): if value is not None: setattr(r...
def set_sensor_thresholds(self, sensor_number, lun=0, unr=None, ucr=None, unc=None, lnc=None, lcr=None, lnr=None)
Set the sensor thresholds that are not 'None' `sensor_number` `unr` for upper non-recoverable `ucr` for upper critical `unc` for upper non-critical `lnc` for lower non-critical `lcr` for lower critical `lnr` for lower non-recoverable
2.71426
3.119863
0.869994
# If the size is equal to or less than 2 then all features are the same if feature_size <= 2: feature_type = 'cube' # What kind of signal is it? if feature_type == 'cube': # Preset the size of the signal signal = np.ones((feature_size, feature_size, feature_size)) el...
def _generate_feature(feature_type, feature_size, signal_magnitude, thickness=1)
Generate features corresponding to signal Generate a single feature, that can be inserted into the signal volume. A feature is a region of activation with a specific shape such as cube or ring Parameters ---------- feature_type : str What shape signal is being inserted? Options are 'c...
2.424691
2.333745
1.03897
# Set up the indexes within which to insert the signal x_idx = [int(feature_centre[0] - (feature_size / 2)) + 1, int(feature_centre[0] - (feature_size / 2) + feature_size) + 1] y_idx = [int(feature_centre[1] - (feature_size / 2)) + 1, int(feature_centre[1] - ...
def _insert_idxs(feature_centre, feature_size, dimensions)
Returns the indices of where to put the signal into the signal volume Parameters ---------- feature_centre : list, int List of coordinates for the centre location of the signal feature_size : list, int How big is the signal's diameter. dimensions : 3 length array, int Wha...
1.638613
1.581871
1.03587
# Preset the volume volume_signal = np.zeros(dimensions) feature_quantity = round(feature_coordinates.shape[0]) # If there is only one feature_size value then make sure to duplicate it # for all signals if len(feature_size) == 1: feature_size = feature_size * feature_quantity ...
def generate_signal(dimensions, feature_coordinates, feature_size, feature_type, signal_magnitude=[1], signal_constant=1, )
Generate volume containing signal Generate signal, of a specific shape in specific regions, for a single volume. This will then be convolved with the HRF across time Parameters ---------- dimensions : 1d array, ndarray What are the dimensions of the volume you wish to create feature_...
2.78498
2.619395
1.063215
# If the timing file is supplied then use this to acquire the if timing_file is not None: # Read in text file line by line with open(timing_file) as f: text = f.readlines() # Pull out file as a an array # Preset onsets = list() event_durations = list(...
def generate_stimfunction(onsets, event_durations, total_time, weights=[1], timing_file=None, temporal_resolution=100.0, )
Return the function for the timecourse events When do stimuli onset, how long for and to what extent should you resolve the fMRI time course. There are two ways to create this, either by supplying onset, duration and weight information or by supplying a timing file (in the three column format used by F...
3.405231
3.418936
0.995992
# Iterate through the stim function stim_counter = 0 event_counter = 0 while stim_counter < stimfunction.shape[0]: # Is it an event? if stimfunction[stim_counter, 0] != 0: # When did the event start? event_onset = str(stim_counter / temporal_resolution) ...
def export_3_column(stimfunction, filename, temporal_resolution=100.0 )
Output a tab separated three column timing file This produces a three column tab separated text file, with the three columns representing onset time (s), event duration (s) and weight, respectively. Useful if you want to run the simulated data through FEAT analyses. In a way, this is the reverse of gen...
2.698643
2.475645
1.090077
hrf_length = 30 # How long is the HRF being created # How many seconds of the HRF will you model? hrf = [0] * int(hrf_length * temporal_resolution) # When is the peak of the two aspects of the HRF response_peak = response_delay * response_dispersion undershoot_peak = undershoot_delay * ...
def _double_gamma_hrf(response_delay=6, undershoot_delay=12, response_dispersion=0.9, undershoot_dispersion=0.9, response_scale=1, undershoot_scale=0.035, temporal_resolution=100.0, ...
Create the double gamma HRF with the timecourse evoked activity. Default values are based on Glover, 1999 and Walvaert, Durnez, Moerkerke, Verdoolaege and Rosseel, 2011 Parameters ---------- response_delay : float How many seconds until the peak of the HRF undershoot_delay : float ...
2.873739
2.85571
1.006313
# Check if it is timepoint by feature if stimfunction.shape[0] < stimfunction.shape[1]: logger.warning('Stimfunction may be the wrong shape') # How will stimfunction be resized stride = int(temporal_resolution * tr_duration) duration = int(stimfunction.shape[0] / stride) # Genera...
def convolve_hrf(stimfunction, tr_duration, hrf_type='double_gamma', scale_function=True, temporal_resolution=100.0, )
Convolve the specified hrf with the timecourse. The output of this is a downsampled convolution of the stimfunction and the HRF function. If temporal_resolution is 1 / tr_duration then the output will be the same length as stimfunction. This time course assumes that slice time correction has occurred an...
4.136591
3.367304
1.228458
# How many timecourses are there within the signal_function timepoints = signal_function.shape[0] timecourses = signal_function.shape[1] # Preset volume signal = np.zeros([volume_signal.shape[0], volume_signal.shape[ 1], volume_signal.shape[2], timepoints]) # Find all the non-zer...
def apply_signal(signal_function, volume_signal, )
Combine the signal volume with its timecourse Apply the convolution of the HRF and stimulus time course to the volume. Parameters ---------- signal_function : timepoint by timecourse array, float The timecourse of the signal over time. If there is only one column then the same tim...
3.267228
2.937279
1.112332
# Make a matrix of brain voxels by time brain_voxels = volume[mask > 0] # Take the means of each voxel over time mean_voxels = np.nanmean(brain_voxels, 1) # Detrend (second order polynomial) the voxels over time and then # calculate the standard deviation. order = 2 seq = np.lins...
def _calc_sfnr(volume, mask, )
Calculate the the SFNR of a volume Calculates the Signal to Fluctuation Noise Ratio, the mean divided by the detrended standard deviation of each brain voxel. Based on Friedman and Glover, 2006 Parameters ---------- volume : 4d array, float Take a volume time series mask : 3d arra...
2.84231
2.73065
1.040891
# If no TR is specified then take all of them if reference_tr is None: reference_tr = list(range(volume.shape[3])) # Dilate the mask in order to ensure that non-brain voxels are far from # the brain if dilation > 0: mask_dilated = ndimage.morphology.binary_dilation(mask, ...
def _calc_snr(volume, mask, dilation=5, reference_tr=None, )
Calculate the the SNR of a volume Calculates the Signal to Noise Ratio, the mean of brain voxels divided by the standard deviation across non-brain voxels. Specify a TR value to calculate the mean and standard deviation for that TR. To calculate the standard deviation of non-brain voxels we can subtrac...
3.141186
2.915963
1.077238
# Pull out the non masked voxels if len(volume.shape) > 1: brain_timecourse = volume[mask > 0] else: # If a 1 dimensional input is supplied then reshape it to make the # timecourse brain_timecourse = volume.reshape(1, len(volume)) # Identify some brain voxels to as...
def _calc_ARMA_noise(volume, mask, auto_reg_order=1, ma_order=1, sample_num=100, )
Calculate the the ARMA noise of a volume This calculates the autoregressive and moving average noise of the volume over time by sampling brain voxels and averaging them. Parameters ---------- volume : 4d array or 1d array, float Take a volume time series to extract the middle slice from th...
2.695072
2.541565
1.060399
# Check the inputs if template.max() > 1.1: raise ValueError('Template out of range') # Create the mask if not supplied and set the mask size if mask is None: raise ValueError('Mask not supplied') # Update noise dict if it is not yet created if noise_dict is None: ...
def calc_noise(volume, mask, template, noise_dict=None, )
Calculates the noise properties of the volume supplied. This estimates what noise properties the volume has. For instance it determines the spatial smoothness, the autoregressive noise, system noise etc. Read the doc string for generate_noise to understand how these different types of noise interact. ...
3.701799
3.572894
1.036079
def noise_volume(dimensions, noise_type, ): if noise_type == 'rician': # Generate the Rician noise (has an SD of 1) noise = stats.rice.rvs(b=0, loc=0, scale=1.527, size=dimensions) elif noise_type == 'exponential': #...
def _generate_noise_system(dimensions_tr, spatial_sd, temporal_sd, spatial_noise_type='gaussian', temporal_noise_type='gaussian', )
Generate the scanner noise Generate system noise, either rician, gaussian or exponential, for the scanner. Generates a distribution with a SD of 1. If you look at the distribution of non-brain voxel intensity in modern scans you will see it is rician. However, depending on how you have calculated the S...
3.346106
3.168952
1.055903
# Make the noise to be added stimfunction_tr = stimfunction_tr != 0 if motion_noise == 'gaussian': noise = stimfunction_tr * np.random.normal(0, 1, size=stimfunction_tr.shape) elif motion_noise == 'rician': noise = stimfunction_tr ...
def _generate_noise_temporal_task(stimfunction_tr, motion_noise='gaussian', )
Generate the signal dependent noise Create noise specific to the signal, for instance there is variability in how the signal manifests on each event Parameters ---------- stimfunction_tr : 1 Dimensional array This is the timecourse of the stimuli in this experiment, each element r...
2.921078
2.702126
1.08103
# Calculate drift differently depending on the basis function if basis == 'discrete_cos': # Specify each tr in terms of its phase with the given period timepoints = np.linspace(0, trs - 1, trs) timepoints = ((timepoints * tr_duration) / period) * 2 * np.pi # Specify the ...
def _generate_noise_temporal_drift(trs, tr_duration, basis="discrete_cos", period=150, )
Generate the drift noise Create a trend (either sine or discrete_cos), of a given period and random phase, to represent the drift of the signal over time Parameters ---------- trs : int How many volumes (aka TRs) are there tr_duration : float How long in seconds is each volum...
3.830505
3.583829
1.06883
# Pull out the relevant noise parameters auto_reg_rho = noise_dict['auto_reg_rho'] ma_rho = noise_dict['ma_rho'] # Specify the order based on the number of rho supplied auto_reg_order = len(auto_reg_rho) ma_order = len(ma_rho) # This code assumes that the AR order is higher than the...
def _generate_noise_temporal_autoregression(timepoints, noise_dict, dimensions, mask, )
Generate the autoregression noise Make a slowly drifting timecourse with the given autoregression parameters. This can take in both AR and MA components Parameters ---------- timepoints : 1 Dimensional array What time points are sampled by a TR noise_dict : dict A dictionary s...
3.725561
3.600928
1.034612
resp_phase = (np.random.rand(1) * 2 * np.pi)[0] heart_phase = (np.random.rand(1) * 2 * np.pi)[0] # Find the rate for each timepoint resp_rate = (resp_freq * 2 * np.pi) heart_rate = (heart_freq * 2 * np.pi) # Calculate the radians for each variable at this # given TR resp_radians ...
def _generate_noise_temporal_phys(timepoints, resp_freq=0.2, heart_freq=1.17, )
Generate the physiological noise. Create noise representing the heart rate and respiration of the data. Default values based on Walvaert, Durnez, Moerkerke, Verdoolaege and Rosseel, 2011 Parameters ---------- timepoints : 1 Dimensional array What time points, in seconds, are sampled by...
2.778005
2.815593
0.98665
# Set up common parameters # How many TRs are there trs = len(stimfunction_tr) # What time points are sampled by a TR? timepoints = list(np.linspace(0, (trs - 1) * tr_duration, trs)) # Preset the volume noise_volume = np.zeros((dimensions[0], dimensions[1], dimensions[2], trs)) ...
def _generate_noise_temporal(stimfunction_tr, tr_duration, dimensions, template, mask, noise_dict )
Generate the temporal noise Generate the time course of the average brain voxel. To change the relative mixing of the noise components, change the sigma's specified below. Parameters ---------- stimfunction_tr : 1 Dimensional array This is the timecourse of the stimuli in this experime...
2.941174
2.801406
1.049892
# Create the default dictionary default_dict = {'task_sigma': 0, 'drift_sigma': 0, 'auto_reg_sigma': 1, 'auto_reg_rho': [0.5], 'ma_rho': [0.0], 'physiological_sigma': 0, 'sfnr': 90, 'snr': 50, 'max_activity': 1000, 'voxel_size': [1.0, 1.0, 1.0], ...
def _noise_dict_update(noise_dict)
Update the noise dictionary parameters with default values, in case any were missing Parameters ---------- noise_dict : dict A dictionary specifying the types of noise in this experiment. The noise types interact in important ways. First, all noise types ending with sigma (e.g....
5.215699
2.723454
1.915104
# Pull out information that is needed dim_tr = noise.shape base = template * noise_dict['max_activity'] base = base.reshape(dim_tr[0], dim_tr[1], dim_tr[2], 1) mean_signal = (base[mask > 0]).mean() target_snr = noise_dict['snr'] # Iterate through different parameters to fit SNR and SF...
def _fit_spatial(noise, noise_temporal, mask, template, spatial_sd, temporal_sd, noise_dict, fit_thresh, fit_delta, iterations, )
Fit the noise model to match the SNR of the data Parameters ---------- noise : multidimensional array, float Initial estimate of the noise noise_temporal : multidimensional array, float The temporal noise that was generated by _generate_temporal_noise ...
4.753002
4.643125
1.023664
if isinstance(in_dir, str): in_dir = Path(in_dir) files = sorted(in_dir.glob("*" + suffix)) for f in files: logger.debug( 'Starting to read file %s', f ) yield nib.load(str(f))
def load_images_from_dir(in_dir: Union[str, Path], suffix: str = "nii.gz", ) -> Iterable[SpatialImage]
Load images from directory. For efficiency, returns an iterator, not a sequence, so the results cannot be accessed by indexing. For every new iteration through the images, load_images_from_dir must be called again. Parameters ---------- in_dir: Path to directory. suffix: ...
3.234015
3.99266
0.80999
for image_path in image_paths: if isinstance(image_path, Path): string_path = str(image_path) else: string_path = image_path logger.debug( 'Starting to read file %s', string_path ) yield nib.load(string_path)
def load_images(image_paths: Iterable[Union[str, Path]] ) -> Iterable[SpatialImage]
Load images from paths. For efficiency, returns an iterator, not a sequence, so the results cannot be accessed by indexing. For every new iteration through the images, load_images must be called again. Parameters ---------- image_paths: Paths to images. Yields ------ ...
3.302713
3.844136
0.859156
if not isinstance(path, str): path = str(path) data = nib.load(path).get_data() if predicate is not None: mask = predicate(data) else: mask = data.astype(np.bool) return mask
def load_boolean_mask(path: Union[str, Path], predicate: Callable[[np.ndarray], np.ndarray] = None ) -> np.ndarray
Load boolean nibabel.SpatialImage mask. Parameters ---------- path Mask path. predicate Callable used to create boolean values, e.g. a threshold function ``lambda x: x > 50``. Returns ------- np.ndarray Boolean array corresponding to mask.
2.444225
2.64141
0.925348
condition_specs = np.load(str(path)) return [c.view(SingleConditionSpec) for c in condition_specs]
def load_labels(path: Union[str, Path]) -> List[SingleConditionSpec]
Load labels files. Parameters ---------- path Path of labels file. Returns ------- List[SingleConditionSpec] List of SingleConditionSpec stored in labels file.
5.61636
8.73932
0.642654
if not isinstance(path, str): path = str(path) img = Nifti1Pair(data, affine) nib.nifti1.save(img, path)
def save_as_nifti_file(data: np.ndarray, affine: np.ndarray, path: Union[str, Path]) -> None
Create a Nifti file and save it. Parameters ---------- data Brain data. affine Affine of the image, usually inherited from an existing image. path Output filename.
4.04369
4.007751
1.008967
prior = self.global_prior_[0:self.prior_size] posterior = self.global_posterior_[0:self.prior_size] diff = prior - posterior max_diff = np.max(np.fabs(diff)) if self.verbose: _, mse = self._mse_converged() diff_ratio = np.sum(diff ** 2) / np.sum(...
def _converged(self)
Check convergence based on maximum absolute difference Returns ------- converged : boolean Whether the parameter estimation converged. max_diff : float Maximum absolute difference between prior and posterior.
4.176016
3.821854
1.092668
prior = self.global_prior_[0:self.prior_size] posterior = self.global_posterior_[0:self.prior_size] mse = mean_squared_error(prior, posterior, multioutput='uniform_average') if mse > self.threshold: return False, mse else: ...
def _mse_converged(self)
Check convergence based on mean squared difference between prior and posterior Returns ------- converged : boolean Whether the parameter estimation converged. mse : float Mean squared error between prior and posterior.
4.22617
3.747982
1.127586
common = np.linalg.inv(prior_cov + global_cov_scaled) observation_mean = np.mean(new_observation, axis=1) posterior_mean = prior_cov.dot(common.dot(observation_mean)) +\ global_cov_scaled.dot(common.dot(prior_mean)) posterior_cov =\ prior_cov.dot(common.d...
def _map_update( self, prior_mean, prior_cov, global_cov_scaled, new_observation)
Maximum A Posterior (MAP) update of a parameter Parameters ---------- prior_mean : float or 1D array Prior mean of parameters. prior_cov : float or 1D array Prior variance of scalar parameter, or prior covariance of multivariate parameter g...
2.895839
2.821453
1.026365
self.global_posterior_ = self.global_prior_.copy() prior_centers = self.get_centers(self.global_prior_) prior_widths = self.get_widths(self.global_prior_) prior_centers_mean_cov = self.get_centers_mean_cov(self.global_prior_) prior_widths_mean_var = self.get_widths_mean_...
def _map_update_posterior(self)
Maximum A Posterior (MAP) update of HTFA parameters Returns ------- HTFA Returns the instance itself.
2.668922
2.71254
0.98392
gather_size = np.zeros(size).astype(int) gather_offset = np.zeros(size).astype(int) num_local_subjs = np.zeros(size).astype(int) subject_map = {} for idx, s in enumerate(np.arange(self.n_subj)): cur_rank = idx % size gather_size[cur_rank] += sel...
def _get_gather_offset(self, size)
Calculate the offset for gather result from this process Parameters ---------- size : int The total number of process. Returns ------- tuple_size : tuple_int Number of elements to send from each process (one integer for each process...
2.575628
2.321582
1.109428
weight_size = np.zeros(1).astype(int) local_weight_offset = np.zeros(n_local_subj).astype(int) for idx, subj_data in enumerate(data): if idx > 0: local_weight_offset[idx] = weight_size[0] weight_size[0] += self.K * subj_data.shape[1] retu...
def _get_weight_size(self, data, n_local_subj)
Calculate the size of weight for this process Parameters ---------- data : a list of 2D array, each in shape [n_voxel, n_tr] The fMRI data from multi-subject. n_local_subj : int Number of subjects allocated to this process. Returns ------- ...
2.59733
2.582598
1.005704
max_sample_tr = np.zeros(n_local_subj).astype(int) max_sample_voxel = np.zeros(n_local_subj).astype(int) for idx in np.arange(n_local_subj): nvoxel = data[idx].shape[0] ntr = data[idx].shape[1] max_sample_voxel[idx] =\ min(self.max_vo...
def _get_subject_info(self, n_local_subj, data)
Calculate metadata for subjects allocated to this process Parameters ---------- n_local_subj : int Number of subjects allocated to this process. data : list of 2D array. Each in shape [n_voxel, n_tr] Total number of MPI process. Returns -------...
2.435736
1.855936
1.312403
rank = self.comm.Get_rank() size = self.comm.Get_size() return rank, size
def _get_mpi_info(self)
get basic MPI info Returns ------- comm : Intracomm Returns MPI communication group rank : integer Returns the rank of this process size : integer Returns total number of processes
3.487
3.404128
1.024345
if rank == 0: idx = np.random.choice(n_local_subj, 1) self.global_prior_, self.global_centers_cov,\ self.global_widths_var = self.get_template(R[idx[0]]) self.global_centers_cov_scaled =\ self.global_centers_cov / float(self.n_subj) ...
def _init_prior_posterior(self, rank, R, n_local_subj)
set prior for this subject Parameters ---------- rank : integer The rank of this process R : list of 2D arrays, element i has shape=[n_voxel, n_dim] Each element in the list contains the scanner coordinate matrix of fMRI data of one subject. ...
3.140879
3.247086
0.967291
if use_gather: self.comm.Gather(self.local_posterior_, self.gather_posterior, root=0) else: target = [ self.gather_posterior, gather_size, gather_offset, MPI.DOUBLE] ...
def _gather_local_posterior(self, use_gather, gather_size, gather_offset)
Gather/Gatherv local posterior Parameters ---------- comm : object MPI communication group use_gather : boolean Whether to use Gather or Gatherv gather_size : 1D array The size of each local posterior gather_offset : 1D array ...
3.075828
3.287954
0.935484
prior_centers = self.get_centers(self.global_prior_) posterior_centers = self.get_centers(self.global_posterior_) posterior_widths = self.get_widths(self.global_posterior_) posterior_centers_mean_cov =\ self.get_centers_mean_cov(self.global_posterior_) poste...
def _assign_posterior(self)
assign posterior to the right prior based on Hungarian algorithm Returns ------- HTFA Returns the instance itself.
2.406347
2.386639
1.008258
if rank == 0: self._map_update_posterior() self._assign_posterior() is_converged, _ = self._converged() if is_converged: logger.info("converged at %d outer iter" % (m)) outer_converged[0] = 1 else: ...
def _update_global_posterior( self, rank, m, outer_converged)
Update global posterior and then check convergence Parameters ---------- rank : integer The rank of current process. m : integer The outer iteration number of HTFA. outer_converged : 1D array Record whether HTFA loop converged Ret...
3.946579
3.922076
1.006247
for s, subj_data in enumerate(data): base = s * self.prior_size centers = self.local_posterior_[base:base + self.K * self.n_dim]\ .reshape((self.K, self.n_dim)) start_idx = base + self.K * self.n_dim end_idx = base + self.prior_size ...
def _update_weight(self, data, R, n_local_subj, local_weight_offset)
update local weight Parameters ---------- data : list of 2D array, element i has shape=[n_voxel, n_tr] Subjects' fMRI data. R : list of 2D arrays, element i has shape=[n_voxel, n_dim] Each element in the list contains the scanner coordinate matrix o...
2.809185
2.916526
0.963196
rank, size = self._get_mpi_info() use_gather = True if self.n_subj % size == 0 else False n_local_subj = len(R) max_sample_tr, max_sample_voxel =\ self._get_subject_info(n_local_subj, data) tfa = [] # init tfa for each subject for s, subj_da...
def _fit_htfa(self, data, R)
HTFA main algorithm Parameters ---------- data : list of 2D array. Each in shape [n_voxel, n_tr] The fMRI data from multiple subjects. R : list of 2D arrays, element i has shape=[n_voxel, n_dim] Each element in the list contains the scanner coordinate matrix ...
3.604767
3.538185
1.018818
# Check data type if not isinstance(X, list): raise TypeError("Input data should be a list") if not isinstance(R, list): raise TypeError("Coordinates should be a list") # Check the number of subjects if len(X) < 1: raise ValueError("...
def _check_input(self, X, R)
Check whether input data and coordinates in right type Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. R : list of 2D arrays, element i has shape=[n_voxel, n_dim] ...
2.498643
2.040391
1.224591
self._check_input(X, R) if self.verbose: logger.info("Start to fit HTFA") self.n_dim = R[0].shape[1] self.cov_vec_size = np.sum(np.arange(self.n_dim) + 1) # centers,widths self.prior_size = self.K * (self.n_dim + 1) # centers,widths,centerCov,...
def fit(self, X, R)
Compute Hierarchical Topographical Factor Analysis Model [Manning2014-1][Manning2014-2] Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. R : list of 2D arrays, el...
5.437384
4.985377
1.090667
z = np.append(x, [min_limit, max_limit]) sigma = np.ones(x.shape) for i in range(x.size): # Calculate the nearest left neighbor of x[i] # Find the minimum of (x[i] - k) for k < x[i] xleft = z[np.argmin([(x[i] - k) if k < x[i] else np.inf for k in z])] # Calculate the n...
def get_sigma(x, min_limit=-np.inf, max_limit=np.inf)
Compute the standard deviations around the points for a 1D GMM. We take the distance from the nearest left and right neighbors for each point, then use the max as the estimate of standard deviation for the gaussian mixture around that point. Arguments --------- x : 1D array Set of poin...
2.323414
2.309467
1.006039
z = np.array(list(zip(x, y)), dtype=np.dtype([('x', float), ('y', float)])) z = np.sort(z, order='y') n = y.shape[0] g = int(np.round(np.ceil(0.15 * n))) ldata = z[0:g] gdata = z[g:n] lymin = ldata['y'].min() lymax = ldata['y'].max() weights = (lymax - ldata['y']) / (lymax - ly...
def get_next_sample(x, y, min_limit=-np.inf, max_limit=np.inf)
Get the next point to try, given the previous samples. We use [Bergstra2013]_ to compute the point that gives the largest Expected improvement (EI) in the optimization function. This model fits 2 different GMMs - one for points that have loss values in the bottom 15% and another for the rest. Then we s...
3.677039
3.493949
1.052402
for s in space: if not hasattr(space[s]['dist'], 'rvs'): raise ValueError('Unknown distribution type for variable') if 'lo' not in space[s]: space[s]['lo'] = -np.inf if 'hi' not in space[s]: space[s]['hi'] = np.inf if len(trials) > init_random_e...
def fmin(loss_fn, space, max_evals, trials, init_random_evals=30, explore_prob=0.2)
Find the minimum of function through hyper parameter optimization. Arguments --------- loss_fn : ``function(*args) -> float`` Function that takes in a dictionary and returns a real value. This is the function to be minimized. space : dictionary Custom dictionary specifying the ...
2.628677
2.578775
1.019351
def my_norm_pdf(xt, mu, sigma): z = (xt - mu) / sigma return (math.exp(-0.5 * z * z) / (math.sqrt(2. * np.pi) * sigma)) y = 0 if (x < self.min_limit): return 0 if (x > self.max_limit): return 0 for _x ...
def get_gmm_pdf(self, x)
Calculate the GMM likelihood for a single point. .. math:: y = \\sum_{i=1}^{N} w_i \\times \\text{normpdf}(x, x_i, \\sigma_i)/\\sum_{i=1}^{N} w_i :label: gmm-likelihood Arguments --------- x : float Point at which likelihood needs to be c...
3.229706
3.266456
0.988749
normalized_w = self.weights / np.sum(self.weights) get_rand_index = st.rv_discrete(values=(range(self.N), normalized_w)).rvs(size=n) samples = np.zeros(n) k = 0 j = 0 while (k < n): i = get_rand_index[j] ...
def get_samples(self, n)
Sample the GMM distribution. Arguments --------- n : int Number of samples needed Returns ------- 1D array Samples from the distribution
2.522917
2.546217
0.990849
time1 = time.time() raw_data = [] labels = [] for sid in range(len(epoch_list)): epoch = epoch_list[sid] for cond in range(epoch.shape[0]): sub_epoch = epoch[cond, :, :] for eid in range(epoch.shape[1]): r = np.sum(sub_epoch[eid, :]) ...
def _separate_epochs(activity_data, epoch_list)
create data epoch by epoch Separate data into epochs of interest specified in epoch_list and z-score them for computing correlation Parameters ---------- activity_data: list of 2D array in shape [nVoxels, nTRs] the masked activity data organized in voxel*TR formats of all subjects epoc...
3.650345
3.38662
1.077873
if seed is not None: np.random.seed(seed) np.random.shuffle(data)
def _randomize_single_subject(data, seed=None)
Randomly permute the voxels of the subject. The subject is organized as Voxel x TR, this method shuffles the voxel dimension in place. Parameters ---------- data: 2D array in shape [nVoxels, nTRs] Activity image data to be shuffled. seed: Optional[int] Seed for random state u...
2.499323
3.264773
0.765543
if random == RandomType.REPRODUCIBLE: for i in range(len(data_list)): _randomize_single_subject(data_list[i], seed=i) elif random == RandomType.UNREPRODUCIBLE: for data in data_list: _randomize_single_subject(data)
def _randomize_subject_list(data_list, random)
Randomly permute the voxels of a subject list. The method shuffles the subject one by one in place according to the random type. If RandomType.NORANDOM, return the original list. Parameters ---------- data_list: list of 2D array in shape [nVxels, nTRs] Activity image data list to be shuf...
2.546766
2.57276
0.989896
rank = comm.Get_rank() labels = [] raw_data1 = [] raw_data2 = [] if rank == 0: logger.info('start to apply masks and separate epochs') if mask2 is not None: masks = (mask1, mask2) activity_data1, activity_data2 = zip(*multimask_images(images, ...
def prepare_fcma_data(images, conditions, mask1, mask2=None, random=RandomType.NORANDOM, comm=MPI.COMM_WORLD)
Prepare data for correlation-based computation and analysis. Generate epochs of interests, then broadcast to all workers. Parameters ---------- images: Iterable[SpatialImage] Data. conditions: List[UniqueLabelConditionSpec] Condition specification. mask1: np.ndarray Mas...
2.574315
2.462748
1.045302
time1 = time.time() epoch_info = [] for sid, epoch in enumerate(epoch_list): for cond in range(epoch.shape[0]): sub_epoch = epoch[cond, :, :] for eid in range(epoch.shape[1]): r = np.sum(sub_epoch[eid, :]) if r > 0: # there is an epoch i...
def generate_epochs_info(epoch_list)
use epoch_list to generate epoch_info defined below Parameters ---------- epoch_list: list of 3D (binary) array in shape [condition, nEpochs, nTRs] Contains specification of epochs and conditions, assuming 1. all subjects have the same number of epochs; 2. len(epoch_list) equals the...
3.40467
2.927635
1.162942
activity_data = list(mask_images(images, mask, np.float32)) epoch_info = generate_epochs_info(conditions) num_epochs = len(epoch_info) (d1, _) = activity_data[0].shape processed_data = np.empty([d1, num_epochs]) labels = np.empty(num_epochs) subject_count = [0] # counting the epochs pe...
def prepare_mvpa_data(images, conditions, mask)
Prepare data for activity-based model training and prediction. Average the activity within epochs and z-scoring within subject. Parameters ---------- images: Iterable[SpatialImage] Data. conditions: List[UniqueLabelConditionSpec] Condition specification. mask: np.ndarray ...
3.008251
2.868508
1.048716
time1 = time.time() epoch_info = generate_epochs_info(conditions) num_epochs = len(epoch_info) processed_data = None logger.info( 'there are %d subjects, and in total %d epochs' % (len(conditions), num_epochs) ) labels = np.empty(num_epochs) # assign labels for i...
def prepare_searchlight_mvpa_data(images, conditions, data_type=np.float32, random=RandomType.NORANDOM)
obtain the data for activity-based voxel selection using Searchlight Average the activity within epochs and z-scoring within subject, while maintaining the 3D brain structure. In order to save memory, the data is processed subject by subject instead of reading all in before processing. Assuming all sub...
2.745694
2.533816
1.08362
symm = np.zeros((dim, dim)) symm[np.triu_indices(dim)] = tri return symm
def from_tri_2_sym(tri, dim)
convert a upper triangular matrix in 1D format to 2D symmetric matrix Parameters ---------- tri: 1D array Contains elements of upper triangular matrix dim : int The dimension of target matrix. Returns ------- symm : 2D array Symmetric matrix in shape=[di...
2.879613
2.976704
0.967383
inds = np.triu_indices_from(symm) tri = symm[inds] return tri
def from_sym_2_tri(symm)
convert a 2D symmetric matrix to an upper triangular matrix in 1D format Parameters ---------- symm : 2D array Symmetric matrix Returns ------- tri: 1D array Contains elements of upper triangular matrix
4.315015
5.306256
0.813194
max_value = data.max(axis=0) result_exp = np.exp(data - max_value) result_sum = np.sum(result_exp, axis=0) return result_sum, max_value, result_exp
def sumexp_stable(data)
Compute the sum of exponents for a list of samples Parameters ---------- data : array, shape=[features, samples] A data array containing samples. Returns ------- result_sum : array, shape=[samples,] The sum of exponents for each sample divided by the exponent of the ...
2.556153
2.134916
1.197309
# Get the indexes of the arrays in the list mask = [] for i in range(len(l)): if l[i] is not None: mask.append(i) # Concatenate them l_stacked = np.concatenate([l[i] for i in mask], axis=axis) return l_stacked
def concatenate_not_none(l, axis=0)
Construct a numpy array by stacking not-None arrays in a list Parameters ---------- data : list of arrays The list of arrays to be concatenated. Arrays have same shape in all but one dimension or are None, in which case they are ignored. axis : int, default = 0 Axis for the co...
2.966005
3.278856
0.904585
assert cov.ndim == 2, 'covariance matrix should be 2D array' inv_sd = 1 / np.sqrt(np.diag(cov)) corr = cov * inv_sd[None, :] * inv_sd[:, None] return corr
def cov2corr(cov)
Calculate the correlation matrix based on a covariance matrix Parameters ---------- cov: 2D array Returns ------- corr: 2D array correlation converted from the covarince matrix
2.802724
3.484059
0.804442
design_info = [[{'onset': [], 'duration': [], 'weight': []} for i_c in range(n_C)] for i_s in range(n_S)] # Read stimulus timing files for i_c in range(n_C): with open(stimtime_files[i_c]) as f: for line in f.readlines(): tmp = line.strip().split(...
def _read_stimtime_FSL(stimtime_files, n_C, n_S, scan_onoff)
Utility called by gen_design. It reads in one or more stimulus timing file comforming to FSL style, and return a list (size of [#run \\* #condition]) of dictionary including onsets, durations and weights of each event. Parameters ---------- stimtime_files: a string or a list of str...
1.796365
1.721491
1.043494
design_info = [[{'onset': [], 'duration': [], 'weight': []} for i_c in range(n_C)] for i_s in range(n_S)] # Read stimulus timing files for i_c in range(n_C): with open(stimtime_files[i_c]) as f: text = f.readlines() assert len(text) == n_S, \ ...
def _read_stimtime_AFNI(stimtime_files, n_C, n_S, scan_onoff)
Utility called by gen_design. It reads in one or more stimulus timing file comforming to AFNI style, and return a list (size of ``[number of runs \\* number of conditions]``) of dictionary including onsets, durations and weights of each event. Parameters ---------- stimtime_files: ...
2.215075
2.075281
1.067361
assert isinstance(interval, tuple), 'interval must be a tuple' assert len(interval) == 2, 'interval must be length two' (interval_left, interval_right) = interval assert interval_left >= 0, 'interval_left must be non-negative' assert interval_right > interval_left, \ 'interval_right mus...
def center_mass_exp(interval, scale=1.0)
Calculate the center of mass of negative exponential distribution p(x) = exp(-x / scale) / scale in the interval of (interval_left, interval_right). scale is the same scale parameter as scipy.stats.expon.pdf Parameters ---------- interval: size 2 tuple, float interval must ...
2.179888
2.075444
1.050324
try: result = len(os.sched_getaffinity(0)) except AttributeError: try: result = len(psutil.Process().cpu_affinity()) except AttributeError: result = os.cpu_count() return result
def usable_cpu_count()
Get number of CPUs usable by the current process. Takes into consideration cpusets restrictions. Returns ------- int
2.242057
2.478339
0.904661
# Check if input is 2-dimensional data_ndim = data.ndim # Get basic shape of data data, n_TRs, n_voxels, n_subjects = _check_timeseries_input(data) # Random seed to be deterministically re-randomized at each iteration if isinstance(random_state, np.random.RandomState): prng = ran...
def phase_randomize(data, voxelwise=False, random_state=None)
Randomize phase of time series across subjects For each subject, apply Fourier transform to voxel time series and then randomly shift the phase of each frequency before inverting back into the time domain. This yields time series with the same power spectrum (and thus the same autocorrelation) as the o...
2.762799
2.619904
1.054542
if side not in ('two-sided', 'left', 'right'): raise ValueError("The value for 'side' must be either " "'two-sided', 'left', or 'right', got {0}". format(side)) n_samples = len(distribution) logger.info("Assuming {0} resampling iterations".for...
def p_from_null(observed, distribution, side='two-sided', exact=False, axis=None)
Compute p-value from null distribution Returns the p-value for an observed test statistic given a null distribution. Performs either a 'two-sided' (i.e., two-tailed) test (default) or a one-sided (i.e., one-tailed) test for either the 'left' or 'right' side. For an exact test (exact=True), does not adj...
3.038612
2.607925
1.165145
# Convert list input to 3d and check shapes if type(data) == list: data_shape = data[0].shape for i, d in enumerate(data): if d.shape != data_shape: raise ValueError("All ndarrays in input list " "must be the same shape!") ...
def _check_timeseries_input(data)
Checks response time series input data (e.g., for ISC analysis) Input data should be a n_TRs by n_voxels by n_subjects ndarray (e.g., brainiak.image.MaskedMultiSubjectData) or a list where each item is a n_TRs by n_voxels ndarray for a given subject. Multiple input ndarrays must be the same shape. If a...
3.172955
2.518322
1.259948
# Accommodate array-like inputs if not isinstance(x, np.ndarray): x = np.asarray(x) if not isinstance(y, np.ndarray): y = np.asarray(y) # Check that inputs are same shape if x.shape != y.shape: raise ValueError("Input arrays must be the same shape") # Transpose i...
def array_correlation(x, y, axis=0)
Column- or row-wise Pearson correlation between two arrays Computes sample Pearson correlation between two 1D or 2D arrays (e.g., two n_TRs by n_voxels arrays). For 2D arrays, computes correlation between each corresponding column (axis=0) or row (axis=1) where axis indexes observations. If axis=0 (def...
2.497293
2.551604
0.978715
num_samples = len(X1) assert num_samples > 0, \ 'at least one sample is needed for correlation computation' num_voxels1 = X1[0].shape[1] num_voxels2 = X2[0].shape[1] assert num_voxels1 * num_voxels2 == self.num_features_, \ 'the number of features...
def _prepare_corerelation_data(self, X1, X2, start_voxel=0, num_processed_voxels=None)
Compute auto-correlation for the input data X1 and X2. it will generate the correlation between some voxels and all voxels Parameters ---------- X1: a list of numpy array in shape [num_TRs, num_voxels1] X1 contains the activity data filtered by ROIs and prepared...
2.823835
2.686363
1.051174
# normalize if necessary if norm_unit > 1: num_samples = len(corr_data) [_, d2, d3] = corr_data.shape second_dimension = d2 * d3 # this is a shallow copy normalized_corr_data = corr_data.reshape(1, ...
def _normalize_correlation_data(self, corr_data, norm_unit)
Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data in shape [num_samples, num_processed_voxels, num_voxels] norm_...
3.817143
3.566755
1.070201
kernel_matrix = np.zeros((self.num_samples_, self.num_samples_), np.float32, order='C') sr = 0 row_length = self.num_processed_voxels num_voxels2 = X2[0].shape[1] normalized_corr_data = None while ...
def _compute_kernel_matrix_in_portion(self, X1, X2)
Compute kernel matrix for sklearn.svm.SVC with precomputed kernel. The method generates the kernel matrix (similarity matrix) for sklearn.svm.SVC with precomputed kernel. It first computes the correlation from X, then normalizes the correlation if needed, and finally computes the kernel...
4.497656
3.999768
1.124479
if not (isinstance(self.clf, sklearn.svm.SVC) and self.clf.kernel == 'precomputed'): # correlation computation corr_data = self._prepare_corerelation_data(X1, X2) # normalization normalized_corr_data = self._normalize_correlation_data( ...
def _generate_training_data(self, X1, X2, num_training_samples)
Generate training data for the classifier. Compute the correlation, do the normalization if necessary, and compute the kernel matrix if the classifier is sklearn.svm.SVC with precomputed kernel. Parameters ---------- X1: a list of numpy array in shape [num_TRs, num_voxe...
3.952181
3.202556
1.234071
time1 = time.time() assert len(X) == len(y), \ 'the number of samples must be equal to the number of labels' for x in X: assert len(x) == 2, \ 'there must be two parts for each correlation computation' X1, X2 = zip(*X) if not (isin...
def fit(self, X, y, num_training_samples=None)
Use correlation data to train a model. First compute the correlation of the input data, and then normalize within subject if more than one sample in one subject, and then fit to a model defined by self.clf. Parameters ---------- X: list of tuple (data1, data2) ...
2.579479
2.394431
1.077283
time1 = time.time() if X is not None: for x in X: assert len(x) == 2, \ 'there must be two parts for each correlation computation' X1, X2 = zip(*X) num_voxels1 = X1[0].shape[1] num_voxels2 = X2[0].shape[1] ...
def predict(self, X=None)
Use a trained model to predict correlation data. first compute the correlation of the input data, and then normalize across all samples in the list if there are more than one sample, and then predict via self.clf. If X is None, use the similarity vectors produced in fit ...
2.995297
2.67913
1.118011
if X is not None and not self._is_equal_to_test_raw_data(X): for x in X: assert len(x) == 2, \ 'there must be two parts for each correlation computation' X1, X2 = zip(*X) num_voxels1 = X1[0].shape[1] num_voxels2 = X2[0]...
def decision_function(self, X=None)
Output the decision value of the prediction. if X is not equal to self.test_raw_data\\_, i.e. predict is not called, first generate the test_data after getting the test_data, get the decision value via self.clf. if X is None, test_data\\_ is ready to be used Parameters ...
3.242971
2.727743
1.188884
from sklearn.metrics import accuracy_score if isinstance(self.clf, sklearn.svm.SVC) \ and self.clf.kernel == 'precomputed' \ and self.training_data_ is None: result = accuracy_score(y, self.predict(), sample_weight=...
def score(self, X, y, sample_weight=None)
Returns the mean accuracy on the given test data and labels. NOTE: In the condition of sklearn.svm.SVC with precomputed kernel when the kernel matrix is computed portion by portion, the function will ignore the first input argument X. Parameters ---------- X: list of tu...
2.687846
2.548647
1.054617
# Standardize structure of input data if type(iscs) == list: iscs = np.array(iscs)[:, np.newaxis] elif isinstance(iscs, np.ndarray): if iscs.ndim == 1: iscs = iscs[:, np.newaxis] # Check if incoming pairwise matrix is vectorized triangle if pairwise: try:...
def _check_isc_input(iscs, pairwise=False)
Checks ISC inputs for statistical tests Input ISCs should be n_subjects (leave-one-out approach) or n_pairs (pairwise approach) by n_voxels or n_ROIs array or a 1D array (or list) of ISC values for a single voxel or ROI. This function is only intended to be used internally by other functions in thi...
4.156906
3.711121
1.120121
if isinstance(targets, np.ndarray) or isinstance(targets, list): targets, n_TRs, n_voxels, n_subjects = ( _check_timeseries_input(targets)) if data.shape[0] != n_TRs: raise ValueError("Targets array must have same number of " "TRs as input ...
def _check_targets_input(targets, data)
Checks ISFC targets input array For ISFC analysis, targets input array should either be a list of n_TRs by n_targets arrays (where each array corresponds to a subject), or an n_TRs by n_targets by n_subjects ndarray. This function also checks the shape of the targets array against the input data ar...
2.615194
1.971706
1.326361
if summary_statistic not in ('mean', 'median'): raise ValueError("Summary statistic must be 'mean' or 'median'") # Compute summary statistic if summary_statistic == 'mean': statistic = np.tanh(np.nanmean(np.arctanh(iscs), axis=axis)) elif summary_statistic == 'median': st...
def compute_summary_statistic(iscs, summary_statistic='mean', axis=None)
Computes summary statistics for ISCs Computes either the 'mean' or 'median' across a set of ISCs. In the case of the mean, ISC values are first Fisher Z transformed (arctanh), averaged, then inverse Fisher Z transformed (tanh). The implementation is based on the work in [SilverDunlap1987]_. .. [S...
2.038105
2.099186
0.970902
# Check if incoming ISFCs are square (redundant) if not type(iscs) == np.ndarray and isfcs.shape[-2] == isfcs.shape[-1]: if isfcs.ndim == 2: isfcs = isfcs[np.newaxis, ...] if isfcs.ndim == 3: iscs = np.diagonal(isfcs, axis1=1, axis2=2) isfcs = np.vstack...
def squareform_isfc(isfcs, iscs=None)
Converts square ISFCs to condensed ISFCs (and ISCs), and vice-versa If input is a 2- or 3-dimensional array of square ISFC matrices, converts this to the condensed off-diagonal ISFC values (i.e., the vectorized triangle) and the diagonal ISC values. In this case, input must be a single array of shape e...
2.459799
2.224867
1.105593
nans = np.all(np.any(np.isnan(data), axis=0), axis=1) # Check tolerate_nans input and use either mean/nanmean and exclude voxels if tolerate_nans is True: logger.info("ISC computation will tolerate all NaNs when averaging") elif type(tolerate_nans) is float: if not 0.0 <= tolera...
def _threshold_nans(data, tolerate_nans)
Thresholds data based on proportion of subjects with NaNs Takes in data and a threshold value (float between 0.0 and 1.0) determining the permissible proportion of subjects with non-NaN values. For example, if threshold=.8, any voxel where >= 80% of subjects have non-NaN values will be left unchanged, ...
3.483085
3.350809
1.039476
# Randomized sign-flips if exact_permutations: sign_flipper = np.array(exact_permutations[i]) else: sign_flipper = prng.choice([-1, 1], size=group_parameters['n_subjects'], replace=True) # If pairwise, apply si...
def _permute_one_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', group_matrix=None, exact_permutations=None, prng=None)
Applies one-sample permutations to ISC data Input ISCs should be n_subjects (leave-one-out approach) or n_pairs (pairwise approach) by n_voxels or n_ROIs array. This function is only intended to be used internally by the permutation_isc function in this module. Parameters ---------- iscs :...
3.816636
3.538696
1.078543
# Shuffle the group assignments if exact_permutations: group_shuffler = np.array(exact_permutations[i]) elif not exact_permutations and pairwise: group_shuffler = prng.permutation(np.arange( len(np.array(group_parameters['group_assignment'])[ gr...
def _permute_two_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', exact_permutations=None, prng=None)
Applies two-sample permutations to ISC data Input ISCs should be n_subjects (leave-one-out approach) or n_pairs (pairwise approach) by n_voxels or n_ROIs array. This function is only intended to be used internally by the permutation_isc function in this module. Parameters ---------- iscs :...
3.456305
3.305428
1.045645
centers, widths = self.init_centers_widths(R) # update prior prior = np.zeros(self.K * (self.n_dim + 1)) self.set_centers(prior, centers) self.set_widths(prior, widths) self.set_prior(prior) return self
def init_prior(self, R)
initialize prior for the subject Returns ------- TFA Returns the instance itself.
3.718247
4.119807
0.902529
prior_centers = self.get_centers(self.local_prior) posterior_centers = self.get_centers(self.local_posterior_) posterior_widths = self.get_widths(self.local_posterior_) # linear assignment on centers cost = distance.cdist(prior_centers, posterior_centers, 'euclidean') ...
def _assign_posterior(self)
assign posterior to prior based on Hungarian algorithm Returns ------- TFA Returns the instance itself.
3.082649
3.0211
1.020373
diff = self.local_prior - self.local_posterior_ max_diff = np.max(np.fabs(diff)) if self.verbose: _, mse = self._mse_converged() diff_ratio = np.sum(diff ** 2) / np.sum(self.local_posterior_ ** 2) logger.info( 'tfa prior posterior max ...
def _converged(self)
Check convergence based on maximum absolute difference Returns ------- converged : boolean Whether the parameter estimation converged. max_diff : float Maximum absolute difference between prior and posterior.
4.388306
4.150525
1.05729
mse = mean_squared_error(self.local_prior, self.local_posterior_, multioutput='uniform_average') if mse > self.threshold: return False, mse else: return True, mse
def _mse_converged(self)
Check convergence based on mean squared error Returns ------- converged : boolean Whether the parameter estimation converged. mse : float Mean squared error between prior and posterior.
5.512938
5.276675
1.044775
nfield = 4 self.map_offset = np.zeros(nfield).astype(int) field_size = self.K * np.array([self.n_dim, 1, self.cov_vec_size, 1]) for i in np.arange(nfield - 1) + 1: self.map_offset[i] = self.map_offset[i - 1] + field_size[i - 1] return self.map_offset
def get_map_offset(self)
Compute offset of prior/posterior Returns ------- map_offest : 1D array The offset to different fields in prior/posterior
3.702704
3.499565
1.058047
kmeans = KMeans( init='k-means++', n_clusters=self.K, n_init=10, random_state=100) kmeans.fit(R) centers = kmeans.cluster_centers_ widths = self._get_max_sigma(R) * np.ones((self.K, 1)) return centers, widths
def init_centers_widths(self, R)
Initialize prior of centers and widths Returns ------- centers : 2D array, with shape [K, n_dim] Prior of factors' centers. widths : 1D array, with shape [K, 1] Prior of factors' widths.
2.701229
2.69337
1.002918
centers, widths = self.init_centers_widths(R) template_prior =\ np.zeros(self.K * (self.n_dim + 2 + self.cov_vec_size)) # template centers cov and widths var are const template_centers_cov = np.cov(R.T) * math.pow(self.K, -2 / 3.0) template_widths_var = self...
def get_template(self, R)
Compute a template on latent factors Parameters ---------- R : 2D array, in format [n_voxel, n_dim] The scanner coordinate matrix of one subject's fMRI data Returns ------- template_prior : 1D array The template prior. template_centers_c...
4.319592
3.525313
1.225307
estimation[self.map_offset[1]:self.map_offset[2]] = widths.ravel()
def set_widths(self, estimation, widths)
Set estimation on widths Parameters ---------- estimation : 1D arrary Either prior of posterior estimation widths : 2D array, in shape [K, 1] Estimation on widths
10.443479
13.580494
0.769006
estimation[self.map_offset[2]:self.map_offset[3]] =\ centers_mean_cov.ravel()
def set_centers_mean_cov(self, estimation, centers_mean_cov)
Set estimation on centers Parameters ---------- estimation : 1D arrary Either prior of posterior estimation centers : 2D array, in shape [K, n_dim] Estimation on centers
7.739701
10.409026
0.743557
centers = estimation[0:self.map_offset[1]]\ .reshape(self.K, self.n_dim) return centers
def get_centers(self, estimation)
Get estimation on centers Parameters ---------- estimation : 1D arrary Either prior of posterior estimation Returns ------- centers : 2D array, in shape [K, n_dim] Estimation on centers
10.570568
10.239848
1.032297
widths = estimation[self.map_offset[1]:self.map_offset[2]]\ .reshape(self.K, 1) return widths
def get_widths(self, estimation)
Get estimation on widths Parameters ---------- estimation : 1D arrary Either prior of posterior estimation Returns ------- fields : 2D array, in shape [K, 1] Estimation of widths
8.092838
7.467132
1.083795
centers_mean_cov = estimation[self.map_offset[2]:self.map_offset[3]]\ .reshape(self.K, self.cov_vec_size) return centers_mean_cov
def get_centers_mean_cov(self, estimation)
Get estimation on the covariance of centers' mean Parameters ---------- estimation : 1D arrary Either prior of posterior estimation Returns ------- centers_mean_cov : 2D array, in shape [K, cov_vec_size] Estimation of the covariance of center...
5.601971
4.326104
1.294923
widths_mean_var = \ estimation[self.map_offset[3]:].reshape(self.K, 1) return widths_mean_var
def get_widths_mean_var(self, estimation)
Get estimation on the variance of widths' mean Parameters ---------- estimation : 1D arrary Either prior of posterior estimation Returns ------- widths_mean_var : 2D array, in shape [K, 1] Estimation on variance of widths' mean
8.575161
8.132083
1.054485
F = np.zeros((len(inds[0]), self.K)) tfa_extension.factor( F, centers, widths, unique_R[0], unique_R[1], unique_R[2], inds[0], inds[1], inds[2]) return F
def get_factors(self, unique_R, inds, centers, widths)
Calculate factors based on centers and widths Parameters ---------- unique_R : a list of array, Each element contains unique value in one dimension of scanner coordinate matrix R. inds : a list of array, Each element contains the indices to reconstr...
3.65668
3.676572
0.994589
beta = np.var(data) trans_F = F.T.copy() W = np.zeros((self.K, data.shape[1])) if self.weight_method == 'rr': W = np.linalg.solve(trans_F.dot(F) + beta * np.identity(self.K), trans_F.dot(data)) else: W = np.linalg....
def get_weights(self, data, F)
Calculate weight matrix based on fMRI data and factors Parameters ---------- data : 2D array, with shape [n_voxel, n_tr] fMRI data from one subject F : 2D array, with shape [n_voxel,self.K] The latent factors from fMRI data. Returns ------- ...
2.956526
3.119288
0.947821