PyAims basic algorithms

soma.aims.AimsThreshold(*args, **kwargs)[source]

Create a AimsThreshold instance from input and output types. Types may be passed as keyword arguments intype and outtype, or dtype if both are the same. Otherwise the arguments are parsed to find types arguments. Types may be specified as allowed by typeCode().

Other arguments are otherwise passed to the constructor of the underlying threshold object. See for instance: soma.aims.AimsThreshold_S16_S16.

class soma.aims.AimsThreshold_S16_S16
AimsThreshold_S16_S16(ttype, th1, th2=0,

background=0)

Thresholding types are specified as the soma.aims.threshold_t enum. Values are:

  • AIMS_LOWER_THAN

  • AIMS_LOWER_OR_EQUAL_TO

  • AIMS_GREATER_THAN

  • AIMS_GREATER_OR_EQUAL_TO

  • AIMS_EQUAL_TO

  • AIMS_DIFFER

  • AIMS_BETWEEN

  • AIMS_OUTSIDE

  • AIMS_BETWEEN_EXCLUDE_LOWER_BOUND

  • AIMS_BETWEEN_EXCLUDE_HIGHER_BOUND

  • AIMS_BETWEEN_EXCLUDE_BOUNDS

  • AIMS_OUTSIDE_INCLUDE_LOWER_BOUND

  • AIMS_OUTSIDE_INCLUDE_HIGHER_BOUND

  • AIMS_OUTSIDE_INCLUDE_BOUNDS

Use:

thresholded_vol = threshold(volume)

Apply non-binary thresholding: voxels passing the theshold are left with their initial value.

thresholded_vol = threshold.bin(volume)

Apply binary thresholding: voxels passing the theshold are set to a constant value – which one ?

Parameters
  • ttype (soma.aims.threshold_t enum) – thresholding type (see above)

  • th1 (short) – first (main) threshold

  • th2 (short) – second threshold (in case of double thresholding)

  • background (short) – value set to elements not passing the threshold condition

  • volume (Volume_S16) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_S16

thresholded_vol = threshold(volume)

Apply non-binary thresholding: voxels passing the theshold are left with their initial value.

Parameters

volume (Volume_S16) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_S16

bin()

thresholded_vol = threshold.bin(volume)

Apply binary thresholding: voxels passing the theshold are set to a constant value – which one ?

Parameters

volume (Volume_S16) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_S16

class soma.aims.AimsThreshold_FLOAT_S16
AimsThreshold_FLOAT_S16(ttype, th1, th2=0,

background=0)

Thresholding types are specified as the soma.aims.threshold_t enum. Values are:

  • AIMS_LOWER_THAN

  • AIMS_LOWER_OR_EQUAL_TO

  • AIMS_GREATER_THAN

  • AIMS_GREATER_OR_EQUAL_TO

  • AIMS_EQUAL_TO

  • AIMS_DIFFER

  • AIMS_BETWEEN

  • AIMS_OUTSIDE

  • AIMS_BETWEEN_EXCLUDE_LOWER_BOUND

  • AIMS_BETWEEN_EXCLUDE_HIGHER_BOUND

  • AIMS_BETWEEN_EXCLUDE_BOUNDS

  • AIMS_OUTSIDE_INCLUDE_LOWER_BOUND

  • AIMS_OUTSIDE_INCLUDE_HIGHER_BOUND

  • AIMS_OUTSIDE_INCLUDE_BOUNDS

Use:

thresholded_vol = threshold(volume)

Apply non-binary thresholding: voxels passing the theshold are left with their initial value.

thresholded_vol = threshold.bin(volume)

Apply binary thresholding: voxels passing the theshold are set to a constant value – which one ?

Parameters
  • ttype (soma.aims.threshold_t enum) – thresholding type (see above)

  • th1 (float) – first (main) threshold

  • th2 (float) – second threshold (in case of double thresholding)

  • background (float) – value set to elements not passing the threshold condition

  • volume (Volume_S16) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_FLOAT

thresholded_vol = threshold(volume)

Apply non-binary thresholding: voxels passing the theshold are left with their initial value.

Parameters

volume (Volume_S16) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_FLOAT

bin()

thresholded_vol = threshold.bin(volume)

Apply binary thresholding: voxels passing the theshold are set to a constant value – which one ?

Parameters

volume (Volume_FLOAT) – input volume to be thresholded

Returns

thresholded_vol – thresholded volume

Return type

rc_ptr_Volume_S16

class soma.aims.SurfaceGenerator

