Quaternion Averaging

Quaternion averaging functions

sksurgerycore.algorithms.averagequaternions.average_quaternions(quaternions)[source]

Calculate average quaternion

Params quaternions:
 is a Nx4 numpy matrix and contains the quaternions to average in the rows. The quaternions are arranged as (w,x,y,z), with w being the scalar
Returns:the average quaternion of the input. Note that the signs of the output quaternion can be reversed, since q and -q describe the same orientation
sksurgerycore.algorithms.averagequaternions.weighted_average_quaternions(quaternions, weights)[source]

Average multiple quaternions with specific weights

Params quaternions:
 is a Nx4 numpy matrix and contains the quaternions to average in the rows. The quaternions are arranged as (w,x,y,z), with w being the scalar
Params weights:The weight vector w must be of the same length as the number of rows in the
Returns:the average quaternion of the input. Note that the signs of the output quaternion can be reversed, since q and -q describe the same orientation
Raises:ValueError if all weights are zero

Registration Error Calculation

Registration Error Calculations

sksurgerycore.algorithms.errors.compute_fre(fixed, moving, rotation, translation)[source]

Computes the Fiducial Registration Error, equal to the root mean squared error between corresponding fiducials.

Parameters:
  • fixed – point set, N x 3 ndarray
  • moving – point set, N x 3 ndarray of corresponding points
  • rotation – 3 x 3 ndarray
  • translation – 3 x 1 ndarray
Returns:

Fiducial Registration Error (FRE)

sksurgerycore.algorithms.errors.compute_fre_from_fle(fiducials, mean_fle_squared)[source]

Computes an estimation of FRE from FLE and a list of fiducial locations.

See: Fitzpatrick (1998), equation 10.

Parameters:
  • fiducials – Nx3 ndarray of fiducial points
  • mean_fle_squared – expected (mean) FLE squared
Returns:

mean FRE squared

sksurgerycore.algorithms.errors.compute_tre_from_fle(fiducials, mean_fle_squared, target_point)[source]

Computes an estimation of TRE from FLE and a list of fiducial locations.

See: Fitzpatrick (1998), equation 46.

Parameters:
  • fiducials – Nx3 ndarray of fiducial points
  • mean_fle_squared – expected (mean) FLE squared
  • target_point – a point for which to compute TRE.
Returns:

mean TRE squared

sksurgerycore.algorithms.errors.validate_procrustes_inputs(fixed, moving)[source]

Validates the fixed and moving set of points

  1. fixed and moving must be numpy array
  2. fixed and moving should have 3 columns
  3. fixed and moving should have at least 3 rows
  4. fixed and moving should have the same number of rows
Parameters:
  • fixed – point set, N x 3 ndarray
  • moving – point set, N x 3 ndarray of corresponding points
Returns:

nothing

Raises:

TypeError, ValueError

Pivot Calibration

Functions for pivot calibration.

sksurgerycore.algorithms.pivot.pivot_calibration(tracking_matrices)[source]

sksurgerycore.algorithms.pivot_calibration is depreciated from v0.6.0, please use skscurgerycalibration.algorithms.pivot_calibration from from scikit-surgerycalibration instead

Raises:NotImplementedError
sksurgerycore.algorithms.pivot.pivot_calibration_with_ransac(tracking_matrices, number_iterations, error_threshold, concensus_threshold, early_exit=False)[source]

sksurgerycore.algorithms.pivot_calibration_with_ransac is depreciated from v0.6.0, please use skscurgerycalibration.algorithms.pivot_calibration_with_ransac from from scikit-surgerycalibration instead

Raises:NotImplementedError

Procrustes Registration

Functions for point based registration using Orthogonal Procrustes.

sksurgerycore.algorithms.procrustes.orthogonal_procrustes(fixed, moving)[source]

Implements point based registration via the Orthogonal Procrustes method.

Based on Arun’s method:

