Brainload API Documentation
Brainload high-level API functions.
- brainload.annot(subject_id, subjects_dir, annotation, hemi='both', meta_data=None, orig_ids=False)
Load annotation for the mesh vertices of a single subject.
An annotation defines a label string and a color to each vertex, it is typically used to define brain regions, e.g., for cortical parcellation. An annotation consists of several groups of vertices, each of which is assigned a label and a color.
- Parameters:
subject_id (string) – The subject identifier.
subject_dir (string) – A string representing the path to the subjects dir.
annotation (string) – An annotation to load, part of the file name of the respective file in the subjects label directory. E.g., ‘aparc’, ‘aparc.a2009s’, or ‘aparc.DKTatlas’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
orig_ids (boolean, optional) – Passed on to nibabel.freesurfer.io.read_annot function. From the documentation of that function: ‘Whether to return the vertex ids as stored in the annotation file or the positional colortable ids. With orig_ids=False vertices with no id have an id set to -1.’ Defaults to False.
- Returns:
vertex_labels (ndarray, shape (n_vertices,)) – If orig_ids is False (the default), returns the index (for each vertex) into the label_colors and label_names datastructures to retrieve the color and name. If some vertex has no annotation, -1 is returned for it.
If orig_ids is True, returns an annotation color id for each vertex listed in the annotation file. IMPORTANT: The annotation value in here is NOT the label id. It is a code based on the color for the vertex. Yes, this is ugly. See https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles#Annotation for details, especially the section ‘Annotation file design surprise’. The color is encoded as a single number. Quoting the linked document, the numer is the ‘RGB value combined into a single 32-bit integer: annotation value = (B * 256^2) + (G * 256) + (R)’. From this it follows that, quoting the doc once more, ‘Code that loads an annotation file … has to compare annotation values to the color values in the ColorLUT part of the annotation file to discover what parcellation label code (ie: structure code) corresponds.’ (Basically this has already been done for you if you simply set orig_ids to False.)
label_colors (ndarray, shape (n_labels, 5)) – RGBT + label id colortable array. The first 4 values encode the label color: RGB is red, green, blue as usual, from 0 to 255 per value. T is the transparency, which is defined as 255 - alpha. The last value represents the label id. The number of labels (n_label) cannot be know in advance by this function in the general case (but the user can know based on the Atlas he is loading, e.g., the Desikan-Killiany Atlas has 36 labels).
label_names (list of strings) – The names of the labels. The length of the list is n_labels. Note that, contrary to the respective nibabel function, this function will always return this as a list of strings, no matter the Python version used.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.annotation_file : the file that was loaded
Examples
Load cortical parcellation annotations for both hemispheres of a subject from the Desikan-Killiany (‘aparc’) atlas:
>>> import brainload as bl; import os >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc', hemi='both') >>> print meta_data['lh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.annot >>> print meta_data['rh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/rh.aparc.annot
Now load cortical parcellation annotations for the left hemisphere of a subject from the Destrieux (‘aparc.a2009s’) atlas:
>>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc.a2009s', hemi='lh') >>> print meta_data['lh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.a2009s.annot
Now load cortical parcellation annotations for the right hemisphere of a subject from the DKT (‘aparc.DKTatlas40’) atlas:
>>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc.DKTatlas40', hemi='rh') >>> print meta_data['rh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.DKTatlas40.annot
Print the color and the annotation name for an example vertex:
>>> vert_idx = 0 # We'll take the first vertex as an example. >>> if vertex_labels[vert_idx] >= 0: # it is -1 if the vertex is not assigned any label/color >>> i = vertex_labels[vert_idx] >>> print "label for vertex %d is %s" % (vert_idx, label_names[i]) >>> print "color for vertex %d in RGBA is (%d %d %d %d)" % (vert_idx, label_colors[idx, 0], label_colors[idx, 1], label_colors[idx, 2], (255 - label_colors[idx, 3]))
References
Atlas information is available at https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation
- brainload.detect_subjects_in_directory(subjects_dir, ignore_dir_names=None, required_subdirs_for_hits=None)
Search for directories containing FreeSurfer output in a directory and return the subject names.
Given a directory, search its sub directories for FreeSurfer data and return the directory names of all directories in which such data was found. The resulting list can be used to create a subjects.txt file. This method searches all direct sub directories of the given subjects_dir for the existance of the typical FreeSurfer output directory structure.
- Parameters:
subjects_dir (string) – Path to a subjects directory.
ignore_dir_names (list of strings | None, optional) – A list of directory names that should be ignored, even if they have the required sub directories. This is useful if you do not want to load certain subjects. It is often used to avoid loading the average subject ‘fsaverage’. Defaults to a list with the single element ‘fsaverage’. You can explicitely pass an empty list if you want to include all subjects.
required_subdirs_for_hits (list of strings | None) – A sub directory of the given subjects_dir is considered a subject if it contains the typical FreeSurfer directory structure. Which sub directories are required is determined by this argument. If all of them are found under a dir, that dir is added tp the output list. This list defaults to a list with the single element ‘surf’. If that leads to false positives in your case, you could pass something like [‘surf’, ‘mri’, ‘label’].
- Returns:
A list of the subject identifiers (or directories that were considered as such).
- Return type:
list of strings
Examples
Guess which directories under the current SUBJECTS_DIR contain subject data:
>>> import brainload.nitools as nit >>> import os >>> my_subject_dir = os.getenv('SUBJECTS_DIR') >>> subjects_ids = nit.detect_subjects_in_directory(my_subject_dir, ignore_dir_names=['fsaverage', 'Copy of subject4'])
- brainload.export_mesh_nocolor_to_file(filename, vertex_coords, faces)
- brainload.fsaverage_mesh(subject_id='fsaverage', surf='white', hemi='both', subjects_dir=None, use_freesurfer_home_if_missing=True)
Load a surface mesh of the fsaverage subject.
Convenience function to load a FreeSurfer surface mesh of the fsaverage subject. Use the subject_mesh function to load the mesh of any other subject.
- Parameters:
subject_id (string, optional) – The subject identifier of the subject. Defaults to ‘fsaverage’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
use_freesurfer_home_if_missing (boolean, optional) – If set to True, first checks whether the directory for the given subject exists in the subjects_dir. If it does not, it will reset the subjects_dir to ‘${FREESURFER_HOME}/subjects’ before proceeding.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> verts, faced, meta_data = bl.fsaverage_mesh()
- brainload.group(measure, surf='white', hemi='both', fwhm='10', subjects_dir=None, average_subject='fsaverage', group_meta_data=None, subjects_list=None, subjects_file='subjects.txt', subjects_file_dir=None, custom_morphometry_file_templates=None, subjects_detection_mode='auto')
Load standard space morphometry data for a number of subjects.
Load group data, i.e., morphometry data for all subjects in a study that has already been mapped to standard space and is ready for group analysis. The information given in the parameters measure, surf, hemi, and fwhm are used to construct the file name that will be loaded by default. This function will NOT load the meshes.
- Parameters:
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Data files for this measure have to exist for all subjects.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
fwhm (string or None, optional) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. Defaults to ‘10’. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string, optional) – A string representing the full path to a directory. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
group_meta_data (dictionary, optional) – A dictionary that should be merged into the return value group_meta_data. Defaults to the empty dictionary if omitted.
subjects_list (list of strings, optional (unless subjects_detection_mode is set to list)) – A list of subject identifiers or directory names that should be loaded from the subjects_dir. Example list: [‘subject1’, ‘subject2’]. Defaults to None. Only allowed if subjects_detection_mode is auto or list. In auto mode, this takes precedence over all other options, i.e., if a subjects_list and the (default or custom) subjects_file are given, the subjects_list will be used.
subjects_file_dir (string, optional) – A string representing the full path to a directory. This directory must contain the subjects_file (see below). Defaults to the subjects_dir.
subjects_file (string, optional) – The name of the subjects file, relative to the subjects_file_dir. Defaults to ‘subjects.txt’. The file must be a simple text file that contains one subject_id per line. It can be a CSV file that has other data following, but the subject_id has to be the first item on each line and the separator must be a comma. So a line is allowed to look like this: subject1, 35, center1, 147. No header is allowed. If you have a different format, consider reading the file yourself and pass the result as subjects_list instead.
custom_morphometry_file_templates (dictionary, optional) –
- Cutom filenames for the left and right hemisphere data files that should be loaded. A dictionary of strings with exactly the following two keys: lh and rh. The value strings can contain hardcoded file names or template strings for them. As always, the files will be loaded relative to the surf/ directory of the respective subject. Example for hard-coded files: {‘lh’: ‘lefthemi.nonstandard.mymeasure44.mgh’, ‘rh’: ‘righthemi.nonstandard.mymeasure44.mgh’}. The strings may contain any of the following variabes, which will be replaced by what you supplied to the other arguments of this function:
${MEASURE} will be replaced with the value of measure.
${SURF} will be replaced with the FreeSurfer file name part for the surface surf. This is the empty string if surf is ‘white’, and a dot followed by the value of surf for all other settings of surf. Examples: when surf is ‘pial’, this will be replaced with ‘.pial’ (Note the dot!). If surf is ‘white’, this will be replaced with the empty string.
${SURF_RAW} will be replaced with the value of surf.
${HEMI} will be replaced with ‘lh’ for the left hemisphere, and with ‘rh’ for the right hemisphere.
${FWHM} will be replaced with the value of fwhm, so something like ‘10’.
${SUBJECT_ID} will be replaced by the id of the subject that is being loaded, e.g., ‘subject3’.
${AVERAGE_SUBJECT} will be replaced by the value of average_subject.
Note that only ${SURF} and ${HEMI} are usually needed, everything else can be hardcoded (or is not part of typical FreeSurfer file names at all, like ${SUBJECT_ID}). Example template string: subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh. Complete example for template strings in dictionary: {‘lh’: ‘subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh’, ‘rh’: ‘subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh’}.
subjects_detection_mode ({'auto', 'list', 'file', 'search_dir'}, optional) –
- The method used to determine the subjects that should be loaded. Defaults to ‘auto’. You can always see which mode was used by looking at the returned run_meta_data, see run_meta_data[‘subjects_detection_mode’].
’auto’: In this mode, all available methods will be tried in the following order: If a subjects_list is given, it is used. Then, the subjects_file is used if it exists. Note that this may be the default file, ‘$SUBJECTS_DIR/subject_surf_dir.txt’, or another if one has explicitely been defined by setting subjects_file and/or subjects_file_dir. If the file does not exist, the directory is searched for directories containing FreeSurfer data as defined in the section for ‘search_dir’ mode below. You can always see which method was used in auto mode by looking at the returned run_meta_data, see run_meta_data[‘subjects_detection_mode_auto_used_method’].
’list’: In this mode, the given subjects_list is used, and you have to supply one. If not, an error is raised. You are not allowed to supply a subjects_file in this mode, or an error will be raised.
’file’: In this mode, the subjects file is used. Note that this may be the default file, ‘$SUBJECTS_DIR/subjects.txt’, or another if one has explicitely been defined by setting subjects_file and/or subjects_file_dir. If the file does not exist, an error is raised. You can see which file was used by looking at the returned run_meta_data, see run_meta_data[‘subjects_file’]. You are not allowed to supply a subjects_list in this mode, or an error will be raised.
’search_dir’: In this mode, the subjects_dir (default or explicitely given) is searched for sub directories which look as if they could contain FreeSurfer data. The latter means that they contain a sub directory named ‘surf’. There is one exception though: if the name of one such directory equals the name of the average_subject, the directory is skipped. You are not allowed to supply a subjects_list in this mode, or an error will be raised.
- Returns:
group_morphometry_data (numpy array) – An array filled with the morphometry data for the subjects. The array has shape (n, m) where n is the number of subjects, and m is the number of vertices of the standard subject. (If you load both hemispheres instead of one, m doubles.) To get the subject id for the entries, look at the respective index in the returned subjects_list.
subjects_list (list of strings) – A list containing the subject identifiers in the same order as the data in group_morphometry_data. (If subjects_detection_mode is ‘list’ or ‘file’, the order in these is guaranteed to be preserved. But in mode ‘search_dir’ or ‘auto’ which may have chosen to fall back to ‘search_dir’ as a last resort, this is helpful: You can use the index of a subject in this list to find its data in group_morphometry_data, as it will have the same index. See the examples below.)
group_meta_data (dictionary) – A dictionary containing detailed information on all subjects and files that were loaded. Each of its keys is a subject identifier. The data value is another dictionary that contains all meta data for this subject as returned by the subject_avg function.
run_meta_data (dictionary) – A dictionary containing general information on the settings used when executing the function and determining which subjects to load.
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for all subjects in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> data, subjects, group_md, run_md = bl.group('area')
Here, we load curv data for the right hemisphere, computed on the pial surface with smooting of 20:
>>> data, subjects, group_md, run_md = bl.group('curv', hemi='rh', surf='pial', fwhm='20')
We may want to be a but more explicit on which subjects are loaded from where:
>>> import os >>> import brainload as bl >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> subjects_list = ['subject1', 'subject4', 'subject8'] >>> data, subjects, group_md, run_md = bl.group('curv', fwhm='20', subjects_dir=subjects_dir, subjects_list=subjects_list)
Continuing the last example, we may want to have a look at the curv value of the vertex at index 100000 of the subject ‘subject4’:
>>> subject4_idx = subjects.index('subject4') >>> print data[subject4_idx][100000]
- brainload.group_native(measure, subjects_dir, subjects_list, surf='white', hemi='both')
Load native space morphometry data for a number of subjects.
Load native space group data, i.e., morphometry data for all subjects in a study. The information given in the parameters measure, surf, and hemi are used to construct the file name that will be loaded by default. This function will NOT load the meshes.
- Parameters:
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Data files for this measure have to exist for all subjects.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. Defaults to ‘white’. Will be added after the measure name unless left at default.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
subjects_list (list of strings, optional (unless subjects_detection_mode is set to list)) – A list of subject identifiers or directory names that should be loaded from the subjects_dir. Example list: [‘subject1’, ‘subject2’]. Defaults to None. Only allowed if subjects_detection_mode is auto or list. In auto mode, this takes precedence over all other options, i.e., if a subjects_list and the (default or custom) subjects_file are given, the subjects_list will be used.
- Returns:
morphdata_by_subject (dictionary) – A dictionary containing the morphometry data. Keys are subject identifiers, and values are the morphometry data numpy 1D arrays.
metadata_by_subject (dictionary) – A dictionary containing detailed information on all subjects and files that were loaded. Each of its keys is a subject identifier. The data value is another dictionary that contains all meta data for this subject.
- brainload.hemi_range(morphometry_meta_data, hemi)
Compute start and end index in the hemisphere data for the given hemisphere.
- Parameters:
morphometry_meta_data (dictionary as returned by the functions that read morphometry data (e.g.,
`subject_data_native`).)hemi (string, one of 'lh' or 'rh'. The hemisphere you want to get the start and end index for.)
- Returns:
start_index (integer) – The start index of the lh data.
end_index (integer) – The end index of the lh data.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject_data_native('subject1', '/mnt/study1_data', 'thickness', 'both') >>> s, e = bl.hemi_range(meta_data, 'lh') >>> print("Mean lh thickness value is: %f" % (np.mean(morphometry_data[s:e])))
- brainload.label(subject_id, subjects_dir, label, hemi='both', meta_data=None)
Load annotation for the mesh vertices of a single subject.
An annotation defines a label string and a color to each vertex, it is typically used to define brain regions, e.g., for cortical parcellation.
- Parameters:
subject_id (string) – The subject identifier.
subject_dir (string) – A string representing the path to the subjects dir.
label (string) – A label to load, part of the file name of the respective file in the subjects label directory. E.g., ‘cortex’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
meta_data (dictionary | None, optional if hemi is 'lh' or 'rh') – Meta data to merge into the output meta_data. Defaults to the empty dictionary. If ‘hemi’ is ‘both’, this dictionary is required and MUST contain at least one of the keys ‘lh.num_vertices’ or ‘lh.num_data_points’, the value of which must contain the number of vertices of the left hemisphere of the subject. Background: If hemi is ‘both’, the vertex indices of both hemispheres are merged in the return value verts_in_label, and thus we need to know the shift, i.e., the number of vertices in the left hemisphere.
- Returns:
verts_in_label (ndarray, shape (n_vertices,)) – Contains the ids of all vertices included in the label.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.label_file : the file that was loaded
Examples
Load the cortex label for the left hemisphere of a subject:
>>> import brainload as bl; import os >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> verts_in_label, meta_data = bl.label('subject1', subjects_dir, 'cortex', hemi='lh') >>> print meta_data['lh.label_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.cortex.label
You could now use the label information to mask your morphology data.
See also
mask_data_using_labelMask data using a label.
- brainload.mesh_to_obj(vertex_coords, faces)
Write an OBJ format string of a mesh.
Write an OBJ PLY format string of a mesh. The format is the Wavefront object format, see https://en.wikipedia.org/wiki/Wavefront_.obj_file for details. This exporter only writes the geometry, vertex colors are not a standard OBJ feature and are not included. Use mesh_to_ply to get vertex colors.
- Parameters:
vertex_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices.
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
- Returns:
The OBJ format string for the mesh.
- Return type:
string
- brainload.mesh_to_ply(vertex_coords, faces, vertex_colors=None)
Write a PLY format string of a mesh.
Write a PLY format string of a mesh. See http://paulbourke.net/dataformats/ply/ for details on the format.
- Parameters:
vertex_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices.
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
vertex_colors (numpy array or None, optional) – A 2D array with shape (n, 4) assigning a color to each vertex (for the n vertices in vertex_coords). The 4 values in each column define the 4 channels of an RGBA color. Channel values should be given as integers in range 0..255. If omitted, no vertex colors will be included in the PLY format string.
- Returns:
The PLY format string for the mesh.
- Return type:
string
- brainload.read_subjects_file(subjects_file, has_header_line=False, index_of_subject_id_field=0, **kwargs)
Read a subjects file in CSV format that has the subject id as the first entry on each line. Arbitrary data may follow in the consecutive fields on each line, and will be ignored. Having nothing but the subject id on the line is also fine, of course.
The file can be a simple text file that contains one subject_id per line. It can also be a CSV file that has other data following, but the subject_id has to be the first item on each line and the separator must be a comma. So a line is allowed to look like this: subject1, 35, center1, 147. No header is allowed. If you have a different format, consider reading the file yourself and pass the result as subjects_list instead.
- Parameters:
subjects_file (string) – Path to a subjects file (see above for format details).
has_header_line (boolean, optional) – Whether the first line is a header line and should be skipped. Defaults to ‘False’.
index_of_subject_id_field (integer, optional) – The column index of the field that contains the subject id in each row. Defaults to ‘0’. Changing this only makes sense for CSV files.
**kwargs (any) – Any other named arguments will be passed on to the call to the call to the csv.reader constructor. That is a class from Python’s standard csv module. Example: pass delimiter=’ ‘ if your CSV file is limited by tabs.
- Returns:
A list of subject identifiers.
- Return type:
list of strings
Examples
Load a list of subjects from a simple text file that contains one subject per line.
>>> import brainload.nitools as nit >>> subjects_ids = nit.read_subjects_file('/home/myuser/data/study5/subjects.txt')
- brainload.rhi(rh_relative_index, meta_data)
Computes the absolute data index given an index relative to the right hemisphere.
This function makes sense only given a morphometry_data and associated meta_data that contains data on two hemispheres (even though the morphometry_data array itself is not passed to this function). E.g., the return value of a function like subject() or subject_avg() when called with hemi=’both’. For such data, it computes the absolute index in the data given a request index relative to the right hemisphere. The name is short for ‘right hemisphere index’.
- Parameters:
rh_relative_index (int) – An index relative to the right hemisphere. E.g., 0 if you want to get the index of the first vertex of the right hemisphere. Its absolute value must be between 0 and the number of vertices of the right hemisphere. Negative values are allowed, and -1 will get you the second-to-last possible index, -2 the third-to-last, and so on.
meta_data (dictionary) – The meta data dictionary returned for your data. It must contain the keys ‘lh.num_data_points’ and ‘rh.num_data_points’.
- Return type:
The absolute index into the data for the given rh_relative_index.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject('heinz', hemi='both')[2:4] >>> print "rh value at index 10, relative to start of right hemisphere: %d." % morphometry_data[bl.rhi(10, meta_data)]
- brainload.rhv(rh_relative_index, morphometry_data, meta_data)
Returns the value in morphometry_data at an index relative to the right hemisphere.
This function makes sense only given a morphometry_data and associated meta_data that contains data on two hemispheres. E.g., the return value of a function like subject() or subject_avg() when called with hemi=’both’. For such data, it returns the value in morphometry_data at a request index given relative to the right hemisphere. The name is short for ‘right hemisphere value’.
- Parameters:
rh_relative_index (int) – An index relative to the start of the right hemisphere in the data. E.g., 0 if you want to get the value for the first vertex of the right hemisphere. Its absolute value must be between 0 and the number of vertices of the right hemisphere. Negative values are allowed, and -1 will get you the last possible value, -2 the second-to-last, and so on.
morphometry_data (numpy array) – The morphometry data array, must represent data for both hemispheres.
meta_data (dictionary) – The meta data dictionary returned for your data. It must contain the keys ‘lh.num_data_points’ and ‘rh.num_data_points’.
- Return type:
The value at the given index that is relative to the start of the right hemisphere in the data.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject('heinz', hemi='both')[2:4] >>> print "rh value at index 10, relative to start of right hemisphere: %d." % bl.rhv(10, morphometry_data, meta_data)
- brainload.stat(file_name)
Read information from a FreeSurfer stats file.
Read information from a FreeSurfer stats file, e.g., subject/stats/lh.aparc.stats or aseg.stats. A stats file is a text file that contains a data table and various meta data.
- Parameters:
file_name (string) – The path to the stats file.
- Returns:
- The result dictionary, containing the following 4 keys:
’ignored_lines’: list of strings. The list of lines that were not parsed in a special way. This is raw data.
’measures’: string list of dimension (n, m) if there are n measures with m properties each stored in the stats file.
’table_data’: string list of dimension (i, j) when there are i lines containing j values each in the table stored in the stats file. You may want to convert the columns to the proper data types and put the result into several numpy arrays or a single Pandas data frame.
’table_column_headers’: string list. The names for the columns for the table_data. This information is parsed from the table_meta_data and given here for convenience.
’table_meta_data’: dictionary. The full table_meta_data. Stores properties in key, value sub dictionaries. For simple table properties, the dictionaries are keys of the returned dictionary. The only exception is the information on the table columns (header data). This information can be found under the key column_info_, which contains one dictionary for each column. In these dictionaries, data is stored as explained for simple table properties.
- Return type:
dictionary of strings (includes nested sub dicts)
Examples
Read the aseg.stats file for a subject:
>>> import brainload as bl >>> stats = bl.stat('/path/to/study/subject1/stats/aseg.stats')
Collect some data, just to show the data structures.
>>> print(len(stats['measures'])) # Will print the number of measures. >>> print("|".join(stats['measures'][0])) # Print all data on the first measure.
Now lets print the table_data:
>>> num_data_rows = len(stats['table_data']) >>> num_entries_per_row = len(stats['table_data'][0])
And get some information on the table columns (the table header):
>>> print stats['table_meta_data']['NTableCols'] # will print "10" (from a simple table property stored directly in the dictionary).
Get the names of all the data columns:
>>> print ",".join(stats['table_column_headers'])
Get the name of the first column:
>>> first_column_name = stats['table_column_headers'][0]
More detailed information on the individual columns can be found under the special column_info_ key if needed:
>>> column2_info_dict = stats['table_meta_data']['column_info_']['2'] >>> print(column2_info_dict['some_key']) # will print the value
Note that all data is returned as string type, you will need to covert it to float (or whatever) yourself.
- brainload.subject(subject_id, surf='white', measure='area', hemi='both', subjects_dir=None, meta_data=None, load_surface_files=True, load_morphometry_data=True)
Load FreeSurfer brain morphometry and/or mesh data for a single subject.
High-level interface to load FreeSurfer brain data for a single space. This parses the data for the surfaces of this subject. If you want to load data that has been mapped to an average subject like ‘fsaverage’, use subject_avg instead.
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string, optional) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
meta_data (dictionary, optional) – A dictionary that should be merged into the return value meta_data. Defaults to the empty dictionary if omitted.
load_surface_files (boolean, optional) – Whether to load mesh data. If set to False, the first return values vert_coords and faces will be None. Defaults to True.
load_morphometry_data (boolean, optional) – Whether to load morphometry data. If set to False, the first return value morphometry_data will be None. Defaults to True.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘subject’. This means that the data loaded represent morphometry data taken from the subject’s surface (as opposed to data mapped to a common or average subject).
hemi : the hemi value that was used
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> vertices, faces, data, md = bl.subject('subject1')
Here, we are a bit more explicit about what we want to load:
>>> import os >>> user_home = os.getenv('HOME') >>> subjects_dir = os.path.join(user_home, 'data', 'my_study_x') >>> vertices, faces, data, md = bl.subject('subject1', hemi='lh', measure='curv', subjects_dir=subjects_dir)
Sometimes we do not care for the mesh, e.g., we only want the morphometry data:
>>> data, md = bl.subject('subject1', hemi='rh', load_surface_files=False)[2:4]
…or the other way around (mesh only, no morphometry data):
>>> vertices, faces = bl.subject('subject1', hemi='rh', load_morphometry_data=False)[0:2]
- brainload.subject_avg(subject_id, measure='area', surf='white', display_surf='white', hemi='both', fwhm='10', subjects_dir=None, average_subject='fsaverage', subjects_dir_for_average_subject=None, meta_data=None, load_surface_files=True, load_morphometry_data=True, custom_morphometry_files=None)
Load morphometry data that has been mapped to an average subject for a subject, i.e., standard space data.
Load data for a single subject that has been mapped to an average subject like the fsaverage subject from FreeSurfer. Can also load the mesh of an arbitrary surface for the average subject.
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string, optional) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
fwhm (string or None, optional) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. Defaults to ‘10’. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
display_surf (string, optional) – The surface of the average subject for which the mesh should be loaded, e.g., ‘white’, ‘pial’, ‘inflated’, or ‘sphere’. Defaults to ‘white’. Ignored if load_surface_files is False.
subjects_dir_for_average_subject (string, optional) – A string representing the full path to a directory. This can be used if the average subject is not in the same directory as all your study subjects. Defaults to the setting of subjects_dir.
meta_data (dictionary, optional) – A dictionary that should be merged into the return value meta_data. Defaults to the empty dictionary if omitted.
load_surface_files (boolean, optional) – Whether to load mesh data. If set to False, the first return values vert_coords and faces will be None. Defaults to True.
load_morphometry_data (boolean, optional) – Whether to load morphometry data. If set to False, the first return value morphometry_data will be None. Defaults to True.
custom_morphometry_files (dictionary, optional) – Cutom filenames for the left and right hemispjere data files that should be loaded. A dictionary of strings with exactly the following two keys: lh and rh. The value strings must contain hardcoded file names or template strings for them. As always, the files will be loaded relative to the surf/ directory of the respective subject. Example: {‘lh’: ‘lefthemi.nonstandard.mymeasure44.mgh’, ‘rh’: ‘righthemi.nonstandard.mymeasure44.mgh’}.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the average subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the average subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the average subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. In many cases, your average subject will have the same number of vertices for both hemispheres and you will know this number beforehand, so you may not have to worry about this at all.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘common’. This means that the data loaded represent morphometry data that has been mapped to a common or average subject.
hemi : the hemi value that was used
display_subject : the name of the common or average subject. This is the subject the surface meshes originate from. Ususally ‘fsaverage’.
display_surf : the surface of the common subject that has been loaded. Something like ‘pial’, ‘white’, or ‘inflated’.
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR, mapped to fsaverage:
>>> import brainload as bl >>> v, f, data, md = bl.subject_avg('subject1') >>> print md['surf'] white
Here, we are a bit more picky and explicit about what we want to load:
>>> import os >>> import brainload as bl >>> user_home = os.getenv('HOME') >>> subjects_dir = os.path.join(user_home, 'data', 'my_study_x') >>> v, f, data, md = bl.subject_avg('subject1', hemi='lh', measure='curv', fwhm='15', display_surf='inflated', subjects_dir=subjects_dir)
Sometime we do not care for the mesh, e.g., we only want the morphometry data:
>>> import brainload as bl >>> data, md = bl.subject_avg('subject1', hemi='rh', fwhm='15', load_surface_files=False)[2:4]
- brainload.subject_data_native(subject_id, subjects_dir, measure, hemi, surf='white')
Load native space morphometry data for a subject (e.g., lh.area).
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. For white, nothing will be added. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}) – The hemisphere that should be loaded.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
- Returns:
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘subject’. This means that the data loaded represent morphometry data taken from the subject’s surface (as opposed to data mapped to a common or average subject).
hemi : the hemi value that was used
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject_data_native('subject1', '/mnt/study1_data', 'thickness', 'both')
- brainload.subject_data_standard(subject_id, subjects_dir, measure, hemi, fwhm, average_subject='fsaverage', surf='white')
Load standard space data for a subject (e.g., lh.area.fwhm10.fsaverage.mgh).
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}) – The hemisphere that should be loaded.
fwhm (string or None) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
- Returns:
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘common’. This means that the data loaded represent morphometry data that has been mapped to a common or average subject.
hemi : the hemi value that was used
- brainload.subject_mesh(subject_id, subjects_dir, surf='white', hemi='both')
Load a surface mesh of a subject.
Convenience function to load a FreeSurfer surface mesh of a subject.
- Parameters:
subject_id (string) – The subject identifier of the subject.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load the pial surface mesh for both hemispheres of the Freeurfer example subject bert:
>>> import brainload as bl, import os >>> subjects_dir = os.path.join('Applications', 'freesurfer', 'subjects') >>> verts, faced, meta_data = bl.subject_mesh('bert', subjects_dir, surf='pial')
Submodules
brainload.freesurferdata module
Functions for loading FreeSurfer data on different levels.
The high-level functions are available directly in the package namespace. Using the functions in here should not be necessary.
- brainload.freesurferdata.fsaverage_mesh(subject_id='fsaverage', surf='white', hemi='both', subjects_dir=None, use_freesurfer_home_if_missing=True)
Load a surface mesh of the fsaverage subject.
Convenience function to load a FreeSurfer surface mesh of the fsaverage subject. Use the subject_mesh function to load the mesh of any other subject.
- Parameters:
subject_id (string, optional) – The subject identifier of the subject. Defaults to ‘fsaverage’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
use_freesurfer_home_if_missing (boolean, optional) – If set to True, first checks whether the directory for the given subject exists in the subjects_dir. If it does not, it will reset the subjects_dir to ‘${FREESURFER_HOME}/subjects’ before proceeding.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> verts, faced, meta_data = bl.fsaverage_mesh()
- brainload.freesurferdata.get_morphometry_file_path(subjects_dir, subject_id, surf, hemi, measure, subdir='surf')
Determine the path to a native space morphometry file, e.g., lh.area.
- brainload.freesurferdata.get_num_fsaverage_verts_per_hemi(fsversion=6)
Return the number of vertices per fsaverage hemisphere.
- Returns:
vertcount – The number of vertices per fsaverage hemisphere.
- Return type:
int
- brainload.freesurferdata.get_standard_space_morphometry_file_path(subjects_dir, subject_id, hemi, measure, fwhm='10', average_subject='fsaverage', surf='white', subdir='surf', file_ext='mgh')
Determine the path to a standard space morphometry file, e.g., lh.area.fwhm10.fsaverage.mgh.
- brainload.freesurferdata.get_surface_file_path(subjects_dir, subject_id, hemi, surf, subdir='surf')
Determine the path to a surface file, e.g., lh.white.
- brainload.freesurferdata.get_vox2ras_and_ras2vox_from_nifti_file(nifti_file, use_sform=True)
Load the vox2ras and ras2vox matrices from a nifti file header.
Load the vox2ras and ras2vox matrices from a nifti file header. The file can be in nifti (.nii) or gzipped nifti (.nii.gz) format. To understand qform and sform, read the nibabel docs or better https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/Orientation%20Explained.
- Parameters:
nifti_file (str) – Path to a nifti or gzipped nifti file.
use_sform (bool, optional) – Whether to report the sform matrix or qform matrix from the nifti header. Defaults to True (=sform). If set to False, the qform will be used.
- Returns:
vox2ras (2D numpy array) – The sform or qform matrix
ras2vox (2D numpy array) – The inverse of the vox2ras matrix.
Examples
>>> import brainload.freesurferdata as fsd >>> vox2ras, ras2vox = fsd.get_vox2ras_and_ras2vox_from_nifti_file("mni152_volume.nii.gz")
- brainload.freesurferdata.group(measure, surf='white', hemi='both', fwhm='10', subjects_dir=None, average_subject='fsaverage', group_meta_data=None, subjects_list=None, subjects_file='subjects.txt', subjects_file_dir=None, custom_morphometry_file_templates=None, subjects_detection_mode='auto')
Load standard space morphometry data for a number of subjects.
Load group data, i.e., morphometry data for all subjects in a study that has already been mapped to standard space and is ready for group analysis. The information given in the parameters measure, surf, hemi, and fwhm are used to construct the file name that will be loaded by default. This function will NOT load the meshes.
- Parameters:
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Data files for this measure have to exist for all subjects.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
fwhm (string or None, optional) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. Defaults to ‘10’. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string, optional) – A string representing the full path to a directory. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
group_meta_data (dictionary, optional) – A dictionary that should be merged into the return value group_meta_data. Defaults to the empty dictionary if omitted.
subjects_list (list of strings, optional (unless subjects_detection_mode is set to list)) – A list of subject identifiers or directory names that should be loaded from the subjects_dir. Example list: [‘subject1’, ‘subject2’]. Defaults to None. Only allowed if subjects_detection_mode is auto or list. In auto mode, this takes precedence over all other options, i.e., if a subjects_list and the (default or custom) subjects_file are given, the subjects_list will be used.
subjects_file_dir (string, optional) – A string representing the full path to a directory. This directory must contain the subjects_file (see below). Defaults to the subjects_dir.
subjects_file (string, optional) – The name of the subjects file, relative to the subjects_file_dir. Defaults to ‘subjects.txt’. The file must be a simple text file that contains one subject_id per line. It can be a CSV file that has other data following, but the subject_id has to be the first item on each line and the separator must be a comma. So a line is allowed to look like this: subject1, 35, center1, 147. No header is allowed. If you have a different format, consider reading the file yourself and pass the result as subjects_list instead.
custom_morphometry_file_templates (dictionary, optional) –
- Cutom filenames for the left and right hemisphere data files that should be loaded. A dictionary of strings with exactly the following two keys: lh and rh. The value strings can contain hardcoded file names or template strings for them. As always, the files will be loaded relative to the surf/ directory of the respective subject. Example for hard-coded files: {‘lh’: ‘lefthemi.nonstandard.mymeasure44.mgh’, ‘rh’: ‘righthemi.nonstandard.mymeasure44.mgh’}. The strings may contain any of the following variabes, which will be replaced by what you supplied to the other arguments of this function:
${MEASURE} will be replaced with the value of measure.
${SURF} will be replaced with the FreeSurfer file name part for the surface surf. This is the empty string if surf is ‘white’, and a dot followed by the value of surf for all other settings of surf. Examples: when surf is ‘pial’, this will be replaced with ‘.pial’ (Note the dot!). If surf is ‘white’, this will be replaced with the empty string.
${SURF_RAW} will be replaced with the value of surf.
${HEMI} will be replaced with ‘lh’ for the left hemisphere, and with ‘rh’ for the right hemisphere.
${FWHM} will be replaced with the value of fwhm, so something like ‘10’.
${SUBJECT_ID} will be replaced by the id of the subject that is being loaded, e.g., ‘subject3’.
${AVERAGE_SUBJECT} will be replaced by the value of average_subject.
Note that only ${SURF} and ${HEMI} are usually needed, everything else can be hardcoded (or is not part of typical FreeSurfer file names at all, like ${SUBJECT_ID}). Example template string: subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh. Complete example for template strings in dictionary: {‘lh’: ‘subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh’, ‘rh’: ‘subj_${SUBJECT_ID}_hemi_${HEMI}.alsononstandard.mgh’}.
subjects_detection_mode ({'auto', 'list', 'file', 'search_dir'}, optional) –
- The method used to determine the subjects that should be loaded. Defaults to ‘auto’. You can always see which mode was used by looking at the returned run_meta_data, see run_meta_data[‘subjects_detection_mode’].
’auto’: In this mode, all available methods will be tried in the following order: If a subjects_list is given, it is used. Then, the subjects_file is used if it exists. Note that this may be the default file, ‘$SUBJECTS_DIR/subject_surf_dir.txt’, or another if one has explicitely been defined by setting subjects_file and/or subjects_file_dir. If the file does not exist, the directory is searched for directories containing FreeSurfer data as defined in the section for ‘search_dir’ mode below. You can always see which method was used in auto mode by looking at the returned run_meta_data, see run_meta_data[‘subjects_detection_mode_auto_used_method’].
’list’: In this mode, the given subjects_list is used, and you have to supply one. If not, an error is raised. You are not allowed to supply a subjects_file in this mode, or an error will be raised.
’file’: In this mode, the subjects file is used. Note that this may be the default file, ‘$SUBJECTS_DIR/subjects.txt’, or another if one has explicitely been defined by setting subjects_file and/or subjects_file_dir. If the file does not exist, an error is raised. You can see which file was used by looking at the returned run_meta_data, see run_meta_data[‘subjects_file’]. You are not allowed to supply a subjects_list in this mode, or an error will be raised.
’search_dir’: In this mode, the subjects_dir (default or explicitely given) is searched for sub directories which look as if they could contain FreeSurfer data. The latter means that they contain a sub directory named ‘surf’. There is one exception though: if the name of one such directory equals the name of the average_subject, the directory is skipped. You are not allowed to supply a subjects_list in this mode, or an error will be raised.
- Returns:
group_morphometry_data (numpy array) – An array filled with the morphometry data for the subjects. The array has shape (n, m) where n is the number of subjects, and m is the number of vertices of the standard subject. (If you load both hemispheres instead of one, m doubles.) To get the subject id for the entries, look at the respective index in the returned subjects_list.
subjects_list (list of strings) – A list containing the subject identifiers in the same order as the data in group_morphometry_data. (If subjects_detection_mode is ‘list’ or ‘file’, the order in these is guaranteed to be preserved. But in mode ‘search_dir’ or ‘auto’ which may have chosen to fall back to ‘search_dir’ as a last resort, this is helpful: You can use the index of a subject in this list to find its data in group_morphometry_data, as it will have the same index. See the examples below.)
group_meta_data (dictionary) – A dictionary containing detailed information on all subjects and files that were loaded. Each of its keys is a subject identifier. The data value is another dictionary that contains all meta data for this subject as returned by the subject_avg function.
run_meta_data (dictionary) – A dictionary containing general information on the settings used when executing the function and determining which subjects to load.
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for all subjects in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> data, subjects, group_md, run_md = bl.group('area')
Here, we load curv data for the right hemisphere, computed on the pial surface with smooting of 20:
>>> data, subjects, group_md, run_md = bl.group('curv', hemi='rh', surf='pial', fwhm='20')
We may want to be a but more explicit on which subjects are loaded from where:
>>> import os >>> import brainload as bl >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> subjects_list = ['subject1', 'subject4', 'subject8'] >>> data, subjects, group_md, run_md = bl.group('curv', fwhm='20', subjects_dir=subjects_dir, subjects_list=subjects_list)
Continuing the last example, we may want to have a look at the curv value of the vertex at index 100000 of the subject ‘subject4’:
>>> subject4_idx = subjects.index('subject4') >>> print data[subject4_idx][100000]
- brainload.freesurferdata.group_native(measure, subjects_dir, subjects_list, surf='white', hemi='both')
Load native space morphometry data for a number of subjects.
Load native space group data, i.e., morphometry data for all subjects in a study. The information given in the parameters measure, surf, and hemi are used to construct the file name that will be loaded by default. This function will NOT load the meshes.
- Parameters:
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Data files for this measure have to exist for all subjects.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. Defaults to ‘white’. Will be added after the measure name unless left at default.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
subjects_list (list of strings, optional (unless subjects_detection_mode is set to list)) – A list of subject identifiers or directory names that should be loaded from the subjects_dir. Example list: [‘subject1’, ‘subject2’]. Defaults to None. Only allowed if subjects_detection_mode is auto or list. In auto mode, this takes precedence over all other options, i.e., if a subjects_list and the (default or custom) subjects_file are given, the subjects_list will be used.
- Returns:
morphdata_by_subject (dictionary) – A dictionary containing the morphometry data. Keys are subject identifiers, and values are the morphometry data numpy 1D arrays.
metadata_by_subject (dictionary) – A dictionary containing detailed information on all subjects and files that were loaded. Each of its keys is a subject identifier. The data value is another dictionary that contains all meta data for this subject.
- brainload.freesurferdata.hemi_range(morphometry_meta_data, hemi)
Compute start and end index in the hemisphere data for the given hemisphere.
- Parameters:
morphometry_meta_data (dictionary as returned by the functions that read morphometry data (e.g.,
`subject_data_native`).)hemi (string, one of 'lh' or 'rh'. The hemisphere you want to get the start and end index for.)
- Returns:
start_index (integer) – The start index of the lh data.
end_index (integer) – The end index of the lh data.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject_data_native('subject1', '/mnt/study1_data', 'thickness', 'both') >>> s, e = bl.hemi_range(meta_data, 'lh') >>> print("Mean lh thickness value is: %f" % (np.mean(morphometry_data[s:e])))
- brainload.freesurferdata.load_subject_mesh_files(lh_surf_file, rh_surf_file, hemi='both', meta_data=None)
Load mesh files for a subject.
Load one or two mesh files for a subject. Which of the two files lh_surf_file and rh_surf_file are actually loaded is determined by the hemi parameter.
- Parameters:
lh_surf_file (string | None) – A string representing an absolute path to a mesh file for the left hemisphere (e.g., the path to ‘lh.white’). If hemi is ‘rh’, this will be ignored and can thus be None.
rh_surf_file (string | None) – A string representing an absolute path to a mesh file for the right hemisphere (e.g., the path to ‘rh.white’). If hemi is ‘lh’, this will be ignored and can thus be None.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
- Returns:
vert_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices. If the argument hemi was ‘both’, this includes vertices from several meshes. You can check the meta_data return values to get the border between meshes, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’].
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces. Look at the respective indices in vert_coords to get the vertex coordinates. If the argument hemi was ‘both’, this includes faces from several meshes. You can check the meta_data return values to get the border between meshes, see meta_data[‘lh.num_faces’] and meta_data[‘rh.num_faces’].
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?h.surf_file : the mesh file that was loaded for this hemisphere
Examples
>>> import brainload.freesurferdata as fsd; import os >>> lh_surf_file = os.path.join('my_subjects_dir', 'subject1', 'surf', 'lh.white') >>> rh_surf_file = os.path.join('my_subjects_dir', 'subject1', 'surf', 'rh.white') >>> vert_coords, faces, meta_data = fsd.load_subject_mesh_files(lh_surf_file, rh_surf_file)
- brainload.freesurferdata.load_subject_morphometry_data_files(lh_morphometry_data_file, rh_morphometry_data_file, hemi='both', format='curv', meta_data=None)
Load morphometry data files for a subject.
Load one or two morphometry data files for a subject. Which of the two files lh_morphometry_data_file and rh_morphometry_data_file are actually loaded is determined by the hemi parameter.
- Parameters:
lh_morphometry_data_file (string | None) – A string representing an absolute path to a morphometry data file for the left hemisphere. If hemi is ‘rh’, this will be ignored and can thus be None.
rh_morphometry_data_file (string | None) – A string representing an absolute path to a morphometry data file for the right hemisphere. If hemi is ‘lh’, this will be ignored and can thus be None.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
format ({'curv', 'mgh'}, optional) – The file format for the files that are to be loaded. Defaults to ‘curv’.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
- Returns:
morphometry_data (numpy array) – An array containing the scalar per-vertex data loaded from the file(s).
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
Examples
Load the lh and rh area files for subject1.
>>> import brainload.freesurferdata as fsd; import os >>> lh_morphometry_file = os.path.join('path', 'to', 'subjects_dir', 'subject1', 'surf', 'lh.area') >>> rh_morphometry_file = os.path.join('path', 'to', 'subjects_dir', 'subject1', 'surf', 'rh.area') >>> morphometry_data, meta_data = fsd.load_subject_morphometry_data_files(lh_morphometry_file, rh_morphometry_file)
Now let’s look at the area value for the vertex at index 10:
>>> print "lh value at index 10: %d." % morphometry_data[10]
But what about the value of vertex 10 at the right hemisphere? We loaded 2 hemispheres, so the data is concatinated. But you can use the meta_data to get the correct index relative to the right hemisphere:
>>> print "rh value at index 10: %d." % morphometry_data[fsd.rhi(10, meta_data)]
You could also get the value directly using the rhv function:
>>> print "rh value at index 10: %d." % fsd.rhv(10, morphometry_data, meta_data)
- brainload.freesurferdata.merge_morphometry_data(morphometry_data_arrays, dtype=<class 'float'>)
Merge morphometry data horizontally.
Merge morphometry data read from several meshes of the same subject horizontally. This is used to merge data from the left and right hemispheres.
- Parameters:
morphometry_data_arrays (2D array) – An array of arrays, each of which represents morphometry data from different hemispheres of the same subject.
dtype (data type, optional) – Data type for the output numpy array. Defaults to float.
- Returns:
Horizontally stacked array containing the data from all arrays in the input array.
- Return type:
numpy array
Examples
Merge some data:
>>> lh_morphometry_data = np.array([0.0, 0.1, 0.2, 0.3]) # some fake data >>> rh_morphometry_data = np.array([0.5, 0.6]) >>> merged_data = fsd.merge_morphometry_data([lh_morphometry_data, rh_morphometry_data]) >>> print merged_data.shape (6, )
Typically, the lh_morphometry_data and rh_morphometry_data come from calls to read_fs_morphometry_data_file_and_record_meta_data as shown here:
>>> lh_morphometry_data, meta_data = read_fs_morphometry_data_file_and_record_meta_data(lh_morphometry_data_file, 'lh') >>> rh_morphometry_data, meta_data = read_fs_morphometry_data_file_and_record_meta_data(rh_morphometry_data_file, 'rh', meta_data=meta_data) >>> both_hemis_morphometry_data = merge_morphometry_data([lh_morphometry_data, rh_morphometry_data])
- brainload.freesurferdata.parse_talairach_file(file_name)
Parse a talairach matrix from a talairach.xfm file.
Parse a talairach matrix from the mri/transforms/talairach.xfm file of a subject. Talairach space is a RAS space with the coordinate center at the Anterior Commisure. RAS (Right-Anterior-Superior) means X points to the right (from subjects point of view), Y points up out of the nose (subject is lying in scanner), and Z points out of the top of the head (so the axis is parallel to the floor). From the Freeurfer Wiki on coordinate systems: ‘Note on Talairach: FreeSurfer does not report true “Talairach” coordinates. The coordinates listed unter “Talairach” are actually based on Matthew Brett’s 10/8/98 non-linear transform from MNI305 space (see http://www.mrc-cbu.cam.ac.uk/Imaging/mnispace.html). FreeSurfer also reports “Talairach MNI” coordinates. These are MNI305 space.’
- Parameters:
file_name (str) – Path to the file, usually SUBJECT/mri/transforms/talairach.xfm
- Returns:
The matrix, a float array with shape (3, 4).
- Return type:
numpy 2D array
- brainload.freesurferdata.read_fs_morphometry_data_file_and_record_meta_data(curv_file, hemisphere_label, meta_data=None, format='curv')
Read a morphometry file and record meta data on it.
Read a morphometry file and record meta data on it. A morphometry file is file containing a scalar value for each vertex on the surface of a FreeSurfer mesh. An example is the file ‘lh.area’, which contains the area values for all vertices of the left hemisphere of the white surface. Such a file can be in two different formats: ‘curv’ or ‘mgh’. The former is used when the data refers to the surface mesh of the original subject, the latter when it has been mapped to a standard subject like fsaverage.
- Parameters:
curv_file (string) – A string representing a path to a morphometry file (e.g., the path to ‘lh.area’).
hemisphere_label ({'lh' or 'rh'}) – A string representing the hemisphere this file belongs to. This is used to write the correct meta data.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
format ({'curv', 'mgh'}, optional) – The file format for the files that are to be loaded. Defaults to ‘curv’.
- Returns:
per_vertex_data (numpy array) – A 1D array containing one scalar value per vertex.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the curv_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
Examples
>>> import brainload.freesurferdata as fsd; import os >>> lh_morphometry_file = os.path.join('my_subjects_dir', 'subject1', 'surf', 'lh.area') >>> lh_morphometry_data, meta_data = read_fs_morphometry_data_file_and_record_meta_data(lh_morphometry_file, 'lh') >>> print meta_data['lh.num_data_points'] 121567 # arbitrary number, depends on the subject mesh >>> print meta_data['lh.morphometry_file'] my_subjects_dir/subject1/surf/lh.area # on UNIX-like systems
- brainload.freesurferdata.read_fs_surface_file_and_record_meta_data(surf_file, hemisphere_label, meta_data=None)
Read a surface file and record meta data on it.
Read a surface file and record meta data on it. A surface file is a mesh file in FreeSurfer format, e.g., ‘lh.white’. It contains vertices and 3-faces made out of them.
- Parameters:
surf_file (string) – A string representing an absolute path to a surface (or ‘mesh’) file (e.g., the path to ‘lh.white’).
hemisphere_label ({'lh' or 'rh'}) – A string representing the hemisphere this file belongs to. This is used to write the correct meta data.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
- Returns:
vert_coords (numpy array) – A 2D array containing 3 coordinates for each vertex in the surf_file.
faces (numpy array) – A 2D array containing 3 vertex indices per face. Look at the respective indices in vert_coords to get the vertex coordinates.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : value of the surf_file argument: the mesh file that was loaded
Examples
>>> vert_coords, faces, meta_data = fsd.read_fs_surface_file_and_record_meta_data(surf_file, 'lh') >>> print meta_data['lh.num_vertices'] 121567 # arbitrary number, depends on the subject mesh
- brainload.freesurferdata.read_lookup_file(lookup_file, dtype='<U50')
Read a FreeSurfer lookup table file in text format.
Read a FreeSurfer lookup table file in text format, this is used for the FreeSurferColorLUT.txt file.
- Parameters:
lookup_file (str) – Path to the FreeSurferColorLUT.txt file. It comes with FreeSurfer and can be found directly in $FREESURFER_HOME for v6.
- Returns:
Array with shape (n, 6) for a file with n relevant lines. A relevant line is a line describing a segmentation in 6 fields (seg_code, structure_name, color_red, color_green, color_blue, color_alpha). There are 2 types of ignored lines in the file: empty lines and those starting with the comment character ‘#’. All other lines are considered relevant and split into the 6 parts.
- Return type:
numpy 2D str array
- brainload.freesurferdata.read_m3z_file(m3z_file)
Read a file in FreeSurfer m3z format.
Read a file in FreeSurfer m3z format, usually mri/transforms/talairach.m3z of a subject. An m3z file is a gzipped binary file containing a dense vector field that describes a 3D registration between two volumes/images. This implementation follows the Matlab implementation from the FreeSurfer source repository at github, see https://github.com/freesurfer/freesurfer/blob/dev/matlab/mris_read_m3z.m. This function is released under the Freesurfer license: https://surfer.nmr.mgh.harvard.edu/fswiki/FreeSurferSoftwareLicense
- Parameters:
m3z_file (str) – Path to a file in m3z format
- Returns:
vol_orig (numpy 4D array) – Array of np.single, containing 3 numbers per voxel. The shape is (width, height, depth, 3), where width, height, and depth are the dimensions of the source volume.
vol_dest (numpy 4D array) – Array of np.single, containing 3 numbers per voxel. The shape is (width, height, depth, 3), where width, height, and depth are the dimensions of the destination volume.
vol_ind0 (numpy 4D array) – Array of np.int32, containing 3 numbers per voxel. The shape is (width, height, depth, 3).
meta_data (dictionary) –
- Contains meta data on the registration. The following keys are included:
version: float, File format version
width: int, Volume width
height: int, Volume height
depth: int, Volume depth
spacing: int, voxel spacing of the volume
exp_k: float, exp_k of the volume
Examples
Read a talairach.m3z file that has been generated by FreeSurfer’s
`recon-all`command.>>> import brainload.freesurferdata as fsd >>> import os >>> m3z_file = os.path.join(os.getenv('HOME'), 'my_study_data', 'subject1', 'mri', 'transforms', 'talairach.m3z') >>> vol_orig, vol_dest, vol_ind0, meta_data = fsd.read_m3z_file(m3z_file)
- brainload.freesurferdata.read_mgh_file(mgh_file_name, collect_meta_data=True, collect_data=True)
Read data from a FreeSurfer output file in mgh format.
Read all data from the MGH file and return it as a numpy array. Optionally, collect meta data from the mgh file header.
- Parameters:
mgh_file_name (string) – A string representing a full path to a file in FreeSurfer MGH file format. If the file name end with ‘.mgz’ or ‘.mgh.gz’, the file is assumed to be in gzipped MGH format.
collect_meta_data (bool, optional) – Whether or not to collect meta data from the MGH file header. Defaults to True.
collect_data (bool, optional) – Whether or not to collect the file data (voxel values) from the MGH file. Defaults to True.
- Returns:
mgh_data (numpy array) – The data from the MGH file, usually one scalar value per voxel.
mgh_meta_data (dictionary) – The meta data collected from the header, or an empty dictionary if the argument collect_meta_data was ‘False’. The keys correspond to the names of the respective nibabel function used to retrieve the data. The values are the data as returned by nibabel.
Examples
Read a file in MGH format from the surf dir of a subject:
>>> import os >>> import brainload.freesurferdata as fsd >>> mgh_file = os.path.join('my_subjects_dir', 'subject1', 'surf', 'rh.area.fsaverage.mgh') >>> mgh_data, mgh_meta_data = fsd.read_mgh_file(mgh_file)
- brainload.freesurferdata.read_mgh_header_matrices(mgh_file_name)
Read the 3 affine transformation matrices from a MGH file header.
Read the 3 affine transformation matrices ras2vox, vox2ras, and vox2ras_tkr from a MGH file header. The input file is assumed to be gzipped (and extracted appropriately) if the file name ends with ‘.mgz’ or ‘.mgh.gz’. See the FreeSurfer wiki on coordinate systems for details on what these matrices are. In short, RAS coordinates are used to specify positions of vertices in FreeSurfer surface files.
In short, VOX is the voxel index and the RAS coordinate is used for the surface coordinate of a vertex.
VOX: After FreeSurfer pre-processing, this is a triplet of integers in range 0 - 255 for 3D images. Note though that the original T1 images (before pre-processing) from a study can - and usually will - have different numbers of voxels (both different between the axes of a single image as well as between subjects). The VOX is sometimes called CRS for voxel column, row, slice.
RAS: Right-Anterior-Superior (anatomical coordinates). According to http://www.grahamwideman.com/gw/brain/fs/coords/fscoords.htm, the RAS coordinate origin (0, 0, 0) is the center of the voxel (128, 128, 128). Note that this voxel could or could NOT be the center of the MRI volume.
- Parameters:
mgh_file_name (string) – Path to a file in MGH format. The input file is assumed to be gzipped (and extracted appropriately) if the file name ends with ‘.mgz’ or ‘.mgh.gz’.
- Returns:
ras2vox (numpy array) – 2D numpy array with shape (4, 4). Transformation matrix from RAS coordinate to voxel index.
vox2ras (numpy array) – 2D numpy array with shape (4, 4). Transformation matrix from voxel index to RAS coordinate.
vox2ras_tkr (numpy array) – 2D numpy array with shape (4, 4). Transformation matrix from voxel index to (tkregister) surface RAS coordinate. This is a RAS coordinate of a vertex on the surface.
Examples
>>> import os; import brainload.freesurferdata as fsd >>> mgh_file = os.path.join(TEST_DATA_DIR, 'subject1', 'mri', 'orig.mgh') >>> ras2vox, vox2ras, vox2ras_tkr = fsd.read_mgh_header_matrices(mgh_file)
- brainload.freesurferdata.rhi(rh_relative_index, meta_data)
Computes the absolute data index given an index relative to the right hemisphere.
This function makes sense only given a morphometry_data and associated meta_data that contains data on two hemispheres (even though the morphometry_data array itself is not passed to this function). E.g., the return value of a function like subject() or subject_avg() when called with hemi=’both’. For such data, it computes the absolute index in the data given a request index relative to the right hemisphere. The name is short for ‘right hemisphere index’.
- Parameters:
rh_relative_index (int) – An index relative to the right hemisphere. E.g., 0 if you want to get the index of the first vertex of the right hemisphere. Its absolute value must be between 0 and the number of vertices of the right hemisphere. Negative values are allowed, and -1 will get you the second-to-last possible index, -2 the third-to-last, and so on.
meta_data (dictionary) – The meta data dictionary returned for your data. It must contain the keys ‘lh.num_data_points’ and ‘rh.num_data_points’.
- Return type:
The absolute index into the data for the given rh_relative_index.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject('heinz', hemi='both')[2:4] >>> print "rh value at index 10, relative to start of right hemisphere: %d." % morphometry_data[bl.rhi(10, meta_data)]
- brainload.freesurferdata.rhv(rh_relative_index, morphometry_data, meta_data)
Returns the value in morphometry_data at an index relative to the right hemisphere.
This function makes sense only given a morphometry_data and associated meta_data that contains data on two hemispheres. E.g., the return value of a function like subject() or subject_avg() when called with hemi=’both’. For such data, it returns the value in morphometry_data at a request index given relative to the right hemisphere. The name is short for ‘right hemisphere value’.
- Parameters:
rh_relative_index (int) – An index relative to the start of the right hemisphere in the data. E.g., 0 if you want to get the value for the first vertex of the right hemisphere. Its absolute value must be between 0 and the number of vertices of the right hemisphere. Negative values are allowed, and -1 will get you the last possible value, -2 the second-to-last, and so on.
morphometry_data (numpy array) – The morphometry data array, must represent data for both hemispheres.
meta_data (dictionary) – The meta data dictionary returned for your data. It must contain the keys ‘lh.num_data_points’ and ‘rh.num_data_points’.
- Return type:
The value at the given index that is relative to the start of the right hemisphere in the data.
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject('heinz', hemi='both')[2:4] >>> print "rh value at index 10, relative to start of right hemisphere: %d." % bl.rhv(10, morphometry_data, meta_data)
- brainload.freesurferdata.subject(subject_id, surf='white', measure='area', hemi='both', subjects_dir=None, meta_data=None, load_surface_files=True, load_morphometry_data=True)
Load FreeSurfer brain morphometry and/or mesh data for a single subject.
High-level interface to load FreeSurfer brain data for a single space. This parses the data for the surfaces of this subject. If you want to load data that has been mapped to an average subject like ‘fsaverage’, use subject_avg instead.
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string, optional) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
meta_data (dictionary, optional) – A dictionary that should be merged into the return value meta_data. Defaults to the empty dictionary if omitted.
load_surface_files (boolean, optional) – Whether to load mesh data. If set to False, the first return values vert_coords and faces will be None. Defaults to True.
load_morphometry_data (boolean, optional) – Whether to load morphometry data. If set to False, the first return value morphometry_data will be None. Defaults to True.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘subject’. This means that the data loaded represent morphometry data taken from the subject’s surface (as opposed to data mapped to a common or average subject).
hemi : the hemi value that was used
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR:
>>> import brainload as bl >>> vertices, faces, data, md = bl.subject('subject1')
Here, we are a bit more explicit about what we want to load:
>>> import os >>> user_home = os.getenv('HOME') >>> subjects_dir = os.path.join(user_home, 'data', 'my_study_x') >>> vertices, faces, data, md = bl.subject('subject1', hemi='lh', measure='curv', subjects_dir=subjects_dir)
Sometimes we do not care for the mesh, e.g., we only want the morphometry data:
>>> data, md = bl.subject('subject1', hemi='rh', load_surface_files=False)[2:4]
…or the other way around (mesh only, no morphometry data):
>>> vertices, faces = bl.subject('subject1', hemi='rh', load_morphometry_data=False)[0:2]
- brainload.freesurferdata.subject_avg(subject_id, measure='area', surf='white', display_surf='white', hemi='both', fwhm='10', subjects_dir=None, average_subject='fsaverage', subjects_dir_for_average_subject=None, meta_data=None, load_surface_files=True, load_morphometry_data=True, custom_morphometry_files=None)
Load morphometry data that has been mapped to an average subject for a subject, i.e., standard space data.
Load data for a single subject that has been mapped to an average subject like the fsaverage subject from FreeSurfer. Can also load the mesh of an arbitrary surface for the average subject.
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string, optional) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
fwhm (string or None, optional) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. Defaults to ‘10’. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string, optional) – A string representing the full path to a directory. This should be the directory containing all subjects of your study. Defaults to the environment variable SUBJECTS_DIR if omitted. If that is not set, used the current working directory instead. This is the directory from which the application was executed.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
display_surf (string, optional) – The surface of the average subject for which the mesh should be loaded, e.g., ‘white’, ‘pial’, ‘inflated’, or ‘sphere’. Defaults to ‘white’. Ignored if load_surface_files is False.
subjects_dir_for_average_subject (string, optional) – A string representing the full path to a directory. This can be used if the average subject is not in the same directory as all your study subjects. Defaults to the setting of subjects_dir.
meta_data (dictionary, optional) – A dictionary that should be merged into the return value meta_data. Defaults to the empty dictionary if omitted.
load_surface_files (boolean, optional) – Whether to load mesh data. If set to False, the first return values vert_coords and faces will be None. Defaults to True.
load_morphometry_data (boolean, optional) – Whether to load morphometry data. If set to False, the first return value morphometry_data will be None. Defaults to True.
custom_morphometry_files (dictionary, optional) – Cutom filenames for the left and right hemispjere data files that should be loaded. A dictionary of strings with exactly the following two keys: lh and rh. The value strings must contain hardcoded file names or template strings for them. As always, the files will be loaded relative to the surf/ directory of the respective subject. Example: {‘lh’: ‘lefthemi.nonstandard.mymeasure44.mgh’, ‘rh’: ‘righthemi.nonstandard.mymeasure44.mgh’}.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the average subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the average subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the average subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. In many cases, your average subject will have the same number of vertices for both hemispheres and you will know this number beforehand, so you may not have to worry about this at all.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘common’. This means that the data loaded represent morphometry data that has been mapped to a common or average subject.
hemi : the hemi value that was used
display_subject : the name of the common or average subject. This is the subject the surface meshes originate from. Ususally ‘fsaverage’.
display_surf : the surface of the common subject that has been loaded. Something like ‘pial’, ‘white’, or ‘inflated’.
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load area data for both hemispheres and white surface of subject1 in the directory defined by the environment variable SUBJECTS_DIR, mapped to fsaverage:
>>> import brainload as bl >>> v, f, data, md = bl.subject_avg('subject1') >>> print md['surf'] white
Here, we are a bit more picky and explicit about what we want to load:
>>> import os >>> import brainload as bl >>> user_home = os.getenv('HOME') >>> subjects_dir = os.path.join(user_home, 'data', 'my_study_x') >>> v, f, data, md = bl.subject_avg('subject1', hemi='lh', measure='curv', fwhm='15', display_surf='inflated', subjects_dir=subjects_dir)
Sometime we do not care for the mesh, e.g., we only want the morphometry data:
>>> import brainload as bl >>> data, md = bl.subject_avg('subject1', hemi='rh', fwhm='15', load_surface_files=False)[2:4]
- brainload.freesurferdata.subject_data_native(subject_id, subjects_dir, measure, hemi, surf='white')
Load native space morphometry data for a subject (e.g., lh.area).
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’. Defaults to ‘area’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. For white, nothing will be added. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}) – The hemisphere that should be loaded.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
- Returns:
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘subject’. This means that the data loaded represent morphometry data taken from the subject’s surface (as opposed to data mapped to a common or average subject).
hemi : the hemi value that was used
Examples
>>> import brainload as bl >>> morphometry_data, meta_data = bl.subject_data_native('subject1', '/mnt/study1_data', 'thickness', 'both')
- brainload.freesurferdata.subject_data_standard(subject_id, subjects_dir, measure, hemi, fwhm, average_subject='fsaverage', surf='white')
Load standard space data for a subject (e.g., lh.area.fwhm10.fsaverage.mgh).
- Parameters:
subject_id (string) – The subject identifier of the subject. As always, it is assumed that this is the name of the directory containing the subject’s data, relative to subjects_dir. Example: ‘subject33’.
measure (string) – The measure to load, e.g., ‘area’ or ‘curv’.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}) – The hemisphere that should be loaded.
fwhm (string or None) – Which averaging version of the data should be loaded. FreeSurfer usually generates different standard space files with a number of smoothing settings. If None is passed, the .fwhmX part is omitted from the file name completely. Set this to ‘0’ to get the unsmoothed version.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
average_subject (string, optional) – The name of the average subject to which the data was mapped. Defaults to ‘fsaverage’.
- Returns:
morphometry_data (numpy array) – A numpy array with as many entries as there are vertices in the subject. If you load two hemispheres instead of one, the length doubles. You can get the start indices for data of the hemispheres in the returned meta_data, see meta_data[‘lh.num_vertices’] and meta_data[‘rh.num_vertices’]. You can be sure that the data for the left hemisphere will always come first (if both were loaded). Indices start at 0, of course. So if the left hemisphere has n vertices, the data for them are at indices 0..n-1, and the data for the right hemisphere start at index n. Note that the two hemispheres do in general NOT have the same number of vertices.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_data_points : the number of data points loaded.
?h.morphometry_file : the value of the ?h_morphometry_data_file argument (data file that was loaded)
?h.morphometry_file_format : the value for format that was used
subject_id : the subject id
subjects_dir : the subjects dir that was used
surf : the surf that was used, e.g., ‘white’
measure : the measure that was loaded as morphometry data, e.g., ‘area’
space : always the string ‘common’. This means that the data loaded represent morphometry data that has been mapped to a common or average subject.
hemi : the hemi value that was used
- brainload.freesurferdata.subject_mesh(subject_id, subjects_dir, surf='white', hemi='both')
Load a surface mesh of a subject.
Convenience function to load a FreeSurfer surface mesh of a subject.
- Parameters:
subject_id (string) – The subject identifier of the subject.
surf (string, optional) – The brain surface where the data has been measured, e.g., ‘white’ or ‘pial’. This will become part of the file name that is loaded. Defaults to ‘white’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere that should be loaded. Defaults to ‘both’.
subjects_dir (string) – A string representing the full path to a directory. This should be the directory containing all subjects of your study.
- Returns:
vert_coords (numpy array) – A 2-dimensional array containing the vertices of the mesh(es) of the subject. Each vertex entry contains 3 coordinates. Each coordinate describes a 3D position in a FreeSurfer surface file (e.g., ‘lh.white’), as returned by the nibabel function nibabel.freesurfer.io.read_geometry.
faces (numpy array) – A 2-dimensional array containing the 3-faces of the mesh(es) of the subject. Each face entry contains 3 indices. Each index references the respective vertex in the vert_coords array.
meta_data (dictionary) –
- A dictionary containing detailed information on all files that were loaded and used settings. The following keys are available (depending on the value of the hemi argument, you can replace ?h with ‘lh’ or ‘rh’ or both ‘lh’ and ‘rh’):
?h.num_vertices : number of vertices in the loaded mesh
?h.num_faces : number of faces in the loaded mesh
?lh.surf_file : the mesh file that was loaded for this hemisphere
- Raises:
ValueError – If one of the parameters with a fixed set of values receives a value that is not allowed.
Examples
Load the pial surface mesh for both hemispheres of the Freeurfer example subject bert:
>>> import brainload as bl, import os >>> subjects_dir = os.path.join('Applications', 'freesurfer', 'subjects') >>> verts, faced, meta_data = bl.subject_mesh('bert', subjects_dir, surf='pial')
brainload.annotations module
Read FreeSurfer vertex label and annotation files.
Functions for reading FreeSurfer vertex annotation files. These are the file in the label sub directory of a subject, with file extensions ‘.label’ and ‘.annot’. Examples are ‘lh.aparc.annot’ and ‘lh.cortex.label’. A label is a set of vertices. An annotation consists of several sets of vertices, each of which is assigned a label and a color.
- class brainload.annotations.AnnotQuery(vertex_lookup_indices, label_colors, label_names, name_dtype='U50', name_null_value='None')
Bases:
objectConvenience class that allows one to query the vertex names and colors for a list of vertex indices. The required parameters for the constructor are what is returned by the annot
- compute_labels()
- get_vertex_label_colors(query_vertex_indices)
Query the label color for a list of vertex indices.
- Parameters:
query_vertex_indices (numpy 1D int array) – The vertex indices (in the mesh) for which you want to query the color.
- Returns:
Color array with shape (n, 4) for n query vertices. Each color is represented by 4 int values that encode an RGBT color, where T is transparency and equal to T = alpha - 255.
- Return type:
numpy 2D int array
- get_vertex_label_names(query_vertex_indices)
Query the label name for a list of vertex indices.
- Parameters:
query_vertex_indices (numpy 1D int array) – The vertex indices (in the mesh) for which you want to query the name.
- Returns:
Name array with shape (n, ) for n query vertices.
- Return type:
numpy 1D string array
- brainload.annotations.annot(subject_id, subjects_dir, annotation, hemi='both', meta_data=None, orig_ids=False)
Load annotation for the mesh vertices of a single subject.
An annotation defines a label string and a color to each vertex, it is typically used to define brain regions, e.g., for cortical parcellation. An annotation consists of several groups of vertices, each of which is assigned a label and a color.
- Parameters:
subject_id (string) – The subject identifier.
subject_dir (string) – A string representing the path to the subjects dir.
annotation (string) – An annotation to load, part of the file name of the respective file in the subjects label directory. E.g., ‘aparc’, ‘aparc.a2009s’, or ‘aparc.DKTatlas’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
orig_ids (boolean, optional) – Passed on to nibabel.freesurfer.io.read_annot function. From the documentation of that function: ‘Whether to return the vertex ids as stored in the annotation file or the positional colortable ids. With orig_ids=False vertices with no id have an id set to -1.’ Defaults to False.
- Returns:
vertex_labels (ndarray, shape (n_vertices,)) – If orig_ids is False (the default), returns the index (for each vertex) into the label_colors and label_names datastructures to retrieve the color and name. If some vertex has no annotation, -1 is returned for it.
If orig_ids is True, returns an annotation color id for each vertex listed in the annotation file. IMPORTANT: The annotation value in here is NOT the label id. It is a code based on the color for the vertex. Yes, this is ugly. See https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles#Annotation for details, especially the section ‘Annotation file design surprise’. The color is encoded as a single number. Quoting the linked document, the numer is the ‘RGB value combined into a single 32-bit integer: annotation value = (B * 256^2) + (G * 256) + (R)’. From this it follows that, quoting the doc once more, ‘Code that loads an annotation file … has to compare annotation values to the color values in the ColorLUT part of the annotation file to discover what parcellation label code (ie: structure code) corresponds.’ (Basically this has already been done for you if you simply set orig_ids to False.)
label_colors (ndarray, shape (n_labels, 5)) – RGBT + label id colortable array. The first 4 values encode the label color: RGB is red, green, blue as usual, from 0 to 255 per value. T is the transparency, which is defined as 255 - alpha. The last value represents the label id. The number of labels (n_label) cannot be know in advance by this function in the general case (but the user can know based on the Atlas he is loading, e.g., the Desikan-Killiany Atlas has 36 labels).
label_names (list of strings) – The names of the labels. The length of the list is n_labels. Note that, contrary to the respective nibabel function, this function will always return this as a list of strings, no matter the Python version used.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.annotation_file : the file that was loaded
Examples
Load cortical parcellation annotations for both hemispheres of a subject from the Desikan-Killiany (‘aparc’) atlas:
>>> import brainload as bl; import os >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc', hemi='both') >>> print meta_data['lh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.annot >>> print meta_data['rh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/rh.aparc.annot
Now load cortical parcellation annotations for the left hemisphere of a subject from the Destrieux (‘aparc.a2009s’) atlas:
>>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc.a2009s', hemi='lh') >>> print meta_data['lh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.a2009s.annot
Now load cortical parcellation annotations for the right hemisphere of a subject from the DKT (‘aparc.DKTatlas40’) atlas:
>>> vertex_labels, label_colors, label_names, meta_data = bl.annot('subject1', subjects_dir, 'aparc.DKTatlas40', hemi='rh') >>> print meta_data['rh.annotation_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.aparc.DKTatlas40.annot
Print the color and the annotation name for an example vertex:
>>> vert_idx = 0 # We'll take the first vertex as an example. >>> if vertex_labels[vert_idx] >= 0: # it is -1 if the vertex is not assigned any label/color >>> i = vertex_labels[vert_idx] >>> print "label for vertex %d is %s" % (vert_idx, label_names[i]) >>> print "color for vertex %d in RGBA is (%d %d %d %d)" % (vert_idx, label_colors[idx, 0], label_colors[idx, 1], label_colors[idx, 2], (255 - label_colors[idx, 3]))
References
Atlas information is available at https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation
- brainload.annotations.color_rgbt_to_rgba(rgbt)
Convert RGBT color to RGBA.
Convert an RGBT color given as (r, g, b, t) with all values in range [0.255] to the respective color in RGBA. The T is for transparency, an defined as 1 - alpha, where alpha is the RGBA value A.
- Parameters:
rgbt (tupel of 4 integers (in range 0..255)) – The color according to RGBT definition, where T is transparency.
- Returns:
The color in RGBA notation.
- Return type:
tupel of 4 integers (in range 0..255)
Examples
Convert a color from RGBT to RGBA:
>>> import brainload.annotations as an >>> an.color_rgbt_to_rgba((120, 0, 240, 40)) (120, 0, 240, 215)
- brainload.annotations.get_atlas_region_names(annotation, subjects_dir, subject_id='fsaverage')
Get the region names of the label for an annotation from the annot file of a subject.
Get the region names of the label for an annotation from the annot file of a subject. It’s best to get them from fsaverage in subjects_dir FREESURFER_HOME/subjects/. Gettings them from stats files (which this function does NOT do), is not recommended, as they only contain regions with >0 vertices assigned to them for each subject, so you may miss regions.
- brainload.annotations.get_atlas_region_names_hardcoded(atlas, freesurfer_version=6)
The region names for the stats files, Freesurfer v6.
Return atlas region names for the stats files, Freesurfer v6. If no hardcoded list exists for the requested atlas, return None. WARNING: These were derived from one subject, and may miss some regions. We still need to verify that these are all possible regions. Also note that the names changed in FreeSurfer 6: all regions names which include an ampersand (’&’) have changed since 5.x. Formlery, the string ‘and’ was used, it has now been replaces with ‘&’. So the label ‘G&S_frontomargin’ was called ‘GandS_frontomargin’ if the data you are reading originates from an older FreeSurfer version.
- Parameters:
atlas (string) – A parcellation or segmentation name. One of ‘aseg’, ‘aparc’, ‘aparc.a2009s’, ‘aparc.DKTatlas’.
freesurfer_version (int, one of 5 or 6.) – The FreeSurfer version for which the names should fit. See the function description for details. Defaults to 6.
- Returns:
The hardcoded region names, or None if none are hardcoded for the given atlas.
- Return type:
list of strings or None
- brainload.annotations.label(subject_id, subjects_dir, label, hemi='both', meta_data=None)
Load annotation for the mesh vertices of a single subject.
An annotation defines a label string and a color to each vertex, it is typically used to define brain regions, e.g., for cortical parcellation.
- Parameters:
subject_id (string) – The subject identifier.
subject_dir (string) – A string representing the path to the subjects dir.
label (string) – A label to load, part of the file name of the respective file in the subjects label directory. E.g., ‘cortex’.
hemi ({'both', 'lh', 'rh'}, optional) – The hemisphere for which data should actually be loaded. Defaults to ‘both’.
meta_data (dictionary | None, optional if hemi is 'lh' or 'rh') – Meta data to merge into the output meta_data. Defaults to the empty dictionary. If ‘hemi’ is ‘both’, this dictionary is required and MUST contain at least one of the keys ‘lh.num_vertices’ or ‘lh.num_data_points’, the value of which must contain the number of vertices of the left hemisphere of the subject. Background: If hemi is ‘both’, the vertex indices of both hemispheres are merged in the return value verts_in_label, and thus we need to know the shift, i.e., the number of vertices in the left hemisphere.
- Returns:
verts_in_label (ndarray, shape (n_vertices,)) – Contains the ids of all vertices included in the label.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.label_file : the file that was loaded
Examples
Load the cortex label for the left hemisphere of a subject:
>>> import brainload as bl; import os >>> subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> verts_in_label, meta_data = bl.label('subject1', subjects_dir, 'cortex', hemi='lh') >>> print meta_data['lh.label_file'] # will print /home/someuser/data/my_study_x/subject1/label/lh.cortex.label
You could now use the label information to mask your morphology data.
See also
mask_data_using_labelMask data using a label.
- brainload.annotations.label_to_mask(verts_in_label, num_verts_total, invert=False)
Generate binary mask from vertex indices.
Generate a binary mask from the list of vertex indices in verts_in_label. The mask contains one entry for each vertex, i.e., it has length num_verts_total.
- Parameters:
verts_in_label (1D numpy array) – Array of vertex indices.
num_verts_total (int) – The total number of vertices that exist. (Obviously, the highest index in verts_in_label does not need to be the last vertex.)
invert (boolean, optional) – Whether the mask should be inverted. If inverse is set to False (or not set at all), vertex indices which occur in verts_in_label will be set to True in the mask. If inverse is set to True, vertex indices which occur in the mask will be set to False in the mask instead. Defaults to False.
- Returns:
mask – The mask array, length is num_verts_total.
- Return type:
numpy array of booleans
See also
mask_data_using_labelMask data using a label.
- brainload.annotations.mask_data_using_label(data, verts_in_label, invert=False)
Mask data using a list of vertex indices.
Set all indices in data which do NOT occur in verts_in_label to np.nan. If invert is True, set all indices which DO occur in verts_in_label to np.nan. In both cases, the other values are not altered.
- Parameters:
data (numpy array) – Array of input data.
verts_in_label (numpy array of int) – Each number in the array represents a vertex index in the data array.
invert (boolean, optional) – Whether the mask should be inverted. If inverse is set to False (default), vertex indices which occur in verts_in_label will be left unaltered, and all others will be set to np.nan. If inverse is set to True, the opposite happens. Defaults to False.
meta_data (dictionary | None, optional if hemi is 'lh' or 'rh') – Meta data to merge into the output meta_data. Defaults to the empty dictionary. If ‘hemi’ is ‘both’, this dictionary is required and MUST contain at least one of the keys ‘lh.num_vertices’ or ‘lh.num_data_points’, the value of which must contain the number of vertices of the left hemisphere of the subject. Background: If hemi is ‘both’, the vertex indices of both hemispheres are merged in the return value verts_in_label, and thus we need to know the shift, i.e., the number of vertices in the left hemisphere.
- Returns:
The masked data. (This is a copy, the input data is not altered.)
- Return type:
numpy array of booleans
- brainload.annotations.read_annotation_md(annotation_file, hemisphere_label, meta_data=None, encoding='utf-8', orig_ids=False)
Read annotation file and record meta data for it.
For details on the first three return values, see http://nipy.org/nibabel/reference/nibabel.freesurfer.html#nibabel.freesurfer.io.read_annot as they are the output of that function. An exception is the last parameter (names, names_str in this function) which returns a different data type depending on the Python version for the nibabel function. This function always returns strings, independent of the Python version.
- Parameters:
annotation_file (string) – A string representing a path to a FreeSurfer vertex annotation file (e.g., the path to ‘lh.aparc.annot’).
hemisphere_label ({'lh' or 'rh'}) – A string representing the hemisphere this file belongs to. This is used to write the correct meta data.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
encoding (string describing an encoding, optional) – The encoding to use when decoding the label strings from binary. Only used in Python 3. Defaults to ‘utf-8’.
orig_ids (boolean, optional) – Passed on to nibabel.freesurfer.io.read_annot function. From the documentation of that function: ‘Whether to return the vertex ids as stored in the annotation file or the positional colortable ids. With orig_ids=False vertices with no id have an id set to -1.’ Defaults to False.
- Returns:
vertex_label_colors (ndarray, shape (n_vertices,)) – Contains an annotation color id for each vertex listed in the annotation file. If orig_ids is False (the default), and some vertex has no annotation, -1 is returned for it. IMPORTANT: The annotation value in here is NOT the label id. It is the color for the vertex, encoded in a weird way! Yes, this is ugly. See https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles#Annotation for details, especially the section ‘Annotation file design surprise’. The color is encoded as a single number. Quoting the linked document, the numer is the ‘RGB value combined into a single 32-bit integer: annotation value = (B * 256^2) + (G * 256) + (R)’. From this it follows that, quoting the doc once more, ‘Code that loads an annotation file … has to compare annotation values to the color values in the ColorLUT part of the annotation file to discover what parcellation label code (ie: structure code) corresponds.’
label_colors (ndarray, shape (n_labels, 5)) – RGBT + label id colortable array. The first 4 values encode the label color: RGB is red, green, blue as usual, from 0 to 255 per value. T is the transparency, which is defined as 255 - alpha. The number of labels (n_label) cannot be know in advance.
label_names (list of strings) – The names of the labels. The length of the list is n_labels. Note that, contrary to the respective nibabel function, this function will always return this as a list of strings, no matter the Python version used.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.annotation_file : the file that was loaded
- brainload.annotations.read_label_md(label_file, hemisphere_label, meta_data=None)
Read label file and record meta data for it.
A label file is a FreeSurfer text file like ‘subject/label/lh.cortex.label’ that contains a list of vertex ids (with RAS coordinates) that are part of the label. It may optionally contain a scalar values for each vertex, but that is currently ignored by this function.
- Parameters:
label_file (string) – A string representing a path to a FreeSurfer vertex annotation file (e.g., the path to ‘lh.cortex.label’).
hemisphere_label ({'lh' or 'rh'}) – A string representing the hemisphere this file belongs to. This is used to write the correct meta data.
meta_data (dictionary | None, optional) – Meta data to merge into the output meta_data. Defaults to the empty dictionary.
- Returns:
verts_in_label (ndarray, shape (num_labeled_verts,)) – Contains an array of vertex ids, one id for each vertex that is part of the label.
meta_data (dictionary) –
- Contains detailed information on the data that was loaded. The following keys are available (replace ?h with the value of the argument hemisphere_label, which must be ‘lh’ or ‘rh’).
?h.label_file : the file that was loaded
- brainload.annotations.read_vertex_list_file(file_name, sep=' ')
Read a vertex list from a text file.
Read a vertex list from a text file. The file must contain vertex indices (integers) separated by spaces. It is OK if it has several lines. Lines starting with ‘#’ are considered to be comments and ignored. Note that a vertex is given by its index in a brain mesh, starting at 0. This is used as a way to import a list of vertices, similar to a FreeSurfer label file. This is a brainload custom format, but a very simple one that follows common file format conventions.
- Parameters:
file_name (str) – Path to a file to read
sep (str, optional) – Separator between integer values on a line. Defaults to a space, ‘ ‘.
- Returns:
The data read from all non-comment lines.
- Return type:
numpy 1D int array
- brainload.annotations.region_data_native(subject_id, subjects_dir, annotation, hemi, morphometry_data, morphometry_meta_data)
Get morphometry data for atlas regions.
Get morphometry data for each region in an annotation file/atlas. You can use these to compute anatomical statistics per region, like average cortical thickness.
- Parameters:
subject_id (string) – The subject identifier.
subjects_dir (string) – A string representing the path to the subjects dir.
annotation (string) – An annotation to load, part of the file name of the respective file in the subjects label directory. E.g., ‘aparc’, ‘aparc.a2009s’, or ‘aparc.DKTatlas’.
hemi (string, one of {'both', 'lh', 'rh'}) – The hemisphere for which data should actually be loaded.
morphometry_data (numpy array) – morphometry data array, one value per vertex
morphometry_meta_data (dictionary) – morphometry meta data dictionary, as returned by the functions that load morphometry data
- Returns:
region_data_per_hemi (nested dictionary) – Has a key for each hemi you requested (only ‘lh’, only ‘rh’, or both ‘lh’ and ‘rh’). The inner one has the region names as keys, and a 1D numpy array of values.
label_names (list of strings) – Names of the atlas regions. The length differs by atlas/annotation file.
Examples
Let us compute the average thickness in region 5 of the aparc atlas for a subject: >>> hemi = ‘lh’ >>> morphometry_data, morphometry_meta_data = bl.subject_data_native(‘subject1’, TEST_DATA_DIR, ‘thickness’, hemi) >>> region_data, label_names = an.region_data_native(‘subject1’, TEST_DATA_DIR, ‘aparc’, hemi, morphometry_data, morphometry_meta_data) >>> region_6_name = label_names[5] >>> mean_thickness_in_region_6 = np.mean(region_data[hemi][region_6_name]) >>> print(“Avg thickness in region ‘%s’ is: %f” % (region_6_name, mean_thickness_in_region_6))
- brainload.annotations.region_stats(region_data_per_hemi, label_names)
Compute descriptive stats for all regions. Return as 2D matrix.
- brainload.annotations.vertices_to_label(selected_vert_indices, all_vert_coords, header='#!ascii label')
Write a string in FreeSurfer label format from the vertices.
Write a string in FreeSurfer label format from the vertices. This can be used to create a label from a list of vertices, e.g., for displaying the vertices in Freeview or other tools supporting FreeSurfers label file format.
brainload.nitools module
Utility functions for loading neuroimaging data.
Most of these functions interact with the filesystem to find data.
- brainload.nitools.detect_subjects_in_directory(subjects_dir, ignore_dir_names=None, required_subdirs_for_hits=None)
Search for directories containing FreeSurfer output in a directory and return the subject names.
Given a directory, search its sub directories for FreeSurfer data and return the directory names of all directories in which such data was found. The resulting list can be used to create a subjects.txt file. This method searches all direct sub directories of the given subjects_dir for the existance of the typical FreeSurfer output directory structure.
- Parameters:
subjects_dir (string) – Path to a subjects directory.
ignore_dir_names (list of strings | None, optional) – A list of directory names that should be ignored, even if they have the required sub directories. This is useful if you do not want to load certain subjects. It is often used to avoid loading the average subject ‘fsaverage’. Defaults to a list with the single element ‘fsaverage’. You can explicitely pass an empty list if you want to include all subjects.
required_subdirs_for_hits (list of strings | None) – A sub directory of the given subjects_dir is considered a subject if it contains the typical FreeSurfer directory structure. Which sub directories are required is determined by this argument. If all of them are found under a dir, that dir is added tp the output list. This list defaults to a list with the single element ‘surf’. If that leads to false positives in your case, you could pass something like [‘surf’, ‘mri’, ‘label’].
- Returns:
A list of the subject identifiers (or directories that were considered as such).
- Return type:
list of strings
Examples
Guess which directories under the current SUBJECTS_DIR contain subject data:
>>> import brainload.nitools as nit >>> import os >>> my_subject_dir = os.getenv('SUBJECTS_DIR') >>> subjects_ids = nit.detect_subjects_in_directory(my_subject_dir, ignore_dir_names=['fsaverage', 'Copy of subject4'])
- brainload.nitools.do_subject_files_exist(subjects_list, subjects_dir, filename=None, filename_template=None, sub_dir='surf')
Checks for the existance of certain files in each subject directory for a group of subjects.
Checks for the existance of certain files in the each subject directory for a group of subjects. This is useful to see whether data you intend to work on exists for all subjects you are interested in.
- Parameters:
subjects_list (list of strings) – List of subject ids.
subjects_dir (string) – Path to a directory that contains the subject data.
filename (string) – A string representing the file name within the sub_dir sub directory of each subject, hardcoded. You must supply this or a filename_template.
filename_template (string) – A string representing the file name within the ‘surf’ sub directory of each subject as a template. You must supply this or a filename, but not both. You can use the variable ${SUBJECT_ID} in the template.
sub_dir (string | None, optional) – The sub directory to look in. You could set any value, but the typical ones are the default FreeSurfer directories, e.g., ‘surf’, ‘mri’, ‘scripts’ and so on. You can set this to None if you want to look directly in the subjct’s dir, but FreeSurfer does not seem to store any data there by default. Defaults to ‘surf’.
- Returns:
A dictionary. The keys are subjects that are missing the respective file, and the value is the absolute path of the file that is missing. If no files are missing, the dictionary is empty. If none of the subjects have the file, the length of the dictionary is equal to the length of the input subjects_list.
- Return type:
dictionary
Examples
Check whether a file exists for all subjects:
>>> import brainload.nitools as nit >>> subjects_list = ['subject1', 'subject4', 'subject7'] >>> subjects_dir = subjects_dir = os.path.join(os.getenv('HOME'), 'data', 'my_study_x') >>> searched_file = 'lh.area' >>> missing = nit.do_subject_files_exist(subjects_list, subjects_dir, filename=searched_file) >>> print "The file '%s' exists for %d of the %d subjects." % (searched_file, len(missing), len(subjects_list))
- brainload.nitools.fill_template_filename(template_string, substitution_dict)
Replace variables in the template with the respective substitution dict entries.
Checks the template_string for variables (i.e., something like ‘${VAR_NAME}’) that are listed as keys in substitution_dict. If such entries are found, they are replaced with the respective values in the substitution_dict. This function only calls ting.Template().substitute() in the background.
- Parameters:
template_string (string) – A template string, see the string.Template constructor in the standard Python string module. Variable names must be enclosed in ${}. Example: ${SUBJECT_ID}_hardcoded_text.
substitution_dict (dictionary string, string) – The keys are variable names, values are the replacements. See string.Template.substitute in the standard Python string module. Example: { ‘SUBJECT_ID’ : ‘subject3’ }.
- Returns:
The result of the replacement.
- Return type:
string
Examples
Fill in a template string:
>>> import brainload.nitools as nit >>> template_str = '${HEMI}.white' >>> substitution_dict = {'HEMI' : 'lh'} >>> print nit.fill_template_filename(template_str, substitution_dict) lh.white
- brainload.nitools.load_vertex_indices(vertex_indices_file)
- brainload.nitools.load_voxel_indices(vertex_indices_file)
- brainload.nitools.read_BIDS_participants_file(participants_file)
Read all subjects from BIDS participants file.
The file must a tab-separated text file with an arbitrary number of columns and one header line. Exactly one of the columns must be named ‘participants_id’. The file should be name ‘participants.tsv’, but this is not enforced. See https://www.nature.com/articles/sdata201644 for details on BIDS, the Brain Imaging Data Structure standard.
- brainload.nitools.read_subjects_file(subjects_file, has_header_line=False, index_of_subject_id_field=0, **kwargs)
Read a subjects file in CSV format that has the subject id as the first entry on each line. Arbitrary data may follow in the consecutive fields on each line, and will be ignored. Having nothing but the subject id on the line is also fine, of course.
The file can be a simple text file that contains one subject_id per line. It can also be a CSV file that has other data following, but the subject_id has to be the first item on each line and the separator must be a comma. So a line is allowed to look like this: subject1, 35, center1, 147. No header is allowed. If you have a different format, consider reading the file yourself and pass the result as subjects_list instead.
- Parameters:
subjects_file (string) – Path to a subjects file (see above for format details).
has_header_line (boolean, optional) – Whether the first line is a header line and should be skipped. Defaults to ‘False’.
index_of_subject_id_field (integer, optional) – The column index of the field that contains the subject id in each row. Defaults to ‘0’. Changing this only makes sense for CSV files.
**kwargs (any) – Any other named arguments will be passed on to the call to the call to the csv.reader constructor. That is a class from Python’s standard csv module. Example: pass delimiter=’ ‘ if your CSV file is limited by tabs.
- Returns:
A list of subject identifiers.
- Return type:
list of strings
Examples
Load a list of subjects from a simple text file that contains one subject per line.
>>> import brainload.nitools as nit >>> subjects_ids = nit.read_subjects_file('/home/myuser/data/study5/subjects.txt')
- brainload.nitools.save_vertex_indices(vertex_indices_file, vertex_indices)
- brainload.nitools.write_BIDS_participants_file(file_name, subjects_list)
- brainload.nitools.write_lines_to_text_file(lines, file_name, line_sep='\n')
Write the lines to a text file.
Write the lines to a text file, overwriting it in case it exists.
- lines: list of str
The lines, must not contain line ending.
- file_name: str
Path to new text file to create (or overwrite if it exists).
- line_sep: str, optional
Line separator. Defaults to “
“.
- brainload.nitools.write_subjects_file(file_name, subjects_list)
brainload.brainlocate module
Find vertices closest to a given coordinate in a brain surface mesh. Some of these functions require scipy, which is an optional dependency and needs to be installed manually.
- class brainload.brainlocate.BrainLocate(vert_coords, faces)
Bases:
object- get_closest_vertex(query_coords)
Find the vertex closest to each of the given coordinates. Requires scipy.
- Parameters:
query_coords (numpy 2D array) – The coordinates, given as a numeric array with shape (n, 3) for n coords.
- Returns:
Array with shape (n, ). Each value represents the index of the vertex closest to the respective query coordinate.
- Return type:
numpy 1D array
- get_closest_vertex_and_distance(query_coords)
Find the vertex closest to each of the given coordinates, and the respective distance. Requires scipy.
- Parameters:
query_coords (numpy 2D array) – The coordinates, given as a numeric array with shape (n, 3) for n coords.
- Returns:
Array with shape (n, 2). Each row represents the index of the vertex closest to the respective query coordinate (at index 0) and the respective distance (at index 1).
- Return type:
numpy 1D array
brainload.brainvoxlocate module
Given a voxel in a brain volume, find the FreeSurfer region it lies in (or the closest one if it is not in any region).
- class brainload.brainvoxlocate.BrainVoxLocate(volume_file, lookup_file)
Bases:
objectVoxel segmentation label locator. This class allows you to determine the label (both label code/number and label name) from a lookup table file (usually FreeSurferColorLUT.txt) that is assigned to a voxel in a segmentation output volume (like aseg.mgz or aparc+asgeg.mgz).
Examples
Initialize a locator based on a volume (a segmentation output, i.e., the value assigned to each voxel in the volume represents the tissue class it has been assigned to by the segmentation) and a lookup table file:
>>> volume_file = os.path.join(TEST_DATA_DIR, 'subject1', 'mri', 'aseg.mgz') >>> lookup_file = os.path.join(TEST_DATA_DIR, 'fs', 'FreeSurferColorLUT.txt') >>> locator = vloc.BrainVoxLocate(volume_file, lookup_file)
Now define some voxels we are interested in. Voxels are given by their column, row, slice (RCS) indices in the volume. These always start at 0 and range from 0 to d-1, where d is the length of the volume along the respective axis. So if your volume file has shape (128, 128, 128), the 3 indices along the 3 axes all range from 0 to 127.
>>> query_vox_crs = np.array([[24, 28, 20], [64, 64, 45], [90, 90, 90], [95, 127, 45]], dtype=int)
Now get the classes of exactly these voxels:
>>> seg_code, seg_name = locator.get_voxel_segmentation_labels(query_vox_crs)
Now print the code and the string for the first query voxel, (24, 28, 20):
>>> print("Voxel has label code %d, which encodes label string '%s'." % (seg_code[0], seg_name[0]))
Note that some voxels may not be assigned any label. These will show the label code 0, which means label name ‘Unknown’. Sometimes, you may want to know the label of the closest voxel which has a valid label for these. For example, because you want to know the brain structure that is closest to this voxel, even if the point does not lie within that structure. You can do this and allow a certain neighborhood to be searched with the
`get_closest_not_unknown`function:>>> voxels, codes, distances, closest_voxels_ras_coords = locator.get_closest_not_unknown(query_vox_crs)
See the documentation for that function for details on the return values.
- get_closest_not_unknown(query_voxels_crs, unknown_label=0, neighborhood_size=10)
Determine the closest voxels which have a non-empty label.
Determine the closest voxels which have a non-empty label, their labels, and the respective distance. Requires scipy. This allow you to determine the brain structure closest to a voxel (within a distance threshold), even if the voxel idoes not lie directly within the brain structure. This function uses Euclidian distance to determine which voxel is closest (but it only checks voxels with the given neighborhood, of course). If one of the query voxels lies directly within a brains structure (i.e., the voxel itself has a valid label), that label will be returned and the distance will be 0.0, of course.
- Parameters:
query_voxels_crs (numpy 2D array of int) – The query voxels, each given by its CRS indices. So the shape is (n, 3) for n query voxels.
neighborhood_size (int, optional) – Distance threshold in voxels along each direction of each axis, must be a positive integer or zero. Only the neighborhood of each query voxel will be searched. Example: If you pass 0, only the voxel itself is searched. If you pass 1, up to 3x3 = 27 voxels around it will be searched. If you pass 3, up to 7x7x7 = 343 voxels will be searched. The ‘up to’ refers to the case where the query voxel is at the border of the volume. In that case, some of the voxels do not exist (and thus are not checked). Defaults to 10. Note that if you set this to a very large value, a pairwise distance matrix of considerable size has to be computed, which may take some time. E.g., if you set it to 100, the distances between 201x201x201=8,120,601 voxels will be computed. This means that 8120601 ^ 2 / 2 - 8120601 = 32,972,072,179,999 distances need to be computed. No matter what you put, only valid voxel indices within the volume will be used for computation.
unknown_label (int, optional) – The segmentation value that represents the ‘Unknown’ class. Defaults to 0, which is suitable for the FreeSurferColorLUT.txt file.
- Returns:
voxels (numpy 2D int array) – The result voxels, one for each query voxel. Each voxel is given by its CRS indices. So the shape is (n, 3) for n query voxels. If no suitable voxel with non-empty label code was found for a query voxel, the coordinates are [-1, -1, -1].
codes (numpy 1D int array) – The label codes for the result voxels. If no suitable voxel with non-empty label code was found for a query voxel, the code is -1.
distances (numpy 1D float array) – The distances from the respective query voxel to the result voxel. These are determined from the RAS coordinates of the voxel pair, using the ras2vox and vox2ras matrices in the volume file header. (The distance is 0.0 if the query voxel itself has a nonzero label.) If no suitable voxel with non-empty label code was found for a query voxel, the distance is -1.0f.
closest_voxels_ras_coords (numpy 2D float array) – The RAS coordinates of the chosen voxel. If the query voxel has a none-empty label, this is its own coordinate. Otherwise, it is the coordinate of the closest voxel with valid label. If no such voxel was found, the coordinates are [-1.0, -1.0, -1.0]. Note that this could theoretically be a valid RAS coordinate, so you should not use this field to determine whether a valid voxel was found. Use the
`voxels`return value for that.
Examples
Initialize a locator based on a volume (a segmentation output, i.e., the value assigned to each voxel in the volume represents the tissue class it has been assigned to by the segmentation) and a lookup table file:
>>> volume_file = os.path.join(TEST_DATA_DIR, 'subject1', 'mri', 'aseg.mgz') >>> lookup_file = os.path.join(TEST_DATA_DIR, 'fs', 'FreeSurferColorLUT.txt') >>> locator = vloc.BrainVoxLocate(volume_file, lookup_file)
Now define some voxels we are interested in. Voxels are given by their column, row, slice (RCS) indices in the volume. These always start at 0 and range from 0 to d-1, where d is the length of the volume along the respective axis. So if your volume file has shape (128, 128, 128), the 3 indices along the 3 axes all range from 0 to 127.
>>> query_vox_crs = np.array([[24, 28, 20], [64, 64, 45], [90, 90, 90], [95, 127, 45]], dtype=int)
Now get the classes of these voxels. If the voxel itself has no label (i.e., it has the ‘Unknown’ label), search with a square neighborhood of 5 voxels along each direction of each axis for the closest valid label.
>>> voxels, codes, distances, closest_voxels_ras_coords = locator.get_closest_not_unknown(query_vox_crs, neighborhood_size=5)
- get_ras_coords_at_voxel_crs(query_crs_coords)
Find the RAS coord of each voxel.
Find the RAS coord of each voxel. A voxel is identified by its indices along the 3 axes, also knows as CRS (column, row, slice). The computation is based on the ras2vox matrix in the file header.
- Parameters:
query_crs_coords (numpy 2D int array) – The 3D row, column, slice indices for each voxel, given as a numeric array with shape (n, 3) for n voxels.
- Returns:
Array with shape (n, 3) representing the RAS coordinates in the volume file (x,y,z).
- Return type:
numpy 2D float array
- get_voxel_crs_at_ras_coords(query_coords)
Find the voxel closest to each of the given coordinates.
Find the voxel closest to each of the given coordinates. A voxel is identified by its indices along the 3 axes, also knows as CRS (column, row, slice). The computation is based on the ras2vox matrix in the file header.
- Parameters:
query_coords (numpy 2D float array) – The 3D coordinates, given as a numeric array with shape (n, 3) for n coords.
- Returns:
Array with shape (n, 3) representing the voxel indices in the volume file.
- Return type:
numpy 2D int array
- get_voxel_segmentation_labels(query_voxels_crs)
Find the exact labels for the given voxels.
Find the exact labels for the given voxels. All voxels will have a label, but label 0 means ‘Unknown’. (Sometimes, you may want to know the label of the closest voxel which has a valid label for these. For example, because you want to know the brain structure that is closest to this voxel, even if the point does not lie within that structure. See the function
`get_closest_not_unknown`for that use case.)- Parameters:
query_vox_crs (numpy 2D array of int) – The query voxels, each given by its CRS indices. So the shape is (n, 3) for n query voxels.
- Returns:
voxel_seg_code (numpy 1D int array) – The voxel segmentation codes from the lookup file. All voxels will have a label, but label 0 means ‘Unknown’.
voxel_seg_name (numpy 1D str array) – The voxel segmentation names from the lookup file. All voxels will have a label, but label 0 means ‘Unknown’.
Examples
Initialize a locator based on a volume (a segmentation output, i.e., the value assigned to each voxel in the volume represents the tissue class it has been assigned to by the segmentation) and a lookup table file:
>>> volume_file = os.path.join(TEST_DATA_DIR, 'subject1', 'mri', 'aseg.mgz') >>> lookup_file = os.path.join(TEST_DATA_DIR, 'fs', 'FreeSurferColorLUT.txt') >>> locator = vloc.BrainVoxLocate(volume_file, lookup_file)
Now define some voxels we are interested in. Voxels are given by their column, row, slice (RCS) indices in the volume. These always start at 0 and range from 0 to d-1, where d is the length of the volume along the respective axis. So if your volume file has shape (128, 128, 128), the 3 indices along the 3 axes all range from 0 to 127.
>>> query_vox_crs = np.array([[24, 28, 20], [64, 64, 45], [90, 90, 90], [95, 127, 45]], dtype=int)
Now get the classes of exactly these voxels:
>>> seg_code, seg_name = locator.get_voxel_segmentation_labels(query_vox_crs)
See also
`get_closest_not_unknown`can find the brain structure closest to a voxel, even if the voxel does not lie within that structure.
brainload.brainwrite module
Some functions for writing brain data to files.
These functions are helpful if you want to generate and write volume or surface data.
- brainload.brainwrite.get_surface_vertices_overlay_text_file_lines(num_verts, vertex_mark_list, background_rgb=[200, 200, 200], dtype=<class 'numpy.uint8'>)
Generates a surface overlay as a text file.
Performs the same task as get_surface_vertices_overlay_volume_data, but outputs the data as lines that can be written to a text file. This is an alternate format for a surface overlay file. You can write the returned lines to a text file and load the result as a surface colormap in Freeview: load a surface like
`lh.pial`, select it on the left pane and then click`Color -> Load RGB Map...`.- Parameters:
num_verts (int) – The number of vertices of the surface. E.g., 163842 if you want to color vertices on a hemisphere from the fsaverage Freesurfer subject.
vertex_mark_list (list of tuples) – Each tuple contains first the voxel indices (1D numpy int array with shape (n, ) for n vertices) and then a 1D array of length 3 that represents the RGB values of the color to assign to all the previously given n vertices.
background_rgb (numpy 1D array of length 3, optional) – The background color, defined as 3 RGB values. Defaults to [200, 200, 200], which is a bright gray. This is assigned to all vertices which do not occur in vertex_mark_list.
dtype (data type, optional) – The data type of the returned data 3D array. Defaults to
`np.uint8`.
- Returns:
lines – A list of lines that can be written to a text file as a surface overlay. Each line represents the color of a single vertex. Vertex order is the same as the order of vertices in the surface file that this overlay is for.
- Return type:
list of str
- brainload.brainwrite.get_surface_vertices_overlay_volume_data(num_verts, vertex_mark_list, background_rgb=[200, 200, 200], dtype=<class 'numpy.uint8'>)
Generates a surface overlay as a binary volume image file.
Generates a surface overlay volume. The volume contains one color value per vertex of the surface and can be used to visualize different vertices on a brain surface. This functions supports coloring different sets of vertices with different colors. All vertices which are not explicitely listed with a color to assign to them are given the background color. You can write the result volume to an mgz file and load the result as a surface overlay in Freeview: load a surface like
`lh.pial`, select it on the left pane and then click`Overlay -> Load generic...`. Note that saving to nifti will not work in many cases (depends on num_verts), as the dimensions are usually too large to be saved to nifti formats.- Parameters:
num_verts (int) – The number of vertices of the surface. E.g., 163842 if you want to color vertices on a hemisphere from the fsaverage Freesurfer subject.
vertex_mark_list (list of tuples) – Each tuple contains first the voxel indices (1D numpy int array with shape (n, ) for n vertices) and then a 1D array of length 3 that represents the RGB values of the color to assign to all the previously given n vertices.
background_rgb (numpy 1D array of length 3, optional) – The background color, defined as 3 RGB values. Defaults to [200, 200, 200], which is a bright gray. This is assigned to all vertices which do not occur in vertex_mark_list.
dtype (data type, optional) – The data type of the returned data 3D array. Defaults to
`np.uint8`.
- Returns:
voxel_data – A 3D array with shape (n, 3, 1) for the n vertices of the surface that contains the colors given by the 3 RGB values.
- Return type:
numpy 3D array
Examples
Create an overlay for an fsaverage hemisphere (which always has exactly 163842 vertices) and mark 3 of the vertices in red and 4 others in green. The rest will be gray.
>>> num_verts = 163842 >>> vertex_mark_list = [(np.array([0, 2, 4], dtype=int), [255, 0, 0]), (np.array([1, 3, 5, 7], dtype=int), [0, 255, 0])] >>> vol_data = bw.get_surface_vertices_overlay_volume_data(num_verts, vertex_mark_list, background_rgb=[200, 200, 200])
You could now write this to a nifti or mgz file and load it as a surface overlay.
See also
`get_surface_vertices_overlay_volume_data_1color`: the same data, but use one intensity value per vertex instead of 3 RGB values. Allows usage of FreeSurfer hack for saving to nifti format in case of fsaverage.`get_surface_vertices_overlay_text_file_lines`: the same data, but for writing to a similar file in text format that can be loaded as a color map. Uses RGB color. No dimension limitations.
- brainload.brainwrite.get_surface_vertices_overlay_volume_data_1color(num_verts, vertex_mark_list, background_value=0, dtype=<class 'numpy.uint8'>)
Generates a surface overlay as a binary volume image file.
Generates a surface overlay volume. The volume contains one color value per vertex of the surface and can be used to visualize different vertices on a brain surface. This functions supports coloring different sets of vertices with different colors. All vertices which are not explicitely listed with a color to assign to them are given the background color. You can write the result volume to a nifti or mgz file and load the result as a surface overlay in Freeview: load a surface like
`lh.pial`, select it on the left pane and then click`Overlay -> Load generic...`. Note that saving to nifti will only works if num_verts is exactly 163842, the number of vertices of fsaverage, as it abuses the FreeSurfer hack to save large dimensions in nifti files.- Parameters:
num_verts (int) – The number of vertices of the surface. E.g., 163842 if you want to color vertices on a hemisphere from the fsaverage Freesurfer subject.
vertex_mark_list (list of tuples) – Each tuple contains first the voxel indices (1D numpy int array with shape (n, ) for n vertices) and then an int that represents the intenstiy value to all the previously given n vertices.
background_value (int, optional) – The background value. This is assigned to all vertices which do not occur in vertex_mark_list.
dtype (data type, optional) – The data type of the returned data 3D array. Defaults to
`np.uint8`.
- Returns:
voxel_data – A 3D array with shape (n, 1, 1) for the n vertices of the surface.
- Return type:
numpy 3D array
Examples
Create an overlay for an fsaverage hemisphere (which always has exactly 163842 vertices) and mark 3 of the vertices in red and 4 others in green. The rest will be gray.
>>> num_verts = 163842 >>> vertex_mark_list = [(np.array([0, 2, 4], dtype=int), [255, 0, 0]), (np.array([1, 3, 5, 7], dtype=int), [0, 255, 0])] >>> vol_data = bw.get_surface_vertices_overlay_volume_data(num_verts, vertex_mark_list, background_rgb=[200, 200, 200])
You could now write this to a nifti or mgz file and load it as a surface overlay.
See also
`get_surface_vertices_overlay_volume_data`: the same data, but for writing to a similar file in text format
- brainload.brainwrite.get_volume_data_with_custom_marks(voxel_mark_list, background_voxel_value=0, shape=(256, 256, 256), dtype=<class 'numpy.uint8'>)
Generate a volume in which the target voxels are marked by the individual colors assigned to each voxel array in the list.
Generate a volume in which the values of all target_voxel_indices are set to a target_voxel_value that can be defined separately for each subject/entry in the list. This is useful for visualizing the voxels in a 3D viewer.
- Parameters:
voxel_mark_list (list of tuples) – Each tuple contains first the voxel indices (2D numpy int array with shape (n, 3)) and then a single integer, the voxel value to use for the voxel indices.
background_voxel_value (np.uint8, optional) – The value to assign to all voxels which are not in the voxel_mark_list, i.e., the background voxels. Defaults to 0. The type must match the dtype parameter.
shape (tupel of int, optional) – The shape of the 3D volume, i.e., the number of voxels along the 3 dimensions. Defaults to (256, 256, 256).
dtype (datatype, optional) – The data type of the returned data 3D array. Defaults to
`np.uint8`.
- Returns:
voxel_data – The shape depends on the shape parameter, and the data type on the dtype parameter of this function. The voxels within this 3D volume are marked with the requested target values (or the background value).
- Return type:
numpy multi-dimensional array
Examples
Create volume data with shape 256x256x256 in which 2 voxels are marked with intensity value 40, and 2 other voxels with intensity value 160: >>> import brainload.brainwrite as bw >>> voxel_mark_list = [(np.array([[15, 25, 30], [24, 24, 24]], dtype=int), 40), (np.array([[44, 44, 44], [55, 55, 55]], dtype=int), 160)] >>> vol_data = bw.get_volume_data_with_custom_marks(voxel_mark_list, background_voxel_value=0, shape=(256, 256, 256))
You could now write vol_data to a nifti file using nibabel:
>>> import nibabel as nib >>> ni_img = nib.Nifti1Image(vol_data, np.eye(4)) >>> nib.save(ni_img, 'my_data.nii')
- brainload.brainwrite.write_voldata_to_mgh_file(mgh_file_name, vol_data, affine=None, header=None)
Write volume data to a MGH format file.
Write the volume data to a file in MGH format. The format is from FreeSurfer and stores volume images. Unless you supply a header, the header will be pretty empty. Thin wrapper around nibabels
`MGHImage`class and the`to_filename`method inherited from`FileBasedImage`. Note that if you just modified data that you loaded from a source image (e.g., you replaced some intensities), you should pass the affine and the header of the original image.- Parameters:
mgh_file_name (str) – Path to output file. Will be overwritten if it exists. Should have file extension mgh.
vol_data (the data to write, usually a multi-dimensional numpy array. Shape could be (256, 256, 256) for a 3D image, or (256, 256, 256, 50) for a 4D image containing 50 time points, but this is up to you.)
affine (numpy 2D array, optional) – The affine registration matrix (4x4) relating the voxel coordinates to world coordinates in RAS+ space. See nibabel docs for details.
header (nibabel.freesurfer.mghformat.MGHHeader, optional) – The MGH file header. If not given, an empty default header will be used.
- brainload.brainwrite.write_voldata_to_nifti_file(file_name, vol_data, affine=None, header=None)
Write volume data to a nifti file.
Write the volume data to a file in NIFTI v1 format. Unless you supply a header, the header will be pretty empty. Very thin wrapper around nibabel.save. Note that if you just modified data that you loaded from a source image (e.g., you replaced some intensities), you should pass the affine and the header of the original image. They are available as orig_image.affine and orig_image.header, where orig_image is the return value of nibabel.load.
- Parameters:
file_name (str) – Path to output file. Will be overwritten if it exists. Should have file extension nii (or ngz for gzip compression).
vol_data (the data to write, usually a multi-dimensional numpy array. Shape could be (256, 256, 256) for a 3D image, or (256, 256, 256, 50) for a 4D image containing 50 time points, but this is up to you. Note however that the Nifti 1 format is limited in how large the individual dimensions may be and how many dimensions are supported. See nibabel for details.)
affine (numpy 2D array, optional) – The affine registration matrix (4x4) relating the voxel coordinates to world coordinates in RAS+ space. See nibabel docs for details.
header (nibabel.Nifti1Header, optional) – The nifti header. If not given, an almost empty default header will be used.
brainload.stats module
Functions for parsing FreeSurfer brain stat files.
You can use these to read files like subject/stats/aseg.stats. Note that these functions read the stats files for a single subject, typically from the ‘stats’ sub directory of that subject.
Notes
You could also use the FreeSurfer command ‘aparcstats2table’ to merge data from many subjects for a measure (like ‘thickness’) into a single file and parse that file. This is NOT what is done by these functions though, they are designed for the stats files that are generated by default.
The information in the aseg.stats file is of interest because many brain properties interact with brain volume or cortical thickness, so people often use these as covariates in their models.
The atlas stats files (e.g., lh.aparc.stats) contain information on the different brain regions, based on registering the respective subject to a brain atlas.
- brainload.stats.extract_column_from_table_data(all_subjects_table_data_dict, column_name_for_dict_keys, column_name_of_values, dtype=<class 'numpy.float64'>)
For all rows and a single column, extract the data for all subjects.
For all rows and a single column, extract the data for all subjects. This results in a dictionary of vectors, representing the column.
- Parameters:
all_subjects_table_data_dict (dict of str to numpy 2D array) – Data as returned by the
`group_stats`function.column_name_for_dict_keys (str) – The column name (key in all_subjects_table_data) of the column of which the values in each row will be used to identify the output data. Think of this as labels.
column_name_of_values (str) – The column name (key in all_subjects_table_data) of the column holding the values you want to retrieve.
- Returns:
The data for column column_name_of_values for all subjects. Each row is represented by one entry. The key is the value of the column column_name_for_dict_keys for the row (must be unique) and the value is the value of the column column_name_of_values. Note that you could turn this into a Pandas DataFrame very easily if you use Pandas.
- Return type:
dictionary string to numpy 1D array
Examples
Load the aseg stats for a group of subjects in the pre-defined directory my_subjects_dir:
>>> _, all_subjects_table_data_dict = st.group_stats_aseg(['subject1', 'subject2'], my_subjects_dir)
Now get the data for the number of voxels for all rows (=brain structures). Label the result with the structure name column:
>>> column_data = st.extract_column_from_table_data(all_subjects_table_data_dict, 'StructName', 'NVoxels')
The aseg.stats table contains 45 rows for the 45 brain structures:
>>> assert len(column_data) == 45
Retrieve the data for all subjects, a 2D numpy array:
>>> assert 'Left-Lateral-Ventricle' in column_data >>> all_subjects_data = column_data['Left-Lateral-Ventricle']
Let us find out the number of voxels for the left lateral ventricle of the first subject:
print(all_subjects_data[0])
- brainload.stats.extract_field_from_table_data(column_name, row_index, all_subjects_table_data_dict, dtype=<class 'numpy.float64'>)
Extract the values in one table field for all subjects.
Extract the values in one table field, given by the column_name and row_index, for all subjects.
- Parameters:
colum_name (str) – The name of the column that should be handled, i.e., the key in all_subjects_table_data_dict. In combination with row_index, this defines the field that should be handled.
row_index (int) – The index of the row that should be handled. In combination with column_name, this defines the field that should be handled. Note: you can use
`extract_table_data_indices_where`to find the row index you want based on any value of any column.all_subjects_table_data_dict (dict of str to numpy 2D array) – Data as returned by the
`group_stats`function.dtype (numpy data type, optional) – The data type of the returned numpy array. Defaults to
`numpy.float_`if omitted.
- Returns:
The data for all subjects, shape is (n, ) for n subjects.
- Return type:
numpy 1D array
- brainload.stats.extract_table_data_indices_where(column_name, target_value_string, all_subjects_table_data_dict)
Find the row index (or indices) in the table where the column column_name takes on the value target_value_string.
Find the row index (or indices) in the table where the column column_name takes on the value target_value_string. Typically you would chose a column and target value combinatin that is unique, leading to a single index (array of length 1). Note that this used the first entry (row) in the 2D matrix to read values: it is assumed that all entries are identical (since the data should come from equivalent stats files for all subjects).
- Parameters:
colum_name (str) – The name of the column that should be handled, i.e., the key in all_subjects_table_data_dict. In combination with row_index, this defines the field that should be handled.
target_value_string (byte string) – The value identifying the row you want. Note that this should be unique. If it is not, the returned list has length > 1. Also note that the comparison happens before casting to dtype, so the value given here must be of type str. Note that this must a byte string, so in Python 3 you have to explicitely pass something like
`b'word_here'`.all_subjects_table_data_dict (dict of str to numpy 2D array) – Data as returned by the
`group_stats`function.
- Returns:
The list of indices.
- Return type:
numpy 1D array
Examples
Find the index of the row where the value of the ‘StructName’ column is ‘Left-Amygdala’:
>>> _, all_subjects_table_data_dict = st.group_stats_aseg(['subject1', 'subject2'], my_subjects_dir) >>> row_indices = st.extract_table_data_indices_where('StructName', 'Left-Amygdala', all_subjects_table_data_dict) >>> assert len(row_indices) == 1 >>> assert row_indices[0] == 12 # see aseg.stats table: amygdala is row 12
- brainload.stats.get_stats_table_column_names(subjects_dir, stats_file_name, subject='fsaverage')
- brainload.stats.group_stats(subjects_list, subjects_dir, stats_file_name, stats_table_type_list=None)
Retrieve stats for a group of subjects.
Retrieve stats for a group of subjects. The file may be for one hemisphere (files like lh.aparc.stats) or for the entire brain (like stats_table_type_list.stats). This function does not care about hemispheres, it parses a file.
- Parameters:
subjects_list (list of str) – List of subject identifiers (subjects in the subjects_dir).
subjects_dir (str) – Subjects directory, as defined by the environment variable SUBJECTS_DIR for FreeSurfer.
stats_file_name (str) – File name of the subjects file including file extension, relative to a subject’s
`stats`directory. Example: ‘aseg.stats’.stats_table_type_list (list of numpy types, optional.) – A list defining the data types for the columns in the table contained in stats files. See the functions typelist_for_aseg_stats and typelist_for_aparc_atlas_stats for examples. If omitted, the table data will be returned as None. The measures data is unaffected.
- Returns:
all_subjects_measures_dict (dict of string to numpy 1D array.) – The data from the measure rows in the files. Each key in the dictionary is the name of a measure, and the value is the data for all subjects in a numpy float array. The array shape is (n, ) for n subjects.
all_subjects_table_data_dict (dict of string to numpy 2D array) – The data for all table columns in the files. Each key in the dictionary is the name of a column in the stats table, and the value is the data for all rows (i.e., atlas regions) for all subjects in a numpy 2D float array. The array shape is (n, m) for n subjects and a table with m rows. Note that the data type differs between the arrays and is defined by the argument
`stats_table_type_list`. The colums include a string column that holds the region names, it is called ‘StructName’ for both aparc and aseg stats files.
See also
typelist_for_aseg_statspre-defined list of numpy data types for the files aseg.stats, can be used to pass stats_table_type_list
typelist_for_aparc_atlas_statspre-defined list of numpy data types for the files lh.aparc.stats and rh.aparc.stats, can be used to pass stats_table_type_list
- brainload.stats.group_stats_aparc(subjects_list, subjects_dir, hemi)
- brainload.stats.group_stats_aparc_DKTatlas(subjects_list, subjects_dir, hemi)
- brainload.stats.group_stats_aparc_a2009s(subjects_list, subjects_dir, hemi)
- brainload.stats.group_stats_aseg(subjects_list, subjects_dir)
- brainload.stats.group_stats_by_row(subjects_list, subjects_dir, stats_file_name, stats_table_type_list=None)
Retrieve stats for a group of subjects.
Retrieve stats for a group of subjects. The file may be for one hemisphere (files like lh.aparc.stats) or for the entire brain (like stats_table_type_list.stats). This function does not care about hemispheres, it parses a file.
- Parameters:
subjects_list (list of str) – List of subject identifiers (subjects in the subjects_dir).
subjects_dir (str) – Subjects directory, as defined by the environment variable SUBJECTS_DIR for FreeSurfer.
stats_file_name (str) – File name of the subjects file including file extension, relative to a subject’s
`stats`directory. Example: ‘aseg.stats’.stats_table_type_list (list of numpy types, optional.) – A list defining the data types for the columns in the table contained in stats files. See the functions typelist_for_aseg_stats and typelist_for_aparc_atlas_stats for examples. If omitted, the table data will be returned as None. The measures data is unaffected.
- Returns:
all_subjects_measures_dict (dict of string to numpy 1D array.) – The data from the measure rows in the files. Each key in the dictionary is the name of a measure, and the value is the data for all subjects in a numpy float array. The array shape is (n, ) for n subjects.
all_subjects_table_data_dict_by_region (dict of string to dict of string to numpy 2D array) – The data for all table rows (regions) in the files. Each key in the dictionary is the name of a region (row, ‘StructName’ column entry in that row) in the stats table. Then the value is another dictionary, where the keys are subject IDs. The value is the data for all columns in the table for that subject. If a subject has no data on a region, it still has an entry, but all the values are NaNs.
See also
typelist_for_aseg_statspre-defined list of numpy data types for the files aseg.stats, can be used to pass stats_table_type_list
typelist_for_aparc_atlas_statspre-defined list of numpy data types for the files lh.aparc.stats and rh.aparc.stats, can be used to pass stats_table_type_list
brainload.annotations.get_atlas_region_namesget region names for an atlas/annotation
- brainload.stats.measures_to_numpy(measures, requested_measures=None, dtype=<class 'numpy.float64'>)
Convert the measures list of lists to a 2D numpy array of the given type.
Convert the measures list of lists to a 2D numpy array of the given type. If only some of the measures are compatible with the type, you can give the names of all requested measures as a dictionary.
- Parameters:
measures (list of str lists) – measures as returned by the stat() function: each element of the outer list represents a row in a stats file, and the inner string list contains the tokens of the line
requested_measures (list of string 2-tuples, optional) – If given, only the measures listed in here are used. Each measure is identified by 2 strings, which must match the first and second token on the measure line. For a line like ‘# Measure Cortex, NumVert, Number of Vertices, 140843, unitless’, the 2 strings of a tuple would be ‘Cortex’ and ‘NumVert’. If omitted, all measures will be used.
dtype (numpy data type, optional) – The data type that should be used for the returned numpy array. Defaults to
`np.float64`if omitted.
- Returns:
measures_data (numpy 1D array) – The measure values, with the requested data type. The shape is (n, ) for n (requested) measures. The order is as given in the parameter measures. (If requested_measures is set, only those are included.)
measure_names (list of string 2-tuples) – The names of the measures (same order as the data). The order is guaranteed to be identical to the order of measures in the input argument. (If requested_measures is set, only those are included.)
- brainload.stats.parse_curve_stats(subject_id, subjects_dir, hemi)
- brainload.stats.parse_curve_stats_file(curv_file)
Parse curv.stats files.
Parse files stats/lh.curv.stats or stats/rh.curv.stats. Return all values and their names.
- brainload.stats.register_dat_matrix(file_path)
Parse the registration matrix from the given file.
Parse the registration matrix from the given file in register.dat file format. See https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat for the file format. The matrix encodes an affine transformation that can be applied to a coordinate vector.
- Parameters:
file_path (str) – Path to the file in register.dat format.
- Returns:
The parsed matrix, with dimension (4, 4).
- Return type:
2D numpy array of floats
Examples
Parse a register.dat file that comes with FreeSurfer v6.0:
>>> reg_data_file = os.path.join(my_freesurfer_dir, 'subjects', 'cvs_avg35_inMNI152', 'mri.2mm', 'register.dat') >>> matrix = st.register_dat_matrix(reg_data_file)
- brainload.stats.stat(file_name)
Read information from a FreeSurfer stats file.
Read information from a FreeSurfer stats file, e.g., subject/stats/lh.aparc.stats or aseg.stats. A stats file is a text file that contains a data table and various meta data.
- Parameters:
file_name (string) – The path to the stats file.
- Returns:
- The result dictionary, containing the following 4 keys:
’ignored_lines’: list of strings. The list of lines that were not parsed in a special way. This is raw data.
’measures’: string list of dimension (n, m) if there are n measures with m properties each stored in the stats file.
’table_data’: string list of dimension (i, j) when there are i lines containing j values each in the table stored in the stats file. You may want to convert the columns to the proper data types and put the result into several numpy arrays or a single Pandas data frame.
’table_column_headers’: string list. The names for the columns for the table_data. This information is parsed from the table_meta_data and given here for convenience.
’table_meta_data’: dictionary. The full table_meta_data. Stores properties in key, value sub dictionaries. For simple table properties, the dictionaries are keys of the returned dictionary. The only exception is the information on the table columns (header data). This information can be found under the key column_info_, which contains one dictionary for each column. In these dictionaries, data is stored as explained for simple table properties.
- Return type:
dictionary of strings (includes nested sub dicts)
Examples
Read the aseg.stats file for a subject:
>>> import brainload as bl >>> stats = bl.stat('/path/to/study/subject1/stats/aseg.stats')
Collect some data, just to show the data structures.
>>> print(len(stats['measures'])) # Will print the number of measures. >>> print("|".join(stats['measures'][0])) # Print all data on the first measure.
Now lets print the table_data:
>>> num_data_rows = len(stats['table_data']) >>> num_entries_per_row = len(stats['table_data'][0])
And get some information on the table columns (the table header):
>>> print stats['table_meta_data']['NTableCols'] # will print "10" (from a simple table property stored directly in the dictionary).
Get the names of all the data columns:
>>> print ",".join(stats['table_column_headers'])
Get the name of the first column:
>>> first_column_name = stats['table_column_headers'][0]
More detailed information on the individual columns can be found under the special column_info_ key if needed:
>>> column2_info_dict = stats['table_meta_data']['column_info_']['2'] >>> print(column2_info_dict['some_key']) # will print the value
Note that all data is returned as string type, you will need to covert it to float (or whatever) yourself.
- brainload.stats.stats_table_region_label_column_name()
Returns the name of the column that contains the region names for the table in stats files. The name is identical for all standard Freesurfer parcellation and segmentation stats files (aseg.stats, ?h.aparc.stats, ?h.aparc.a2009s.stats, and ?h.aparc.DKTatlas.stats), so the current version returns a fixed string.
- brainload.stats.stats_table_to_numpy(stat, type_list)
Given types, convert the string matrix to a dictionary of numpy arrays (one for each table column).
Given types, convert the string matrix to a dictionary of numpy arrays (one for each table column). The stat dictionary is returned by the stat function, and you have to specify a list of numpy types, one for each column, to convert this. The type list is specific for the file that has been parsed, i.e., it differs between asge.stats and lh.aparc.stats. Determine it by looking at the file data. See the typelist_for_* functions in this module for pre-defined type lists for commonly parsed FreeSurfer stats files. Note that this function works by column, which is fine for a single subject, but may be problematic for group stats: the reason is that Freesurfer seems to omit regions from the stats file if the subject has no vertices which are assigned to that particular region. This means one cannot rely on all subjects having the same number of lines in the same stats file. It also means that if a subject does not contain the expected, full number of rows, the row number of a certain region differs by subject. This means parsing on a column-basis, like this function does it, does not work well for group stats. See the
`stats_table_to_numpy_by_row`function for a solution.- Parameters:
stat (dictionary) – The data returned by the stat() function. Must contain the keys ‘table_data’ (2D list of strings, dimension n x m for n rows with m columns each) and ‘table_column_headers’ (1D list of m strings).
type_list (list of numpy types) – List of numpy types with length m. Types must be listed in the order in which they should be applied to the columns.
- Returns:
dictionary of string – Each key is a column name, and each value is a numpy column array containing the typed data with shape (n, ) for n data rows in the table for the subject.
- Return type:
numpy array
- brainload.stats.stats_table_to_numpy_by_row(stat, type_list, subject_id, label_column_index=-1)
Given types, convert the string matrix to a dictionary of numpy arrays (one for each table row, i.e., atlas region).
Given types, convert the string matrix to a dictionary of numpy arrays (one for each table row, i.e., atlas region).
- Parameters:
stat (dictionary) – The data returned by the stat() function. Must contain the keys ‘table_data’ (2D list of strings, dimension n x m for n rows with m columns each) and ‘table_column_headers’ (1D list of m strings).
type_list (list of numpy types for columns) – List of numpy types with length m. Types must be listed in the order in which they should be applied to the columns.
subject_id (string) – The subject id for the data.
label_column_index (int, optional) – The index of the label column, i.e., the column that contains the values to be used as the key in the returned dictionary. Usually the index of the column named ‘StructName’. Optional. Defaults to -1, which means that the first column of type string (according to the
`type_list`argument) will be used.
- Returns:
dictionary of string – Each key is a row (i.e., atlas region) name, and each value is a numpy row array containing the data as np.floats with shape (n, ) for n data columns in the table for the subject. If the type of a column (as specified in the
`type_list`argument) is NOT a subtype of np.number, the value is returned as NaN.- Return type:
numpy array
- brainload.stats.typelist_for_aparc_atlas_stats()
Determine list of numpy data types for the table in an aparc atlas file.
Determine list of numpy data types for the table in an aparc atlas file. The type list is identical for the files ?h.aparc.stats, ?h.aparc.2009s.stats, and ?h.aparc.DKTatlas.stats. The 10 columns in each file are: StructName NumVert SurfArea GrayVol ThickAvg ThickStd MeanCurv GausCurv FoldInd CurvInd
- Returns:
List of the proper numpy data types to use for each data column in the file.
- Return type:
list of numpy data types
- brainload.stats.typelist_for_aseg_stats()
Determine list of numpy data types for the table in an aseg.stats file.
Determine list of numpy data types for the table in an aseg.stats file. The 10 columns in this file are: Index SegId NVoxels Volume_mm3 StructName normMean normStdDev normMin normMax normRange.
- Returns:
List of the proper numpy data types to use for each data column in the file.
- Return type:
list of numpy data types
brainload.surfacegraph module
brainload.braindescriptors module
Collect various brain descriptors.
Functions to collect brain descriptors from neuroimaging data preprocessed with FreeSurfer.
- class brainload.braindescriptors.BrainDescriptors(subjects_dir, subjects_list, hemi='both')
Bases:
objectCollects brain descriptors for one or more subjects.
This class can parse all standard statistics files which are written by FreeSurfer when a subject is preprocessed using the recon-all pipeline. This includes brain segmentation stats (volume-based, like the
`stats/aseg.stats`file), brain parcellation stats (surface-based, like`?h.aparc.a2009s.stats`) and special stats file like the`curv.stats`files.It can also compute stats based on a parcellation atlas and any custom morphometry measure that you may have computed (e.g., local gyrifiaction index or some arbitrary vertex-wise measure you have computed yourself).
You can export the resulting data to a CSV file so you can load them in your favorite statistical software later. (No, I did not mention AI.) If that favorite software happens to be python, you can just access the
`descriptor_names`and`descriptor_values`properties of the class instead.- add_curv_stats()
Add surface curvature stats.
Add brain surface curvature stats. This add the data from the
`stats/?h.curv.stats`files.
- add_custom_measure_stats(atlas_list, measure_list)
Add custom stats for a measure and atlas.
Add custom stats for a measure and atlas. E.g., compute descriptive stats (min, max, mean, …) for a measure like ‘pial_lgi’ in all regions of an atlas like ‘aparc’.
- Parameters:
atlas_list (list of string) – Each entry should be a valid FreeSurfer segmentation name, like
`aseg`. A file with that name has to exist in the subjects directory under`stats/`, e.g.,`stats/aseg.stats`for`aseg`.measure_list (list of string) – A list of vertex-wise morphometry measurements, like
`volume`,`thickness`, or`area`. A hemisphere-dependent file with that name has to exist in the subjects directory under`surf/`, e.g.,`surf/lh.area`and`surf/rh.area`for the two hemispheres is the given string is`area`.
- add_parcellation_stats(atlas_list)
Add brain parcellation stats.
Add brain parcellation stats for a list of atlases, i.e., annotation files.
- Parameters:
atlas_list (list of strings) – The atlas names. E.g.,
`['aparc', 'aparc.a2009s']`.
- add_segmentation_stats(segmentation_list)
Add brain parcellation stats.
Add brain parcellation stats. This add the data from the stats/aseg.stats file.
- Parameters:
segmentation_list (list of string) – Each entry should be a valid FreeSurfer segmentation name, like
`aseg`. A file with that name has to exist in the subjects directory under`stats/`, e.g.,`stats/aseg.stats`for`aseg`.
- add_single_segmentation_stats(atlas)
Add brain parcellation stats.
Add brain parcellation stats. This add the data from the stats/aseg.stats file.
- Parameters:
atlas (string) – A valid FreeSurfer segmentation name, like
`aseg`. A file with that name has to exist in the subjects directory under`stats/`, e.g.,`stats/aseg.stats`for`aseg`.
- add_standard_stats()
Convenience function to add all descriptors which are computed by default when running Freesurfer v6 recon-all on a subject.
- check_for_NaNs(threshold=0.6)
Check for descriptors and subjects with all NaN values.
- Parameters:
threshold (float) – The NaN threshold, subjects and descriptors for which the share of NaN values exceeds this threshold are reported. Must be between .0 and 1.0 to make sense. Defaults to 0.6.
- Returns:
subjects_over_threshold (list of string) – The subjects
descriptors_over_threshold (list of string) – The descriptors
nan_share_per_subject (numpy float array) – The share of NaN values for each subject. Numpy array with length n for the n subjects.
nan_share_per_descriptor (numpy float array) – The share of NaN values for each descriptor. Numpy array with length m for the m descriptor.
- check_for_curv_stats_files()
- check_for_custom_measure_stats_files(annot_list, morph_list, morph_file_format='curv')
Check for custom annotation files.
Check for the existence of custom annotation and morphometry files.
- Parameters:
annot_list (list of strings) – The annotations (atlas file names), a typical entry in the list would be “aparc” or “aparc.a2009s”.
morph_list (list of strings) – The morphometry data, a typical entry in the list would be “area” or “thickness”.
morph_file_format (string, one of 'curv', 'mgh', or 'mgz'. Defaults to 'curv'.)
- check_for_hemi_dependent_file(parts)
Check for hemi-dependent file.
Check for the existence of a file that has an lh and an rh version.
- Parameters:
parts (list of strings) – Path to file, relative to the subject’s directory. The last list element should be the file name (all other ones are directories). The last element must NOT contain the prefix “lh.” or “rh.”, as these will be added automatically.
- check_for_hemi_independent_file(parts)
- check_for_parcellation_stats_files(atlas_list)
- check_for_segmentation_stats_files(segmentation_list)
- report_descriptors()
Print some information on descriptors to stdout.
- save(stats_file, subjects_file=None, delim=',')
Save the descriptors to files.
Save the descriptors to text files in CSV format.
- Parameters:
stats_file (string) – Path and file name for the CSV file that will hold the descriptor data.
subjects_file (string, optional) – Path a filename of a text file. If given, the subject IDs will be written to this file, one per line. The order of the subjects matches the order of the data in the stats_file.
delim (str) – Delimiter for stats_file, defaults to “,”.
Examples
>>> bd.save("braindescriptors.csv", subjects_file="subjects.txt")
brainload.spatial module
Simple functions for spatial tranformation of 3-dimensional coordinates.
These functions are helpful if you want to rotate, translate, mirror, or scale (brain) meshes. In general, you would use them roughly like this:
>>> import brainload as bl
>>> vert_coords, faces = bl.subject('bert')[0:2]
>>> x, y, z = bl.spatial.coords_a2s(vert_coords)
Now you have the coordinates of the mesh vertices in the required format and can call any function from this module:
>>> xt, yt, zt = bl.spatial.translate_3D_coordinates_along_axes(x, y, z, 5, 0, 0) # or some other function
- brainload.spatial.apply_affine(i, j, k, affine_matrix)
Applies an affine matrix to the given coordinates. The affine matrix consists of a 3x3 rotation matrix and a 3x1 transposition matrix (plus the last row).
- Parameters:
i (numeric scalars or array-likes) – The source coordinates.
j (numeric scalars or array-likes) – The source coordinates.
k (numeric scalars or array-likes) – The source coordinates.
affine_matrix (numpy 2D float array with shape (4, 4)) – The affine matrix
- Return type:
The coordinate vector after applying the matrix. A 1D array (vector) of shape (3, ) if the inputs were scalar, a 2D array with shape (n, 3) otherwise, were n is the length of the input array-likes.
See also
`apply_affine_3D`can handle a 2D matrix of coordinates, e.g., with shape (n, 3) for n 3D coordinates.
- brainload.spatial.apply_affine_3D(coords_3d, affine_matrix)
Apply an affine transformation to all coordinates.
- Parameters:
coords_3d (numpy 2D array) – The source coordinates, given as a 2D numpy array with shape (n, 3). Each of the n rows represents a point in space, given by its x, y and z coordinates.
affine_matrix (numpy 2D float array with shape (4, 4)) – The affine matrix
- Return type:
The coordinates after applying the matrix, 2D numpy array with shape (n, 3). Same shape as the input coords.
- brainload.spatial.coords_a2s(coords)
Split single array for all 3 coords into 3 separate ones.
Split a 2D array with shape (3, n) of coordinates (x, y, z values) into 3 separate 1D arrays of length n.
- Parameters:
coords (Numpy 2D array of numbers) – The merged coordinate array.
- Returns:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Has the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Has the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Has the same length as the x and y arrays.
Examples
>>> import brainload.spatial as st; import numpy as np; >>> coords = np.array([[5, 7, 9], [6, 8, 10]]) >>> x, y, z = st.coords_a2s(coords) >>> print y[1] 8
- brainload.spatial.coords_s2a(x, y, z)
Separate a single xyz coordinate array into x, y and z arrays.
Merge 3 arrays of length n with coordinates (x, y, z values) into a single 2D coordinate array of shape (3, n).
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays.
- Returns:
The merged coordinate array.
- Return type:
Numpy 2D array of numbers
Examples
>>> import brainload.spatial as st; import numpy as np >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> coords = st.coords_s2a(x, y, z) >>> print coords[1][2] 10
- brainload.spatial.deg2rad(degrees)
Convert an angle given in degrees to radians.
Convert an angle given in degrees to radians. 360 degrees are 2 Pi radians. If negative values or values larger than 360 are passed, use the modulo operation to bring them to a suitable range first. In other words, passing -90 will be transformed to 360 - 90 = 270 degrees, and will thus return 1.5 Pi radians.
- Parameters:
degrees (float) – The angle in degrees.
- Returns:
The angle in radians.
- Return type:
float
Examples
>>> import brainload.spatial as st >>> rad = st.deg2rad(180) # will be Pi
- brainload.spatial.get_affine_matrix_MNI152_to_MNI305()
Get the transformation matrix from MNI152 sapce to fsaverage space (=MNI305 space).
This is the inverse of the MNI305 to MNI152 matrix.
- Returns:
The affine transformation matrix, a float matrix with shape (4, 4).
- Return type:
2D numpy array
- brainload.spatial.get_affine_matrix_MNI305_to_MNI152()
Get the transformation matrix from fsaverage space (=MNI305 space) to MNI152 space.
Get the transformation matrix from fsaverage space (=MNI305 space) to MNI152 space. This matrix was retrieved from http://freesurfer.net/fswiki/CoordinateSystems, see use case 8 at the very bottom of the page. Quoting the linked page: ‘The above matrix is V152*inv(T152)*R*T305*inv(V305), where V152 and V305 are the vox2ras matrices from the 152 and 305 spaces, T152 and T305 are the tkregister-vox2ras matrices from the 152 and 305 spaces, and R is from $FREESURFER_HOME/average/mni152.register.dat’
- brainload.spatial.get_equivalent_voxel_of_raw_volume_in_conformed_volume(raw_volume_file, conformed_volume_file, raw_volume_query_voxels_crs)
Find the position of a voxel in the conformed volume.
Find the voxel CRS in the conformed volume that is equivalent to the query voxel CRS in the raw volume. Note that this always returns a single voxel for a query voxel. It does not compute all voxel that may represent the source voxel (e.g., if the voxel size is much smaller in the destination volume). Note that this function also works in reverse (simply exchange the order of the 2 volumes and give query voxels in the first one). In fact, it will work between any pair of volume files as long as they within the same space (i.e., the RAS coordinates of the same spot in both files are identical). The function works based on the vox2ras matrix in the source file and the ras2vox matrix in the destination file.
- Parameters:
raw_volume_file (string) – Path to the raw volume, i.e., the volume that has not yet been processed using FreeSurfer. You could also use
`rawavg.mgz`in the`mri`sub directory of a subject. Must be in mgh or mgz format. You can use the`mri_convert`binary that comes with FreeSurfer to convert from nifti to mgz.conformed_volume_file (string) – Path to a conformed volume, i.e., a volume that has been conformed to 256x256x256 voxels with 1mm^3 voxel volume. This applies to all subject volumes in the
`mri`directory of a subject, e.g.,`brain.mgz`or`orig.mgz`. Must be in mgh or mgz format. You can use the`mri_convert`binary that comes with FreeSurfer to convert from nifti to mgz. Hint: You can create a conformed version from a raw volume using the`--conform`option of`mri_convert`.raw_volume_query_voxels_crs (numpy 2D array of int) – The column, row, slice indices of the query voxels in the raw volume. The array must have dimension (n, 3) for n query voxels.
- Returns:
conf_volume_voxels_crs – The column, row, slice indices of the query voxels in the conformed volume. The array has dimension (n, 3) for n query voxels.
- Return type:
numpy 2D array of int
- brainload.spatial.get_freesurfer_matrix_ras2vox()
Get standard matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes.
Get matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes. See the documentation for get_freesurfer_matrix_vox2ras for background information.
- Returns:
The affine transformation matrix, a float matrix with shape (4, 4).
- Return type:
2D numpy array
- brainload.spatial.get_freesurfer_matrix_vox2ras()
The FreeSurfer vox2ras matrix, this is identical to the vox2ras-tkr matrix.
- Retrieved from http://freesurfer.net/fswiki/CoordinateSystems, use case 4. Note that fsaverage is in MNI305 space. Generated by running: mri_info –vox2ras-tkr $FREESURFER_HOME/subjects/fsaverage/mri/orig.mgz. See also http://eeg.sourceforge.net/doc_m2html/bioelectromagnetism/freesurfer_surf2voxels.html. Quoting from that page: ‘FreeSurfer MRI volumes are 256^3 voxels, 1mm^3 each. The MRI volume index has an origin at the left, posterior, inferior voxel, such that:
Sagital increases from left to right (+X Right)
Coronal increases from posterior to anterior (+Y Anterior)
Axial increases from inferior to superior (+Z Superior).
The MRI RAS values have an origin at the middle of the volume, in approximately voxel 128, 128, 128.’
- Returns:
The affine transformation matrix, a float matrix with shape (4, 4).
- Return type:
2D numpy array
- brainload.spatial.get_n_neighborhood_indices_3D(volume_shape, point, n)
Compute the indices of the n-neighborhood of the point within the volume.
Compute the indices of the square n-neighborhood of the point within the volume, including the point itself. This function returns only valid indices in the volume.
- Parameters:
volume_shape (3-tuple of int) – The shape of the volume (e.g., whole 3D image)
point (1D array of length 3) – The x, y, and z coordinates of the query point. Must lie within the volume. This is the point around which the neighborhood will be computed.
n (int >= 0) – The neighborhood size (in every direction, the neighborhood is always square). For 0, only the index of the point itself will be returned. For 1, the 26 neighbors in distance 1 plus the index of the point itself (so 27 indices) will be returned. If the point is close to the border of the volume, only the valid subset will be returned of course. For n=2 you get (up to) 125 indices.
- Returns:
indices – The 3 arrays have identical size and contain the x, y, and z indices of the neighborhood.
- Return type:
tuple of 3 numpy 1D arrays
Examples
>>> volume = np.zeros((3, 3, 3)) >>> point = [1, 1, 1] >>> indices = st.get_n_neighborhood_indices_3D(volume.shape, point, 1)
- brainload.spatial.get_n_neighborhood_indices_3D_points(volume_shape, points, n)
Compute the indices of the n-neighborhood of the point within the volume.
Compute the indices of the square n-neighborhood of the point within the volume, including the point itself. This function returns only valid indices in the volume.
- Parameters:
volume_shape (3-tuple of int) – The shape of the volume (e.g., whole 3D image)
points (2D array of shape (n, 3) for n points) – The x, y, and z coordinates of the query points. Must lie within the volume. These are the points around which the neighborhoods will be computed.
n (int >= 0) – The neighborhood size (in every direction, the neighborhood is always square). For 0, only the index of the point itself will be returned. For 1, the 26 neighbors in distance 1 plus the index of the point itself (so 27 indices) will be returned. If the point is close to the border of the volume, only the valid subset will be returned of course. For n=2 you get (up to) 125 indices.
- Returns:
indices – The 3 arrays have identical size and contain the x, y, and z indices of the neighborhood.
- Return type:
tuple of 3 numpy 1D arrays
Examples
>>> volume = np.zeros((3, 3, 3)) >>> points = np.array([[1, 1, 1], [2, 2, 2]]) >>> indices = st.get_n_neighborhood_indices_3D_points(volume.shape, points, 1)
- brainload.spatial.get_n_neighborhood_start_stop_indices_3D(volume_shape, point, n)
Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the point within the 3D volume.
Note that this returns an index range where the end is non-inclusive! So for a point at x,y,z with 0-neighborhood (only the point itself), you will get x,x+1,y,y+1,z,z+1 as return values.
- Parameters:
volume_shape (3-tuple of int) – The shape of the volume (e.g., whole 3D image)
point (1D array of length 3) – The x, y, and z coordinates of the query point. Must lie within the volume. This is the point around which the neighborhood will be computed.
n (int >= 0) – The neighborhood size (in every direction, the neighborhood is always square). For 0, only the index of the point itself will be returned. For 1, the 26 neighbors in distance 1 plus the index of the point itself (so 27 indices) will be returned. If the point is close to the border of the volume, only the valid subset will be returned of course. For n=2 you get (up to) 125 indices.
- Returns:
xstart (int) – The x start index, inclusive.
xend (int) – The x end index, exclusive.
ystart (int) – The y start index, inclusive.
yend (int) – The y end index, exclusive.
zstart (int) – The z start index, inclusive.
zend (int) – The z end index, exclusive.
Examples
>>> volume = np.zeros((3, 3, 3)) >>> point = [2, 2, 2] >>> xstart, xend, ystart, yend, zstart, zend = st.get_n_neighborhood_start_stop_indices_3D(volume.shape, point, 1) # 1-neighborhood
- brainload.spatial.get_n_neighborhood_start_stop_indices_3D_points(volume_shape, points, n)
Compute the start and stop indices along the 3 dimensions for the n-neighborhood of the points within the 3D volume.
Note that this returns an index range where the end is non-inclusive! So for a point at x,y,z with 0-neighborhood (only the point itself), you will get x,x+1,y,y+1,z,z+1 as return values.
- Parameters:
volume_shape (3-tuple of int) – The shape of the volume (e.g., whole 3D image)
points (2D array of shape (n, 3) for n points) – The x, y, and z coordinates of the query points. Must lie within the volume. These are the points around which the neighborhoods will be computed.
n (int >= 0) – The neighborhood size (in every direction, the neighborhood is always square). For 0, only the index of the point itself will be returned. For 1, the 26 neighbors in distance 1 plus the index of the point itself (so 27 indices) will be returned. If the point is close to the border of the volume, only the valid subset will be returned of course. For n=2 you get (up to) 125 indices.
- Returns:
xstart (1D numpy int array) – The x start indices, inclusive.
xend (1D numpy int array) – The x end indices, exclusive.
ystart (1D numpy int array) – The y start indices, inclusive.
yend (1D numpy int array) – The y end indices, exclusive.
zstart (1D numpy int array) – The z start indices, inclusive.
zend (1D numpy int array) – The z end indices, exclusive.
Examples
>>> volume = np.zeros((3, 3, 3)) >>> points = np.array([[1, 1, 1], [2,2,2]]) >>> xstart, xend, ystart, yend, zstart, zend = st.get_n_neighborhood_start_stop_indices_3D_points(volume.shape, points, 1) # 1-neighborhood
- brainload.spatial.mirror_3D_coordinates_at_axis(x, y, z, axis, mirror_at_axis_coordinate=None)
Mirror the given 3D coordinates on the given mirror plane.
Mirror or reflect the given 3D coordinates on a plane (perpendicular to the axis) at axis coordinate mirror_at_axis_coordinate at the given axis. If mirror_at_axis_coordinate is not given, the smallest coordinate along the mirror axis in the data is used.
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays.
axis (string, one of {'x', 'y', 'z'}) – An axis identifier.
mirror_at_axis_coordinate (number | None) – The coordinate along the axis axis at which the mirror plane should be created. If you set axis to ‘x’ and specify 5 for this, a yz-plane will be used at x coordinate 5. If not given, it defaults to the minimal axis coordinate for the respective axis in the data.
- Returns:
x_mirrored (Numpy array of numbers) – The mirrored x coordinates.
y_mirrored (Numpy array of numbers) – The mirrored y coordinates.
z_mirrored (Numpy array of numbers) – The mirrored z coordinates.
Examples
Mirror at the origin of the x axis:
>>> import brainload.spatial as st; import numpy as np >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> xm, ym, zm = st.mirror_3D_coordinates_at_axis(x, y, z, 'x', 0) >>> print "%d %d %d" % (xm[0], ym[0], zm[0]) # -5 7 9 >>> print "%d %d %d" % (xm[1], ym[1], zm[1]) # -6 8 10
- brainload.spatial.parse_registration_matrix(matrix_lines)
Parse a registration matrix.
Parse a registration matrix from the 4 lines representing it in a register.dat file. See https://surfer.nmr.mgh.harvard.edu/fswiki/RegisterDat for the file format. This function expects only the 4 matrix lines.
- Parameters:
matrix_lines (list of str) – The 4 matrix lines of a file in register.dat format. Each line muyt contain 4 floats, separated by spaces.
- Returns:
The parsed matrix, with dimension (4, 4).
- Return type:
2D numpy array of floats
- brainload.spatial.point_mirror_3D_coordinates(x, y, z, point_x, point_y, point_z)
Point-mirror or reflect the given coordinates at the given point.
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays.
point_x (number) – The x coordinate of the point used for mirroring.
point_y (number) – The y coordinate of the point used for mirroring.
point_z (number) – The z coordinate of the point used for mirroring.
- Returns:
xm (Numpy array of numbers) – The mirrored x coordinates.
ym (Numpy array of numbers) – The mirrored y coordinates.
zm (Numpy array of numbers) – The mirrored z coordinates.
Examples
Mirror at the origin:
>>> import brainload.spatial as st; import numpy as np >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> xm, ym, zm = st.point_mirror_3D_coordinates(x, y, z, 0, 0, 0) >>> print "%d %d %d" % (xm[0], ym[0], zm[0]) # -5 -7 -9 >>> print "%d %d %d" % (xm[1], ym[1], zm[1]) # -6 -8 -10
- brainload.spatial.rad2deg(rad)
Convert an angle given in radians to degrees.
Convert an angle given in radians to degrees. 2 Pi radians are 360 degrees. If negative values or values larger than 2 Pi are passed, use the modulo operation to bring them to a suitable range first. In other words, passing -0.5 * Pi will be transformed to 2 - 0.5 = 1.5 Pi, and will thus return 270 degrees.
- Parameters:
rad (float) – The angle in radians.
- Returns:
The angle in degrees.
- Return type:
float
Examples
>>> import brainload.spatial as st >>> deg = st.rad2deg(2 * np.pi) # will be 360
- brainload.spatial.rotate_3D_coordinates_around_axes(x, y, z, radians_x, radians_y, radians_z)
Rotate coordinates around the 3 axes.
Rotate coordinates around the x, y, and z axes. The rotation values must be given in radians.
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays. (See coords_a2s if you have a single 2D array containing all 3.)
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays. (See coords_a2s if you have a single 2D array containing all 3.)
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays. (See coords_a2s if you have a single 2D array containing all 3.)
radians_x (number) – A single number, representing the rotation in radians around the x axis.
radians_y (number) – A single number, representing the rotation in radians around the y axis.
radians_z (number) – A single number, representing the rotation in radians around the z axis.
- Returns:
xr (Numpy array of numbers) – The rotated x coordinates.
yr (Numpy array of numbers) – The rotated y coordinates.
zr (Numpy array of numbers) – The rotated z coordinates.
Examples
>>> import brainload.spatial as st; import numpy as np; >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> xr, yr, zr = st.rotate_3D_coordinates_around_axes(x, y, z, np.pi, 0, 0)
- brainload.spatial.scale_3D_coordinates(x, y, z, x_scale_factor, y_scale_factor=None, z_scale_factor=None)
Scale coordinates by factors.
Scale the given coordinates by the given scale factor or factors.
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays.
x_scale_factor (number) – A single number, representing the scaling factor along the x axis. If the other values are not given, this counts for all axes.
y_scale_factor (number | None) – A single number, representing the scaling factor along the y axis. If this is None, the value given for x_scale_factor is used.
z_scale_factor (number | None) – A single number, representing the scaling factor along the z axis. If this is None, the value given for x_scale_factor is used.
- Returns:
x_scaled (Numpy array of numbers) – The scaled x coordinates.
y_scaled (Numpy array of numbers) – The scaled y coordinates.
z_scaled (Numpy array of numbers) – The scaled z coordinates.
Examples
>>> import brainload.spatial as st; import numpy as np >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> xs, ys, zs = st.scale_3D_coordinates(x, y, z, 3.0) >>> print "%d %d %d" % (xs[0], ys[0], zs[0]) # 15 21 27 >>> print "%d %d %d" % (xs[1], ys[1], zs[1]) # 18 24 30
- brainload.spatial.translate_3D_coordinates_along_axes(x, y, z, shift_x, shift_y, shift_z)
Translate coordinates along one or more axes.
Translate or shift coordinates along one or more axes.
- Parameters:
x (Numpy array of numbers) – A 1D array representing x axis coordinates. Must have the same length as the y and z arrays.
y (Numpy array of numbers) – A 1D array representing y axis coordinates. Must have the same length as the x and z arrays.
z (Numpy array of numbers) – A 1D array, representing z axis coordinates. Must have the same length as the x and y arrays.
shift_x (number) – A single number, representing the shift along the x axis.
shift_y (number) – A single number, representing the shift along the y axis.
shift_z (number) – A single number, representing the shift along the z axis.
- Returns:
x_shifted (Numpy array of numbers) – The shifted x coordinates.
y_shifted (Numpy array of numbers) – The shifted y coordinates.
z_shifted (Numpy array of numbers) – The shifted z coordinates.
Examples
>>> import brainload.spatial as st; import numpy as np >>> x = np.array([5, 6]) >>> y = np.array([7, 8]) >>> z = np.array([9, 10]) >>> xt, yt, zt = st.translate_3D_coordinates_along_axes(x, y, z, 2, -4, 0) >>> print "%d %d %d" % (xt[0], yt[0], zt[0]) # 7 3 9 >>> print "%d %d %d" % (xt[1], yt[1], zt[1]) # 8 4 10
brainload.meshexport module
Functions for exporting meshes.
Functions for exporting brain meshes to formats used by common 3D modeling software.
- brainload.meshexport.mesh_to_obj(vertex_coords, faces)
Write an OBJ format string of a mesh.
Write an OBJ PLY format string of a mesh. The format is the Wavefront object format, see https://en.wikipedia.org/wiki/Wavefront_.obj_file for details. This exporter only writes the geometry, vertex colors are not a standard OBJ feature and are not included. Use mesh_to_ply to get vertex colors.
- Parameters:
vertex_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices.
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
- Returns:
The OBJ format string for the mesh.
- Return type:
string
- brainload.meshexport.mesh_to_off(vertex_coords, faces)
Write an OFF format string of a mesh.
Write an OFF format string of a mesh. The format is the Object File Format, see https://en.wikipedia.org/wiki/OFF_(file_format) for details.
- Parameters:
vertex_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices.
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
- Returns:
The OFF string for the mesh.
- Return type:
string
- brainload.meshexport.mesh_to_ply(vertex_coords, faces, vertex_colors=None)
Write a PLY format string of a mesh.
Write a PLY format string of a mesh. See http://paulbourke.net/dataformats/ply/ for details on the format.
- Parameters:
vertex_coords (numpy array of floats) – A 2D array containing 3 coordinates for each vertex. Dimension is (n, 3) for n vertices.
faces (numpy array of integers) – A 2D array containing 3 vertex indices per face. Dimension is (m, 3) for m faces.
vertex_colors (numpy array or None, optional) – A 2D array with shape (n, 4) assigning a color to each vertex (for the n vertices in vertex_coords). The 4 values in each column define the 4 channels of an RGBA color. Channel values should be given as integers in range 0..255. If omitted, no vertex colors will be included in the PLY format string.
- Returns:
The PLY format string for the mesh.
- Return type:
string
- brainload.meshexport.scalars_to_colors_clist(scalars, color_list)
Given scalar values and a color list, assign a color to each scalar value.
Given scalar values and a color list, assign a color to each scalar value. This is useful for exporting vertex colored brain meshes.
- Parameters:
scalars (scalar numpy array of shape (i, ).) – 1D array of i numerical scalar values, usually floats.
cmap (numpy array of shape (n, m)) – Array containing n colors, each of which is defined by m values (e.g., m=3 for RGB colors, m=4 for RGBA colors, but this function does not care for the meaning in any way).
- Returns:
An array that assigns one color to each value from the scalars parameter (use the index).
- Return type:
numpy int array of shape (i, m)
- brainload.meshexport.scalars_to_colors_matplotlib(data, matplotlib_cmap_name='viridis', data_normalization='linear', custom_cmap=None, scale=True)
Assign colors to scalars using a colormap from matplotlib.
Assign colors to scalars using functions and a colormap from matplotlib. This requires matplotlib to be installed, which is NOT a hard dependency of brainload. If you want to use this function, you need to install matplotlib.
- Parameters:
data (1D numpy array of numerical data, length n.) – The scalars data, each data point will be assigned a color.
matplotlib_cmap_name (string) – A valid name of a matplotlib colormap. Example: ‘Spectral’. Note that it is important to chose the color map based on the data and your application. For sequential data, try ‘viridis’ or ‘plasma’. For diverging data, try ‘Spectral’ or ‘coolwarm’. For qualitative color maps, try ‘tab10’ or ‘tab20’. See https://matplotlib.org/users/colormaps.html for details. If the parameter custom_cmap is given, this can be a freeform name for your that colormap. Defaults to ‘viridis’.
data_normalization (string, one of ('linear', 'log'), optional) – How the data should be normalized to match the range of the color map. Defaults to ‘linear’.
custom_cmap (matplotlib colormap instance, optional) – A custom matplotlib colormap, e.g., one created using LinearSegmentedColormap.from_list() or other matplotlib functions. Optional. If given, takes precedence over matplotlib_cmap_name.
scale (boolean) – Whether to scale the returned color values to the range 1..255. If False, the colors will be in range 0..1. Defaults to TRUE.
- Returns:
An array that assigns one RGBA color to each value from the scalars parameter (use the index). A color is given as 4 floats (RGBA), each in range 0.0 to 1.0 or 1 to 255, depending on the parameter ‘scale’.
- Return type:
numpy float array of shape (n, 4)