Surface Generator Object. Available Methods are :

  • cube(center_p, radius_f, smoothnormal_b=false)

  • cylinder(p1_p, p2_p, radius1_f, radius2_f, nfacets_i, closed_b, smooth_b=false)

  • cone(arrow_p, base_p, radius_f, nfacets_i, closed_b, smooth_b=false)

  • arrow(arrow_p, base_p, radius_f, arrowradius_f, nfacets_i, arrowlengthfract_f)

  • icosahedron(center_p, radius_f)

  • sphere(center_p, radius_f, nfacets_i)

  • icosphere(center_p, radius_f, nfacets_i)

With arguments suffix _f:float, _i:int, _b:bool, _p: Point3df or 3-tuple

Alternatively, all those may be called with a GenericObject as only parameter.

This doc might not be up-to-date, use the printDescription() method for more info.

arrow()

static arrow( dictionary ) See the description() and printDescription() methods for more information.

static arrow( Point3df arrowhead, Point3df base, float headradius, float arrowradius, unsigned nfaces, float arrowlengthfactor )

circle_wireframe()
Circle, or part of circle.

center, radius are classical. nseg is the number of segments in the circle polygon normal is a normal vector to the circle plane. startdir is a vector in the circle plane determining the beginning of angles (circle ray). startangle, stopangle are meant to make parts of circle

cone()

static cone( dictionary ) See the description() and printDescription() methods for more information.

static cone( Point3df arrowhead, Point3df base, float radius, unsigned nfaces, bool closed, bool smooth=False )

cube()

static cube( dictionary ) See the description() and printDescription() methods for more information.

static cube( Point3df center, float radius, bool smoothnormals=False )

cylinder()

static cylinder( dictionary ) See the description() and printDescription() methods for more information.

static cylinder( Point3df center1, Point3df center2, float radius1, float radius2, unsigned nfaces, bool closed, bool smooth=False )

ellipse()

static ellipse( dictionary ) See the description() and printDescription() methods for more information.

static ellipse( Point3df center, float radius1, float radius2, unsigned nfaces, bool uniquevertices=False )

grid(dict)

See the description() and printDescription() methods for more information.

grid(Point3df boundingbox_min, Point3df boundingbox_max, Point3df grid_sampling) Regular, wireframe grid

icosahedron()

static icosahedron( dictionary ) See the description() and printDescription() methods for more information.

static icosahedron( Point3df center, float radius )

icosphere(dictionary)

See the description() and printDescription() methods for more information.

icosphere( Point3df center, float radius, unsigned nfaces=320 )

Compared to sphere() which performs meridian / parallels tesselation, icosphere over-segments an icosahedron to get equal, equilateral triangles.

parallelepiped(boundingbox_min, boundingbox_max, smooth=False)
Parameters
  • boundingbox_min (Point3df) – “lower bound” corner position

  • boundingbox_min – “upper bound” corner position

  • smooth (bool) – if True, make smooth faces and shared vertices in corners

parallelepiped_wireframe(Point3df boundingbox_min, Point3df boundingbox_max)
sphere()

static sphere( dictionary ) See the description() and printDescription() methods for more information.

static sphere( Point3df center, float radius, unsigned nfaces, bool uniquevertices=False )

class soma.aims.SurfaceManip

Surface Manipulation Object. All mehtods are static in this class, it is just a means of grouping functions.

cutMesh(in_mesh, plane, cut_mesh, border_line)

Cut a mesh by a plane and that’s all.

Parameters
  • in_mesh (AimsSurfaceTriangle) – Triangular mesh to be cut.

  • plane (Point4df) – cut plane equation (4 coefs)

  • cut_mesh (AimsSurfaceTriangle) – output cut mesh (the part satisfying the plane equation). Polygons crossing the plane will be cut into smaller ones.

  • border_line (AimsTimeSurface_2_VOID) – output cut section polygon

Returns

Return type

None

invertSurfacePolygons(mesh)

Invert polygons order (flips 2 vertex indices in each triangle) to flip its interior / exterior notions (used by OpenGL rendering). The input mesh is modified in-place.

joinTexturedMesh()

Join a mesh and a texture into a textured mesh

lineDirections(segments_mesh)

calculate directions of a line mesh, for each vertex

Parameters

segments_mesh (AimsTimeSurface_2_VOID) –

Returns

directions

Return type

vector_POINT3DF

meshArea()

Surface area of a triangular mesh, in mm^2

Surface areas of regions of a triangular mesh, in mm^2. Regions are given as a texture.

meshDensity(mesh, as_distance=False)