Least-Squares Fitting of two, 3-D Point Sets, Arun, 1987, 10.1109/TPAMI.1987.4767965.

Also see this and this.

Parameters:
  • fixed – point set, N x 3 ndarray
  • moving – point set, N x 3 ndarray of corresponding points
Returns:

3x3 rotation ndarray, 3x1 translation ndarray, FRE

Raises:

ValueError

Tracker Data Smoothing

Classes and functions for smoothing tracking data

class sksurgerycore.algorithms.tracking_smoothing.RollingMean(vector_size=3, buffer_size=1, datatype=<class 'float'>)[source]

Bases: object

Performs rolling average calculations on numpy arrays

getmean()[source]

Returns the mean vector across the buffer, ignoring NaNs

pop(vector)[source]

Adds a new vector to the buffer, removing the oldest one.

Params vector:A new vector to place at the start of the buffer.
class sksurgerycore.algorithms.tracking_smoothing.RollingMeanRotation(buffer_size=1)[source]

Bases: sksurgerycore.algorithms.tracking_smoothing.RollingMean

Performs rolling average calculations on rotation vectors

getmean()[source]

Returns the mean quaternion across the buffer, ignoring NaNs

pop(rvector, is_quaternion=False)[source]

Adds a new vector to the buffer, removing the oldest one.

Params vector:A new rotation vector to place at the start of the buffer.
Params is_quaternion:
 if true treat the rvector as a quaternion
sksurgerycore.algorithms.tracking_smoothing.quaternion_to_matrix(quat)[source]

Convert a quaternion to a rotation vector

Params quat:the quaternion (1x4)
Returns:the rotation matrix (4x4)

Math Utilities

Various small maths utilities.

sksurgerycore.algorithms.vector_math.distance_from_line(p_1, p_2, p_3)[source]

Computes distance of a point p_3, from a line defined by p_1 and p_2.

See here.

Returns:euclidean distance

Configuration Manager

Class to load application configuration information from a json file.

Design principles:
  • All errors as Exceptions

  • Fail early in constructor, so the rest of the program never
    has an invalid instance of ConfigurationManager.
    If its constructed, its valid.
  • Setter and Getter do a deepcopy, so only suitable for small config files.

  • Pass ConfigurationManager to any consumer of the data,
    its up to the consumer to know where to find the data.
class sksurgerycore.configuration.configuration_manager.ConfigurationManager(file_name, write_on_setter=False)[source]

Bases: object

Class to load application configuration from a json file. For example, this might be used at the startup of an application.

Parameters:
  • file_name – a json file to read.
  • write_on_setter – if True, will write back to the same file whenever the setter is called.
Raises:

All errors raised as various Exceptions.

get_copy()[source]

Returns a copy of the data read from file.

Returns:deep copy of whatever data structure is stored internally.
get_dir_name()[source]

Returns the directory name of the file that was used when creating the ConfigurationManager.

Returns:str dir name
get_file_name()[source]

Returns the absolute filename that was used when the ConfigurationManager was created.

Returns:str absolute file name
set_data(config_data)[source]

Stores the provided data internally.

Note that: you would normally load settings from disk, and then use get_copy() to get a copy, change some settings, and then use set_data() to pass the data structure back in. So, the data provided for this method should still represent the settings you want to save, not just be a completely arbitrary data structure.

Parameters:config_data – data structure representing your settings.

Data Loading

Functions to load MITK’s mps point set file.

sksurgerycore.io.load_mps.load_mps(file_name)[source]

Load a pointset from a .mps file. For now, just loads points, without geometry information.

Parameters:file_name – string representing file path.
Returns:ids (length N), points (Nx3)

Matrix Functions

Construct 3x3 rotation matrices for rotating around the x, y and z axes individually, as well as 3x3 rotation matrices from sequences of three Euler angles.

sksurgerycore.transforms.matrix.construct_rigid_transformation(rot_m, trans_v)[source]

