<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>pymskt.mesh.anatomical.femur_cylinder API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>pymskt.mesh.anatomical.femur_cylinder</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">from scipy.optimize import least_squares
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import numpy as np
from pymskt.statistics.pca import pca_svd
class FitCylinderFemur:
def __init__(
self,
femur,
labels_name='labels',
labels=(12, 13, 14, 15),
z_resolution=50,
theta_resolution=50,
cylinder_percent_bone_width=0.9,
# copy_femur=True,
ftol=1e-4
):
# not using the copy method becuase the femur is a pymskt object not vtk so it
# doesnt work with vtk_deep_copy - would need to create new femur object.
# if copy_femur is True:
# self.femur = mskt.mesh.utils.vtk_deep_copy(femur)
# else:
# self.femur = femur
self.femur = femur
self.labels_name = labels_name
if (type(labels) == int) or (type(labels) == float):
self.labels = [labels,]
else:
self.labels = labels
self.z_resolution = z_resolution
self.theta_resolution = theta_resolution
self.cylinder_percent_bone_width = cylinder_percent_bone_width
self.ftol = ftol
self.pts_articular_cylinder = None
self.inertial_matrix_artic_surf = None
self.inertial_aligned_pts_articular_cylinder = None
self._height = None
self._origin = None
self._vector = None
self._radius = None
self.bounds = None
self.params = None
def get_initial_parameters(self):
self.get_articular_surf_points()
self.guess_height()
self.guess_origin()
self.guess_vector()
self.guess_radius()
def get_articular_surf_points(self):
label_idx = vtk_to_numpy(self.femur.mesh.GetPointData().GetArray(self.labels_name))
cylinder_labels = label_idx == self.labels[0]
if len(self.labels) > 1:
for idx in range(1, len(self.labels)):
cylinder_labels += (label_idx == self.labels[idx])
cylinder_labels = np.asarray(cylinder_labels, dtype=int)
cylinder_scalars = numpy_to_vtk(cylinder_labels)
cylinder_scalars.SetName('cylinder labels')
self.femur.mesh.GetPointData().AddArray(cylinder_scalars)
self.pts_articular_cylinder = self.femur.point_coords[cylinder_labels == 1, :]
def get_inertial_matrix_articular_surface(self):
self.inertial_matrix_artic_surf, _ = pca_svd(self.pts_articular_cylinder.T)
self.inv_inertial_matrix_artic_surf = np.linalg.inv(self.inertial_matrix_artic_surf)
def get_artic_pts_aligned_inertial_matrix(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
self.inertial_aligned_pts_articular_cylinder = self.inertial_matrix_artic_surf @ self.pts_articular_cylinder.T
def guess_height(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
height_guess = self.inertial_aligned_pts_articular_cylinder[0,:].max() - self.inertial_aligned_pts_articular_cylinder[0,:].min()
self._height = self.cylinder_percent_bone_width * height_guess
def guess_origin(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
min_x = self.inertial_aligned_pts_articular_cylinder[0,:].min() # this is going to be fully medial or laterl
max_x = self.inertial_aligned_pts_articular_cylinder[0,:].max() # this is going to be fully medial or laterl (opposite above)
mean_y = self.inertial_aligned_pts_articular_cylinder[1,:].mean() # use this as the origin y
mean_z = self.inertial_aligned_pts_articular_cylinder[2,:].mean() # I think this is going to be too close to the articular surface... but maybe good enought start?
# Get points in roughly the center of the cylinder of the condyle on the medial & lateral sides.
origin1 = np.asarray([[min_x, mean_y, mean_z],])
origin2 = np.asarray([[max_x, mean_y, mean_z],])
origin1 = self.inv_inertial_matrix_artic_surf @ origin1.T
origin1 = np.squeeze(origin1.T)
origin2 = self.inv_inertial_matrix_artic_surf @ origin2.T
origin2 = np.squeeze(origin2.T)
# Set the origin to a point just inside of the extreme on the min_x side (whether thats medial or lateral)
origin = (origin2 - origin1) * 0.05 + origin1
self._origin = origin
def guess_vector(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
vector = np.asarray([
self.inertial_matrix_artic_surf[0,0], # vector X
self.inertial_matrix_artic_surf[1,0], # vector Y
self.inertial_matrix_artic_surf[2,0], # vector Z
], dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
self._vector = vector
def guess_radius(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
range_y = self.inertial_aligned_pts_articular_cylinder[1,:].max() - self.inertial_aligned_pts_articular_cylinder[1,:].min()
radius = range_y/2
self._radius = radius
@staticmethod
def get_unit_cylinder(z_resolution, theta_resolution):
theta = np.linspace(0, 2*np.pi, theta_resolution)
unit_cylinder = np.zeros((theta_resolution * z_resolution, 3))
unit_cylinder[:, 0] = np.tile(np.cos(theta), z_resolution)
unit_cylinder[:, 1] = np.tile(np.sin(theta), z_resolution)
# for i in range(z_resolution):
unit_cylinder[:, 2] = np.repeat(np.linspace(0, 1, z_resolution), theta_resolution)
return unit_cylinder
def cylinder_function(self, origin, height, radius, vector, z_resolution=None, theta_resolution=None):
if z_resolution is None:
z_resolution = self.z_resolution
if theta_resolution is None:
theta_resolution = self.theta_resolution
# ensure vector is np array of floats.
vector = np.asarray(vector, dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
# scale the size of the cylinder
unit_cylinder = FitCylinderFemur.get_unit_cylinder(z_resolution=z_resolution, theta_resolution=theta_resolution)
unit_cylinder[:, 0] = unit_cylinder[:, 0] * radius
unit_cylinder[:, 1] = unit_cylinder[:, 1] * radius
unit_cylinder[:, 2] = unit_cylinder[:, 2] * height
# Create rotation matrix to rotate cylinder axis
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (vector == not_v).all():
not_v = np.array([0, 1, 0])
#make vector perpendicular to v
norm1 = np.cross(vector, not_v)
#normalize n1
norm1 /= np.linalg.norm(norm1)
#make unit vector perpendicular to v and n1
norm2 = np.cross(vector, norm1)
rot_matrix = np.zeros((3,3))
rot_matrix[:,0] = norm1
rot_matrix[:,1] = norm2
rot_matrix[:,2] = vector
# rotate the cylinder along the vector axis
unit_cylinder = rot_matrix @ unit_cylinder.T
unit_cylinder = unit_cylinder.T
unit_cylinder += origin
return unit_cylinder
@staticmethod
def residuals(points, cylinder):
"""
Find closest point on cylinder for each point. Calcualte
"""
diff = points[None, :, :] - cylinder[:, None, :]
diff = np.sqrt(np.sum(diff **2, axis=-1))
resids = diff.min(axis=0)
return resids
def get_func(self):
"""
Function to create the function that we want to minimize. The returned function
returns the residuals of the points vs the generated cylinder.
"""
def func(params):
cylinder = self.cylinder_function(
origin=[params[0], params[1], params[2]],
height=params[3],
radius=params[4],
vector=np.asarray([params[5],params[6],params[7]], dtype=float),
z_resolution=self.z_resolution,
theta_resolution=self.theta_resolution
)
resid = FitCylinderFemur.residuals(self.pts_articular_cylinder, cylinder)
return resid
return func
def get_bounds(self):
self.bounds = [
[
self.pts_articular_cylinder[:,0].min(),
self.pts_articular_cylinder[:,1].min(),
self.pts_articular_cylinder[:,2].min(),
self._height - self._height * 0.2,
self._radius - self._radius * 0.2,
-1,
-1,
-1
],
[
self.pts_articular_cylinder[:,0].max(),
self.pts_articular_cylinder[:,1].max(),
self.pts_articular_cylinder[:,2].max(),
self._height + self._height * 0.2,
self._radius + self._radius * 0.2,
1,
1,
1
]
]
def get_params(self):
if (self._origin is None) or (self._height is None) or (self._radius is None) or (self._vector is None):
self.get_initial_parameters()
self.params = [
self._origin[0],
self._origin[1],
self._origin[2],
self._height,
self._radius,
self._vector[0],
self._vector[1],
self._vector[2]
]
def fit(self):
if self.params is None:
self.get_params()
if self.bounds is None:
self.get_bounds()
func = self.get_func()
result = least_squares(
func,
self.params,
bounds=self.bounds,
ftol=self.ftol
)
self.optimization_success = result['success']
self.params = result['x']
self._origin = np.array([self.params[0], self.params[1], self.params[2]])
self._height = self.params[3]
self._radius = self.params[4]
self._vector = np.array([self.params[5], self.params[6], self.params[7]])
self._vector /= np.linalg.norm(self._vector)
if self.optimization_success is True:
print('Fitting cylinder to condyles completed successfully!')
else:
print('Fitting cylinder to condyles did not converge properly:\n', result)
@property
def height(self):
return self._height
@property
def radius(self):
return self._radius
@property
def origin(self):
return self._origin
@property
def vector(self):
return self._vector
@property
def cylinder(self):
return self.cylinder_function(
origin=self._origin,
height=self._height,
radius=self._radius,
vector=self._vector
)</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur"><code class="flex name class">
<span>class <span class="ident">FitCylinderFemur</span></span>
<span>(</span><span>femur, labels_name='labels', labels=(12, 13, 14, 15), z_resolution=50, theta_resolution=50, cylinder_percent_bone_width=0.9, ftol=0.0001)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class FitCylinderFemur:
def __init__(
self,
femur,
labels_name='labels',
labels=(12, 13, 14, 15),
z_resolution=50,
theta_resolution=50,
cylinder_percent_bone_width=0.9,
# copy_femur=True,
ftol=1e-4
):
# not using the copy method becuase the femur is a pymskt object not vtk so it
# doesnt work with vtk_deep_copy - would need to create new femur object.
# if copy_femur is True:
# self.femur = mskt.mesh.utils.vtk_deep_copy(femur)
# else:
# self.femur = femur
self.femur = femur
self.labels_name = labels_name
if (type(labels) == int) or (type(labels) == float):
self.labels = [labels,]
else:
self.labels = labels
self.z_resolution = z_resolution
self.theta_resolution = theta_resolution
self.cylinder_percent_bone_width = cylinder_percent_bone_width
self.ftol = ftol
self.pts_articular_cylinder = None
self.inertial_matrix_artic_surf = None
self.inertial_aligned_pts_articular_cylinder = None
self._height = None
self._origin = None
self._vector = None
self._radius = None
self.bounds = None
self.params = None
def get_initial_parameters(self):
self.get_articular_surf_points()
self.guess_height()
self.guess_origin()
self.guess_vector()
self.guess_radius()
def get_articular_surf_points(self):
label_idx = vtk_to_numpy(self.femur.mesh.GetPointData().GetArray(self.labels_name))
cylinder_labels = label_idx == self.labels[0]
if len(self.labels) > 1:
for idx in range(1, len(self.labels)):
cylinder_labels += (label_idx == self.labels[idx])
cylinder_labels = np.asarray(cylinder_labels, dtype=int)
cylinder_scalars = numpy_to_vtk(cylinder_labels)
cylinder_scalars.SetName('cylinder labels')
self.femur.mesh.GetPointData().AddArray(cylinder_scalars)
self.pts_articular_cylinder = self.femur.point_coords[cylinder_labels == 1, :]
def get_inertial_matrix_articular_surface(self):
self.inertial_matrix_artic_surf, _ = pca_svd(self.pts_articular_cylinder.T)
self.inv_inertial_matrix_artic_surf = np.linalg.inv(self.inertial_matrix_artic_surf)
def get_artic_pts_aligned_inertial_matrix(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
self.inertial_aligned_pts_articular_cylinder = self.inertial_matrix_artic_surf @ self.pts_articular_cylinder.T
def guess_height(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
height_guess = self.inertial_aligned_pts_articular_cylinder[0,:].max() - self.inertial_aligned_pts_articular_cylinder[0,:].min()
self._height = self.cylinder_percent_bone_width * height_guess
def guess_origin(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
min_x = self.inertial_aligned_pts_articular_cylinder[0,:].min() # this is going to be fully medial or laterl
max_x = self.inertial_aligned_pts_articular_cylinder[0,:].max() # this is going to be fully medial or laterl (opposite above)
mean_y = self.inertial_aligned_pts_articular_cylinder[1,:].mean() # use this as the origin y
mean_z = self.inertial_aligned_pts_articular_cylinder[2,:].mean() # I think this is going to be too close to the articular surface... but maybe good enought start?
# Get points in roughly the center of the cylinder of the condyle on the medial & lateral sides.
origin1 = np.asarray([[min_x, mean_y, mean_z],])
origin2 = np.asarray([[max_x, mean_y, mean_z],])
origin1 = self.inv_inertial_matrix_artic_surf @ origin1.T
origin1 = np.squeeze(origin1.T)
origin2 = self.inv_inertial_matrix_artic_surf @ origin2.T
origin2 = np.squeeze(origin2.T)
# Set the origin to a point just inside of the extreme on the min_x side (whether thats medial or lateral)
origin = (origin2 - origin1) * 0.05 + origin1
self._origin = origin
def guess_vector(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
vector = np.asarray([
self.inertial_matrix_artic_surf[0,0], # vector X
self.inertial_matrix_artic_surf[1,0], # vector Y
self.inertial_matrix_artic_surf[2,0], # vector Z
], dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
self._vector = vector
def guess_radius(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
range_y = self.inertial_aligned_pts_articular_cylinder[1,:].max() - self.inertial_aligned_pts_articular_cylinder[1,:].min()
radius = range_y/2
self._radius = radius
@staticmethod
def get_unit_cylinder(z_resolution, theta_resolution):
theta = np.linspace(0, 2*np.pi, theta_resolution)
unit_cylinder = np.zeros((theta_resolution * z_resolution, 3))
unit_cylinder[:, 0] = np.tile(np.cos(theta), z_resolution)
unit_cylinder[:, 1] = np.tile(np.sin(theta), z_resolution)
# for i in range(z_resolution):
unit_cylinder[:, 2] = np.repeat(np.linspace(0, 1, z_resolution), theta_resolution)
return unit_cylinder
def cylinder_function(self, origin, height, radius, vector, z_resolution=None, theta_resolution=None):
if z_resolution is None:
z_resolution = self.z_resolution
if theta_resolution is None:
theta_resolution = self.theta_resolution
# ensure vector is np array of floats.
vector = np.asarray(vector, dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
# scale the size of the cylinder
unit_cylinder = FitCylinderFemur.get_unit_cylinder(z_resolution=z_resolution, theta_resolution=theta_resolution)
unit_cylinder[:, 0] = unit_cylinder[:, 0] * radius
unit_cylinder[:, 1] = unit_cylinder[:, 1] * radius
unit_cylinder[:, 2] = unit_cylinder[:, 2] * height
# Create rotation matrix to rotate cylinder axis
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (vector == not_v).all():
not_v = np.array([0, 1, 0])
#make vector perpendicular to v
norm1 = np.cross(vector, not_v)
#normalize n1
norm1 /= np.linalg.norm(norm1)
#make unit vector perpendicular to v and n1
norm2 = np.cross(vector, norm1)
rot_matrix = np.zeros((3,3))
rot_matrix[:,0] = norm1
rot_matrix[:,1] = norm2
rot_matrix[:,2] = vector
# rotate the cylinder along the vector axis
unit_cylinder = rot_matrix @ unit_cylinder.T
unit_cylinder = unit_cylinder.T
unit_cylinder += origin
return unit_cylinder
@staticmethod
def residuals(points, cylinder):
"""
Find closest point on cylinder for each point. Calcualte
"""
diff = points[None, :, :] - cylinder[:, None, :]
diff = np.sqrt(np.sum(diff **2, axis=-1))
resids = diff.min(axis=0)
return resids
def get_func(self):
"""
Function to create the function that we want to minimize. The returned function
returns the residuals of the points vs the generated cylinder.
"""
def func(params):
cylinder = self.cylinder_function(
origin=[params[0], params[1], params[2]],
height=params[3],
radius=params[4],
vector=np.asarray([params[5],params[6],params[7]], dtype=float),
z_resolution=self.z_resolution,
theta_resolution=self.theta_resolution
)
resid = FitCylinderFemur.residuals(self.pts_articular_cylinder, cylinder)
return resid
return func
def get_bounds(self):
self.bounds = [
[
self.pts_articular_cylinder[:,0].min(),
self.pts_articular_cylinder[:,1].min(),
self.pts_articular_cylinder[:,2].min(),
self._height - self._height * 0.2,
self._radius - self._radius * 0.2,
-1,
-1,
-1
],
[
self.pts_articular_cylinder[:,0].max(),
self.pts_articular_cylinder[:,1].max(),
self.pts_articular_cylinder[:,2].max(),
self._height + self._height * 0.2,
self._radius + self._radius * 0.2,
1,
1,
1
]
]
def get_params(self):
if (self._origin is None) or (self._height is None) or (self._radius is None) or (self._vector is None):
self.get_initial_parameters()
self.params = [
self._origin[0],
self._origin[1],
self._origin[2],
self._height,
self._radius,
self._vector[0],
self._vector[1],
self._vector[2]
]
def fit(self):
if self.params is None:
self.get_params()
if self.bounds is None:
self.get_bounds()
func = self.get_func()
result = least_squares(
func,
self.params,
bounds=self.bounds,
ftol=self.ftol
)
self.optimization_success = result['success']
self.params = result['x']
self._origin = np.array([self.params[0], self.params[1], self.params[2]])
self._height = self.params[3]
self._radius = self.params[4]
self._vector = np.array([self.params[5], self.params[6], self.params[7]])
self._vector /= np.linalg.norm(self._vector)
if self.optimization_success is True:
print('Fitting cylinder to condyles completed successfully!')
else:
print('Fitting cylinder to condyles did not converge properly:\n', result)
@property
def height(self):
return self._height
@property
def radius(self):
return self._radius
@property
def origin(self):
return self._origin
@property
def vector(self):
return self._vector
@property
def cylinder(self):
return self.cylinder_function(
origin=self._origin,
height=self._height,
radius=self._radius,
vector=self._vector
)</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_unit_cylinder"><code class="name flex">
<span>def <span class="ident">get_unit_cylinder</span></span>(<span>z_resolution, theta_resolution)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def get_unit_cylinder(z_resolution, theta_resolution):
theta = np.linspace(0, 2*np.pi, theta_resolution)
unit_cylinder = np.zeros((theta_resolution * z_resolution, 3))
unit_cylinder[:, 0] = np.tile(np.cos(theta), z_resolution)
unit_cylinder[:, 1] = np.tile(np.sin(theta), z_resolution)
# for i in range(z_resolution):
unit_cylinder[:, 2] = np.repeat(np.linspace(0, 1, z_resolution), theta_resolution)
return unit_cylinder</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.residuals"><code class="name flex">
<span>def <span class="ident">residuals</span></span>(<span>points, cylinder)</span>
</code></dt>
<dd>
<div class="desc"><p>Find closest point on cylinder for each point. Calcualte</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def residuals(points, cylinder):
"""
Find closest point on cylinder for each point. Calcualte
"""
diff = points[None, :, :] - cylinder[:, None, :]
diff = np.sqrt(np.sum(diff **2, axis=-1))
resids = diff.min(axis=0)
return resids</code></pre>
</details>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder"><code class="name">var <span class="ident">cylinder</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def cylinder(self):
return self.cylinder_function(
origin=self._origin,
height=self._height,
radius=self._radius,
vector=self._vector
)</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.height"><code class="name">var <span class="ident">height</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def height(self):
return self._height</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.origin"><code class="name">var <span class="ident">origin</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def origin(self):
return self._origin</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.radius"><code class="name">var <span class="ident">radius</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def radius(self):
return self._radius</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.vector"><code class="name">var <span class="ident">vector</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@property
def vector(self):
return self._vector</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder_function"><code class="name flex">
<span>def <span class="ident">cylinder_function</span></span>(<span>self, origin, height, radius, vector, z_resolution=None, theta_resolution=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def cylinder_function(self, origin, height, radius, vector, z_resolution=None, theta_resolution=None):
if z_resolution is None:
z_resolution = self.z_resolution
if theta_resolution is None:
theta_resolution = self.theta_resolution
# ensure vector is np array of floats.
vector = np.asarray(vector, dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
# scale the size of the cylinder
unit_cylinder = FitCylinderFemur.get_unit_cylinder(z_resolution=z_resolution, theta_resolution=theta_resolution)
unit_cylinder[:, 0] = unit_cylinder[:, 0] * radius
unit_cylinder[:, 1] = unit_cylinder[:, 1] * radius
unit_cylinder[:, 2] = unit_cylinder[:, 2] * height
# Create rotation matrix to rotate cylinder axis
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (vector == not_v).all():
not_v = np.array([0, 1, 0])
#make vector perpendicular to v
norm1 = np.cross(vector, not_v)
#normalize n1
norm1 /= np.linalg.norm(norm1)
#make unit vector perpendicular to v and n1
norm2 = np.cross(vector, norm1)
rot_matrix = np.zeros((3,3))
rot_matrix[:,0] = norm1
rot_matrix[:,1] = norm2
rot_matrix[:,2] = vector
# rotate the cylinder along the vector axis
unit_cylinder = rot_matrix @ unit_cylinder.T
unit_cylinder = unit_cylinder.T
unit_cylinder += origin
return unit_cylinder</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.fit"><code class="name flex">
<span>def <span class="ident">fit</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def fit(self):
if self.params is None:
self.get_params()
if self.bounds is None:
self.get_bounds()
func = self.get_func()
result = least_squares(
func,
self.params,
bounds=self.bounds,
ftol=self.ftol
)
self.optimization_success = result['success']
self.params = result['x']
self._origin = np.array([self.params[0], self.params[1], self.params[2]])
self._height = self.params[3]
self._radius = self.params[4]
self._vector = np.array([self.params[5], self.params[6], self.params[7]])
self._vector /= np.linalg.norm(self._vector)
if self.optimization_success is True:
print('Fitting cylinder to condyles completed successfully!')
else:
print('Fitting cylinder to condyles did not converge properly:\n', result)</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_artic_pts_aligned_inertial_matrix"><code class="name flex">
<span>def <span class="ident">get_artic_pts_aligned_inertial_matrix</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_artic_pts_aligned_inertial_matrix(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
self.inertial_aligned_pts_articular_cylinder = self.inertial_matrix_artic_surf @ self.pts_articular_cylinder.T</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_articular_surf_points"><code class="name flex">
<span>def <span class="ident">get_articular_surf_points</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_articular_surf_points(self):
label_idx = vtk_to_numpy(self.femur.mesh.GetPointData().GetArray(self.labels_name))
cylinder_labels = label_idx == self.labels[0]
if len(self.labels) > 1:
for idx in range(1, len(self.labels)):
cylinder_labels += (label_idx == self.labels[idx])
cylinder_labels = np.asarray(cylinder_labels, dtype=int)
cylinder_scalars = numpy_to_vtk(cylinder_labels)
cylinder_scalars.SetName('cylinder labels')
self.femur.mesh.GetPointData().AddArray(cylinder_scalars)
self.pts_articular_cylinder = self.femur.point_coords[cylinder_labels == 1, :]</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_bounds"><code class="name flex">
<span>def <span class="ident">get_bounds</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_bounds(self):
self.bounds = [
[
self.pts_articular_cylinder[:,0].min(),
self.pts_articular_cylinder[:,1].min(),
self.pts_articular_cylinder[:,2].min(),
self._height - self._height * 0.2,
self._radius - self._radius * 0.2,
-1,
-1,
-1
],
[
self.pts_articular_cylinder[:,0].max(),
self.pts_articular_cylinder[:,1].max(),
self.pts_articular_cylinder[:,2].max(),
self._height + self._height * 0.2,
self._radius + self._radius * 0.2,
1,
1,
1
]
]</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_func"><code class="name flex">
<span>def <span class="ident">get_func</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Function to create the function that we want to minimize. The returned function
returns the residuals of the points vs the generated cylinder.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_func(self):
"""
Function to create the function that we want to minimize. The returned function
returns the residuals of the points vs the generated cylinder.
"""
def func(params):
cylinder = self.cylinder_function(
origin=[params[0], params[1], params[2]],
height=params[3],
radius=params[4],
vector=np.asarray([params[5],params[6],params[7]], dtype=float),
z_resolution=self.z_resolution,
theta_resolution=self.theta_resolution
)
resid = FitCylinderFemur.residuals(self.pts_articular_cylinder, cylinder)
return resid
return func</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_inertial_matrix_articular_surface"><code class="name flex">
<span>def <span class="ident">get_inertial_matrix_articular_surface</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_inertial_matrix_articular_surface(self):
self.inertial_matrix_artic_surf, _ = pca_svd(self.pts_articular_cylinder.T)
self.inv_inertial_matrix_artic_surf = np.linalg.inv(self.inertial_matrix_artic_surf)</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_initial_parameters"><code class="name flex">
<span>def <span class="ident">get_initial_parameters</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_initial_parameters(self):
self.get_articular_surf_points()
self.guess_height()
self.guess_origin()
self.guess_vector()
self.guess_radius()</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_params"><code class="name flex">
<span>def <span class="ident">get_params</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_params(self):
if (self._origin is None) or (self._height is None) or (self._radius is None) or (self._vector is None):
self.get_initial_parameters()
self.params = [
self._origin[0],
self._origin[1],
self._origin[2],
self._height,
self._radius,
self._vector[0],
self._vector[1],
self._vector[2]
]</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_height"><code class="name flex">
<span>def <span class="ident">guess_height</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def guess_height(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
height_guess = self.inertial_aligned_pts_articular_cylinder[0,:].max() - self.inertial_aligned_pts_articular_cylinder[0,:].min()
self._height = self.cylinder_percent_bone_width * height_guess</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_origin"><code class="name flex">
<span>def <span class="ident">guess_origin</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def guess_origin(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
min_x = self.inertial_aligned_pts_articular_cylinder[0,:].min() # this is going to be fully medial or laterl
max_x = self.inertial_aligned_pts_articular_cylinder[0,:].max() # this is going to be fully medial or laterl (opposite above)
mean_y = self.inertial_aligned_pts_articular_cylinder[1,:].mean() # use this as the origin y
mean_z = self.inertial_aligned_pts_articular_cylinder[2,:].mean() # I think this is going to be too close to the articular surface... but maybe good enought start?
# Get points in roughly the center of the cylinder of the condyle on the medial & lateral sides.
origin1 = np.asarray([[min_x, mean_y, mean_z],])
origin2 = np.asarray([[max_x, mean_y, mean_z],])
origin1 = self.inv_inertial_matrix_artic_surf @ origin1.T
origin1 = np.squeeze(origin1.T)
origin2 = self.inv_inertial_matrix_artic_surf @ origin2.T
origin2 = np.squeeze(origin2.T)
# Set the origin to a point just inside of the extreme on the min_x side (whether thats medial or lateral)
origin = (origin2 - origin1) * 0.05 + origin1
self._origin = origin</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_radius"><code class="name flex">
<span>def <span class="ident">guess_radius</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def guess_radius(self):
if self.inertial_aligned_pts_articular_cylinder is None:
self.get_artic_pts_aligned_inertial_matrix()
range_y = self.inertial_aligned_pts_articular_cylinder[1,:].max() - self.inertial_aligned_pts_articular_cylinder[1,:].min()
radius = range_y/2
self._radius = radius</code></pre>
</details>
</dd>
<dt id="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_vector"><code class="name flex">
<span>def <span class="ident">guess_vector</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def guess_vector(self):
if self.inertial_matrix_artic_surf is None:
self.get_inertial_matrix_articular_surface()
vector = np.asarray([
self.inertial_matrix_artic_surf[0,0], # vector X
self.inertial_matrix_artic_surf[1,0], # vector Y
self.inertial_matrix_artic_surf[2,0], # vector Z
], dtype=float)
if np.linalg.norm(vector) != 1:
vector = vector/np.linalg.norm(vector)
self._vector = vector</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="pymskt.mesh.anatomical" href="index.html">pymskt.mesh.anatomical</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur">FitCylinderFemur</a></code></h4>
<ul class="">
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder">cylinder</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder_function" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.cylinder_function">cylinder_function</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.fit" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.fit">fit</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_artic_pts_aligned_inertial_matrix" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_artic_pts_aligned_inertial_matrix">get_artic_pts_aligned_inertial_matrix</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_articular_surf_points" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_articular_surf_points">get_articular_surf_points</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_bounds" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_bounds">get_bounds</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_func" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_func">get_func</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_inertial_matrix_articular_surface" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_inertial_matrix_articular_surface">get_inertial_matrix_articular_surface</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_initial_parameters" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_initial_parameters">get_initial_parameters</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_params" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_params">get_params</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_unit_cylinder" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.get_unit_cylinder">get_unit_cylinder</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_height" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_height">guess_height</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_origin" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_origin">guess_origin</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_radius" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_radius">guess_radius</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_vector" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.guess_vector">guess_vector</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.height" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.height">height</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.origin" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.origin">origin</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.radius" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.radius">radius</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.residuals" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.residuals">residuals</a></code></li>
<li><code><a title="pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.vector" href="#pymskt.mesh.anatomical.femur_cylinder.FitCylinderFemur.vector">vector</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
</footer>
</body>
</html>