Calculate a mesh density: inverse of the average edges distance.

Parameters
  • mesh (AimsSurfaceTriangle) –

  • as_distance (bool (optional)) – if True, the average distance is not inverted, thus the output is an average distance map.

Returns

density_texture

Return type

TimeTexture_FLOAT

meshEdgeLengthRatioTexture(numerator_mesh, denominator_mesh)

Calculate an edge length ratio in edges of two meshes with the same topology. The max length ratios of edges is kept for each vertex.

Parameters
  • numerator_mesh (AimsSurfaceTriangle) –

  • denominator_mesh (AimsSurfaceTriangle) –

Returns

ratio_texture

Return type

TimeTexture_FLOAT

meshExtract(mesh, texture, label_value)

Extracts a sub-mesh defined by a texture label value.

Returns

  • sub_mesh (AimsTimeSurface_3_VOID) – extracted sub-mesh

  • vertices (vector_ULONG) – indices of extracted vertices

meshMerge(input_output_mesh, input_mesh)

Concatenates the second mesh to the first one. The first argument will be modified.

Parameters
Returns

Return type

None

meshPlanarPolygon(plane, polygon)

Tesselate a planar polygon to fill it by a triangular mesh

Parameters
  • plane (Point4df) – plane equation

  • polygon (AimsTimeSurface_2_VOID) – planar polygon to tesselate. Typically, the output of cutMesh()

Returns

planar_mesh – the mesh filling the polygon

Return type

AimsSurfaceTriangle

meshTextureBoundary(mesh, label_texture, region_value)

Extracts the boundary of region of value <region_value> of the input texture, on the mesh.

If region_value is negative, take boundaries of all regions. The input texture is a label texture.

Parameters
Returns

boundary – output segments mesh (filar mesh) for the boundary

Return type

AimsTimeSurface_2_VOID

meshTransform(mesh, transformation)

Apply linear coordinates transformation to a mesh. The input mesh will be modified in-place.

Parameters
Returns

Return type

None

meshVolume(mesh)

Volume inside a triangular mesh, in mm^3. The mesh must enclode a closed volume, with no holes, otherwise the volume processing will “leak” and will be wrong.

rasterizeMesh(mesh, volume, value=2)

Rasterize polygons into a volume.

Parameters
  • mesh (AimsTimeSurface_*) –

  • volume (Volume_S16) – Volume to write mesh imprint to

  • value (int) – label value used to write the mesh imprint in the volume

rasterizeMeshWireframe(mesh, volume, value=1)

Rasterize polygons edges into a volume.

Parameters
  • mesh (AimsTimeSurface_*) –

  • volume (Volume_S16) – Volume to write mesh imprint to

  • value (int) – label value used to write the mesh imprint in the volume

refineMeshTri4(mesh, selected_polygons=None)

Refine a mesh by subdivising every triangle into 4 smaller ones.

Parameters
  • mesh (AimsSurfaceTriangle) – mesh to be refined

  • selected_polygons (vector_U32) – optional list of polygons indices to be selectively refined. Others will not be changed, unless they are at the border of a refined one, in which case they have to be split in some way.

Returns

refined_mesh – refined mesh

Return type

AimsSurfaceTriangle

sortPolygonsAlongDirection(mesh, timestep, direction)

Sort polygons along a given direction. Polygons centers will be used for sorting. Only one timestep is performed (to be fast).

Parameters
  • mesh (AimsTimeSurface_*) – The mesh will be modified.

  • timestep (int) –

  • direction (Point3df) –

sortPolygonsAlongDirection(mesh, timestep, direction)

Sort polygons along a given direction. Polygons centers will be used for sorting. Only one timestep is performed (to be fast).

Parameters
  • mesh (AimstimeSurface_*) – The mesh will be modified.

  • timestep (int) –

  • direction (Point3df) –

sortPolygonsAlongDirection(mesh, timestep, direction)

Sort polygons along a given direction. Polygons centers will be used for sorting. Only one timestep is performed (to be fast).

Parameters
  • mesh (AimstimeSurface_*) – The mesh will be modified.

  • timestep (int) –

  • direction (Point3df) –

splitTexturedMesh()

Split a textured mesh into a mesh and a texture

class soma.aims.GraphManip
getICBM2009cTemplateTransform()

transform = aims.GraphManip.getICBM2009cTemplateTransform(graph)