Construct a 4x4 rigid-body transformation from a 3x3 rotation matrix and a 3x1 vector as translation

Parameters:
  • rot_m – 3x3 rotation matrix, numpy array
  • trans_v – 3x1 vector as translation, numpy array
Returns:

rigid_transformation – 4x4 rigid transformation matrix,

numpy array

sksurgerycore.transforms.matrix.construct_rotm_from_euler(angle_a, angle_b, angle_c, sequence, is_in_radians=True)[source]

Construct a rotation matrix from a sequence of three Euler angles, to pre-multiply column vectors. In the case of tracking, the column vector is under the local coordinate system and the resulting vector is under the world (reference) coordinate system. The three elemental rotations represented by the Euler angles are about the INTRINSIC axes. They can also be interpreted to be about the EXTRINSIC axes, in the reverse order.

Parameters:
  • angle_a – first Euler angle, float, int allowed if in degrees
  • angle_b – second Euler angle, float, int allowed if in degrees
  • angle_c – third Euler angle, float, int allowed if in degrees
  • sequence – the sequence of axes the three elemental rotations are about, with respect to the intrinsic axes, string
  • is_in_radians – if the angles are in radians, default being True, bool
Returns:

rot_m – the 3x3 rotation matrix, numpy array

Raises:

TypeError if angles are not float or of difference types

Raises:

ValueError if sequence is not 3 letters long or contains letters other than x, y or z

sksurgerycore.transforms.matrix.construct_rx_matrix(angle, is_in_radians=True)[source]

Construct a rotation matrix for rotation around the x axis.

Parameters:angle – the angle to rotate radians, float
Returns:rot_x – the 3x3 rotation matrix constructed, numpy array
Raises:TypeError if angle is not float or int
sksurgerycore.transforms.matrix.construct_ry_matrix(angle, is_in_radians=True)[source]

Construct a rotation matrix for rotation around the y axis.

Parameters:
  • angle – the angle to rotate, float
  • is_in_radians – if angle is in radians, default being True, bool
Returns:

rot_y – the 3x3 rotation matrix constructed, numpy array

Raises:

TypeError if angle is not float or int

sksurgerycore.transforms.matrix.construct_rz_matrix(angle, is_in_radians=True)[source]

Construct a rotation matrix for rotation around the z axis.

Parameters:
  • angle – the angle to rotate, float
  • is_in_radians – if angle is in radians, default being True, bool
Returns:

rot_z – the 3x3 rotation matrix constructed, numpy array

Raises:

TypeError if angle is not float or int

Transform Manager

Class implementing a general purpose 4x4 transformation matrix manager.

class sksurgerycore.transforms.transform_manager.TransformManager[source]

Bases: object

Class for managing 4x4 transformation matrices. This class is NOT designed to be thread-safe.

The transforms are required to be 4x4 matrices. There is no checking that the upper left 3x3 is an orthonormal rotation matrix.

Usage:

tm = TransformManager()

# Imagine some example transformations:
t1 = np.eye(4)
t2 = np.eye(4)
t3 = np.eye(4)

# Add transformations to the TransformManager.
tm.add("model2world", t1)
tm.add("hand2eye",t2)
tm.add("hand2world",t3)

# Returns a transform from model to eye,
# by working through the above transforms.
t4 = tm.get("model2eye")

and so on.

add(name, transform)[source]

Adds a transform called name. If the name already exists, the corresponding transform is replaced without warning.

Parameters:
  • name – the name of the transform, e.g. model2world
  • transform – the transform, e.g. 4x4 matrix
count()[source]

Returns how many transforms are in the manager. Internally this class also stores the inverse, so this method will count those matrices as well.

exists(name)[source]

Returns True if the transform exists in the manager, and False otherwise. Internally this class stores the inverse. So, if you add model2world, you are also implicitly adding world2model, so this method will return True for both the originally added transform, and its own inverse.

static flip_name(name)[source]

Returns the inverse name.

