Skip to content

Commit

Permalink
add code
Browse files Browse the repository at this point in the history
  • Loading branch information
tzing committed Jul 2, 2018
1 parent ba79d45 commit 6c943f8
Show file tree
Hide file tree
Showing 8 changed files with 293 additions and 0 deletions.
12 changes: 12 additions & 0 deletions License
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Copyright 2014, Daeyun Shin. All rights reserved.
Copyright 2018, tzing

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13 changes: 13 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
numpy = "*"

[dev-packages]
yapf = "*"

[requires]
python_version = "3.6"
59 changes: 59 additions & 0 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# TPS deformation

Python implementation of [thin plate spline] function.

Rewrite from [daeyun/TPS-Deformation], which was originally matlab code.


[thin plate spline]: https://en.wikipedia.org/wiki/Thin_plate_spline
[daeyun/TPS-Deformation]: https://github.com/daeyun/TPS-Deformation
9 changes: 9 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from setuptools import setup, find_packages

setup(
name='tps',
version='0.2.1',
author='tzing',
install_requires=['numpy'],
packages=find_packages(),
)
2 changes: 2 additions & 0 deletions tps/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .functions import *
from .instance import *
147 changes: 147 additions & 0 deletions tps/functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import numpy

__all__ = ['find_coefficients', 'transform']


def cdist(K: numpy.ndarray, B: numpy.ndarray) -> numpy.ndarray:
"""Calculate Euclidean distance between K[i, :] and B[j, :].
Args:
K (numpy.array): ~
B (numpy.array): ~
"""
K = numpy.atleast_2d(K)
B = numpy.atleast_2d(B)
assert K.ndim == 2
assert B.ndim == 2

K = numpy.expand_dims(K, 1)
B = numpy.expand_dims(B, 0)
D = K - B
return numpy.linalg.norm(D, axis=2)


def pairwise_radial_basis(K: numpy.ndarray, B: numpy.ndarray) -> numpy.ndarray:
"""Compute the TPS radial basis function phi(r) between every row-pair of K
and B where r is the Euclidean distance.
Args:
K: n by d vector containing n d-dimensional points.
B: m by d vector containing m d-dimensional points.
Return:
```math
P - P(i, j) = phi(norm(K(i,:)-B(j,:)))
where phi(r) = r^2*log(r) for r >= 1
r*log(r^r) for r < 1
```
References:
1. https://en.wikipedia.org/wiki/Polyharmonic_spline
2. https://en.wikipedia.org/wiki/Radial_basis_function
"""
# r_mat(i, j) is the Euclidean distance between K(i, :) and B(j, :).
r_mat = cdist(K, B)

pwise_cond_ind1 = r_mat >= 1
pwise_cond_ind2 = r_mat < 1
r_mat_p1 = r_mat[pwise_cond_ind1]
r_mat_p2 = r_mat[pwise_cond_ind2]

# P correcponds to the matrix K from [1].
P = numpy.empty(r_mat.shape)
P[pwise_cond_ind1] = (r_mat_p1**2) * numpy.log(r_mat_p1)
P[pwise_cond_ind2] = r_mat_p2 * numpy.log(numpy.power(r_mat_p2, r_mat_p2))

return P


def find_coefficients(control_points: numpy.ndarray,
target_points: numpy.ndarray,
lambda_: float = 0.,
solver: str = 'exact') -> numpy.ndarray:
"""Given a set of control points and their displacements, compute the
coefficients of the TPS interpolant f(S) deforming surface S.
Args:
control_points (numpy.array): p by d vector of control points.
target_points (numpy.array): p by d vector of corresponding control
points in the mapping function f(S).
lambda_ (float): regularization parameter. See page 4 in reference.
solver: (str): the solver to the coefficients. default is 'exact' for
the exact solution. Or use 'lstsq' for the least square solution.
Return:
(numpy.ndarray) the coefficients
References:
http://cseweb.ucsd.edu/~sjb/pami_tps.pdf
"""
# ensure data type and shape
control_points = numpy.atleast_2d(control_points)
target_points = numpy.atleast_2d(target_points)
if control_points.shape != target_points.shape:
raise ValueError(
'Shape of and control points {cp} and target points {tp} are not the same.'.
format(cp=control_points.shape, tp=target_points.shape))

p, d = control_points.shape

# The matrix
K = pairwise_radial_basis(control_points, control_points)
P = numpy.hstack([numpy.ones((p, 1)), control_points])

# Relax the exact interpolation requirement by means of regularization.
K = K + lambda_ * numpy.identity(p)

# Target points
M = numpy.vstack([
numpy.hstack([K, P]),
numpy.hstack([P.T, numpy.zeros((d + 1, d + 1))])
])
Y = numpy.vstack([target_points, numpy.zeros((d + 1, d))])

# solve for M*X = Y.
# At least d+1 control points should not be in a subspace; e.g. for d=2, at
# least 3 points are not on a straight line. Otherwise M will be singular.
solver = solver.lower()
if solver == 'exact':
X = numpy.linalg.solve(M, Y)
elif solver == 'lstsq':
X, _, _, _ = numpy.linalg.lstsq(M, Y, None)
else:
raise ValueError('Unknown solver: ' + solver)

return X


def transform(source_points: numpy.ndarray, control_points: numpy.ndarray,
coefficient: numpy.ndarray) -> numpy.ndarray:
"""Given a set of control points and mapping coefficients, compute a
deformed surface f(S) using a thin plate spline radial basis function
phi(r).
Args:
source_points (numpy.array): n by 3 array of X, Y, Z components of
the surface.
control_points (numpy.array): the control points used in the function
`find_coefficients`.
coefficient (numpy.array): the computed coefficients.
Return:
n by 3 vectors of X, Y, Z components of the deformed surface.
"""
source_points = numpy.atleast_2d(source_points)
control_points = numpy.atleast_2d(control_points)
if source_points.shape[-1] != control_points.shape[-1]:
raise ValueError(
'Dimension of source points ({sd}D) and control points ({cd}D) are not the same.'.
format(sd=source_points.shape[-1], cd=control_points.shape[-1]))

n = source_points.shape[0]

A = pairwise_radial_basis(source_points, control_points)
K = numpy.hstack([A, numpy.ones((n, 1)), source_points])

deformed_points = numpy.dot(K, coefficient)
return deformed_points
42 changes: 42 additions & 0 deletions tps/instance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import numpy

from . import functions

__all__ = ['TPS']


class TPS:
"""
The thin plate spline deformation warpping
"""

def __init__(self,
control_points: numpy.ndarray,
target_points: numpy.ndarray,
lambda_: float = 0.,
solver: str = 'exact'):
"""Create a instance that preserve the TPS coefficients.
Args:
control_points (numpy.array): p by d vector of control points.
target_points (numpy.array): p by d vector of corresponding control
points in the mapping function f(S).
lambda_ (float): regularization parameter. See page 4 in reference.
"""
self.control_points = control_points
self.coefficient = functions.find_coefficients(
control_points, target_points, lambda_, solver)

def __call__(self, source_points):
"""Transform the source points form the original surface to the
destination (deformed) surface.
Args:
source_points (numpy.array): n by 3 array of X, Y, Z components of
the surface.
this funcaiton i
"""
return functions.transform(source_points, self.control_points,
self.coefficient)

transform = __call__

0 comments on commit 6c943f8

Please sign in to comment.