Extract the transformation to the MNI ICBM152 space, shifted to the “most standard” field of view of the template image, the one from the ICBM2009c_nlin_asym template from the MNI. Actually we find various fields of view for the templates. The one we use here is (193, 229, 193). The transform to the “real” ICBM space (0 roughly at AC) is provided in the output transformation header. This space has a fixed transformation with our Aims Talairach, along with the template volume size and voxel size. This space has a fixed transformation with our Aims Talairach. Includes shifts and axes inversions.

getICBMTransform()

transform = aims.GraphManip.getICBMTransform(graph)

Extract the transformation to the MNI ICBM152 space. This space has a fixed transformation with our Aims Talairach.

get_element_table()

Get the GraphElementTable as a dict. The dict has the following shape:

{
    syntax_name: {
        id_name: GraphElementCode_object
    }
}

GraphElementCode objects are given as dicts (str, str):

{
    'id': <same_as_key: filename (globals) or attribute for filename (locals)>,
    'attribute': <attribute_name_in_graph_element>,
    'objectType': <type of object>,
    'dataType': <data type of object>,
    'storageType': <'Global', 'Local', or 'GlobalPacked'>,
    'local_file_attribute': <attribute giving the filename for local storage in each graph elememt>,
    'global_index_attribute': <attribute giving the index for global storage in each graph elememt>,
    'global_filename': <filename for global storage>,
    'global_attribute': <attribute>,
    'syntax': <syntax_name>
}
graphFromVolume()

graph = graphFromVolume(vol, background=0, trans=None) graphFromVolume(vol, graph, background=0, trans=None,

automaticBackgroundSearch=True)

builds a ROI graph from a volume of labels

soma.aims.apctools module

.APC (commissure coordinates) IO and other tools

soma.aims.apctools.apcFileTransform(inAPCfilename, outAPCfilename, transform, outimagevoxelsize, imagefile=None)[source]

Transforms the coordinates of a .APC file points through a given transformation. It basically reads inAPCfilename, transforms its contents using apcTransform(), then writes the result to outAPCfilename.

soma.aims.apctools.apcRead(filename, imagefile=None)[source]

Read a .APC file - filename: string - imagefile: string

optional filename for the image file from which the AC/PC coordinates are taken from. Its header may be used to recover millimeters positions from voxels if they are not specified in the .APC file itself (for older versions of the .APC files)

  • returns: dict

    the contents of the file as a dictionary, keys being ‘ac’, ‘pc’, ‘ih’ for voxel coordinates, and ‘acmm’, ‘pcmm’, ‘ihmm’ for millimeters coordinates, and optionally ‘comment’.

soma.aims.apctools.apcTransform(apcdict, transform, outimagevoxelsize)[source]

Transforms coordinates of commissures points through a specified transformation

  • apcdict: dict

    Commissures coordinates, as a dictionary with ‘ac’, ‘pc’, ‘ih’ keys for voxel coordinates, ‘acmm’, ‘pcmm’, ‘ihmm’ for millimeters coordinates

  • transform: AffineTransformation3d object

  • outimagevoxelsize:

    • as string: filename for the image whose voxel size should be used

    • as Volume or any other object with a header() method: voxel_size is taken from its header

    • as dict or header object: voxel size is takes as the voxel_size entry of the dictionary

Coordinates are transformed in the apcdict dictionary, which is modified in-place.

soma.aims.apctools.apcWrite(apcdict, filename)[source]

Writes a .APC file from a dictionary

soma.aims.colormaphints module

soma.aims.colormaphints.anatomicalColormaps = [('B-W LINEAR', (1.0, 1.0, 1.0)), ('Blue-White', (0.0, 0.0, 1.0)), ('Green-White-linear', (0.0, 1.0, 0.0)), ('Green-White-exponential', (0.0, 1.0, 0.0))]

predefined list of colormaps suitable for anatomical volumes

soma.aims.colormaphints.anatomicalFusionColormaps = [('B-W LINEAR-fusion', (1.0, 1.0, 1.0)), ('Blue-White-fusion', (0.0, 0.0, 1.0)), ('Green-White-linear-fusion', (0.0, 1.0, 0.0))]

predefined list of colormaps suitable for fusionned anatomical volumes

soma.aims.colormaphints.binaryColormaps = [('BLUE-lfusion', (0.0, 0.0, 1.0)), ('GREEN-lfusion', (0.0, 1.0, 0.0)), ('RED-lfusion', (1.0, 0.0, 0.0)), ('CYAN-lfusion', (0.0, 1.0, 1.0)), ('VIOLET-lfusion', (1.0, 0.0, 1.0)), ('YELLOW-lfusion', (1.0, 1.0, 0.0)), ('WHITE-lfusion', (1.0, 1.0, 1.0))]