Parameters:name – the name of a transformation, e.g. model2world
Returns:str – the opposite transformation name, e.g. world2model
get(name)[source]

Returns the named transform or throws ValueError.

Raises:ValueError
static is_valid_name(name)[source]

Validates the name, which must match “^([a-z]+)2([a-z]+)$”.

i.e. one or more lowercase letters, followed by the number 2, followed by one or more lowercase letters.

For example:

a2b
model2world

Identity transforms such as model2model raise ValueError.

Parameters:name – the name of the transform, eg. model2world
Raises:TypeError, ValueError
Returns:str, str – parts of string before and after the 2.
static is_valid_transform(transform)[source]

Validates the transform as a 4x4 numpy matrix.

Parameters:transform – 4x4 transformation matrix.
Raises:TypeError, ValueError
multiply_point(name, points)[source]

Multiplies points (4xN) by the named transform (4x4).

Returns:ndarray – 4xN matrix of transformed points
Raises:ValueError
remove(name)[source]

Removes a transform from the manager. If the transform name doesn’t exist, will throw ValueError.

Raises:ValueError

File Utilities

File processing utils.

sksurgerycore.utilities.file_utilities.get_absolute_path_of_file(file_name, dir_name=None)[source]

Filenames in our .json config could be absolute or relative to the current working dir. This method tries to find the valid, full file path.

Parameters:
  • file_name
  • dir_name – prefix, for example, the dirname of our .json file.
Returns:

absolute path name of file if found, otherwise None.

Various file utilities, often calling standard functions in the os package, but throwing nice informative Exception messages.

sksurgerycore.utilities.validate_file.validate_is_file(file_name)[source]

Check if file_name is a file.

Parameters:file_name – string containing path name
Raises:TypeError if not string, ValueError if not file
Returns:True
sksurgerycore.utilities.validate_file.validate_is_writable_file(file_name)[source]

Check if file_name is a writable file.

Parameters:file_name – string containing path name
Raises:TypeError if not string, ValueError if not file
Returns:True

Matrix Validation

Various validation routines for checking matrices.

sksurgerycore.utilities.validate_matrix.validate_camera_matrix(matrix)[source]

Validates that a matrix is a camera (intrinsic) matrix.

  1. Is a numpy array
  2. Is 2D
  3. Has 3 rows
  4. Has 3 columns
Parameters:matrix – camera matrix
Raises:TypeError, ValueError if not
Returns:True
sksurgerycore.utilities.validate_matrix.validate_distortion_coefficients(matrix)[source]

Validates that a matrix is a set of OpenCV style distortion coefficients.

  1. Is a numpy array
  2. Is 2D
  3. Has 1 row
  4. Has either 4, 5, 8, 12 or 14 columns
Parameters:matrix – set of distortion coefficients
Raises:TypeError, ValueError if not
Returns:True
sksurgerycore.utilities.validate_matrix.validate_rigid_matrix(matrix)[source]

Validates that a matrix is a 4x4 rigid transform.

Parameters:matrix – rigid transform
Raises:TypeError, ValueError if not
Returns:True
sksurgerycore.utilities.validate_matrix.validate_rotation_matrix(matrix)[source]

Validates that a matrix is rotation matrix.

  1. Is a numpy array
  2. Is 2D
  3. Has 3 rows
  4. Has 3 columns
  5. Is orthogonal, i.e., transpose(matrix) * matrix = identity matrix.
  6. Is its determinant positive (+1) (c.f., it is a reflection matrix (improper rotation) if the determinant is negative (-1))
Parameters:matrix – rotation matrix
Raises:TypeError, ValueError if not
Returns:True
sksurgerycore.utilities.validate_matrix.validate_translation_column_vector(matrix)[source]

Validates that a translation matrix is a column vector.

  1. Is numpy array
  2. Is 2D
  3. Has 3 rows
  4. Has 1 column
Parameters:matrix – translation matrix
Raises:TypeError, ValueError if not
Returns:True