predefined list of colormaps suitable for binary volumes

soma.aims.colormaphints.binaryFusionColormaps = [('BLUE-ufusion', (0.0, 0.0, 1.0)), ('GREEN-ufusion', (0.0, 1.0, 0.0)), ('RED-ufusion', (1.0, 0.0, 0.0)), ('CYAN-ufusion', (0.0, 1.0, 1.0)), ('VIOLET-ufusion', (1.0, 0.0, 1.0)), ('YELLOW-ufusion', (1.0, 1.0, 0.0)), ('Black-ufusion', (1.0, 1.0, 1.0))]

predefined list of colormaps suitable for fusionned binary volumes

soma.aims.colormaphints.checkVolume(vol)[source]

Checks colormap-related clues in a volume, and tries to determine whether it is an anatomical volume, a diffusion volume, a functional volume, or a labels volume. This is determined as “likelihoods” for each class (based on a pure empirical heurisrtic), based on, mainly, the histogram, voxel type, and voxel sizes.

soma.aims.colormaphints.chooseColormaps(vols)[source]

Automatically chooses distinc colormaps for a list of volumes

  • returns: a list of colormaps names. They should be known from Anatomist.

soma.aims.colormaphints.diffusionColormaps = [('B-W LINEAR', (1.0, 1.0, 1.0)), ('Blue-White', (0.0, 0.0, 1.0)), ('Green-White-linear', (0.0, 1.0, 0.0)), ('Green-White-exponential', (0.0, 1.0, 0.0))]

predefined list of colormaps suitable for diffusion volumes

soma.aims.colormaphints.diffusionFusionColormaps = [('B-W LINEAR-fusion', (1.0, 1.0, 1.0)), ('Blue-White-fusion', (0.0, 0.0, 1.0)), ('Green-White-linear-fusion', (0.0, 1.0, 0.0))]

predefined list of colormaps suitable for fusionned diffusion volumes

soma.aims.colormaphints.functionalColormaps = [('RED TEMPERATURE', (1.0, 0.5, 0.0)), ('RAINBOW', (1.0, 0.0, 0.0)), ('Blue-Red', (1.0, 0.0, 0.0)), ('actif-ret', (1.0, 1.0, 0.0)), ('Yellow-red', (1.0, 1.0, 0.0))]

predefined list of colormaps suitable for functional volumes

soma.aims.colormaphints.functionalFusionColormaps = [('Rainbow1-fusion', (1.0, 0.0, 0.0)), ('Blue-Red-fusion', (1.0, 0.0, 0.0)), ('Yellow-red-fusion', (1.0, 1.0, 0.0))]

predefined list of colormaps suitable for fusionned functional volumes

soma.aims.colormaphints.labelsColormaps = [('Blue-Red', (1.0, 0.0, 0.0)), ('Talairach', (0.0, 0.0, 0.0))]

predefined list of colormaps suitable for labels volumes

soma.aims.colormaphints.labelsFusionColormaps = []

predefined list of colormaps suitable for fusionned labels volumes

soma.aims.colormaphints.twotailColormaps = [('tvalues100-200-100-lfusion', (1.0, 0.0, 0.0)), ('tvalues100-100-100-lfusion', (1.0, 0.0, 0.0))]

predefined list of colormaps suitable for two-tail T-values volumes

soma.aims.colormaphints.twotailFusionColormaps = [('tvalues100-200-100', (1.0, 0.0, 0.0)), ('tvalues100-100-100', (1.0, 0.0, 0.0))]

predefined list of colormaps suitable for fusionned two-tail T-values volumes

soma.aims.fslTransformation module

FSL matrixes seem to transform from/to internal refs, like Aims but with a different convention:

  • X: right -> left

  • Y: back -> front

  • Z: bottom -> top

which appears to be Y and Z flipped compared to Aims

soma.aims.fslTransformation.fslMatToTrm(matfile, srcimage, dstimage)[source]

As far as I have understood:

A FSL transformation goes from the disk referential of the source image to the disk referential of the destination image.

BUT:

if the qform of an image (disk -> “real world”) implies a flip (goes from a direct referential to an indirect one or the contrary), then a flip along X axis is inserted in the matrix, since FSL flirt doesn’t allow flipping.

soma.aims.spmnormalizationreader module

soma.aims.spmnormalizationreader.readSpmNormalization(matfilename, source=None, destref=None, srcref=None)[source]

Read a SPM *_sn.mat normalization file and converts it to an Aims AffineTransformation3d. The converted transformation has for source the AIMS referential of the source image, and for destination the template referential of the SPM .mat file. All coordinates are in millimeters.

The source image information may be provided either as its filename, its header object, or the image itself. It should carry the needed information: source volume storage_to_memory transformation matrix, voxel_size, etc. If None is passed as source (the default), then the source image name will be built from the .mat filename and will be read if found.

  • matfilename: string

    file name of the *_sn.mat normalization file to reading

  • source: filename (string), or Volume Volume, or volume header (MappingType)

    file name of the *_sn.mat normalization file to reading

  • destref: string or UUID (Uuid)

    destination referential for the transformation. If not specified, none will be set. If provided as a symbolic name (‘Talairach-MNI template-SPM’), it will be converted to an UUID string.

  • srcref: string or UUID

    source referential for the transformation. If not specified, an attempt will be made to take it from the source image, otherwise it will not be set. If provided as a symbolic name (‘Talairach-MNI template-SPM’), it will be converted to an UUID string.

  • returns: AffineTransformation3d object

    the converted transformation

soma.aims.meshSplit module

soma.aims.meshSplit.meshSplit(mesh, tex, graph, tex_time_step=0)[source]

Splits a mesh into patches corresponding to a labels texture. Patches are organized into a graph.

The graph must preexist, and nodes will be inserted into it.

soma.aims.meshSplit.meshSplit2(mesh, tex, graph, voxel_size=None, tex_time_step=None)[source]

Split mesh according to texture patches

Compared to meshSplit, this version also adds buckets (voxels lists) in each graph node.

Parameters
  • mesh (cortex mesh for example) –

  • tex (aims.TimeTexture_S16) – texture of labels (parcellation of the mesh, labels between 1 and nb_labels, background = 0)

  • graph (Graph) – the graph __syntax__ attribute should be: ‘roi’

  • voxel_size ((optional)) – if a voxel size is given, a bucket will be built with the specified voxel size to follow the mesh. Otherwise there will be no bucket.

  • tex_time_step (int (optional)) – time step to be used in the texture for regions split. default: 0

  • Outputs

  • -------

  • None – modify the input graph: add vertex : submeshes (one per texture label) and associated buckets add vertex “others” : void

soma.aims.volumetools module

Volume functions

soma.aims.volumetools.crop_volume(vol, threshold=0, border=0)[source]

Crop the input volume, removing slices filled with values under a given threshold, and keeping a given border.

If no crop actually takes place, the input volume is returned without duplication. If crop is actually performed, then a view into the original volume is returned, sharing the same data block which is not copied.

Transformations in the header are adapted accordingly.

Parameters
  • vol (aims Volume) – volume to be cropped

  • threshold (volume value, optional) – Minimum value over which a slice cannot be cropped (is supposed to contain real data). The default is 0: only value <= 0 is croppable

  • border (int, optional) – border around the cropped volume: the cropped volume is enlarged by twice this value in each direction, within the limits of the original volume (the bounding box always fits in the original volume). Values in the border are taken from the original volume, the border is not artificially filled with a constant value. The default is 0: no border

soma.aims.volumetools.fill_border_constant(data, value=0, whole=False)[source]

Fill the border of data using a constant value. In aims, a Volume with border is managed as an unallocated view (the visible data) in a larger allocated Volume (the Volume that contains borders). In order to be filled, the borders must exists, otherwise the function has no effect on the Volume.

Parameters
  • data (Volume_* or rc_ptr_Volume_*) –

  • value (value to fill border with (optional)) – Default is 0.

  • whole (bool (optional)) – For partially read Volume, it forces to fill the borders also when they has been already filled with data from parent full unallocated Volume. Default is False

soma.aims.volumetools.fill_border_median(data, size=(- 1, - 1, - 1, - 1), whole=False)[source]

Fill the border of data using the median value processed in the inside border. In aims, a Volume with border is managed as an unallocated view (the visible data) in a larger allocated Volume (the Volume that contains borders). In order to be filled, the borders must exists, otherwise the function has no effect on the Volume.

Parameters
  • data (Volume_* or rc_ptr_Volume_*) –

  • size (list or Point4dl size of the inside border to process median) – value. (-1,-1,-1,-1) means that the median value is processed in the inside border of equal outside border size. if the outside border is of size (2, 2, 0) in dimensions x, y, z, the inside border is also of size (2, 2, 0) (optional) Default is (-1,-1,-1,-1).

  • whole (bool (optional)) – For partially read Volume, it forces to fill the borders also when they has been already filled with data from parent full unallocated Volume. Default is False

soma.aims.volumetools.fill_border_mirror(data, whole=False)[source]

Fills the border mirroring the inside border. In aims, a Volume with border is managed as an unallocated view (the visible data) in a larger allocated Volume (the Volume that contains borders). In order to be filled, the borders must exists, otherwise the function has no effect on the Volume.

Parameters
  • data (Volume_* or rc_ptr_Volume_*) –

  • whole (bool (optional)) – For partially read Volume, it forces to fill the borders also when they has been already filled with data from parent full unallocated Volume. Default is False

soma.aims.volumetools.fill_border_nearest(data, whole=False)[source]

Fill the border of data using the inside border voxel value. In aims, a Volume with border is managed as an unallocated view (the visible data) in a larger allocated Volume (the Volume that contains borders). In order to be filled, the borders must exists, otherwise the function has no effect on the Volume.

Parameters
  • data (Volume_* or rc_ptr_Volume_*) –

  • whole (bool (optional)) – For partially read Volume, it forces to fill the borders also when they has been already filled with data from parent full unallocated Volume. Default is False

soma.aims.texturetools module

soma.aims.texturetools.average_texture(output, inputs)[source]

Create average gyri texture from a group of subject.

soma.aims.texturetools.change_wrong_labels(cc_label, label, gyri_tex, mesh_neighbors_vector, cc_tex_label)[source]

After a study of its neighbors, wrong label is replaced by the correct number.

Parameters
  • cc_label (label of connected component in cc_tex_label) –

  • label (label of associated vertices in gyri texture) –

  • S16) (gyri_tex (aims time texture) –

  • mesh_neighbors_vector (aims.SurfaceManip.surfaceNeighbours(mesh)) –

  • cc_tex_label (texture representing connected components of label) –

Returns

  • gyri_tex (aims time texture S16) (new gyri_tex texture,) – without isolated vertex.

  • winner_label (the correct number.)

soma.aims.texturetools.clean_gyri_texture(mesh, gyri_tex)[source]

Cleaning a gyri texture by using connected components.

Parameters
  • surface) (mesh (aims time) – white mesh associated to gyri_tex

  • S16) (gyri_tex (aims time texture) – gyri texture as full FreeSurfer parcellation.

Returns

new gyri texture, without isolated vertex.

Return type

gyri_tex (aims time texture S16)

soma.aims.texturetools.connectedComponents(mesh, tex, areas_mode=0)[source]
Parameters
  • mesh

  • tex (aimsTimeTexture_S16) – (one time step) labeled between 1 and LabelsNb, background = 0, ignored_vertex = -1.

  • areas_mode – if = 1: computing area measures of the connected components, if = 0: no measure (by default).

Returns

  • step_cc (connectedComponentTex: aimsTimeTexture_S16) – time step = LabelsNb, for each time step (label in the tex), texture of the connected components corresponding to this label (background = -1, and connected components = values between 1 and nb_cc).

  • areas_measure (python dictionary) – areas_measures[label] = [16.5, 6.0] (numpy array) if label (in tex) has two connected Components 1 and 2 with area = 16.5 and 6.0 respectively, areas are in square mm

soma.aims.texturetools.extractLabelsFromTexture(tex, labels_list, new_label)[source]
inputs:

tex: labeled texture ( from FreeSurfer or an other ) labels_list, new_label: you can overwrite numbers ( labels_list ) with your own number ( new_label )

output:

otex: labeled texture with merged regions only

soma.aims.texturetools.find_wrong_labels(mesh, gyriTex)[source]
Parameters
  • mesh

  • gyriTex (gyri texture) –

Returns

wrong_labels – [cctex: connectedComponentTex: aimsTimeTexture_S16, time step = LabelsNb, for each time step (label in the tex), texture of the connected components corresponding to this label (background = -1, and connected components = values between 1 and ccNb) areas_measures = python dictionary, areas_measures[label] = [16.5, 6.0] (numpy array) if label (in tex) has two connected Components 1 and 2 with area = 16.5 and 6.0 respectively, areas are in square mm]

Return type

list of wrong labels

soma.aims.texturetools.mergeLabelsFromTexture(tex, labels_list, new_label)[source]
inputs:

tex: labeled texture ( from FreeSurfer or an other ) labels_list, new_label: you can overwrite numbers ( labels_list ) with your own number ( new_label )

ouput:

otex: labeled texture with merged regions

soma.aims.texturetools.meshDiceIndex(mesh, texture1, texture2, timestep1=0, timestep2=0, labels_table1=None, labels_table2=None)[source]

DICE index calculation between two sets of regions defined by label textures on a common mesh. texture1, texture2: aims.TimeTexture instances, should be int (labels). timestep1, timestep2: timestep to use in texture1 and texture2. labels_table1, labels_table2: optional labels translation tables (dicts or arrays) to translate values of texture1 and/or texture2.

return

soma.aims.texturetools.mesh_to_polygon_textured_mesh(mesh, poly_tex)[source]
soma.aims.texturetools.nomenclature_to_colormap(hierarchy, labels_list, as_float=True, default_color=[0.3, 0.6, 1.0, 1.0])[source]

Make a colormap from labels and colors of a nomenclature (hierarchy), following a labels_list order.

Parameters
  • hierarchy (Hierarchy object) – nomenclature

  • labels_list (list of strings) – labels with order. The returned colormap will follow this ordering.

  • as_float (bool (optional, default: True)) – if True, colors will be float values in the [0-1] range. If False, they will be int values in the [0-255] range.

  • default_color (list (4 floats) (optional)) – Color used for labels not found in the nomenclature. It is given as floats ([0-1] range).

Returns

colormap – array of colors (4 float values in [0-1] range)

Return type

numpy array

soma.aims.texturetools.parcels_surface_features(mesh, texture, tex_index=- 1, as_csv_table=False)[source]

Record area and boundary length features on a set of parcels (in a texture).

The mesh should be a single one (single timestep), the texture may have several timesteps. The timestep index can be specified, or all timesteps will be recorded, and the result will be a dict.

The result is a dict, unless as_csv_table is set. In that case it will be a CSV-shaped array.

soma.aims.texturetools.remove_non_principal_connected_components(mesh, tex, trash_label)[source]

Keep only the largest connected component in each label, for a label texture.

Parameters
  • mesh

  • tex (label texture (S16, int)) –

  • trash_label (value to replace non-principal components) –

Returns

out_tex

Return type

label texture

soma.aims.texturetools.set_texture_colormap(texture, colormap, cmap_name='custom', tex_max=None, tex_min=None, tex_index=0, col_mapping='all')[source]

Set a colormap in a texture object header.

The texture object may be any kind of textured object: a TimeTexture instance, or a Volume.

Parameters
  • texture (TimeTexture, Volume...) – The texture object should have a header() method.

  • colormap (array, Volume, or filename) – The colormap may be provided as RGB or RGBA, and as an aims Volume object, or a numpy array, or as an image filename. It should be a 1D colormap (for now at least).

  • cmap_name (str (optional)) – name of the colormap to be used in Anatomist.

  • tex_max (float (optional)) – Max texture value to be mapped to the colormap bounds. It is used to scale the max value of the colormap in Anatomist. If not specified, the texture or volume max will be looked for in the texture object. Used only if col_mapping is “one”.

  • tex_min (float (optional)) – Min texture value to be mapped to the colormap bounds. It is used to scale the max value of the colormap in Anatomist. If not specified, the texture or volume max will be looked for in the texture object. Used only if col_mapping is “one”.

  • tex_index (int (optional)) – Texture index in the textured object

  • col_mapping (str or None (optional)) – “all”: map the full texture range to the colormap bounds (default); “one”: one-to-one mapping between colors and values (int values); “none” or None: don’t force any mapping - anatomist will choose to use a histogram if needed.

soma.aims.texturetools.set_texture_labels(texture, labels, tex_index=0)[source]

Set a labels list or dict in a texture object header.

The texture object may be any kind of textured object: a TimeTexture instance, or a Volume.

Parameters
  • texture (TimeTexture, Volume...) – The texture object should have a header() method.

  • labels (list ot dict) – Values are labels strings. Keys are ints. It may be either a list (keys are list indices) or a dict.

  • tex_index (int (optional)) – Texture index in the textured object

soma.aims.texturetools.vertex_texture_to_polygon_texture(mesh, tex, allow_cut=False)[source]

Make a “polygon texture” from a vartex-based label texture. A polygon texture has a value for each polygon.

For a given polygon the value is taken as the majority of values on its vertices. If an absolute majority cannot be obtained, the mesh polygons may be cut to avoid losing precision. This is done if allow_cut is True.

When allow_cut is False, the returned value is the polygon texture. It may work on meshes of any polygon size (triangles, quads, segments…)

When allow_cut is True, the returned value is a tuple:
  • polygon texture

  • new mesh with possibly split triangles

It only works for meshes of triangles.