repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
emcee3
|
emcee3-master/emcee3/numgrad.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
__all__ = ["numerical_gradient_1", "numerical_gradient_2"]
class numerical_gradient_1(object):
"""Wrap a function to numerically compute first order gradients.
The function is expected to take a numpy array as its first argument and
calling an instance of this object will return the gradient with respect
to this first argument.
Args:
f (callable): The function.
eps (Optional[float]): The step size.
"""
def __init__(self, f, eps=1.234e-7):
self.eps = eps
self.f = f
def __call__(self, x, *args, **kwargs):
y0 = self.f(x, *args, **kwargs)
g = np.zeros(len(x))
for i, v in enumerate(x):
x[i] = v + self.eps
y = self.f(x, *args, **kwargs)
g[i] = (y - y0) / self.eps
x[i] = v
return g
class numerical_gradient_2(object):
"""Wrap a function to numerically compute second order gradients.
The function is expected to take a numpy array as its first argument and
calling an instance of this object will return the gradient with respect
to this first argument.
Args:
f (callable): The function.
eps (Optional[float]): The step size.
"""
def __init__(self, f, eps=1.234e-7):
self.eps = eps
self.f = f
def __call__(self, x, *args, **kwargs):
g = np.zeros(len(x))
for i, v in enumerate(x):
x[i] = v + self.eps
yp = self.f(x, *args, **kwargs)
x[i] = v - self.eps
ym = self.f(x, *args, **kwargs)
g[i] = 0.5 * (yp - ym) / self.eps
x[i] = v
return g
| 1,749 | 26.34375 | 76 |
py
|
emcee3
|
emcee3-master/emcee3/backends/hdf.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
try:
import h5py
except ImportError:
h5py = None
from .backend import Backend
__all__ = ["HDFBackend"]
class HDFBackend(Backend):
def __init__(self, filename, name="mcmc", **kwargs):
if h5py is None:
raise ImportError("h5py")
self.filename = filename
self.name = name
super(HDFBackend, self).__init__(**kwargs)
def open(self, mode="r"):
return h5py.File(self.filename, mode)
def reset(self):
"""Clear the chain and reset it to its default state.
"""
self.initialized = False
super(HDFBackend, self).reset()
def extend(self, n):
k = self.nwalkers
if not self.initialized:
with self.open("w") as f:
g = f.create_group(self.name)
g.attrs["niter"] = 0
g.attrs["size"] = n
g.create_dataset("chain", (n, k), dtype=self.dtype,
maxshape=(None, k))
g.create_dataset("acceptance",
data=np.zeros(k, dtype=np.uint64))
self.initialized = True
else:
with self.open("a") as f:
g = f[self.name]
# Update the size entry.
niter = g.attrs["niter"]
size = g.attrs["size"]
l = niter + n
g.attrs["size"] = size
g["chain"].resize(l, axis=0)
def update(self, ensemble):
# Get the current file shape and dimensions.
with self.open() as f:
g = f[self.name]
niter = g.attrs["niter"]
size = g.attrs["size"]
# Resize the chain if necessary.
if niter >= size:
self.extend(niter - size + 1)
# Update the file.
with self.open("a") as f:
g = f[self.name]
for j, walker in enumerate(ensemble.walkers):
g["chain"][niter, j] = walker.to_array()
g["acceptance"][:] += ensemble.acceptance
state = ensemble.random.get_state()
for i, v in enumerate(state):
g.attrs["random_state_{0}".format(i)] = v
g.attrs["niter"] = niter + 1
def __getitem__(self, name_and_index_or_slice):
try:
name, index_or_slice = name_and_index_or_slice
except ValueError:
name = name_and_index_or_slice
index_or_slice = slice(None)
try:
with self.open() as f:
g = f[self.name]
i = g.attrs["niter"]
return g["chain"][name][:i][index_or_slice]
except IOError:
raise KeyError(name)
@property
def current_coords(self):
try:
with self.open() as f:
g = f[self.name]
i = g.attrs["niter"]
if i <= 0:
raise IOError()
return g["chain"]["coords"][i - 1]
except IOError:
raise AttributeError("You need to run the chain first or store "
"the chain using the 'store' keyword "
"argument to Sampler.sample")
@property
def niter(self):
with self.open() as f:
return f[self.name].attrs["niter"]
# This no-op is here for compatibility with the default Backend.
@niter.setter
def niter(self, value):
pass
@property
def acceptance(self):
with self.open() as f:
return f[self.name]["acceptance"][...]
@property
def random_state(self):
with self.open() as f:
elements = [
v
for k, v in sorted(f[self.name].attrs.items())
if k.startswith("random_state_")
]
return elements if len(elements) else None
| 3,972 | 28.213235 | 76 |
py
|
emcee3
|
emcee3-master/emcee3/backends/backend.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from ..autocorr import integrated_time
__all__ = ["Backend"]
class Backend(object):
"""The default backend that stores the data in memory as numpy arrays.
The backend can be subscripted to access the data.
Attributes:
acceptance: An array of ``nwalkers`` integer acceptance counts.
acceptance_fraction: An array of ``nwalkers`` acceptance fractions.
coords: An array of ``(niter, nwalkers, ndim)`` coordinates.
log_prior: An array of ``(niter, nwalkers)`` log prior evaluations.
log_likelihood: An array of ``(niter, nwalkers)`` log likelihood
evaluations.
log_probability: An array of ``(niter, nwalkers)`` log probability
evaluations.
"""
def __init__(self):
self._data = None
self.reset()
def __len__(self):
return self.niter
def reset(self):
"""Clear the chain and reset it to its default state."""
self.niter = 0
self.size = 0
self.nwalkers = None
self.dtype = None
del self._data
self._data = None
self._random_state = None
def check_dimensions(self, ensemble):
"""Check that an ensemble is consistent with the current chain.
Args:
ensemble (Ensemble): The ensemble to check.
Raises:
ValueError: If the dimension or data type of the ensemble is
inconsistent with the stored data.
"""
if self.nwalkers is None:
self.nwalkers = ensemble.nwalkers
if self.dtype is None:
self.dtype = ensemble.dtype
if self.nwalkers != ensemble.nwalkers:
raise ValueError("Dimension mismatch")
if self.dtype != ensemble.dtype:
raise ValueError("Data type mismatch")
def extend(self, n):
"""Extend the chain by a given number of steps.
Args:
n (int): The number of steps to extend the chain by.
"""
k = self.nwalkers
self.size = l = self.niter + n
if self._data is None:
self._data = np.empty((l, k), dtype=self.dtype)
self._acceptance = np.zeros(k, dtype=np.uint64)
else:
dl = l - self._data.shape[0]
if dl > 0:
self._data = np.concatenate((
self._data, np.empty((dl, k), dtype=self._data.dtype)
), axis=0)
def update(self, ensemble):
"""Append an ensemble to the chain.
Args:
ensemble (Ensemble): The ensemble to append.
"""
i = self.niter
if i >= self.size:
self.extend(i - self.size + 1)
for j, walker in enumerate(ensemble):
self._data[i, j] = walker.to_array()
self._acceptance += ensemble.acceptance
self._random_state = ensemble.random.get_state()
self.niter += 1
def __getitem__(self, name_and_index_or_slice):
if self.niter <= 0:
raise AttributeError("You need to run the chain first or store "
"the chain using the 'store' keyword "
"argument to Sampler.sample")
try:
name, index_or_slice = name_and_index_or_slice
except ValueError:
name = name_and_index_or_slice
index_or_slice = slice(None)
return self._data[name][:self.niter][index_or_slice]
def get_coords(self, **kwargs):
"""Get the stored chain of MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): Take only every ``thin`` steps from the
chain. (default: ``1``)
discard (Optional[int]): Discard the first ``discard`` steps in
the chain as burn-in. (default: ``0``)
Returns:
array[..., nwalkers, ndim]: The MCMC samples.
"""
return self.get_value("coords", **kwargs)
def get_log_prior(self, **kwargs):
"""Get the chain of log priors evaluated at the MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): Take only every ``thin`` steps from the
chain. (default: ``1``)
discard (Optional[int]): Discard the first ``discard`` steps in
the chain as burn-in. (default: ``0``)
Returns:
array[..., nwalkers]: The chain of log priors.
"""
return self.get_value("log_prior", **kwargs)
def get_log_likelihood(self, **kwargs):
"""Get the chain of log likelihoods evaluated at the MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): Take only every ``thin`` steps from the
chain. (default: ``1``)
discard (Optional[int]): Discard the first ``discard`` steps in
the chain as burn-in. (default: ``0``)
Returns:
array[..., nwalkers]: The chain of log likelihoods.
"""
return self.get_value("log_likelihood", **kwargs)
def get_log_probability(self, **kwargs):
"""Get the chain of log probabilities evaluated at the MCMC samples.
Args:
flat (Optional[bool]): Flatten the chain across the ensemble.
(default: ``False``)
thin (Optional[int]): Take only every ``thin`` steps from the
chain. (default: ``1``)
discard (Optional[int]): Discard the first ``discard`` steps in
the chain as burn-in. (default: ``0``)
Returns:
array[..., nwalkers]: The chain of log probabilities.
"""
return (
self.get_value("log_prior", **kwargs) +
self.get_value("log_likelihood", **kwargs)
)
def get_integrated_autocorr_time(self, **kwargs):
"""Get the integrated autocorrelation time for each dimension.
Any arguments are passed directly to :func:`autocorr.integrated_time`.
Returns:
array[ndim]: The estimated autocorrelation time in each dimension.
"""
return integrated_time(np.mean(self.get_value("coords"), axis=1),
**kwargs)
def get_value(self, name, flat=False, thin=1, discard=0):
v = self[name, discard::thin]
if flat:
s = list(v.shape[1:])
s[0] = np.prod(v.shape[:2])
return v.reshape(s)
return v
@property
def acceptance(self):
return self._acceptance
@property
def acceptance_fraction(self):
return self.acceptance / float(self.niter)
@property
def current_coords(self):
if self.niter <= 0:
raise AttributeError("You need to run the chain first or store "
"the chain using the 'store' keyword "
"argument to Sampler.sample")
return self._data["coords"][self.niter-1]
@property
def coords(self):
return self.get_coords()
@property
def log_prior(self):
return self.get_log_prior()
@property
def log_likelihood(self):
return self.get_log_likelihood()
@property
def log_probability(self):
return self.get_log_probability()
@property
def random_state(self):
return self._random_state
| 7,700 | 31.357143 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/backends/__init__.py
|
# -*- coding: utf-8 -*-
"""
These backends abstract the storage of and access to emcee3 MCMC chains.
"""
from .backend import Backend
from .hdf import HDFBackend
__all__ = ["Backend", "HDFBackend"]
| 201 | 17.363636 | 72 |
py
|
emcee3
|
emcee3-master/emcee3/pools/jl.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["JoblibPool"]
try:
from joblib import Parallel, delayed
except ImportError:
Parallel = None
class JoblibPool(object):
def __init__(self, *args, **kwargs):
if Parallel is None:
raise ImportError("joblib")
self.args = args
self.kwargs = kwargs
def map(self, func, iterable):
dfunc = delayed(func)
return Parallel(*(self.args), **(self.kwargs))(
dfunc(a) for a in iterable
)
| 550 | 20.192308 | 55 |
py
|
emcee3
|
emcee3-master/emcee3/pools/__init__.py
|
# -*- coding: utf-8 -*-
from .default import DefaultPool
from .interruptible import InterruptiblePool
from .jl import JoblibPool
__all__ = ["DefaultPool", "InterruptiblePool", "JoblibPool"]
| 192 | 23.125 | 60 |
py
|
emcee3
|
emcee3-master/emcee3/pools/default.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["DefaultPool"]
try:
from itertools import imap
except ImportError:
imap = map
class DefaultPool(object):
def map(self, fn, iterable):
return imap(fn, iterable)
| 269 | 14.882353 | 47 |
py
|
emcee3
|
emcee3-master/emcee3/pools/interruptible.py
|
# -*- coding: utf-8 -*-
"""
Python's multiprocessing.Pool class doesn't interact well with
``KeyboardInterrupt`` signals, as documented in places such as:
* `<http://stackoverflow.com/questions/1408356/>`_
* `<http://stackoverflow.com/questions/11312525/>`_
* `<http://noswap.com/blog/python-multiprocessing-keyboardinterrupt>`_
Various workarounds have been shared. Here, we adapt the one proposed in the
last link above, by John Reese, and shared as
* `<https://github.com/jreese/multiprocessing-keyboardinterrupt/>`_
Our version is a drop-in replacement for multiprocessing.Pool ... as long as
the map() method is the only one that needs to be interrupt-friendly.
Contributed by Peter K. G. Williams <[email protected]>.
*Added in version 2.1.0*
"""
from __future__ import division, print_function
import signal
import functools
from multiprocessing.pool import Pool
from multiprocessing import TimeoutError
__all__ = ["InterruptiblePool"]
def _initializer_wrapper(actual_initializer, *rest):
"""
We ignore SIGINT. It's up to our parent to kill us in the typical
condition of this arising from ``^C`` on a terminal. If someone is
manually killing us with that signal, well... nothing will happen.
"""
signal.signal(signal.SIGINT, signal.SIG_IGN)
if actual_initializer is not None:
actual_initializer(*rest)
class InterruptiblePool(Pool):
"""
A modified version of :class:`multiprocessing.pool.Pool` that has better
behavior with regard to ``KeyboardInterrupts`` in the :func:`map` method.
:param processes: (optional)
The number of worker processes to use; defaults to the number of CPUs.
:param initializer: (optional)
Either ``None``, or a callable that will be invoked by each worker
process when it starts.
:param initargs: (optional)
Arguments for *initializer*; it will be called as
``initializer(*initargs)``.
:param kwargs: (optional)
Extra arguments. Python 2.7 supports a ``maxtasksperchild`` parameter.
"""
wait_timeout = 3600
def __init__(self, processes=None, initializer=None, initargs=(),
**kwargs):
new_initializer = functools.partial(_initializer_wrapper, initializer)
super(InterruptiblePool, self).__init__(processes, new_initializer,
initargs, **kwargs)
def map(self, func, iterable, chunksize=None):
"""
Equivalent of ``map()`` built-in, without swallowing
``KeyboardInterrupt``.
:param func:
The function to apply to the items.
:param iterable:
An iterable of items that will have `func` applied to them.
"""
# The key magic is that we must call r.get() with a timeout, because
# a Condition.wait() without a timeout swallows KeyboardInterrupts.
r = self.map_async(func, iterable, chunksize)
while True:
try:
return r.get(self.wait_timeout)
except TimeoutError:
pass
except KeyboardInterrupt:
self.terminate()
self.join()
raise
# Other exceptions propagate up.
| 3,252 | 31.207921 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/tests/common.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import os
import numpy as np
from tempfile import NamedTemporaryFile
from .. import backends
from ..model import Model, SimpleModel
__all__ = ["NormalWalker", "MetadataWalker", "UniformWalker"]
class NormalWalker(Model):
def __init__(self, ivar, width=np.inf):
self.ivar = ivar
self.width = width
def compute_log_prior(self, state):
p = state.coords
state.log_prior = 0.0
if np.any(np.abs(p) > self.width):
state.log_prior = -np.inf
return state
def compute_log_likelihood(self, state):
p = state.coords
state.log_likelihood = -0.5 * np.sum(p ** 2 * self.ivar)
return state
def compute_grad_log_prior(self, state):
state.grad_log_prior = np.zeros_like(state.coords)
return state
def compute_grad_log_likelihood(self, state):
p = state.coords
state.grad_log_likelihood = -p * self.ivar
return state
class MetadataWalker(NormalWalker):
def compute_log_likelihood(self, state):
p = state.coords
state.mean = np.mean(p)
state.median = np.median(p)
return super(MetadataWalker, self).compute_log_likelihood(state)
class UniformWalker(SimpleModel):
def __init__(self):
super(UniformWalker, self).__init__(
lambda p, *args: 0.0,
lambda p, *args: 0.0 if np.all((-1 < p) * (p < 1)) else -np.inf,
args=("nothing", "something")
)
class TempHDFBackend(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def __enter__(self):
f = NamedTemporaryFile("w", delete=False)
f.close()
self.filename = f.name
return backends.HDFBackend(f.name, "test", **(self.kwargs))
def __exit__(self, exception_type, exception_value, traceback):
os.remove(self.filename)
| 1,935 | 24.813333 | 76 |
py
|
emcee3
|
emcee3-master/emcee3/tests/__init__.py
|
# -*- coding: utf-8 -*-
from . import unit, integration
__all__ = ["unit", "integration"]
| 92 | 14.5 | 33 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_pickle.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pickle
import numpy as np
from multiprocessing import Pool
from ... import moves, pools, Ensemble
from ...model import SimpleModel
from ..common import NormalWalker
__all__ = ["test_walker_pickle", "test_ensemble_pickle", "test_moves_pickle"]
def f(x):
return 0.0
def test_walker_pickle():
# Check to make sure that the standard walker types pickle.
walker = NormalWalker(1.0)
pickle.dumps(walker)
# And the "simple" form with function pointers.
walker = SimpleModel(f, f)
pickle.dumps(walker)
def test_ensemble_pickle(seed=1234):
np.random.seed(seed)
# The standard ensemble should pickle.
e = Ensemble(NormalWalker(1.), np.random.randn(10, 3))
s = pickle.dumps(e, -1)
pickle.loads(s)
# It should also work with a pool. NOTE: the pool gets lost in this
# process.
e = Ensemble(NormalWalker(1.0), np.random.randn(10, 3), pool=Pool())
s = pickle.dumps(e, -1)
pickle.loads(s)
# It should also work with a pool. NOTE: the pool gets lost in this
# process.
e = Ensemble(NormalWalker(1.0), np.random.randn(10, 3),
pool=pools.InterruptiblePool())
s = pickle.dumps(e, -1)
pickle.loads(s)
def test_moves_pickle():
for m in [moves.StretchMove(), moves.GaussianMove(1.0),
moves.MHMove(None), moves.DEMove(1e-2), moves.WalkMove()]:
s = pickle.dumps(m, -1)
pickle.loads(s)
| 1,493 | 26.163636 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_backends.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from ... import backends, Sampler, Ensemble
from ..common import NormalWalker, TempHDFBackend, MetadataWalker
__all__ = ["test_metadata", "test_hdf", "test_hdf_reload"]
def run_sampler(backend, model=NormalWalker(1.0), nwalkers=32, ndim=3,
nsteps=5, seed=1234):
rnd = np.random.RandomState()
rnd.seed(seed)
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(model, coords, random=rnd)
sampler = Sampler(backend=backend)
list(sampler.sample(ensemble, nsteps))
return sampler
def test_metadata():
sampler1 = run_sampler(backends.Backend(), MetadataWalker(1.0))
# Check to make sure that the metadata was stored in the right order.
assert np.allclose(np.mean(sampler1.coords, axis=-1),
sampler1.get_value("mean"))
assert np.allclose(np.mean(sampler1.get_coords(flat=True), axis=-1),
sampler1.get_value("mean", flat=True))
assert np.allclose(np.median(sampler1.coords, axis=-1),
sampler1.get_value("median"))
assert np.allclose(np.median(sampler1.get_coords(flat=True), axis=-1),
sampler1.get_value("median", flat=True))
with TempHDFBackend() as backend:
sampler2 = run_sampler(backend, MetadataWalker(1.0))
assert np.allclose(sampler1.get_value("mean"),
sampler2.get_value("mean"))
assert np.allclose(sampler1.get_value("median"),
sampler2.get_value("median"))
def test_hdf():
# Run a sampler with the default backend.
sampler1 = run_sampler(backends.Backend())
with TempHDFBackend() as backend:
sampler2 = run_sampler(backend)
# Check all of the components.
for k in ["coords", "log_prior", "log_likelihood", "log_probability",
"acceptance_fraction"]:
a = getattr(sampler1, k)
b = getattr(sampler2, k)
assert np.allclose(a, b), "inconsistent {0}".format(k)
def test_hdf_reload():
with TempHDFBackend() as backend1:
run_sampler(backend1)
# Test the state
state = backend1.random_state
np.random.set_state(state)
# Load the file using a new backend object.
backend2 = backends.HDFBackend(backend1.filename, backend1.name)
assert state[0] == backend2.random_state[0]
assert all(np.allclose(a, b)
for a, b in zip(state[1:], backend2.random_state[1:]))
# Check all of the components.
for k in ["coords", "log_prior", "log_likelihood", "log_probability",
"acceptance", "acceptance_fraction"]:
a = getattr(backend1, k)
b = getattr(backend2, k)
assert np.allclose(a, b), "inconsistent {0}".format(k)
| 2,894 | 34.740741 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_models.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ..common import UniformWalker
__all__ = ["test_simple"]
def test_simple():
UniformWalker()
| 177 | 13.833333 | 47 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_numgrad.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
import numpy as np
from itertools import product
from ...numgrad import numerical_gradient_1, numerical_gradient_2
__all__ = ["test_numgrad"]
def f1(x):
return -0.5 * np.sum(x**2)
def dfdx1(x):
return -x
def f2(x):
return np.sum(x)
def dfdx2(x):
return np.ones(len(x))
@pytest.mark.parametrize("funcs,gf", product(
[(f1, dfdx1), (f2, dfdx2)],
[numerical_gradient_1, numerical_gradient_2],
))
def test_numgrad(funcs, gf, seed=42):
f, dfdx = funcs
np.random.seed(seed)
numgrad = gf(f)
x = np.zeros(5)
assert np.allclose(dfdx(x), numgrad(x), atol=2*numgrad.eps)
x = np.ones(2)
assert np.allclose(dfdx(x), numgrad(x), atol=2*numgrad.eps)
x = np.random.randn(7)
assert np.allclose(dfdx(x), numgrad(x), atol=2*numgrad.eps)
| 882 | 17.020408 | 65 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_sampler.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
import numpy as np
from ... import moves, backends, Sampler, Ensemble
from ..common import NormalWalker, TempHDFBackend
__all__ = ["test_schedule", "test_shapes", "test_errors", "test_thin"]
def test_schedule():
# The default schedule should be a single stretch move.
s = Sampler()
assert len(s._moves) == 1
assert len(s._weights) == 1
# A single move.
s = Sampler(moves.GaussianMove(0.5))
assert len(s._moves) == 1
assert len(s._weights) == 1
# A list of moves.
s = Sampler([moves.StretchMove(), moves.GaussianMove(0.5)])
assert len(s._moves) == 2
assert len(s._weights) == 2
# A weighted list of moves.
s = Sampler([(moves.StretchMove(), 0.3), (moves.GaussianMove(0.5), 0.1)])
assert len(s._moves) == 2
assert len(s._weights) == 2
assert np.allclose(s._weights, [0.75, 0.25])
def test_shapes():
run_shapes(backends.Backend())
with TempHDFBackend() as backend:
run_shapes(backend)
run_shapes(backends.Backend(), moves=[moves.GaussianMove(0.5),
moves.DEMove(0.5)])
run_shapes(backends.Backend(), moves=[(moves.GaussianMove(0.5), 0.1),
(moves.DEMove(0.5), 0.3)])
def run_shapes(backend, moves=None, nwalkers=32, ndim=3, nsteps=100,
seed=1234):
# Set up the random number generator.
rnd = np.random.RandomState()
rnd.seed(seed)
# Initialize the ensemble, moves and sampler.
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(NormalWalker(1.), coords, random=rnd)
sampler = Sampler(moves=moves, backend=backend)
# Run the sampler.
ensembles = list(sampler.sample(ensemble, nsteps))
assert len(ensembles) == nsteps, "wrong number of steps"
tau = sampler.get_integrated_autocorr_time(c=1, quiet=True)
assert tau.shape == (ndim,)
for obj in [sampler, sampler.backend]:
# Check the shapes.
assert obj.coords.shape == (nsteps, nwalkers, ndim), \
"incorrect coordinate dimensions"
assert obj.log_prior.shape == (nsteps, nwalkers), \
"incorrect prior dimensions"
assert obj.log_likelihood.shape == (nsteps, nwalkers), \
"incorrect likelihood dimensions"
assert obj.log_probability.shape == (nsteps, nwalkers), \
"incorrect probability dimensions"
assert obj.acceptance_fraction.shape == (nwalkers,), \
"incorrect acceptance fraction dimensions"
# Check the shape of the flattened coords.
assert obj.get_coords(flat=True).shape == \
(nsteps * nwalkers, ndim), "incorrect coordinate dimensions"
assert obj.get_log_prior(flat=True).shape == \
(nsteps * nwalkers,), "incorrect prior dimensions"
assert obj.get_log_likelihood(flat=True).shape == \
(nsteps*nwalkers,), "incorrect likelihood dimensions"
assert obj.get_log_probability(flat=True).shape == \
(nsteps*nwalkers,), "incorrect probability dimensions"
assert np.allclose(sampler.current_coords, sampler.coords[-1])
assert np.allclose(sampler.backend.current_coords,
sampler.backend.coords[-1])
# This should work (even though it's dumb).
sampler.reset()
for i, e in enumerate(sampler.sample(ensemble, store=True)):
if i >= nsteps - 1:
break
assert sampler.coords.shape == (nsteps, nwalkers, ndim), \
"incorrect coordinate dimensions"
assert sampler.log_prior.shape == (nsteps, nwalkers), \
"incorrect prior dimensions"
assert sampler.log_likelihood.shape == (nsteps, nwalkers), \
"incorrect likelihood dimensions"
assert sampler.log_probability.shape == (nsteps, nwalkers), \
"incorrect probability dimensions"
assert sampler.acceptance_fraction.shape == (nwalkers,), \
"incorrect acceptance fraction dimensions"
def test_errors(nwalkers=32, ndim=3, nsteps=5, seed=1234):
# Set up the random number generator.
rnd = np.random.RandomState()
rnd.seed(seed)
# Initialize the ensemble, proposal, and sampler.
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(NormalWalker(1.0), coords, random=rnd)
# Test for not running.
sampler = Sampler()
with pytest.raises(AttributeError):
sampler.coords
with pytest.raises(AttributeError):
sampler.log_probability
# What about not storing the chain.
list(sampler.sample(ensemble, nsteps, store=False))
with pytest.raises(AttributeError):
sampler.coords
# Now what about if we try to continue using the sampler with an ensemble
# of a different shape.
list(sampler.sample(ensemble, nsteps))
coords2 = rnd.randn(nwalkers, ndim+1)
ensemble2 = Ensemble(NormalWalker(1.), coords2, random=rnd)
with pytest.raises(ValueError):
list(sampler.sample(ensemble2, nsteps))
# Iterating without an end state shouldn't save the chain.
for i, e in enumerate(sampler.sample(ensemble)):
if i >= nsteps:
break
with pytest.raises(AttributeError):
sampler.coords
def run_sampler(nwalkers=32, ndim=3, nsteps=25, seed=1234, thin=1):
rnd = np.random.RandomState()
rnd.seed(seed)
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(NormalWalker(1.0), coords, random=rnd)
sampler = Sampler()
list(sampler.sample(ensemble, nsteps, thin=thin))
return sampler
def test_thin():
thinby = 3
sampler1 = run_sampler()
sampler2 = run_sampler(thin=thinby)
for k in ["coords", "log_prior", "log_likelihood", "log_probability"]:
a = getattr(sampler1, k)[thinby-1::thinby]
b = getattr(sampler2, k)
assert np.allclose(a, b), "inconsistent {0}".format(k)
def test_restart(nwalkers=32, ndim=3, nsteps=25, seed=1234):
rnd = np.random.RandomState()
rnd.seed(seed)
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(NormalWalker(1.0), coords, random=rnd)
sampler = Sampler()
sampler.run(ensemble, nsteps)
ensemble = Ensemble(NormalWalker(1.0), sampler.current_coords)
sampler.run(ensemble, nsteps)
| 6,278 | 34.275281 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_stretch.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from ... import moves, Ensemble
from ..common import NormalWalker
__all__ = ["test_live_dangerously"]
def test_live_dangerously(nwalkers=32, nsteps=3000, seed=1234):
# Set up the random number generator.
rnd = np.random.RandomState()
rnd.seed(seed)
coords = rnd.randn(nwalkers, 2 * nwalkers)
ensemble = Ensemble(NormalWalker(1.), coords, random=rnd)
proposal = moves.StretchMove()
# Test to make sure that the error is thrown if there aren't enough
# walkers.
try:
proposal.update(ensemble)
except RuntimeError:
pass
else:
assert False, "This should raise a RuntimeError"
# Living dangerously...
proposal.live_dangerously = True
proposal.update(ensemble)
| 834 | 24.30303 | 71 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_autocorr.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
import numpy as np
from ...autocorr import integrated_time, AutocorrError
__all__ = ["test_nd", "test_too_short"]
def get_chain(seed=1234, ndim=3, N=100000):
np.random.seed(seed)
a = 0.9
x = np.empty((N, ndim))
x[0] = np.zeros(ndim)
for i in range(1, N):
x[i] = x[i-1] * a + np.random.rand(ndim)
return x
def test_1d(seed=1234, ndim=1, N=150000, c=6):
x = get_chain(seed=seed, ndim=ndim, N=N)
tau, M = integrated_time(x, c=c, full_output=True)
assert np.all(M > c * tau)
assert np.all(np.abs(tau - 19.0) / 19. < 0.2)
def test_nd(seed=1234, ndim=3, N=150000):
x = get_chain(seed=seed, ndim=ndim, N=N)
tau = integrated_time(x)
assert np.all(np.abs(tau - 19.0) / 19. < 0.2)
def test_too_short(seed=1234, ndim=3, N=500):
x = get_chain(seed=seed, ndim=ndim, N=N)
with pytest.raises(AutocorrError):
integrated_time(x)
with pytest.raises(AutocorrError):
integrated_time(x, low=100)
tau = integrated_time(x, quiet=True) # NOQA
| 1,109 | 25.428571 | 54 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/__init__.py
| 0 | 0 | 0 |
py
|
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_state.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from ...state import State
__all__ = ["test_dtype", "test_serialization", "test_repr"]
def test_dtype(seed=1234):
np.random.seed(seed)
dtype = [
("coords", np.float64, (4, )),
("log_prior", np.float64),
("log_likelihood", np.float64),
("accepted", bool)
]
coords = np.random.randn(4)
state = State(coords)
assert state.dtype == np.dtype(dtype)
state = State(coords, face=10.0, blah=6, _hidden=None)
dtype += [
("blah", int),
("face", float),
]
assert state.dtype == np.dtype(dtype)
state = State(coords, face=10.0, blah=6, _hidden=None,
matrix=np.ones((3, 1)))
dtype += [
("matrix", float, (3, 1)),
]
assert state.dtype == np.dtype(dtype)
state = State(coords, face=10.0, blah=6, _hidden=None,
matrix=np.ones((3, 1)), vector=np.zeros(3))
dtype += [
("vector", float, (3,)),
]
assert state.dtype == np.dtype(dtype)
def test_serialization(seed=1234):
np.random.seed(seed)
coords = np.random.randn(4)
state = State(coords, 0.0, -1.5, True, face="blah")
array = state.to_array()
assert np.allclose(array["coords"], coords)
new_state = State.from_array(array)
assert state == new_state
def test_repr():
coords = np.zeros(1)
lnp = 0.0
lnl = -1.5
state = State(coords, lnp, lnl, True)
assert (
repr(state) ==
"State(array({0}), log_prior={1}, log_likelihood={2}, accepted=True)"
.format(coords, lnp, lnl)
)
| 1,654 | 23.338235 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/tests/unit/test_ensemble.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
import numpy as np
from ... import Ensemble
from ..common import NormalWalker, UniformWalker
__all__ = ["test_invalid_coords_init", "test_invalid_dims_init",
"test_valid_init"]
def test_invalid_coords_init(nwalkers=32, ndim=5, seed=1234):
# Check for invalid coordinates.
np.random.seed(seed)
coords = \
np.ones(nwalkers)[:, None] + 0.001 * np.random.randn(nwalkers, ndim)
with pytest.raises(ValueError):
Ensemble(UniformWalker(), coords)
def test_invalid_dims_init(nwalkers=32, ndim=5, seed=1234):
# Check for invalid coordinate dimensions.
np.random.seed(seed)
coords = np.ones((nwalkers, ndim, 3))
coords += 0.001 * np.random.randn(*(coords.shape))
with pytest.raises(ValueError):
Ensemble(UniformWalker(), coords)
def test_valid_init(nwalkers=32, ndim=5, seed=1234):
# Check to make sure that valid coordinates work too.
np.random.seed(seed)
ivar = np.random.rand(ndim)
coords = 0.002 * np.random.rand(nwalkers, ndim) - 0.001
ens = Ensemble(NormalWalker(ivar), coords)
repr(ens.walkers[0])
assert np.all(np.isfinite(ens.log_probability))
| 1,237 | 29.195122 | 76 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_gaussian.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
import numpy as np
from ... import moves
from itertools import product
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_gaussian", "test_uniform_gaussian",
"test_normal_gaussian_nd"]
@pytest.mark.parametrize("mode,factor", product(
["vector"], [None, 2.0, 5.0]
))
def test_normal_gaussian(mode, factor, **kwargs):
_test_normal(moves.GaussianMove(0.5, mode=mode, factor=factor), **kwargs)
@pytest.mark.parametrize("mode,factor", product(
["vector", "random", "sequential"], [None, 2.0]
))
def test_normal_gaussian_nd(mode, factor, **kwargs):
ndim = 3
kwargs["nsteps"] = 6000
# Isotropic.
_test_normal(moves.GaussianMove(0.5, factor=factor, mode=mode), ndim=ndim,
**kwargs)
# Axis-aligned.
_test_normal(moves.GaussianMove(0.5 * np.ones(ndim), factor=factor,
mode=mode), ndim=ndim, **kwargs)
with pytest.raises(ValueError):
_test_normal(moves.GaussianMove(0.5 * np.ones(ndim-1), factor=factor,
mode=mode), ndim=ndim,
**kwargs)
# Full matrix.
if mode == "vector":
_test_normal(moves.GaussianMove(np.diag(0.5 * np.ones(ndim)),
factor=factor, mode=mode), ndim=ndim,
**kwargs)
with pytest.raises(ValueError):
_test_normal(moves.GaussianMove(np.diag(0.5 * np.ones(ndim-1))),
ndim=ndim, **kwargs)
else:
with pytest.raises(ValueError):
_test_normal(moves.GaussianMove(np.diag(0.5 * np.ones(ndim)),
factor=factor, mode=mode),
ndim=ndim, **kwargs)
@pytest.mark.parametrize("mode,factor", product(
["vector"], [None, 2.0, 5.0]
))
def test_uniform_gaussian(mode, factor, **kwargs):
_test_uniform(moves.GaussianMove(0.5, factor=factor, mode=mode), **kwargs)
| 2,067 | 32.901639 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_proposal.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from scipy import stats
from ... import Ensemble
from ..common import NormalWalker, UniformWalker
__all__ = ["_test_normal", "_test_uniform"]
def _test_normal(proposal, ndim=1, nwalkers=32, nsteps=2000, seed=1234,
check_acceptance=True):
# Set up the random number generator.
rnd = np.random.RandomState()
rnd.seed(seed)
# Initialize the ensemble and proposal.
coords = rnd.randn(nwalkers, ndim)
ensemble = Ensemble(NormalWalker(1.), coords, random=rnd)
# Run the chain.
chain = np.empty((nsteps, nwalkers, ndim))
acc = np.zeros(nwalkers, dtype=int)
for i in range(len(chain)):
proposal.update(ensemble)
chain[i] = ensemble.coords
acc += ensemble.acceptance
# Check the acceptance fraction.
if check_acceptance:
acc = acc / nsteps
assert np.all((acc < 0.9) * (acc > 0.1)), \
"Invalid acceptance fraction\n{0}".format(acc)
# Check the resulting chain using a K-S test and compare to the mean and
# standard deviation.
samps = chain.flatten()
mu, sig = np.mean(samps, axis=0), np.std(samps, axis=0)
assert np.all(np.abs(mu) < 0.05), "Incorrect mean"
assert np.all(np.abs(sig - 1) < 0.05), "Incorrect standard deviation"
if ndim == 1:
ks, _ = stats.kstest(samps, "norm")
assert ks < 0.05, "The K-S test failed"
def _test_uniform(proposal, nwalkers=32, nsteps=2000, seed=1234):
# Set up the random number generator.
rnd = np.random.RandomState()
rnd.seed(seed)
# Initialize the ensemble and proposal.
coords = 2 * rnd.rand(nwalkers, 1) - 1
ensemble = Ensemble(UniformWalker(), coords, random=rnd)
# Run the chain.
chain = np.empty((nsteps, nwalkers, 1))
acc = np.zeros(nwalkers, dtype=int)
for i in range(len(chain)):
proposal.update(ensemble)
chain[i] = ensemble.coords
acc += ensemble.acceptance
# Check the acceptance fraction.
acc = acc / nsteps
assert np.all((acc < 0.9) * (acc > 0.1)), \
"Invalid acceptance fraction\n{0}".format(acc)
# Check that the resulting chain "fails" the K-S test.
samps = chain.flatten()
np.random.shuffle(samps)
ks, _ = stats.kstest(samps, "norm")
assert ks > 0.1, "The K-S test failed"
| 2,389 | 30.038961 | 76 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_de_snooker.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_de_snooker", "test_uniform_de_snooker"]
def test_normal_de_snooker(**kwargs):
_test_normal(moves.DESnookerMove(), **kwargs)
def test_uniform_de_snooker(**kwargs):
_test_uniform(moves.DESnookerMove(), **kwargs)
| 398 | 22.470588 | 63 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_hmc.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal
__all__ = ["test_normal_hmc", "test_normal_hmc_nd"]
def test_normal_hmc(**kwargs):
_test_normal(moves.HamiltonianMove((10, 20), (0.05, 0.1)), nsteps=100,
check_acceptance=False)
def test_uniform_hmc(**kwargs):
_test_normal(moves.HamiltonianMove((10, 20), (0.05, 0.1)), nsteps=100,
check_acceptance=False)
def test_normal_hmc_nd(**kwargs):
_test_normal(moves.HamiltonianMove(10, 0.1), ndim=3, nsteps=100,
check_acceptance=False)
| 634 | 25.458333 | 74 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_walk.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_walk", "test_uniform_walk"]
def test_normal_walk(**kwargs):
_test_normal(moves.WalkMove(s=3), **kwargs)
def test_uniform_walk(**kwargs):
_test_uniform(moves.WalkMove(s=3), **kwargs)
| 370 | 20.823529 | 54 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_nuts.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import pytest
from ... import moves
from .test_proposal import _test_normal
__all__ = ["test_normal_nuts", ]
@pytest.mark.xfail
def test_normal_nuts(**kwargs):
_test_normal(moves.NoUTurnsMove((1.0, 2.0)), nwalkers=1, nsteps=2000,
check_acceptance=False)
| 352 | 21.0625 | 73 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_stretch.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_stretch", "test_uniform_stretch",
"test_nsplits_stretch"]
def test_normal_stretch(**kwargs):
_test_normal(moves.StretchMove(), **kwargs)
def test_uniform_stretch(**kwargs):
_test_uniform(moves.StretchMove(), **kwargs)
def test_nsplits_stretch(**kwargs):
_test_normal(moves.StretchMove(nsplits=5), **kwargs)
def test_randomize_stretch(**kwargs):
_test_normal(moves.StretchMove(randomize_split=True), **kwargs)
| 620 | 22.884615 | 67 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_kde.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_kde", "test_uniform_kde", "test_nsplits_kde"]
def test_normal_kde(**kwargs):
_test_normal(moves.KDEMove(), **kwargs)
def test_uniform_kde(**kwargs):
_test_uniform(moves.KDEMove(), **kwargs)
def test_nsplits_kde(**kwargs):
_test_normal(moves.KDEMove(nsplits=5), **kwargs)
| 465 | 21.190476 | 69 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/test_de.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_de", "test_uniform_de"]
def test_normal_de(**kwargs):
_test_normal(moves.DEMove(1e-2), **kwargs)
def test_uniform_de(**kwargs):
_test_uniform(moves.DEMove(1e-2), **kwargs)
| 360 | 20.235294 | 54 |
py
|
emcee3
|
emcee3-master/emcee3/tests/integration/__init__.py
| 0 | 0 | 0 |
py
|
|
emcee3
|
emcee3-master/emcee3/samplers/sampler.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import logging
import numpy as np
from collections import Iterable
from ..moves import StretchMove
from ..backends import Backend
try:
from tqdm import tqdm
except ImportError:
tqdm = None
__all__ = ["Sampler"]
class Sampler(object):
"""A simple MCMC sampler with a customizable schedule of moves.
Args:
moves (Optional): This can be a single move object, a list of moves,
or a "weighted" list of the form
``[(emcee3.moves.StretchMove(), 0.1), ...]``. When running, the
sampler will randomly select a move from this list (optionally
with weights) for each proposal. (default: :class:`StretchMove`)
backend (Optional): The interface used for saving the samples. By
default, the samples will be saved to memory using the
:class:`Backend` interface.
"""
def __init__(self, moves=None, backend=None):
# Save the schedule. This should be a list of proposals.
if not moves:
self._moves = [StretchMove()]
self._weights = [1.0]
elif isinstance(moves, Iterable):
try:
self._moves, self._weights = zip(*moves)
except TypeError:
self._moves = moves
self._weights = np.ones(len(moves))
else:
self._moves = [moves]
self._weights = [1.0]
self._weights = np.atleast_1d(self._weights).astype(float)
self._weights /= np.sum(self._weights)
# Set up the backend.
if backend is None:
self.backend = Backend()
else:
self.backend = backend
def reset(self):
"""Clear the chain and reset it to its default state."""
self.backend.reset()
def run(self, ensemble, niter, progress=False, **kwargs):
"""Run the specified number of iterations of MCMC.
Starting from a given ensemble, run ``niter`` steps of MCMC. In
practice, this method just calls :func:`Sampler.sample` and
and returns the final ensemble from the iterator.
Args:
ensemble (Ensemble): The starting :class:`Ensemble`.
niter (int): The number of steps to run.
progress (Optional[bool]): Optionally show the sampling progress
using `tqdm <https://github.com/tqdm/tqdm>`_.
(default: ``False``)
**kwargs: Any other arguments are passed to :func:`Sampler.sample`.
Returns:
Ensemble: The final state of the ensemble.
"""
g = self.sample(ensemble, niter=niter, **kwargs)
if progress:
if tqdm is None:
raise ImportError("'tqdm' must be installed to show progress")
g = tqdm(g, total=niter)
for ensemble in g:
pass
return ensemble
def sample(self, ensemble, niter=None, store=None, thin=1):
"""Run MCMC iterations and yield each updated ensemble.
Args:
ensemble (Ensemble): The starting :class:`Ensemble`.
niter (Optional[int]): The number of steps to run. If not provided,
the sampler will run forever.
store (Optional[bool]): If ``True``, save the chain using the
backend. If ``False``, reset the backend but don't store
anything.
thin (Optional[int]): Only store every ``thin`` step. Note: the
backend won't ever know about this thinning. Instead, it will
just think that the chain had only ``niter // thin`` steps.
(default: ``1``)
Yields:
Ensemble: The state of the ensemble at every ``thin``-th step.
"""
# Set the default backend behavior if not overridden.
if niter is not None:
store = True if store is None else store
else:
store = False if store is None else store
# Warn the user about trying to store the chain without setting the
# number of iterations.
if niter is None and store:
logging.warn("Storing the chain without specifying the total "
"number of iterations is very inefficient")
# Check that the thin keyword is reasonable.
thin = int(thin)
if thin <= 0:
raise ValueError("Invalid thinning argument")
# Check the ensemble dimensions.
if store:
self.backend.check_dimensions(ensemble)
else:
self.backend.reset()
# Extend the chain to the right length.
if store:
if niter is None:
self.backend.extend(0)
else:
self.backend.extend(niter // thin)
# Start the generator.
i = 0
while True:
# Choose a random proposal.
p = ensemble.random.choice(self._moves, p=self._weights)
# Run the update on the current ensemble.
ensemble = p.update(ensemble)
# Store this update if required and if not thinned.
if (i + 1) % thin == 0:
if store:
self.backend.update(ensemble)
yield ensemble
# Finish the chain if the total number of steps was reached.
i += 1
if niter is not None and i >= niter:
return
def get_coords(self, **kwargs):
return self.backend.get_coords(**kwargs)
get_coords.__doc__ = Backend.get_coords.__doc__
def get_log_prior(self, **kwargs):
return self.backend.get_log_prior(**kwargs)
get_log_prior.__doc__ = Backend.get_log_prior.__doc__
def get_log_likelihood(self, **kwargs):
return self.backend.get_log_likelihood(**kwargs)
get_log_likelihood.__doc__ = Backend.get_log_likelihood.__doc__
def get_log_probability(self, **kwargs):
return self.backend.get_log_probability(**kwargs)
get_log_probability.__doc__ = Backend.get_log_probability.__doc__
def get_integrated_autocorr_time(self, **kwargs):
return self.backend.get_integrated_autocorr_time(**kwargs)
get_integrated_autocorr_time.__doc__ = \
Backend.get_integrated_autocorr_time.__doc__
@property
def acceptance(self):
return self.backend.acceptance
@property
def acceptance_fraction(self):
return self.backend.acceptance_fraction
@property
def current_coords(self):
return self.backend.current_coords
@property
def coords(self):
return self.backend.coords
@property
def log_prior(self):
return self.backend.log_prior
@property
def log_likelihood(self):
return self.backend.log_likelihood
@property
def log_probability(self):
return self.backend.log_probability
def __getattr__(self, attr):
try:
return getattr(self.backend, attr)
except AttributeError:
raise AttributeError("'Sampler' object has no attribute '{0}'"
.format(attr))
| 7,172 | 32.518692 | 79 |
py
|
emcee3
|
emcee3-master/emcee3/samplers/__init__.py
|
# -*- coding: utf-8 -*-
from .sampler import Sampler
__all__ = ["Sampler"]
| 77 | 12 | 28 |
py
|
emcee3
|
emcee3-master/emcee3/moves/de_snooker.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from .red_blue import RedBlueMove
__all__ = ["DESnookerMove"]
class DESnookerMove(RedBlueMove):
"""A snooker proposal using differential evolution.
Based on `Ter Braak & Vrugt (2008)
<http://link.springer.com/article/10.1007/s11222-008-9104-9>`_.
Credit goes to GitHub user `mdanthony17 <https://github.com/mdanthony17>`_
for proposing this as an addition to the original emcee package.
Args:
gammas (Optional[float]): The mean stretch factor for the proposal
vector. By default, it is :math:`1.7` as recommended by MAGIC and
the reference.
"""
def __init__(self, gammas=1.7, **kwargs):
self.gammas = gammas
super(DESnookerMove, self).__init__(**kwargs)
def get_proposal(self, ens, s, c):
Ns, Nc = len(s), len(c)
q = np.empty((Ns, ens.ndim), dtype=np.float64)
metropolis = np.empty(Ns, dtype=np.float64)
for i in range(Ns):
inds = ens.random.choice(Nc, 3, replace=False)
z, z1, z2 = c[inds]
delta = s[i] - z
norm = np.linalg.norm(delta)
u = delta / np.sqrt(norm)
q[i] = s[i] + u * self.gammas * (np.dot(u, z1) - np.dot(u, z2))
metropolis[i] = np.log(np.linalg.norm(q[i]-z)) - np.log(norm)
return q, 0.5 * (ens.ndim - 1.0) * metropolis
| 1,444 | 32.604651 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/moves/kde.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
try:
from scipy.stats import gaussian_kde
except ImportError:
gaussian_kde = None
from .red_blue import RedBlueMove
__all__ = ["KDEMove"]
class KDEMove(RedBlueMove):
"""
Use a continuously evolving KDE proposal. This is a simplified version of
the method used in `kombine <https://github.com/bfarr/kombine>`_. If you
use this proposal, you should use *a lot* of walkers in your ensemble.
:param bw_method:
The bandwidth estimation method. See `the scipy docs
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html>`_
for allowed values.
"""
def __init__(self, bw_method=None, **kwargs):
if gaussian_kde is None:
raise ImportError("you need scipy.stats.gaussian_kde to use the "
"KDEMove")
self.bw_method = bw_method
super(KDEMove, self).__init__(**kwargs)
def get_proposal(self, ens, s, c):
kde = gaussian_kde(c.T, bw_method=self.bw_method)
q = kde.resample(len(s))
factor = np.log(kde.evaluate(s.T)) - np.log(kde.evaluate(q))
return q.T, factor
| 1,237 | 29.195122 | 93 |
py
|
emcee3
|
emcee3-master/emcee3/moves/gaussian.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from .mh import MHMove
__all__ = ["GaussianMove"]
class GaussianMove(MHMove):
"""A Metropolis step with a Gaussian proposal function.
Args:
cov: The covariance of the proposal function. This can be a scalar,
vector, or matrix and the proposal will be assumed isotropic,
axis-aligned, or general respectively.
mode (Optional): Select the method used for updating parameters. This
can be one of ``"vector"``, ``"random"``, or ``"sequential"``. The
``"vector"`` mode updates all dimensions simultaneously,
``"random"`` randomly selects a dimension and only updates that
one, and ``"sequential"`` loops over dimensions and updates each
one in turn.
factor (Optional[float]): If provided the proposal will be made with a
standard deviation uniformly selected from the range
``exp(U(-log(factor), log(factor))) * cov``. This is invalid for
the ``"vector"`` mode.
Raises:
ValueError: If the proposal dimensions are invalid or if any of any of
the other arguments are inconsistent.
"""
def __init__(self, cov, mode="vector", factor=None):
# Parse the proposal type.
try:
float(cov)
except TypeError:
cov = np.atleast_1d(cov)
if len(cov.shape) == 1:
# A diagonal proposal was given.
ndim = len(cov)
proposal = _diagonal_proposal(np.sqrt(cov), factor, mode)
elif len(cov.shape) == 2 and cov.shape[0] == cov.shape[1]:
# The full, square covariance matrix was given.
ndim = cov.shape[0]
proposal = _proposal(cov, factor, mode)
else:
raise ValueError("Invalid proposal scale dimensions")
else:
# This was a scalar proposal.
ndim = None
proposal = _isotropic_proposal(np.sqrt(cov), factor, mode)
super(GaussianMove, self).__init__(proposal, ndim=ndim)
class _isotropic_proposal(object):
allowed_modes = ["vector", "random", "sequential"]
def __init__(self, scale, factor, mode):
self.index = 0
self.scale = scale
if factor is None:
self._log_factor = None
else:
if factor < 1.0:
raise ValueError("'factor' must be >= 1.0")
self._log_factor = np.log(factor)
if mode not in self.allowed_modes:
raise ValueError(("'{0}' is not a recognized mode. "
"Please select from: {1}")
.format(mode, self.allowed_modes))
self.mode = mode
def get_factor(self, rng):
if self._log_factor is None:
return 1.0
return np.exp(rng.uniform(-self._log_factor, self._log_factor))
def get_updated_vector(self, rng, x0):
return x0 + self.get_factor(rng) * self.scale * rng.randn(*(x0.shape))
def __call__(self, rng, x0):
nw, nd = x0.shape
xnew = self.get_updated_vector(rng, x0)
if self.mode == "random":
m = (range(nw), rng.randint(x0.shape[-1], size=nw))
elif self.mode == "sequential":
m = (range(nw), self.index % nd + np.zeros(nw, dtype=int))
self.index = (self.index + 1) % nd
else:
return xnew, np.zeros(nw)
x = np.array(x0)
x[m] = xnew[m]
return x, np.zeros(nw)
class _diagonal_proposal(_isotropic_proposal):
def get_updated_vector(self, rng, x0):
return x0 + self.get_factor(rng) * self.scale * rng.randn(*(x0.shape))
class _proposal(_isotropic_proposal):
allowed_modes = ["vector"]
def get_updated_vector(self, rng, x0):
return x0 + self.get_factor(rng) * rng.multivariate_normal(
np.zeros(len(self.scale)), self.scale)
| 4,020 | 32.789916 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/moves/mh.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
__all__ = ["MHMove"]
class MHMove(object):
"""
A general Metropolis-Hastings proposal.
:param proposal:
The proposal function. It should take 2 arguments: a numpy-compatible
random number generator and a ``(K, ndim)`` list of coordinate
vectors. This function should return the proposed position and the
log-ratio of the proposal probabilities (:math:`\ln q(x;\,x^\prime) -
\ln q(x^\prime;\,x)` where :math:`x^\prime` is the proposed
coordinate).
:param ndim: (optional)
If this proposal is only valid for a specific dimension of parameter
space, set that here.
"""
def __init__(self, proposal_function, ndim=None):
self.ndim = ndim
self.proposal = proposal_function
def update(self, ensemble):
"""
Execute a single step starting from the given :class:`Ensemble` and
updating it in-place.
:param ensemble:
The starting :class:`Ensemble`.
:return ensemble:
The same ensemble updated in-place.
"""
# Check to make sure that the dimensions match.
ndim = ensemble.ndim
if self.ndim is not None and self.ndim != ndim:
raise ValueError("Dimension mismatch in proposal")
# Compute the proposal.
q, factor = self.proposal(ensemble.random, ensemble.coords)
states = ensemble.propose(q)
# Loop over the walkers and update them accordingly.
for i, state in enumerate(states):
lnpdiff = (
state.log_probability -
ensemble.walkers[i].log_probability +
factor[i]
)
if lnpdiff > 0.0 or ensemble.random.rand() < np.exp(lnpdiff):
state.accepted = True
# Update the ensemble's coordinates and log-probabilities.
ensemble.update(states)
return ensemble
| 2,019 | 30.5625 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/moves/walk.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from .red_blue import RedBlueMove
__all__ = ["WalkMove"]
class WalkMove(RedBlueMove):
"""
A `Goodman & Weare (2010)
<http://msp.berkeley.edu/camcos/2010/5-1/p04.xhtml>`_ "walk move" with
parallelization as described in `Foreman-Mackey et al. (2013)
<http://arxiv.org/abs/1202.3665>`_.
:param s: (optional)
The number of helper walkers to use. By default it will use all the
walkers in the complement.
"""
def __init__(self, s=None, **kwargs):
self.s = s
super(WalkMove, self).__init__(**kwargs)
def get_proposal(self, ens, s, c):
Ns, Nc = len(s), len(c)
q = np.empty((Ns, ens.ndim), dtype=np.float64)
s0 = Nc if self.s is None else self.s
for i in range(Ns):
inds = ens.random.choice(Nc, s0, replace=False)
cov = np.atleast_2d(np.cov(c[inds], rowvar=0))
q[i] = ens.random.multivariate_normal(s[i], cov)
return q, np.zeros(Ns, dtype=np.float64)
| 1,087 | 29.222222 | 75 |
py
|
emcee3
|
emcee3-master/emcee3/moves/hmc.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from ..state import State
__all__ = ["HamiltonianMove"]
class _hmc_wrapper(object):
def __init__(self, random, model, cov, epsilon, nsteps=None):
self.random = random
self.model = model
self.nsteps = nsteps
self.epsilon = epsilon
if len(np.atleast_1d(cov).shape) == 2:
self.cov = _hmc_matrix(np.atleast_2d(cov))
else:
self.cov = _hmc_vector(np.asarray(cov))
def __call__(self, args):
current_state, current_p = args
# Sample the initial momentum.
current_q = current_state.coords
q = current_q
p = current_p
# First take a half step in momentum.
current_state = self.model.compute_grad_log_probability(current_state)
p = p + 0.5 * self.epsilon * current_state.grad_log_probability
# Alternate full steps in position and momentum.
for i in range(self.nsteps):
# First, a full step in position.
q = q + self.epsilon * self.cov.apply(p)
# Then a full step in momentum.
if i < self.nsteps - 1:
state = self.model.compute_grad_log_probability(State(q))
p = p + self.epsilon * state.grad_log_probability
# Finish with a half momentum step to synchronize with the position.
state = self.model.compute_grad_log_probability(State(q))
p = p + 0.5 * self.epsilon * state.grad_log_probability
# Negate the momentum. This step really isn't necessary but it doesn't
# hurt to keep it here for completeness.
p = -p
# Compute the log probability of the final state.
state = self.model.compute_log_probability(state)
# Automatically reject zero probability states.
state.accepted = False
if not np.isfinite(state.log_probability):
return state, 0.0
# Compute the acceptance probability factor.
factor = 0.5 * np.dot(current_p, self.cov.apply(current_p))
factor -= 0.5 * np.dot(p, self.cov.apply(p))
return state, factor
class HamiltonianMove(object):
"""A Hamiltonian Monte Carlo move.
This implementation is based on the algorithm in Figure 2 of Neal (2012;
http://arxiv.org/abs/1206.1901). By default, gradients of your model are
computed numerically but this is unlikely to be efficient so it's best if
you compute the gradients yourself using the
:func:`Model.compute_grad_log_prior` and
:func:`Model.compute_grad_log_likelihood` methods.
Args:
nsteps (int or (2,)): The number of leapfrog steps to take when
integrating the dynamics. If an integer is provided, the number of
steps will be constant. Instead, you can also provide a tuple with
two integers and these will be treated as lower and upper limits
on the number of steps and the used value will be uniformly
sampled within that range.
epsilon (float or (2,)): The step size used in the integration. Like
``nsteps`` a float can be given for a constant step size or a
range can be given and the final value will be uniformly sampled.
cov (Optional): An estimate of the parameter covariances. The inverse
of ``cov`` is used as a mass matrix in the integration. (default:
``1.0``)
"""
_wrapper = _hmc_wrapper
def __init__(self, nsteps, epsilon, nsplits=2, cov=1.0):
self.nsteps = nsteps
self.epsilon = epsilon
self.nsplits = nsplits
self.cov = cov
def get_args(self, ensemble):
# Randomize the stepsize if requested.
rand = ensemble.random
try:
eps = float(self.epsilon)
except TypeError:
eps = rand.uniform(self.epsilon[0], self.epsilon[1])
# Randomize the number of steps.
try:
L = int(self.nsteps)
except TypeError:
L = rand.randint(self.nsteps[0], self.nsteps[1])
return eps, L
def update(self, ensemble):
# Set up the integrator and sample the initial momenta.
integrator = self._wrapper(ensemble.random, ensemble.model,
self.cov, *(self.get_args(ensemble)))
momenta = integrator.cov.sample(ensemble.random, ensemble.nwalkers,
ensemble.ndim)
# Integrate the dynamics in parallel.
res = ensemble.pool.map(integrator, zip(ensemble.walkers, momenta))
# Loop over the walkers and update them accordingly.
states = []
for i, (state, factor) in enumerate(res):
lnpdiff = (
factor +
state.log_probability -
ensemble.walkers[i].log_probability
)
if lnpdiff > np.log(ensemble.random.rand()):
state.accepted = True
states.append(state)
ensemble.update(states)
return ensemble
class _hmc_vector(object):
def __init__(self, cov):
self.cov = cov
self.inv_cov = 1.0 / cov
def sample(self, random, *shape):
return random.randn(*shape) * np.sqrt(self.inv_cov)
def apply(self, x):
return self.cov * x
class _hmc_matrix(object):
def __init__(self, cov):
self.cov = cov
self.inv_cov = np.linalg.inv(self.cov)
def sample(self, random, *shape):
return random.multivariate_normal(np.zeros(shape[-1]),
self.inv_cov,
*(shape[:-1]))
def apply(self, x):
return np.dot(self.cov, x)
| 5,773 | 33.16568 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/moves/stretch.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from .red_blue import RedBlueMove
__all__ = ["StretchMove"]
class StretchMove(RedBlueMove):
"""
A `Goodman & Weare (2010)
<http://msp.berkeley.edu/camcos/2010/5-1/p04.xhtml>`_ "stretch move" with
parallelization as described in `Foreman-Mackey et al. (2013)
<http://arxiv.org/abs/1202.3665>`_.
:param a: (optional)
The stretch scale parameter. (default: ``2.0``)
"""
def __init__(self, a=2.0, **kwargs):
self.a = a
super(StretchMove, self).__init__(**kwargs)
def get_proposal(self, ens, s, c):
Ns, Nc = len(s), len(c)
zz = ((self.a - 1.) * ens.random.rand(Ns) + 1) ** 2. / self.a
factors = (ens.ndim - 1.) * np.log(zz)
rint = ens.random.randint(Nc, size=(Ns,))
return c[rint] - (c[rint] - s) * zz[:, None], factors
| 914 | 27.59375 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/moves/__init__.py
|
# -*- coding: utf-8 -*-
from .walk import WalkMove
from .stretch import StretchMove
from .de import DEMove
from .de_snooker import DESnookerMove
from .kde import KDEMove
from .mh import MHMove
from .gaussian import GaussianMove
from .hmc import HamiltonianMove
from .nuts import NoUTurnsMove
__all__ = [
"StretchMove",
"WalkMove",
"DEMove",
"DESnookerMove",
"KDEMove",
"MHMove",
"GaussianMove",
"HamiltonianMove",
"NoUTurnsMove",
]
| 472 | 17.192308 | 37 |
py
|
emcee3
|
emcee3-master/emcee3/moves/nuts.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import copy
import numpy as np
from ..state import State
from .hmc import HamiltonianMove, _hmc_wrapper
__all__ = ["NoUTurnsMove"]
class _nuts_wrapper(_hmc_wrapper):
def __init__(self, random, model, cov, epsilon, max_depth=500,
delta_max=1000.0):
self.max_depth = max_depth
self.delta_max = delta_max
super(_nuts_wrapper, self).__init__(random, model, cov, epsilon)
def leapfrog(self, state, epsilon):
p = state._momentum + 0.5 * epsilon * state.grad_log_probability
q = state.coords + epsilon * self.cov.apply(p)
state = self.model.compute_log_probability(State(q))
state = self.model.compute_grad_log_probability(state)
state._momentum = p + 0.5 * epsilon * state.grad_log_probability
return state
def build_tree(self, state, u, v, j):
if j == 0:
state_pr = self.leapfrog(state, v * self.epsilon)
K_pr = np.dot(state_pr._momentum,
self.cov.apply(state_pr._momentum))
log_prob_pr = state_pr.log_probability - 0.5 * K_pr
n_pr = int(np.log(u) < log_prob_pr)
s_pr = np.log(u) - self.delta_max < log_prob_pr
return state_pr, state_pr, state_pr, n_pr, s_pr
# Recurse.
state_m, state_p, state_pr, n_pr, s_pr = \
self.build_tree(state, u, v, j - 1)
if s_pr:
if v < 0.0:
state_m, _, state_pr_2, n_pr_2, s_pr_2 = \
self.build_tree(state_m, u, v, j - 1)
else:
_, state_p, state_pr_2, n_pr_2, s_pr_2 = \
self.build_tree(state_p, u, v, j - 1)
# Accept.
sm = n_pr + n_pr_2
if sm > 0 and self.random.rand() < n_pr_2 / sm:
state_pr = state_pr_2
n_pr += n_pr_2
s_pr = s_pr & s_pr_2 & self.stop_criterion(state_m, state_p)
return state_m, state_p, state_pr, n_pr, s_pr
def stop_criterion(self, state_m, state_p):
delta = state_p.coords - state_m.coords
return ((np.dot(delta, state_m._momentum) >= 0.0) &
(np.dot(delta, state_p._momentum) >= 0.0))
def __call__(self, args):
state, current_p = args
# Compute the initial gradient.
state = self.model.compute_log_probability(state)
state = self.model.compute_grad_log_probability(state)
state._momentum = current_p
# Initialize.
state_plus = copy.deepcopy(state)
state_minus = copy.deepcopy(state)
n = 1
# Slice sample u.
f = state.log_probability
f -= 0.5 * np.dot(current_p, self.cov.apply(current_p))
u = self.random.uniform(0.0, np.exp(f))
for j in range(self.max_depth):
v = 2.0 * (self.random.rand() < 0.5) - 1.0
if v < 0.0:
state_minus, _, state_pr, n_pr, s = \
self.build_tree(state_minus, u, v, j)
else:
_, state_plus, state_pr, n_pr, s = \
self.build_tree(state_plus, u, v, j)
# Accept or reject.
if s and self.random.rand() < float(n_pr) / n:
state = state_pr
n += n_pr
# Break out after a U-Turn.
if s and self.stop_criterion(state_minus, state_plus):
break
state._nuts_steps = j + 1
state.accepted = True
return state, np.inf
class NoUTurnsMove(HamiltonianMove):
"""A HMC move that automatically tunes the number of integration steps.
This implementations follows `Hoffman & Gelman
<http://arxiv.org/abs/1111.4246>`_ to tune the number of integration steps
by watching for "U-turns".
Args:
epsilon (float or (2,)): The step size used in the integration. A
float can be given for a constant step size or a range can be
given and the final value will be uniformly sampled.
cov (Optional): An estimate of the parameter covariances. The inverse
of ``cov`` is used as a mass matrix in the integration. (default:
``1.0``)
"""
_wrapper = _nuts_wrapper
def __init__(self, epsilon, nsplits=2, cov=1.0):
self.epsilon = epsilon
self.nsplits = nsplits
self.cov = cov
def get_args(self, ensemble):
try:
eps = float(self.epsilon)
except TypeError:
eps = ensemble.random.uniform(self.epsilon[0], self.epsilon[1])
return (eps, )
| 4,630 | 33.303704 | 78 |
py
|
emcee3
|
emcee3-master/emcee3/moves/de.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
from .red_blue import RedBlueMove
__all__ = ["DEMove"]
class DEMove(RedBlueMove):
"""A proposal using differential evolution.
This `Differential evolution proposal
<http://www.stat.columbia.edu/~gelman/stuff_for_blog/cajo.pdf>`_ is
implemented following `Nelson et al. (2013)
<http://arxiv.org/abs/1311.5229>`_.
Args:
sigma (float): The standard deviation of the Gaussian used to stretch
the proposal vector.
gamma0 (Optional[float]): The mean stretch factor for the proposal
vector. By default, it is :math:`2.38 / \sqrt{2\,\mathrm{ndim}}`
as recommended by MAGIC and the two references.
"""
def __init__(self, sigma, gamma0=None, **kwargs):
self.sigma = sigma
self.gamma0 = gamma0
super(DEMove, self).__init__(**kwargs)
def setup(self, ensemble):
self.g0 = self.gamma0
if self.g0 is None:
# Fuckin' MAGIC.
self.g0 = 2.38 / np.sqrt(2 * ensemble.ndim)
def get_proposal(self, ens, s, c):
Ns, Nc = len(s), len(c)
q = np.empty((Ns, ens.ndim), dtype=np.float64)
f = ens.random.randn(Ns)
for i in range(Ns):
inds = ens.random.choice(Nc, 2, replace=False)
g = np.diff(c[inds], axis=0) * (1 + self.g0 * f[i])
q[i] = s[i] + g
return q, np.zeros(Ns, dtype=np.float64)
| 1,492 | 30.765957 | 77 |
py
|
emcee3
|
emcee3-master/emcee3/moves/red_blue.py
|
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
__all__ = ["RedBlueMove"]
class RedBlueMove(object):
"""
An abstract red-blue ensemble move with parallelization as described in
`Foreman-Mackey et al. (2013) <http://arxiv.org/abs/1202.3665>`_.
Args:
nsplits (Optional[int]): The number of sub-ensembles to use. Each
sub-ensemble is updated in parallel using the other sets as the
complementary ensemble. The default value is ``2`` and you
probably won't need to change that.
randomize_split (Optional[bool]): Randomly shuffle walkers between
sub-ensembles. The same number of walkers will be assigned to
each sub-ensemble on each iteration. By default, this is ``False``.
live_dangerously (Optional[bool]): By default, an update will fail with
a ``RuntimeError`` if the number of walkers is smaller than twice
the dimension of the problem because the walkers would then be
stuck on a low dimensional subspace. This can be avoided by
switching between the stretch move and, for example, a
Metropolis-Hastings step. If you want to do this and suppress the
error, set ``live_dangerously = True``. Thanks goes (once again)
to @dstndstn for this wonderful terminology.
"""
def __init__(self,
nsplits=2,
randomize_split=False,
live_dangerously=False):
self.nsplits = int(nsplits)
self.live_dangerously = live_dangerously
self.randomize_split = randomize_split
def setup(self, ensemble):
pass
def get_proposal(self, ensemble, sample, complement):
raise NotImplementedError("The proposal must be implemented by "
"subclasses")
def finalize(self, ensemble):
pass
def update(self, ensemble):
"""
Execute a move starting from the given :class:`Ensemble` and updating
it in-place.
:param ensemble:
The starting :class:`Ensemble`.
:return ensemble:
The same ensemble updated in-place.
"""
# Check that the dimensions are compatible.
nwalkers, ndim = ensemble.nwalkers, ensemble.ndim
if nwalkers < 2 * ndim and not self.live_dangerously:
raise RuntimeError("It is unadvisable to use a red-blue move "
"with fewer walkers than twice the number of "
"dimensions.")
# Run any move-specific setup.
self.setup(ensemble)
# Split the ensemble in half and iterate over these two halves.
inds = np.arange(nwalkers) % self.nsplits
if self.randomize_split:
ensemble.random.shuffle(inds)
for i in range(self.nsplits):
S1 = inds == i
S2 = inds != i
# Get the two halves of the ensemble.
s = ensemble.coords[S1]
c = ensemble.coords[S2]
# Get the move-specific proposal.
q, factors = self.get_proposal(ensemble, s, c)
# Compute the lnprobs of the proposed position.
states = ensemble.propose(q)
# Loop over the walkers and update them accordingly.
for i, (j, f, state) in enumerate(zip(
np.arange(len(ensemble))[S1], factors, states)):
lnpdiff = (
f +
state.log_probability -
ensemble.walkers[j].log_probability
)
if lnpdiff > np.log(ensemble.random.rand()):
state.accepted = True
# Update the ensemble with the accepted walkers.
ensemble.update(states, subset=S1)
# Do any move-specific cleanup.
self.finalize(ensemble)
return ensemble
| 3,974 | 34.810811 | 79 |
py
|
emcee3
|
emcee3-master/examples/plot_face.py
|
# -*- coding: utf-8 -*-
"""
=====================
A short Python script
=====================
A script that is not executed when gallery is generated but nevertheless
gets included as an example.
Doing a list
"""
# Code source: Óscar Nájera
# License: BSD 3 clause
from __future__ import print_function
print([i for i in range(10)])
| 335 | 20 | 72 |
py
|
emcee3
|
emcee3-master/documents/emcee/plots/plot_acor.py
|
import numpy as np
import matplotlib.pyplot as pl
import os
import sys
# sys.path.prepend(os.path.abspath(os.path.join(__file__, "..", "..", "..")))
# import emcee
def plot_acor(acorfn):
pass
| 200 | 14.461538 | 77 |
py
|
emcee3
|
emcee3-master/documents/emcee/plots/oned.py
|
import os
import sys
import time
import numpy as np
import matplotlib.pyplot as pl
import h5py
from multiprocessing import Pool
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..", "..")))
import emcee
# import acor
def lnprobfn(p, icov):
return -0.5 * np.dot(p, np.dot(icov, p))
def random_cov(ndim, dof=1):
v = np.random.randn(ndim * (ndim + dof)).reshape((ndim + dof, ndim))
return (sum([np.outer(v[i], v[i]) for i in range(ndim + dof)])
/ (ndim + dof))
_rngs = {}
def _worker(args):
i, outfn, nsteps = args
pid = os.getpid()
_random = _rngs.get(pid, np.random.RandomState(int(int(pid)
+ time.time())))
_rngs[pid] = _random
ndim = int(np.ceil(2 ** (7 * _random.rand())))
nwalkers = 2 * ndim + 2
# nwalkers += nwalkers % 2
print ndim, nwalkers
cov = random_cov(ndim)
icov = np.linalg.inv(cov)
ens_samp = emcee.EnsembleSampler(nwalkers, ndim, lnprobfn,
args=[icov])
ens_samp.random_state = _random.get_state()
pos, lnprob, state = ens_samp.run_mcmc(np.random.randn(nwalkers * ndim)
.reshape([nwalkers, ndim]), nsteps)
proposal = np.diag(cov.diagonal())
mh_samp = emcee.MHSampler(proposal, ndim, lnprobfn,
args=[icov])
mh_samp.random_state = state
mh_samp.run_mcmc(np.random.randn(ndim), nsteps)
f = h5py.File(outfn)
f["data"][i, :] = np.array([ndim, np.mean(ens_samp.acor),
np.mean(mh_samp.acor)])
f.close()
def oned():
nsteps = 10000
niter = 10
nthreads = 2
outfn = os.path.join(os.path.split(__file__)[0], "gauss_scaling.h5")
print outfn
f = h5py.File(outfn, "w")
f.create_dataset("data", (niter, 3), "f")
f.close()
pool = Pool(nthreads)
pool.map(_worker, [(i, outfn, nsteps) for i in range(niter)])
f = h5py.File(outfn)
data = f["data"][...]
f.close()
pl.clf()
pl.plot(data[:, 0], data[:, 1], "ks", alpha=0.5)
pl.plot(data[:, 0], data[:, 2], ".k", alpha=0.5)
pl.savefig(os.path.join(os.path.split(__file__)[0], "gauss_scaling.png"))
if __name__ == "__main__":
oned()
| 2,164 | 22.791209 | 77 |
py
|
emcee3
|
emcee3-master/docs/conf.py
|
# -*- coding: utf-8 -*-
import os
import sys
d = os.path.dirname
sys.path.insert(0, d(d(os.path.abspath(__file__))))
import emcee3 # NOQA
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.mathjax",
"sphinx.ext.napoleon",
"sphinx_gallery.gen_gallery",
]
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
# General information about the project.
project = u"emcee3"
copyright = u"2014-2016 Dan Foreman-Mackey & contributors"
version = emcee3.__version__
release = emcee3.__version__
exclude_patterns = ["_build", "_static/notebooks/profile"]
pygments_style = "sphinx"
# Sphinx-gallery
sphinx_gallery_conf = dict(
examples_dirs="../examples",
gallery_dirs="examples",
)
# Readthedocs.
on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd:
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
htmp_theme_options = dict(
analytics_id="analytics_id",
)
html_context = dict(
display_github=True,
github_user="dfm",
github_repo="emcee",
github_version="emcee3",
conf_py_path="/docs/",
favicon="favicon.png",
script_files=[
"_static/jquery.js",
"_static/underscore.js",
"_static/doctools.js",
"//cdn.mathjax.org/mathjax/latest/MathJax.js"
"?config=TeX-AMS-MML_HTMLorMML",
"_static/js/analytics.js",
],
)
html_static_path = ["_static"]
html_show_sourcelink = False
| 1,488 | 22.265625 | 62 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Image_Functions/image.py
|
import numpy as np
def pad_vol_2_size(im, shape, fill_method='constant', fill_value=0):
r""" Utility function to center and copy the given volumetric image into a larger volume.
Parameters
----------
im : (MxNxL) array
input volume to copy
shape : (m,n,l) array
new volume shape
fill_method : str
method of specifying the missing pixels, one of
'constant' : str
fill with a constant value specifed by the additional argument ``fill_value``
'mean' : str
fill with the mean value of ``im``
'median' : str
fill with the median value of ``im``
fill_value : scalar
the constant value to initialise the new array if ``fill_method=='constant'``
Returns
-------
new_im : (MxNxL) array
output volume the same shape as that specified by ``shape``
"""
import numpy as np
shift_1 = (shape[0] - im.shape[0]) // 2
shift_2 = (shape[1] - im.shape[1]) // 2
shift_3 = (shape[2] - im.shape[2]) // 2
new_im = np.zeros(shape, dtype=np.uint8)
new_im[shift_1:shift_1+im.shape[0],
shift_2:shift_2+im.shape[1],
shift_3:shift_3+im.shape[2]] = im.copy()
return new_im
def mean_vol_img(vol_img_list, target_shape, fill_method='constant', fill_value=0):
r""" Utility function to find the mean volume image given a list of volumetric image files. The volumes will automatically be padded to the specified target shape.
Parameters
----------
vol_img_list : array of filepaths
list of volumetric image filepaths to compute the mean image for
target_shape : (m,n,l) array
desired volume shape, must be at least the size of the largest volume shape.
fill_method : str
method of specifying the missing pixels, one of
'constant' : str
fill with a constant value specifed by the additional argument ``fill_value``
'mean' : str
fill with the mean value of ``im``
'median' : str
fill with the median value of ``im``
fill_value : scalar
the constant value to initialise the new array if ``fill_method=='constant'``
Returns
-------
mean_vol : (MxNxL) array
mean volume with the same datatype as that of the input volumes
"""
import skimage.io as skio
# work in float but convert to ubytes for allocation?
mean_vol = np.zeros(target_shape)
n_imgs = len(vol_img_list)
for v in vol_img_list:
im = skio.imread(v)
im = pad_vol_2_size(im, target_shape, fill_method=fill_method, fill_value=fill_value)
mean_vol += im/float(n_imgs)
mean_vol = mean_vol.astype(im.dtype)
return mean_vol # cast to the same type
def max_vol_img(vol_img_list, target_shape, fill_method='constant', fill_value=0):
r""" Utility function to find the maximum intensty volume image given a list of volumetric image files. The volumes will automatically be padded to the specified target shape.
Parameters
----------
vol_img_list : array of filepaths
list of volumetric image filepaths to compute the mean image for
target_shape : (m,n,l) array
desired volume shape, must be at least the size of the largest volume shape.
fill_method : str
method of specifying the missing pixels, one of
'constant' : str
fill with a constant value specifed by the additional argument ``fill_value``
'mean' : str
fill with the mean value of ``im``
'median' : str
fill with the median value of ``im``
fill_value : scalar
the constant value to initialise the new array if ``fill_method=='constant'``
Returns
-------
max_vol : (MxNxL) array
maximum intensity volume with the same datatype as that of the input volumes
"""
import skimage.io as skio
max_vol = np.zeros(target_shape)
for v in vol_img_list:
im = skimage.imread(v)
im = pad_vol_2_size(im, target_shape, fill_method=fill_method, fill_value=fill_value)
max_vol = np.maximum(max_vol, im)
return max_vol
def imadjust(vol, p1, p2):
r""" A crucial preprocessing for many applications is to contrast stretch the original microscopy volume intensities. This is done here through percentiles similar to Matlabs imadjust function.
Parameters
----------
vol : nd array
arbitrary n-dimensional image
p1 : scalar
lower percentile of intensity, specified as a number in the range 0-100. All intensities in a lower percentile than p1 will be mapped to 0.
p2 : scalar
upper percentile of intensity, specified as a number in the range 0-100. All intensities in the upper percentile than p2 will be mapped to the maximum value of the data type.
Returns
-------
vol_rescale : nd array
image of the same dimensions as the input with contrast enchanced
"""
import numpy as np
from skimage.exposure import rescale_intensity
# this is based on contrast stretching and is used by many of the biological image processing algorithms.
p1_, p2_ = np.percentile(vol, (p1,p2))
vol_rescale = rescale_intensity(vol, in_range=(p1_,p2_))
return vol_rescale
def normalize_mi_ma(x, mi, ma, clip=False, eps=1e-20, dtype=np.float32):
r""" Linear image intensity rescaling based on the given minimum and maximum intensities, with optional clipping
The new intensities will be
.. math::
x_{new} = \frac{x-\text{mi}}{\text{ma}-\text{mi} + \text{eps}}
Parameters
----------
x : nd array
arbitrary n-dimensional image
mi : scalar
minimum intensity value
ma : scalar
maximum intensity value
clip : bool
whether to clip the transformed image intensities to [0,1]
eps : scalar
small number for numerical stability
dtype : np.dtype
if not None, casts the input x into the specified dtype
Returns
-------
x : nd array
normalized output image of the same dimensionality as the input image
"""
if dtype is not None:
x = x.astype(dtype,copy=False)
mi = dtype(mi) if np.isscalar(mi) else mi.astype(dtype,copy=False)
ma = dtype(ma) if np.isscalar(ma) else ma.astype(dtype,copy=False)
eps = dtype(eps)
try:
import numexpr
x = numexpr.evaluate("(x - mi) / ( ma - mi + eps )")
except ImportError:
x = (x - mi) / ( ma - mi + eps )
if clip:
x = np.clip(x,0,1)
return x
def normalize(x, pmin=2, pmax=99.8, axis=None, clip=False, eps=1e-20, dtype=np.float32):
r""" Percentile-based image normalization, same as :func:`unwrap3D.Image_Functions.image.imadust` but exposes more flexibility in terms of axis selection and optional clipping.
Parameters
----------
x : nd array
arbitrary n-dimensional image
pmin : scalar
lower percentile of intensity, specified as a number in the range 0-100. All intensities in a lower percentile than p1 will be mapped to 0.
pmax : scalar
upper percentile of intensity, specified as a number in the range 0-100. All intensities in the upper percentile than p2 will be mapped to the maximum value of the data type.
axis : int
if not None, compute the percentiles restricted to the specified axis, otherwise they will be based on the statistics of the whole image.
clip : bool
whether to clip to the maximum and minimum of [0,1] for float32 or float64 data types.
eps : scalar
small number for numerical stability
dtype : np.dtype
if not None, casts the input x into the specified dtype
Returns
-------
x_out : nd array
normalized output image of the same dimensionality as the input image
"""
mi = np.percentile(x,pmin,axis=axis,keepdims=True)
ma = np.percentile(x,pmax,axis=axis,keepdims=True)
x_out = normalize_mi_ma(x, mi, ma, clip=clip, eps=eps, dtype=dtype)
return x_out
def std_norm(im, mean=None, factor=1, cutoff=4, eps=1e-8):
r""" Contrast normalization using the mean and standard deviation with optional clipping.
The intensities are transformed relative to mean :math:`\mu` and standard deviation :math:`\sigma`. The transformed pixel intensities can then be effectively gated based on properties of a Gaussian distribution. Compared to percentile normalisation this methods is easier to tune.
.. math::
I_{new} = \frac{I-\mu}{\text{factor}\cdot\sigma + \text{eps}}
The extent of enhancement is effectively adjusted through ``factor``. If clipping is specified through ``cutoff`` the positive intensities up to ``cutoff`` is retained
.. math::
I_{final} &= \text{clip}(I_{new}, 0, \text{cutoff}) \\
I_{final} &= \frac{I_{final}-\min(I_{final})}{\max(I_{final})-\min(I_{final}) + \text{eps}}
Parameters
----------
im : nd array
arbitrary n-dimensional image
mean : scalar
The mean intensity to subtract off. if None, it is computed as the global mean of `im`.
factor : scalar
adjusts the extent of contrast enhancment.
cutoff : int
if not None, clip the transformed intensities to the range [0, cutoff] and then rescale the result to [0,1]
eps : scalar
small number for numerical stability
Returns
-------
im_ : nd array
normalized output image of the same dimensionality as the input image
"""
if mean is None:
im_ = im - im.mean()
else:
im_ = im - mean
im_ = im_/(factor*im.std() + eps)
if cutoff is not None:
im_ = np.clip(im_, 0, cutoff) # implement clipping.
im_ = (im_ - im_.min()) / (im_.max() - im_.min() + eps) # rescale.
return im_
def map_intensity_interp2(query_pts,
grid_shape,
I_ref,
method='linear',
cast_uint8=False,
s=0,
fill_value=0):
r""" Interpolate a 2D image at specified coordinate points.
Parameters
----------
query_pts : (n_points,2) array
array of (y,x) image coordinates to interpolate intensites at from ``I_ref``
grid_shape : (M,N) tuple
shape of the image to get intensities from
I_ref : (M,N) array
2D image to interpolate intensities from
method : str
Interpolating algorithm. Either 'spline' to use scipy.interpolate.RectBivariateSpline or any other e.g. 'linear' from scipy.interpolate.RegularGridInterpolator
cast_uint8 : bool
Whether to return the result as a uint8 image.
s : scalar
if method='spline', s=0 is a interpolating spline else s>0 is a smoothing spline.
fill_value : scalar
specifies the imputation value if any of query_pts needs to extrapolated.
Returns
-------
I_query : (n_points,) array
the intensities of ``I_ref`` interpolated at the specified ``query_pts``
"""
import numpy as np
from scipy.interpolate import RectBivariateSpline, RegularGridInterpolator
if method == 'spline':
spl = RectBivariateSpline(np.arange(grid_shape[0]),
np.arange(grid_shape[1]),
I_ref,
s=s)
I_query = spl.ev(query_pts[...,0],
query_pts[...,1])
else:
spl = RegularGridInterpolator((np.arange(grid_shape[0]),
np.arange(grid_shape[1])),
I_ref, method=method, bounds_error=False,
fill_value=fill_value)
I_query = spl((query_pts[...,0],
query_pts[...,1]))
if cast_uint8:
I_query = np.uint8(I_query)
return I_query
def scattered_interp2d(pts2D, pts2Dvals, gridsize, method='linear', cast_uint8=False, fill_value=None):
r""" Given an unordered set of 2D points with associated intensities, use Delaunay triangulation to interpolate a 2D image of the given size. Grid points outside of the convex hull of the points will be set to the given ``fill_value``
Parameters
----------
pts2D : (n_points,2)
array of (y,x) image coordinates where intensites are known
pts2Dvals : (n_points,)
array of corresponding image intensities at ``pts2D``
gridsize : (M,N) tupe
shape of the image to get intensities
method : str
one of the interpolatiion methods in ``scipy.interpolate.griddata``
cast_uint8 : bool
Whether to return the result as a uint8 image.
fill_value :
specifies the imputation value if any of query_pts needs to extrapolated.
Returns
-------
img : (M,N)
the interpolated dense image intensities of the given unordered 2D points
"""
import scipy.interpolate as scinterpolate
import numpy as np
if fill_value is None:
fill_value = np.nan
YY, XX = np.indices(gridsize)
img = scinterpolate.griddata(pts2D,
pts2Dvals,
(YY, XX), method=method, fill_value=fill_value)
return img
def map_intensity_interp3(query_pts,
grid_shape,
I_ref,
method='linear',
cast_uint8=False,
fill_value=0):
r""" Interpolate a 3D volume image at specified coordinate points.
Parameters
----------
query_pts : (n_points,3) array
array of (x,y,z) image coordinates to interpolate intensites at from ``I_ref``
grid_shape : (M,N,L) tuple
shape of the volume image to get intensities from
I_ref : (M,N,L) array
3D image to interpolate intensities from
method : str
Interpolating order. One of those e.g. 'linear' from scipy.interpolate.RegularGridInterpolator
cast_uint8 : bool
Whether to return the result as a uint8 image.
fill_value : scalar
specifies the imputation value if any of query_pts needs to extrapolated.
Returns
-------
I_query : (n_points,) array
the intensities of ``I_ref`` interpolated at the specified ``query_pts``
"""
# interpolate instead of discretising to avoid artifact.
from scipy.interpolate import RegularGridInterpolator #, RBFInterpolator
# from scipy.interpolate import griddata
from scipy import ndimage
import numpy as np
spl_3 = RegularGridInterpolator((np.arange(grid_shape[0]),
np.arange(grid_shape[1]),
np.arange(grid_shape[2])),
I_ref, method=method, bounds_error=False,
fill_value=fill_value)
I_query = spl_3((query_pts[...,0],
query_pts[...,1],
query_pts[...,2]))
if cast_uint8:
I_query = np.uint8(I_query)
return I_query
| 13,486 | 31.420673 | 281 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Image_Functions/smoothn.py
|
# from numpy import *
# def _H(y,t0=0):
# '''
# Step fn with step at t0
# '''
# h = np.zeros_like(y)
# args = tuple([slice(0,y.shape[i]) for i in y.ndim])
from scipy.fftpack.realtransforms import dct,idct
def smoothn(y, nS0=10,
axis=None,
smoothOrder=2.0,
sd=None,
verbose=False,
s0=None,
z0=None,
isrobust=False,
W=None,
s=None,
MaxIter=100,
TolZ=1e-3, weightstr='bisquare'):
r""" This function is translated from Matlab
function [z,s,exitflag,Wtot] = smoothn(varargin)
SMOOTHN Robust spline smoothing for 1-D to N-D data.
SMOOTHN provides a fast, automatized and robust discretized smoothing
spline for data of any dimension.
see [1]_ for all the details of the algorithm
Z = SMOOTHN(Y) automatically smoothes the uniformly-sampled array Y. Y
can be any N-D noisy array (time series, images, 3D data,...). Non
finite data (NaN or Inf) are treated as missing values.
Z = SMOOTHN(Y,S) smoothes the array Y using the smoothing parameter S.
S must be a real positive scalar. The larger S is, the smoother the
output will be. If the smoothing parameter S is omitted (see previous
option) or empty (i.e. S = []), it is automatically determined using
the generalized cross-validation (GCV) method.
Z = SMOOTHN(Y,W) or Z = SMOOTHN(Y,W,S) specifies a weighting array W of
real positive values, that must have the same size as Y. Note that a
nil weight corresponds to a missing value.
**Robust Smoothing**
Z = SMOOTHN(...,'robust') carries out a robust smoothing that minimizes
the influence of outlying data.
[Z,S] = SMOOTHN(...) also returns the calculated value for S so that
you can fine-tune the smoothing subsequently if needed.
An iteration process is used in the presence of weighted and/or missing
values. Z = SMOOTHN(...,OPTION_NAME,OPTION_VALUE) smoothes with the
termination parameters specified by OPTION_NAME and OPTION_VALUE. They
can contain the following criteria
*TolZ*\: Termination tolerance on Z (default = 1e-3) TolZ must be in [0,1]
*MaxIter*\: Maximum number of iterations allowed (default = 100)
*Initial*\: Initial value for the iterative process (default = original data)
Syntax: [Z,...] = SMOOTHN(...,'MaxIter',500,'TolZ',1e-4,'Initial',Z0);
[Z,S,EXITFLAG] = SMOOTHN(...) returns a boolean value EXITFLAG that
describes the exit condition of SMOOTHN
1 SMOOTHN converged.
0 Maximum number of iterations was reached.
Parameters
----------
y : array
uniformly-sampled array to smooth and fill, np.ma.masked_array or np.ndarray
nS0 : int
the number of samples used for cross-validation to determine optimal smoothing factor
axis : array
specifies the order of the input image axis. By default assumes it is the order of the dimensions the image is passed.
smoothOrder : scalar
used in the Lambda weighting controlling smoothness regularization in the penalized least squares process
sd : scalar
used to set the weights of missing pixels if running in infilling mode.
verbose : bool
if True, print out the steps
s0 : scalar
initial guess of s, the smoothing parameter in cross-validation
z0 : array
initial guess for z, the output, calculated with nearest neighbor if not provided
isrobust : bool
if True, perform iterative reweighting for outliers
W : 0-1
data weights
s : scalar
smoothing parameter if not specified it is determined with GCVS (cross validation)
MaxIter : int
maximum number of iterations for convergence
TolZ : scalar
relative tolerance for change between iterations
weightstr : str
specifies the reweighting loss for outliers if isrobust=True. One of 'cauchy', 'talworth' and bisquare'
Returns
-------
z : array
the smoothed input array
S : scalar
returns the calculated value for smoothing, S to allow for fine-tuning if required.
exitflag : 0 or 1
if 1, smoothn converged. if 0, the maximum number of iterations was used
Wtot : scalar
return the weightings computed for the regression
References
----------
.. [1] Garcia D, Robust smoothing of gridded data in one and higher dimensions with missing values. Computational Statistics & Data Analysis, 2010.
"""
import scipy.optimize.lbfgsb as lbfgsb
import numpy.linalg
from numpy.linalg import norm
from scipy.fftpack.realtransforms import dct,idct
import numpy as np
import numpy.ma as ma
if type(y) == ma.core.MaskedArray: # masked array
is_masked = True
mask = y.mask
y = np.array(y)
y[mask] = 0.
if np.any(W != None):
W = np.array(W)
W[mask] = 0.
if np.any(sd != None):
W = np.array(1./sd**2)
W[mask] = 0.
sd = None
y[mask] = np.nan
if np.any(sd != None):
sd_ = np.array(sd)
mask = (sd > 0.)
W = np.zeros_like(sd_)
W[mask] = 1./sd_[mask]**2
sd = None
if np.any(W != None):
W = W/W.max()
sizy = y.shape;
# sort axis
if axis == None:
axis = tuple(np.arange(y.ndim))
noe = y.size # number of elements
if noe<2:
z = y
exitflag = 0;Wtot=0
return z,s,exitflag,Wtot
#---
# Smoothness parameter and weights
#if s != None:
# s = []
if np.all(W == None):
W = np.ones(sizy);
#if z0 == None:
# z0 = y.copy()
#---
# "Weighting function" criterion
weightstr = weightstr.lower()
#---
# Weights. Zero weights are assigned to not finite values (Inf or NaN),
# (Inf/NaN values = missing data).
IsFinite = np.array(np.isfinite(y)).astype(bool);
nof = IsFinite.sum() # number of finite elements
W = W*IsFinite;
if np.any(W<0):
raise RuntimeError('smoothn:NegativeWeights',\
'Weights must all be >=0')
else:
#W = W/np.max(W)
pass
#---
# Weighted or missing data?
isweighted = np.any(W != 1);
#---
# Robust smoothing?
#isrobust
#---
# Automatic smoothing?
isauto = not s;
#---
# DCTN and IDCTN are required
try:
from scipy.fftpack.realtransforms import dct,idct
except:
z = y
exitflag = -1;Wtot=0
return z,s,exitflag,Wtot
## Creation of the Lambda tensor
#---
# Lambda contains the eingenvalues of the difference matrix used in this
# penalized least squares process.
axis = tuple(np.array(axis).flatten())
d = y.ndim;
Lambda = np.zeros(sizy);
for i in axis:
# create a 1 x d array (so e.g. [1,1] for a 2D case
siz0 = np.ones((1,y.ndim))[0].astype(int);
siz0[i] = sizy[i];
# cos(pi*(reshape(1:sizy(i),siz0)-1)/sizy(i)))
# (arange(1,sizy[i]+1).reshape(siz0) - 1.)/sizy[i]
Lambda = Lambda + (np.cos(np.pi*(np.arange(1,sizy[i]+1) - 1.)/sizy[i]).reshape(siz0))
#else:
# Lambda = Lambda + siz0
Lambda = -2.*(len(axis)-Lambda);
if not isauto:
Gamma = 1./(1+(s*abs(Lambda))**smoothOrder);
## Upper and lower bound for the smoothness parameter
# The average leverage (h) is by definition in [0 1]. Weak smoothing occurs
# if h is close to 1, while over-smoothing appears when h is near 0. Upper
# and lower bounds for h are given to avoid under- or over-smoothing. See
# equation relating h to the smoothness parameter (Equation #12 in the
# referenced CSDA paper).
N = np.sum(np.array(sizy) != 1); # tensor rank of the y-array
hMin = 1e-6; hMax = 0.99;
# (h/n)**2 = (1 + a)/( 2 a)
# a = 1/(2 (h/n)**2 -1)
# where a = sqrt(1 + 16 s)
# (a**2 -1)/16
try:
sMinBnd = np.sqrt((((1+np.sqrt(1+8*hMax**(2./N)))/4./hMax**(2./N))**2-1)/16.);
sMaxBnd = np.sqrt((((1+np.sqrt(1+8*hMin**(2./N)))/4./hMin**(2./N))**2-1)/16.);
except:
sMinBnd = None
sMaxBnd = None
## Initialize before iterating
#---
Wtot = W;
#--- Initial conditions for z
if isweighted:
#--- With weighted/missing data
# An initial guess is provided to ensure faster convergence. For that
# purpose, a nearest neighbor interpolation followed by a coarse
# smoothing are performed.
#---
if z0 != None: # an initial guess (z0) has been provided
z = z0;
else:
z = y #InitialGuess(y,IsFinite);
z[~IsFinite] = 0.
else:
z = np.zeros(sizy);
#---
z0 = z;
y[~IsFinite] = 0; # arbitrary values for missing y-data
#---
tol = 1.;
RobustIterativeProcess = True;
RobustStep = 1;
nit = 0;
#--- Error on p. Smoothness parameter s = 10^p
errp = 0.1;
#opt = optimset('TolX',errp);
#--- Relaxation factor RF: to speedup convergence
RF = 1 + 0.75*isweighted;
# ??
## Main iterative process
#---
if isauto:
try:
xpost = np.array([(0.9*np.log10(sMinBnd) + np.log10(sMaxBnd)*0.1)])
except:
np.array([100.])
else:
xpost = np.array([np.log10(s)])
while RobustIterativeProcess:
#--- "amount" of weights (see the function GCVscore)
aow = np.sum(Wtot)/noe; # 0 < aow <= 1
print (aow)
#---
while tol>TolZ and nit<MaxIter:
if verbose:
print('tol',tol,'nit',nit)
nit = nit+1;
DCTy = _dctND(Wtot*(y-z)+z,f=dct);
if isauto and not np.remainder(np.log2(nit),1):
#---
# The generalized cross-validation (GCV) method is used.
# We seek the smoothing parameter s that minimizes the GCV
# score i.e. s = Argmin(GCVscore).
# Because this process is time-consuming, it is performed from
# time to time (when nit is a power of 2)
#---
# errp in here somewhere
#xpost,f,d = lbfgsb.fmin_l_bfgs_b(gcv,xpost,fprime=None,factr=10.,\
# approx_grad=True,bounds=[(log10(sMinBnd),log10(sMaxBnd))],\
# args=(Lambda,aow,DCTy,IsFinite,Wtot,y,nof,noe))
# if we have no clue what value of s to use, better span the
# possible range to get a reasonable starting point ...
# only need to do it once though. nS0 is teh number of samples used
if not s0:
ss = np.arange(nS0)*(1./(nS0-1.))*(np.log10(sMaxBnd)-np.log10(sMinBnd))+ np.log10(sMinBnd)
g = np.zeros_like(ss)
for i,p in enumerate(ss):
g[i] = _gcv(p,Lambda,aow,DCTy,IsFinite,Wtot,y,nof,noe,smoothOrder)
#print 10**p,g[i]
xpost = [ss[g==g.min()]]
#print '==============='
#print nit,tol,g.min(),xpost[0],s
#print '==============='
else:
xpost = [s0]
xpost,f,d = lbfgsb.fmin_l_bfgs_b(_gcv,xpost,fprime=None,factr=1e7,\
approx_grad=True,bounds=[(np.log10(sMinBnd),np.log10(sMaxBnd))],\
args=(Lambda,aow,DCTy,IsFinite,Wtot,y,nof,noe,smoothOrder))
s = 10**xpost[0];
# update the value we use for the initial s estimate
s0 = xpost[0]
Gamma = 1./(1+(s*np.abs(Lambda))**smoothOrder);
z = RF*_dctND(Gamma*DCTy,f=idct) + (1-RF)*z;
# if no weighted/missing data => tol=0 (no iteration)
tol = isweighted*norm(z0-z)/norm(z);
z0 = z; # re-initialization
exitflag = nit<MaxIter;
if isrobust: #-- Robust Smoothing: iteratively re-weighted process
#--- average leverage
h = np.sqrt(1+16.*s);
h = np.sqrt(1+h)/np.sqrt(2)/h;
h = h**N;
#--- take robust weights into account
Wtot = W*_RobustWeights(y-z,IsFinite,h,weightstr);
#--- re-initialize for another iterative weighted process
isweighted = True; tol = 1; nit = 0;
#---
RobustStep = RobustStep+1;
RobustIterativeProcess = RobustStep<3; # 3 robust steps are enough.
else:
RobustIterativeProcess = False; # stop the whole process
## Warning messages
#---
if isauto:
if np.abs(np.log10(s)-np.log10(sMinBnd))<errp:
_warning('MATLAB:smoothn:SLowerBound',\
['s = %.3f '%(s) + ': the lower bound for s '\
+ 'has been reached. Put s as an input variable if required.'])
elif np.abs(np.log10(s)-np.log10(sMaxBnd))<errp:
_warning('MATLAB:smoothn:SUpperBound',\
['s = %.3f '%(s) + ': the upper bound for s '\
+ 'has been reached. Put s as an input variable if required.'])
#warning('MATLAB:smoothn:MaxIter',\
# ['Maximum number of iterations (%d'%(MaxIter) + ') has '\
# + 'been exceeded. Increase MaxIter option or decrease TolZ value.'])
return z,s,exitflag,Wtot
def _warning(s1,s2):
print(s1)
print(s2[0])
## GCV score
#---
#function GCVscore = gcv(p)
def _gcv(p,Lambda,aow,DCTy,IsFinite,Wtot,y,nof,noe,smoothOrder):
import numpy as np
# Search the smoothing parameter s that minimizes the GCV score
#---
s = 10**p;
Gamma = 1./(1+(s*np.abs(Lambda))**smoothOrder);
#--- RSS = Residual sum-of-squares
if aow>0.9: # aow = 1 means that all of the data are equally weighted
# very much faster: does not require any inverse DCT
RSS = np.linalg.norm(DCTy*(Gamma-1.))**2;
else:
# take account of the weights to calculate RSS:
yhat = _dctND(Gamma*DCTy,f=idct);
RSS = np.linalg.norm(np.sqrt(Wtot[IsFinite])*(y[IsFinite]-yhat[IsFinite]))**2;
#---
TrH = np.sum(Gamma);
GCVscore = RSS/float(nof)/(1.-TrH/float(noe))**2;
return GCVscore
## Robust weights
#function W = RobustWeights(r,I,h,wstr)
def _RobustWeights(r,I,h,wstr):
# weights for robust smoothing.
MAD = np.median(np.abs(r[I]-np.median(r[I]))); # median absolute deviation
u = abs(r/(1.4826*MAD)/np.sqrt(1-h)); # studentized residuals
if wstr == 'cauchy':
c = 2.385; W = 1./(1+(u/c)**2); # Cauchy weights
elif wstr == 'talworth':
c = 2.795; W = u<c; # Talworth weights
else:
c = 4.685; W = (1-(u/c)**2)**2.*((u/c)<1); # bisquare weights
W[np.isnan(W)] = 0;
return W
## Initial Guess with weighted/missing data
#function z = InitialGuess(y,I)
def _InitialGuess(y,I):
#-- nearest neighbor interpolation (in case of missing values)
if any(~I):
try:
from scipy.ndimage.morphology import distance_transform_edt
#if license('test','image_toolbox')
#[z,L] = bwdist(I);
L = distance_transform_edt(1-I)
z = y;
z[~I] = y[L[~I]];
except:
# If BWDIST does not exist, NaN values are all replaced with the
# same scalar. The initial guess is not optimal and a warning
# message thus appears.
z = y;
z[~I] = np.nanmean(y[I]);
else:
z = y;
# coarse fast smoothing
z = _dctND(z,f=dct)
k = np.array(z.shape)
m = np.ceil(k/10)+1
d = []
for i in range(len(k)):
d.append(np.arange(m[i],k[i]))
d = np.array(d).astype(int)
z[d] = 0.
z = _dctND(z,f=idct)
return z
#-- coarse fast smoothing using one-tenth of the DCT coefficients
#siz = z.shape;
#z = dct(z,norm='ortho',type=2);
#for k in np.arange(len(z.shape)):
# z[ceil(siz[k]/10)+1:-1] = 0;
# ss = tuple(roll(array(siz),1-k))
# z = z.reshape(ss)
# z = np.roll(z.T,1)
#z = idct(z,norm='ortho',type=2);
# NB: filter is 2*I - (np.roll(I,-1) + np.roll(I,1))
def _dctND(data,f=dct):
nd = len(data.shape)
if nd == 1:
return f(data,norm='ortho',type=2)
elif nd == 2:
return f(f(data,norm='ortho',type=2).T,norm='ortho',type=2).T
elif nd ==3:
return f(f(f(data,norm='ortho',type=2,axis=0)\
,norm='ortho',type=2,axis=1)\
,norm='ortho',type=2,axis=2)
elif nd ==4:
return f(f(f(f(data,norm='ortho',type=2,axis=0)\
,norm='ortho',type=2,axis=1)\
,norm='ortho',type=2,axis=2)\
,norm='ortho',type=2,axis=3)
def _peaks(n):
'''
Mimic basic of matlab peaks fn
'''
import numpy as np
xp = np.arange(n)
[x,y] = np.meshgrid(xp,xp)
z = np.zeros_like(x).astype(float)
for i in np.arange(n/5):
x0 = np.random.random()*n
y0 = np.random.random()*n
sdx = np.random.random()*n/4.
sdy = sdx
c = np.random.random()*2 - 1.
f = np.exp(-((x-x0)/sdx)**2-((y-y0)/sdy)**2 - (((x-x0)/sdx))*((y-y0)/sdy)*c)
#f /= f.sum()
f *= np.random.random()
z += f
return z
# ''
def _test1():
plt.figure(1)
plt.clf()
# 1-D example
x = np.linspace(0,100,2**8);
y = np.cos(x/10)+(x/50)**2 + np.random.randn(np.size(x))/10;
y[[70, 75, 80]] = [5.5, 5, 6];
z = smoothn(y)[0]; # Regular smoothing
zr = smoothn(y,isrobust=True)[0]; # Robust smoothing
plt.subplot(121)
plt.plot(x,y,'r.')
plt.plot(x,z,'k')
plt.title('Regular smoothing')
plt.subplot(122)
plt.plot(x,y,'r.')
plt.plot(x,zr,'k')
plt.title('Robust smoothing')
plt.show()
def _test2(axis=None):
# 2-D example
plt.figure(2)
plt.clf()
xp = np.arange(0,1,.02)
[x,y] = np.meshgrid(xp,xp);
f = np.exp(x+y) + np.sin((x-2*y)*3);
fn = f + (np.random.randn(f.size)*0.5).reshape(f.shape);
fs = smoothn(fn,axis=axis)[0];
plt.subplot(121); plt.imshow(fn,interpolation='Nearest');# axis square
plt.subplot(122); plt.imshow(fs,interpolation='Nearest'); # axis square
def _test3(axis=None):
# 2-D example with missing data
plt.figure(3)
plt.clf()
n = 256;
y0 = _peaks(n);
y = (y0 + np.random.random(np.shape(y0))*2 - 1.0).flatten();
I = np.random.permutation(range(n**2));
y[I[1:int(n**2*0.5)]] = np.nan; # lose 50% of data
y = y.reshape(y0.shape)
y[40:90,140:190] = np.nan; # create a hole
yData = y.copy()
plt.figure()
plt.imshow(yData)
plt.show()
z0,s,exitflag,Wtot = smoothn(yData,axis=axis); # smooth data
yData = y.copy()
z,s,exitflag,Wtot = smoothn(yData,isrobust=True,axis=axis); # smooth data
y = yData
vmin = np.min([np.min(z),np.min(z0),np.min(y),np.min(y0)])
vmax = np.max([np.max(z),np.max(z0),np.max(y),np.max(y0)])
plt.subplot(221); plt.imshow(y,interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('Noisy corrupt data')
plt.subplot(222); plt.imshow(z0,interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('Recovered data #1')
plt.subplot(223); plt.imshow(z,interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('Recovered data #2')
plt.subplot(224); plt.imshow(y0,interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('... compared with original data')
def _test4(i=10,step=0.2,axis=None):
[x,y,z] = np.mgrid[-2:2:step,-2:2:step,-2:2:step]
x = np.array(x);y=np.array(y);z=np.array(z)
xslice = [-0.8,1]; yslice = 2; zslice = [-2,0];
v0 = x*np.exp(-x**2-y**2-z**2)
vn = v0 + np.random.randn(x.size).reshape(x.shape)*0.06
v = smoothn(vn)[0];
plt.figure(4)
plt.clf()
vmin = np.min([np.min(v[:,:,i]),np.min(v0[:,:,i]),np.min(vn[:,:,i])])
vmax = np.max([np.max(v[:,:,i]),np.max(v0[:,:,i]),np.max(vn[:,:,i])])
plt.subplot(221); plt.imshow(v0[:,:,i],interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('clean z=%d'%i)
plt.subplot(223); plt.imshow(vn[:,:,i],interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('noisy')
plt.subplot(224); plt.imshow(v[:,:,i],interpolation='Nearest',vmin=vmin,vmax=vmax);
plt.title('cleaned')
def _test5():
t = np.linspace(0,2*np.pi,1000);
x = 2*np.cos(t)*(1-np.cos(t)) + np.random.randn(np.size(t))*0.1;
y = 2*np.sin(t)*(1-np.cos(t)) + np.random.randn(np.size(t))*0.1;
zx = smoothn(x)[0];
zy = smoothn(y)[0];
plt.figure(5)
plt.clf()
plt.title('Cardioid')
plt.plot(x,y,'r.')
plt.plot(zx,zy,'k')
def _test6(noise=0.05,nout=30):
plt.figure(6)
plt.clf()
[x,y] = np.meshgrid(np.linspace(0,1,24),np.linspace(0,1,24))
Vx0 = np.cos(2*np.pi*x+np.pi/2)*np.cos(2*np.pi*y);
Vy0 = np.sin(2*np.pi*x+np.pi/2)*np.sin(2*np.pi*y);
Vx = Vx0 + noise*np.random.randn(24,24); # adding Gaussian noise
Vy = Vy0 + noise*np.random.randn(24,24); # adding Gaussian noise
I = np.random.permutation(range(Vx.size))
Vx = Vx.flatten()
Vx[I[0:nout]] = (np.random.rand(nout)-0.5)*5; # adding outliers
Vx = Vx.reshape(Vy.shape)
Vy = Vy.flatten()
Vy[I[0:nout]] = (np.random.rand(nout)-0.5)*5; # adding outliers
Vy = Vy.reshape(Vx.shape)
Vsx = smoothn(Vx,isrobust=True)[0];
Vsy = smoothn(Vy,isrobust=True)[0];
plt.subplot(131);plt.quiver(x,y,Vx,Vy,2.5)
plt.title('Noisy')
plt.subplot(132); plt.quiver(x,y,Vsx,Vsy)
plt.title('Recovered')
plt.subplot(133); plt.quiver(x,y,Vx0,Vy0)
plt.title('Original')
def _sparseSVD(D):
import scipy.sparse
try:
import sparsesvd
except:
print('bummer ... better get sparsesvd')
exit(0)
Ds = scipy.sparse.csc_matrix(D)
a = sparsesvd.sparsesvd(Ds,Ds.shape[0])
return a
def _sparseTest(n=1000):
I = np.identity(n)
# define a 'traditional' D1 matrix
# which is a right-side difference
# and which is *not* symmetric :-(
D1 = np.matrix(I - np.roll(I,1))
# so define a symemtric version
D1a = D1.T - D1
U, s, Vh = scipy.linalg.svd(D1a)
# now, get eigenvectors for D1a
Ut,eigenvalues,Vt = _sparseSVD(D1a)
Ut = np.matrix(Ut)
# then, an equivalent 2nd O term would be
D2a = D1a**2
# show we can recover D1a
D1a_est = Ut.T * np.diag(eigenvalues) * Ut
# Now, because D2a (& the target D1a) are symmetric:
D1a_est = Ut.T * np.diag(eigenvalues**0.5) * Ut
D = 2*I - (np.roll(I,-1) + np.roll(I,1))
a = _sparseSVD(-D)
eigenvalues = np.matrix(a[1])
Ut = np.matrix(a[0])
Vt = np.matrix(a[2])
orig = (Ut.T * np.diag(np.array(eigenvalues).flatten()) * Vt)
Feigenvalues = np.diag(np.array(np.c_[eigenvalues,0]).flatten())
FUt = np.c_[Ut.T,np.zeros(Ut.shape[1])]
# confirm: FUt * Feigenvalues * FUt.T ~= D
# m is a 1st O difference matrix
# with careful edge conditions
# such that m.T * m = D2
# D2 being a 2nd O difference matrix
m = np.matrix(np.identity(100) - np.roll(np.identity(100),1))
m[-1,-1] = 0
m[0,0] = 1
a = _sparseSVD(m)
eigenvalues = np.matrix(a[1])
Ut = np.matrix(a[0])
Vt = np.matrix(a[2])
orig = (Ut.T * np.diag(np.array(eigenvalues).flatten()) * Vt)
# Vt* Vt.T = I
# Ut.T * Ut = I
# ((Vt.T * (np.diag(np.array(eigenvalues).flatten())**2)) * Vt)
# we see you get the same as m.T * m by squaring the eigenvalues
# '''
if __name__=="__main__":
# from numpy import *
import numpy as np
import pylab as plt
import scipy
_test1()
_test2()
_test3()
_test4()
_test5()
_test6()
| 22,583 | 31.401722 | 151 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Image_Functions/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Image_Functions/recolor.py
|
"""
This module collects together scripts to recolor images for applications such as histogram matching, color transfer etc.
"""
import numpy as np
def image_stats(image):
r""" Computes the mean and standard deivation of each channel in an RGB-like 2D image, (MxNx3)
Parameters
----------
image : (MxNx3) array
input three channel RGB image
Returns
-------
(lMean, lStd, aMean, aStd, bMean, bStd) : 6-tuple
the mean and standard deviation of the 1st, 2nd and 3rd channels respectively
"""
import cv2
# compute the mean and standard deviation of each channel
(l, a, b) = cv2.split(image)
(lMean, lStd) = (np.nanmean(l), np.nanstd(l))
(aMean, aStd) = (np.nanmean(a), np.nanstd(a))
(bMean, bStd) = (np.nanmean(b), np.nanstd(b))
# return the color statistics
return (lMean, lStd, aMean, aStd, bMean, bStd)
def color_transfer_stats(source, target, eps=1e-8):
r""" Fast linear colour transfer between 2D 8-bit images based on mean and standard deviation colour statistics.
Parameters
----------
source : (MxNx3) array
RGB image to resample color from
target : (MxNx3) array
RGB image to recolor
eps : scalar
a small regularization number to ensure numerical stability
Returns
-------
transfer : (MxNx3) array
the 2nd image recolored based on the statistics of the 1st image
"""
# convert the images from the RGB to L*ab* color space, being
# sure to utilizing the floating point data type (note: OpenCV
# expects floats to be 32-bit, so use that instead of 64-bit)
import cv2
if target.max() > 1.0000000001:
# ensure range in [0,1.], converts to float.
source = cv2.cvtColor(source, cv2.COLOR_RGB2LAB).astype("float32")
target = cv2.cvtColor(target, cv2.COLOR_RGB2LAB).astype("float32")
else:
source = cv2.cvtColor(np.uint8(255*source), cv2.COLOR_RGB2LAB).astype("float32")
target = cv2.cvtColor(np.uint8(255*target), cv2.COLOR_RGB2LAB).astype("float32")
# compute color statistics for the source and target images
(lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source)
(lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target)
# subtract the means from the target image
(l, a, b) = cv2.split(target)
l -= lMeanTar
a -= aMeanTar
b -= bMeanTar
# scale by the standard deviations
l = (lStdTar )/ (lStdSrc + eps) * l
a = (aStdTar )/ (aStdSrc + eps) * a
b = (bStdTar )/ (bStdSrc + eps) * b
# add in the source mean
l += lMeanSrc
a += aMeanSrc
b += bMeanSrc
# clip the pixel intensities to [0, 255] if they fall outside
# this range
l = np.clip(l, 0, 255)
a = np.clip(a, 0, 255)
b = np.clip(b, 0, 255)
# merge the channels together and convert back to the RGB color
# space, being sure to utilize the 8-bit unsigned integer data
# type
transfer = cv2.merge([l, a, b])
transfer = cv2.cvtColor(transfer.astype("uint8"), cv2.COLOR_LAB2RGB)
# return the color transferred image
return transfer
def match_color(source_img, target_img, mode='pca', eps=1e-8, source_mask=None, target_mask=None, ret_matrix=False):
r"""Matches the colour distribution of a target image to that of a source image using a linear transform based on matrix decomposition. This effectively matches the mean and convariance of the distributions.
Images are expected to be of form (w,h,c) and can be either float in [0,1] or uint8 [0,255]. Decomposition modes are chol (Cholesky), pca (principal components) or sym for different choices of basis. The effect is slightly different in each case.
Optionally image masks can be used to selectively bias the color transformation.
This method was popularised by the Neural style transfer paper by Gatsys et al. [1]_
Parameters
----------
source_img : (MxNx3) array
RGB image to resample color from
target_img : (MxNx3) array
RGB image to recolor
mode : str
selection of matrix decomposition
'pca' : str
this is principal components or Single value decomposition of the matrix
'chol' : str
this is a Cholesky matrix decomposition
'sym' : str
this is a symmetrizable decomposition
eps : scalar
a small regularization number to ensure numerical stability
source_mask : (MxN) array
binary mask, specifying the select region to obtain source color statistics from
target_mask : (MxN) array
binary mask, specifying the select region to recolor with color from the ``source_img``
ret_matrix : bool
if True, returns the 3x3 matrix capturing the correlation between the colorspace of ``source_img`` and ``target_img``
Returns
-------
matched_img : (MxNx3) array
the 2nd image recolored based on the statistics of the 1st image
mix_matrix : (3x3) array
if ret_matrix==True, the 3x3 matrix capturing the correlation between the colorspace of ``source_img`` and ``target_img`` is returned as a second output
See Also
--------
unwrap3D.Image_Functions.recolor.recolor_w_matrix :
A function to reuse the learnt mixing matrix to recolor further images without relearning.
References
----------
.. [1] Gatys, Leon A., et al. "Controlling perceptual factors in neural style transfer." Proceedings of the IEEE conference on computer vision and pattern recognition. 2017.
"""
if target_img.max() > 1.0000000001:
# ensure range in [0,1.], converts to float.
source_img = source_img/255.
target_img = target_img/255
else:
# ensure range in [0,255.]
source_img = source_img.astype(np.float32);
target_img = target_img.astype(np.float32);
# 1. Compute the eigenvectors of the source color distribution (possibly masked)
if source_mask is not None:
mu_s = np.hstack([np.mean(source_img[:,:,0][source_mask==1]), np.mean(source_img[:,:,1][source_mask==1]), np.mean(source_img[:,:,2][source_mask==1])])
else:
mu_s = np.hstack([np.mean(source_img[:,:,0]), np.mean(source_img[:,:,1]), np.mean(source_img[:,:,2])])
s = source_img - mu_s # demean
s = s.transpose(2,0,1).reshape(3,-1) # convert to (r,g,b), 3 x n_pixels
if source_mask is not None:
s = s[:, source_mask.ravel()==1]
Cs = s.dot(s.T) / s.shape[1] + eps * np.eye(s.shape[0]) # 3x3 covariance matrix.
# 2. Computes the eigenvectors of the target color distribution (possibly masked)
if target_mask is not None:
mu_t = np.hstack([np.mean(target_img[:,:,0][target_mask==1]), np.mean(target_img[:,:,1][target_mask==1]), np.mean(target_img[:,:,2][target_mask==1])])
else:
mu_t = np.hstack([np.mean(target_img[:,:,0]), np.mean(target_img[:,:,1]), np.mean(target_img[:,:,2])])
t = target_img - mu_t
t = t.transpose(2,0,1).reshape(3,-1)
if target_mask is not None:
temp = t.copy()
t = t[:, target_mask.ravel()==1]
Ct = t.dot(t.T) / t.shape[1] + eps * np.eye(t.shape[0]) # 3x3 covariance matrix.
"""
Color match the mean and covariance of the source image.
"""
if mode == 'chol':
chol_t = np.linalg.cholesky(Ct)
chol_s = np.linalg.cholesky(Cs)
mix_matrix = chol_s.dot(np.linalg.inv(chol_t))
ts = mix_matrix.dot(t)
if mode == 'pca':
eva_t, eve_t = np.linalg.eigh(Ct)
Qt = eve_t.dot(np.sqrt(np.diag(eva_t))).dot(eve_t.T)
eva_s, eve_s = np.linalg.eigh(Cs)
Qs = eve_s.dot(np.sqrt(np.diag(eva_s))).dot(eve_s.T)
mix_matrix = Qs.dot(np.linalg.inv(Qt))
ts = mix_matrix.dot(t)
if mode == 'sym':
eva_t, eve_t = np.linalg.eigh(Ct)
Qt = eve_t.dot(np.sqrt(np.diag(eva_t))).dot(eve_t.T)
Qt_Cs_Qt = Qt.dot(Cs).dot(Qt)
eva_QtCsQt, eve_QtCsQt = np.linalg.eigh(Qt_Cs_Qt)
QtCsQt = eve_QtCsQt.dot(np.sqrt(np.diag(eva_QtCsQt))).dot(eve_QtCsQt.T)
mix_matrix = np.linalg.inv(Qt).dot(QtCsQt).dot(np.linalg.inv(Qt))
ts = mix_matrix.dot(t)
# recover the image shape.
if target_mask is not None:
matched_img_flatten = np.zeros_like(temp)
matched_img_flatten[:,target_mask.ravel()==1] = ts.copy()
else:
matched_img_flatten = ts.copy()
matched_img = matched_img_flatten.reshape(*target_img.transpose(2,0,1).shape).transpose(1,2,0)
matched_img += mu_s
if target_mask is not None:
rgb_mask = np.dstack([target_mask, target_mask, target_mask])
matched_img[rgb_mask==0] = target_img[rgb_mask==0]
# clip limits.
matched_img[matched_img>1] = 1
matched_img[matched_img<0] = 0
if ret_matrix:
return matched_img, mix_matrix
else:
return matched_img
def recolor_w_matrix(source_img, target_img, mix_matrix, source_mask=None, target_mask=None):
r""" Matches the colour distribution of a target image to that of a source image using a linear transform based on matrix decomposition. This effectively matches the mean and convariance of the distributions and can be used instead of histogram normalization
Images are expected to be of form (w,h,c) and can be either float in [0,1] or uint8 [0,255]
Modes are chol, pca or sym for different choices of basis. The effect is slightly different in each case.
Optionally image masks can be used to selectively bias the color transformation.
This method was popularised by the Neural style transfer paper by Gatsys et al. [1]_
Parameters
----------
source_img : (MxNx3) array
RGB image to resample color from
target_img : (MxNx3) array
RGB image to recolor
mix_matrix : (3x3) array
the mixing matrix capturing the covariance between the source and target img colorspaces
source_mask : (MxN) array
binary mask, specifying the select region to obtain source color statistics from
target_mask : (MxN) array
binary mask, specifying the select region to recolor with color from the ``source_img``
Returns
-------
matched_img : (MxNx3) array
the 2nd image recolored based on the statistics of the 1st image
See Also
--------
unwrap3D.Image_Functions.recolor.match_color :
A function to learn the mixing matrix given the source and target images
References
----------
.. [1] Gatys, Leon A., et al. "Controlling perceptual factors in neural style transfer." Proceedings of the IEEE conference on computer vision and pattern recognition. 2017.
"""
if target_img.max() > 1.0000000001:
# ensure range in [0,1.], converts to float.
source_img = source_img/255.
target_img = target_img/255
else:
# ensure range in [0,255.]
source_img = source_img.astype(np.float32);
target_img = target_img.astype(np.float32);
# 1. Compute the eigenvectors of the source color distribution (possibly masked)
if source_mask is not None:
mu_s = np.hstack([np.mean(source_img[:,:,0][source_mask==1]), np.mean(source_img[:,:,1][source_mask==1]), np.mean(source_img[:,:,2][source_mask==1])])
else:
mu_s = np.hstack([np.mean(source_img[:,:,0]), np.mean(source_img[:,:,1]), np.mean(source_img[:,:,2])])
s = source_img - mu_s # demean
s = s.transpose(2,0,1).reshape(3,-1) # convert to (r,g,b), 3 x n_pixels
# if source_mask is not None:
# s = s[:, source_mask.ravel()==1]
# Cs = s.dot(s.T) / s.shape[1] + eps * np.eye(s.shape[0]) # 3x3 covariance matrix.
# 2. Computes the eigenvectors of the target color distribution (possibly masked)
if target_mask is not None:
mu_t = np.hstack([np.mean(target_img[:,:,0][target_mask==1]), np.mean(target_img[:,:,1][target_mask==1]), np.mean(target_img[:,:,2][target_mask==1])])
else:
mu_t = np.hstack([np.mean(target_img[:,:,0]), np.mean(target_img[:,:,1]), np.mean(target_img[:,:,2])])
t = target_img - mu_t
t = t.transpose(2,0,1).reshape(3,-1)
temp = t.copy()
# recolor the zero-meaned vector.
ts = mix_matrix.dot(t)
# handles masking operations
# recover the image shape.
if target_mask is not None:
matched_img_flatten = np.zeros_like(temp)
matched_img_flatten[:,target_mask.ravel()==1] = ts.copy()
else:
matched_img_flatten = ts.copy()
matched_img = matched_img_flatten.reshape(*target_img.transpose(2,0,1).shape).transpose(1,2,0)
matched_img += mu_s
if target_mask is not None:
rgb_mask = np.dstack([target_mask, target_mask, target_mask])
matched_img[rgb_mask==0] = target_img[rgb_mask==0]
# clip limits.
matched_img[matched_img>1] = 1
matched_img[matched_img<0] = 0
return matched_img
def calc_rgb_histogram(rgb, bins=256, I_range=(0,255)):
r""" compute the RGB histogram of a 2D image, returning the bins and individual R, G, B histograms as a 3-tuple.
Parameters
----------
rgb : (MxNx3) array
2D RGB image
bins : int
the number of intensity bins
I_range : 2-tuple
the (min, max) intensity range, :math:`\min\le I \le\max` to compute histograms. Intensities outside this range are not counted
Returns
-------
bins_ : (MxNx3) array
the edge intensities of all bins of length ``bins`` + 1
(r_hist,g_hist, b_hist) : 3-tuple
individual 1-D histograms of length ``bins``
"""
r_hist, bins_ = np.histogram(rgb[:,:,0].ravel(), range=I_range, bins=bins)
g_hist, bins_ = np.histogram(rgb[:,:,1].ravel(), range=I_range, bins=bins)
b_hist, bins_ = np.histogram(rgb[:,:,2].ravel(), range=I_range, bins=bins)
return bins_, (r_hist,g_hist, b_hist)
| 14,184 | 37.546196 | 262 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Unzipping/unzip.py
|
import numpy as np
def voxelize_unwrap_params(unwrap_params,
vol_shape,
preupsample=None,
ksize=3,
smooth_sigma=3,
erode_ksize=1):
r""" Voxelizes an unwrapped surface mesh described in (u,v) in (x,y,z) original space for propagation.
Parameters
----------
unwrap_params : (UxVx3) array
the unwrapped 2D lookup table implicitly associating 2D (u,v) to corresponding (x,y,z) coordinates
vol_shape : (3,) array
the shape of the original volume image.
preupsample : scalar
if not none, unwrap_params is resized to preupsample times the current image size. This effectively increases the mesh sampling and is recommended to get a closed volume voxelization.
ksize : int
morphological closing radius of the Ball kernel to close small holes after voxelization
smooth_sigma : scalar
if not None, a Gaussian smooth of the indicated sigma is applied to smooth the voxelized binary, then rebinariesd by thresholding >= 0.5. This process helps to diffuse and close over larger holes than binary closing.
erode_ksize : int
if not None, the voxelized binary is eroded by erode_ksize. This is done when the voxelized binary is larger than the original shape.
Returns
-------
surf_unwrap_vol : (MxNxL) array
voxelized mesh in original Cartesian (x,y,z) space.
"""
import skimage.transform as sktform
import skimage.morphology as skmorph
# from skimage.filters import gaussian
import scipy.ndimage as ndimage
import numpy as np
from scipy.ndimage.morphology import binary_fill_holes
unwrap_params_ = unwrap_params.copy()
surf_unwrap_vol = np.zeros(vol_shape, dtype=np.bool)
if preupsample is not None:
unwrap_params_ = np.dstack([sktform.resize(unwrap_params_[...,ch], output_shape=(np.hstack(unwrap_params.shape[:2])*preupsample).astype(np.int), preserve_range=True) for ch in np.arange(unwrap_params.shape[-1])])
# discretize.
unwrap_params_ = np.round(unwrap_params_).astype(np.int) # 6-connectivity
surf_unwrap_vol[unwrap_params_[...,0],
unwrap_params_[...,1],
unwrap_params_[...,2]] = 1
surf_unwrap_vol = skmorph.binary_closing(surf_unwrap_vol>0, skmorph.ball(ksize));
surf_unwrap_vol = binary_fill_holes(surf_unwrap_vol)
if smooth_sigma is not None:
# surf_unwrap_vol = gaussian(surf_unwrap_vol*1., sigma=smooth_sigma, preserve_range=True)
surf_unwrap_vol = ndimage.gaussian_filter(surf_unwrap_vol*1., sigma=smooth_sigma)
surf_unwrap_vol = surf_unwrap_vol/surf_unwrap_vol.max()
surf_unwrap_vol = surf_unwrap_vol >= 0.5
if erode_ksize is not None:
surf_unwrap_vol = skmorph.binary_erosion(surf_unwrap_vol, skmorph.ball(erode_ksize))
return surf_unwrap_vol
def prop_ref_surface(unwrap_params_ref,
vol_size,
preupsample=3,
vol_binary=None,
ksize=1,
smooth_sigma=None,
d_step=1,
n_dist=None,
surf_pts_ref=None,
pad_dist=5,
smoothgradient=100,
smoothrobust=True,
smooth_method='uniform',
smooth_win=15,
invertorder=False,
squarenorm=False):
r""" Propagate a (u,v) indexed (x,y,z) surface such as that from unwrapping normally into or outwards at a uniform stepsize of ``d_step`` for ``n_dist`` total number of steps. This function is used to create the topography space to map a whole volume given an unwrapping of a single surface.
1. if vol_binary is not provided, a voxelization is first computed
2. based on the vol_binary, the signed distance function and the gradient field for propagation is computed
3. initial points are then integrated along the gradient field iteratively using explicit Euler with new position x_next = x + d_step * gradient
4. smoothing is used after each iteration to regularise the advected points. this is crucial for outward stepping when the interspacing between mesh points are increasing
Parameters
----------
unwrap_params_ref : (UxVx3) array
the unwrapped (u,v) image-indexed (x,y,z) surface to propagate
vol_size : (m,n,l) 3-tuple
the size of the original volume image
preupsample : scalar
if not none, unwrap_params is resized to preupsample times the current image size. This effectively increases the mesh sampling and is recommended to get a closed volume voxelization.
smooth_sigma : scalar
if not None, a Gaussian smooth of the indicated sigma is applied to smooth the voxelized binary, then rebinariesd by thresholding >= 0.5. This process helps to diffuse and close over larger holes than binary closing.
d_step : scalar
the step size in voxels to move in the normal direction. A d_step of negative sign reverses the direction of advection
n_dist : int
if not None, the total number of steps to take in the normal direction.
surf_pts_ref : (N,3) array
if provided, this is a reference surface with which to automatically determine the n_dist when propagating the surface outwards to ensure the full reference shape is sampled in topography space.
pad_dist : int
an additional fudge factor added to the automatically determined n_dist when surf_pts_ref is provided and n_dist is not user provided
smoothgradient : scalar
if given, this is the parameter that controls the amount of smoothing in the `smoothN <https://www.biomecardio.com/matlab/smoothn_doc.html>`_ algorithm
smoothrobust : bool
if True, use the robust smoothing mode of smoothN algorithm
smooth_method : str
specifies the gradient smoothing mode per iteration to regularise the points.
'smoothN' : str
applies a spline-based smoothing of `Garcia <https://www.biomecardio.com/matlab/smoothn_doc.html>`_. This algorithm can be pretty slow. See :func:`unwrap3D.Unzipping.unzip.smooth_unwrap_params_3D_spherical_SmoothN`
'uniform' : str
treats the spacing of mesh points as uniform and applies fast separable 1D Gaussian smoothing along each axis of the 2D parameterization. See :func:`unwrap3D.Unzipping.unzip.smooth_unwrap_params_3D_spherical`
smooth_win : int
the smoothing window to smooth the advected points used in the uniform method.
invertorder : bool
if invertorder, the final concatenated stack of points of (D,U,V,3) where D is the total number of steps is inverted in the first dimension.
squarenorm : bool
if True, propagate using the gradient field, V normalised by magnitude squared i.e. :math:`V/(|V|^2)` instead of the unit magnitude normalization :math:`V/|V|`.
Returns
-------
unwrapped_coord_depth : (DxUxVx3) array
the final unwrapped topography space of (d,u,v) image-indexed (x,y,z) surface which map an entire volume space to topography space.
"""
import numpy as np
from tqdm import tqdm
# import pylab as plt
from ..Segmentation.segmentation import surf_normal_sdf
from ..Image_Functions.image import map_intensity_interp3
if vol_binary is None:
# construct a binary of the input mesh/points. # todo change to the better voxelizer....
vol_binary = voxelize_unwrap_params(unwrap_params_ref,
vol_shape=vol_size,
preupsample=preupsample,
ksize=ksize,
smooth_sigma=smooth_sigma)
# print(np.sum(vol_binary))
# plt.figure()
# plt.imshow(vol_binary[vol_binary.shape[0]//2])
# plt.show()
# get the surface normal gradient outwards.
# binary_vol_grad = vol_gradient(vol_binary, smooth_sigma=smooth_sigma, normalize=True, invert=True, squarenorm=squarenorm) # always outwards. # i see. # we should get the sdf !.
# binary_sdf_vol = sdf_distance_transform(binary, rev_sign=True, method='edt')
binary_vol_grad, binary_vol_sdf = surf_normal_sdf(vol_binary,
smooth_gradient=smooth_sigma,
eps=1e-12,
norm_vectors=False)
binary_vol_grad = -1*binary_vol_grad.transpose(1,2,3,0)
# print(binary_vol_grad.shape)
# print(np.min(binary_vol_sdf), np.max(binary_vol_sdf))
# plt.figure()
# plt.imshow(binary_vol_grad[vol_binary.shape[0]//2,...,0])
# plt.show()
# plt.figure()
# plt.imshow(binary_vol_sdf[vol_binary.shape[0]//2])
# plt.show()
else:
# print(np.sum(vol_binary))
# plt.figure()
# plt.imshow(vol_binary[vol_binary.shape[0]//2])
# plt.show()
# get the surface normal gradient outwards.
# binary_vol_grad = vol_gradient(vol_binary, smooth_sigma=smooth_sigma, normalize=True, invert=True, squarenorm=squarenorm) # always outwards. # i see. # we should get the sdf !.
# binary_sdf_vol = sdf_distance_transform(binary, rev_sign=True, method='edt')
binary_vol_grad, binary_vol_sdf = surf_normal_sdf(vol_binary,
smooth_gradient=smooth_sigma,
eps=1e-12,
norm_vectors=False)
binary_vol_grad = -1*binary_vol_grad.transpose(1,2,3,0)
# print(binary_vol_grad.shape)
# print(np.min(binary_vol_sdf), np.max(binary_vol_sdf))
# plt.figure()
# plt.imshow(binary_vol_grad[vol_binary.shape[0]//2,...,0])
# plt.show()
# plt.figure()
# plt.imshow(binary_vol_sdf[vol_binary.shape[0]//2])
# plt.show()
# infer the number of dists to step for from the reference if not prespecified.
if n_dist is None :
unwrap_params_ref_flat = unwrap_params_ref.reshape(-1, unwrap_params_ref.shape[-1])
# infer the maximum step size so as to cover the initial otsu surface.
mean_pt = np.nanmean(unwrap_params_ref_flat, axis=0)
# # more robust to do an ellipse fit. ? => doesn't seem so... seems best to take the extremal point -> since we should have a self-similar shape.
# unwrap_params_fit_major_len = np.max(np.linalg.eigvalsh(np.cov((unwrap_params_ref_flat-mean_pt[None,:]).T))); unwrap_params_fit_major_len=np.sqrt(unwrap_params_fit_major_len)
# surf_ref_major_len = np.max(np.linalg.eigvalsh(np.cov((surf_pts_ref-mean_pt[None,:]).T))); surf_ref_major_len = np.sqrt(surf_ref_major_len)
mean_dist_unwrap_params_ref = np.linalg.norm(unwrap_params_ref_flat-mean_pt[None,:], axis=-1).max()
mean_surf_pts_ref = np.linalg.norm(surf_pts_ref-mean_pt[None,:], axis=-1).max() # strictly should do an ellipse fit...
n_dist = np.int(np.ceil(mean_surf_pts_ref-mean_dist_unwrap_params_ref))
n_dist = n_dist + pad_dist # this is in pixels
n_dist = np.int(np.ceil(n_dist / float(d_step))) # so if we take 1./2 step then we should step 2*
# print(n_dist)
# print('----')
unwrapped_coord_depth = [unwrap_params_ref] # initialise with the reference surface.
for d_ii in tqdm(np.arange(n_dist)):
pts_next = unwrapped_coord_depth[-1].copy(); pts_next = pts_next.reshape(-1,pts_next.shape[-1]) # pull the last and flatten.
# get the gradient at the next point.
grad_next_x = map_intensity_interp3(pts_next,
grid_shape=binary_vol_grad.shape[:-1], I_ref=binary_vol_grad[...,0], method='linear', cast_uint8=False)
grad_next_y = map_intensity_interp3(pts_next,
grid_shape=binary_vol_grad.shape[:-1], I_ref=binary_vol_grad[...,1], method='linear', cast_uint8=False)
grad_next_z = map_intensity_interp3(pts_next,
grid_shape=binary_vol_grad.shape[:-1], I_ref=binary_vol_grad[...,2], method='linear', cast_uint8=False)
grad_next = (np.vstack([grad_next_x, grad_next_y, grad_next_z]).T).reshape(unwrapped_coord_depth[-1].shape)
# smooth the gradients.
if smooth_method is not None:
if smooth_method == 'smoothN':
grad_next = smooth_unwrap_params_3D_spherical_SmoothN(grad_next,
S=smoothgradient,
isrobust=smoothrobust,
pad_size=None) # what is none?
if smooth_method == 'uniform':
grad_next = smooth_unwrap_params_3D_spherical(grad_next,
sigma_window=smooth_win,
filter_func=None,
filter1d=True,
filter2d=False,
filterALS=False,
ALS_lam=None,
ALS_p=None,
ALS_iter=None)
# if pad_size is None:
# # # pad the mesh.....
# # grad_next = np.hstack([grad_next, grad_next, grad_next])
# # grad_next = np.vstack([grad_next[1:][::-1,::-1],
# # grad_next,
# # grad_next[:-1][::-1,::-1]])
# # # else:
# grad_next = smooth_unwrap_params_3D_spherical(grad_next,
# sigma_window=35,
# isrobust=smoothrobust,
# pad_size=None)
# # unwrap_xyz, sigma_window=15, filter_func=None,
# # filter1d=True, filter2d=False,
# # filterALS=True,
# # ALS_lam=None,
# # ALS_p=None,
# # ALS_iter=None
# # renormalize.
if squarenorm:
grad_next = grad_next / (np.linalg.norm(grad_next, axis=-1)[...,None]**2 + 1e-12) # renormalize! or we do square of the norm ?
else:
grad_next = grad_next / (np.linalg.norm(grad_next, axis=-1)[...,None] + 1e-12) # renormalize! or we do square of the norm ?
else:
# renormalize.
if squarenorm:
grad_next = grad_next / (np.linalg.norm(grad_next, axis=-1)[...,None]**2 + 1e-12) # renormalize! or we do square of the norm ?
else:
grad_next = grad_next / (np.linalg.norm(grad_next, axis=-1)[...,None] + 1e-12) # renormalize! or we do square of the norm ?
# get the next point and clip.
pts_next_ = unwrapped_coord_depth[-1] + d_step * grad_next
# clip the pts to the range of the image.
pts_next_[...,0] = np.clip(pts_next_[...,0], 0, vol_binary.shape[0]-1)
pts_next_[...,1] = np.clip(pts_next_[...,1], 0, vol_binary.shape[1]-1)
pts_next_[...,2] = np.clip(pts_next_[...,2], 0, vol_binary.shape[2]-1)
unwrapped_coord_depth.append(pts_next_)
unwrapped_coord_depth = np.array(unwrapped_coord_depth)
if invertorder:
unwrapped_coord_depth = unwrapped_coord_depth[::-1]
return unwrapped_coord_depth
# function to fix the bounds by reinterpolation based on griddata.
def fix_unwrap_params_boundaries_spherical(unwrap_xyz, pad=10, rescale=False):
r""" Given a UV unwrapping of a closed spherical-like surface, this function enforces that the first and last rows map to single coordinate representing the North and South poles and conducts scattered interpolation to impute missing values.
Parameters
----------
unwrap_xyz : (UxVx3) array
the unwrapped (u,v) image-indexed (x,y,z) surface to propagate
pad : int
the internal padding of unwrap_xyz to allow interpolation of missed edge coordinates and to have better continuity in internal regions.
rescale : bool
if True, rescales points to unit cube before performing interpolation. This is useful if some of the input dimensions have incommensurable units and differ by many orders of magnitude. see `griddata <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html>`_
Returns
-------
unwrap_xyz_fix : (UxVx3) array
the fixed unwrapped (u,v) image-indexed (x,y,z) of the same size as the input
"""
from scipy.interpolate import griddata
import numpy as np
# assuming a spherical geometry.
unwrap_xyz_fix = unwrap_xyz.copy()
# use this to define the bound
min_x = np.nanmin(unwrap_xyz_fix[...,0])
max_x = np.nanmax(unwrap_xyz_fix[...,0])
min_y = np.nanmin(unwrap_xyz_fix[...,1])
max_y = np.nanmax(unwrap_xyz_fix[...,1])
min_z = np.nanmin(unwrap_xyz_fix[...,2])
max_z = np.nanmax(unwrap_xyz_fix[...,2])
# first and last row map to singular points.
unwrap_xyz_fix[0,:] = np.nanmean(unwrap_xyz[0,:], axis=0)
unwrap_xyz_fix[-1,:] = np.nanmean(unwrap_xyz[-1,:], axis=0)
# wrap around to get a convex hull.
unwrap_xyz_fix = np.hstack([unwrap_xyz_fix[:,-pad:], unwrap_xyz_fix, unwrap_xyz_fix[:,:pad]])
valid_mask = np.logical_not(np.max(np.isnan(unwrap_xyz_fix), axis=-1))
# now create a griddata.
rows, cols = np.indices((unwrap_xyz_fix[:,:,0]).shape)
rows_ = rows[valid_mask]
cols_ = cols[valid_mask]
interp_x = griddata(np.hstack([cols_[:,None], rows_[:,None]]), unwrap_xyz_fix[valid_mask,0],(cols, rows), method='linear', fill_value=np.nan, rescale=rescale)
interp_y = griddata(np.hstack([cols_[:,None], rows_[:,None]]), unwrap_xyz_fix[valid_mask,1],(cols, rows), method='linear', fill_value=np.nan, rescale=rescale)
interp_z = griddata(np.hstack([cols_[:,None], rows_[:,None]]), unwrap_xyz_fix[valid_mask,2],(cols, rows), method='linear', fill_value=np.nan, rescale=rescale)
unwrap_xyz_fix = np.dstack([interp_x,
interp_y,
interp_z])
unwrap_xyz_fix = unwrap_xyz_fix[:,pad:-pad]
unwrap_xyz_fix[unwrap_xyz_fix[...,0]<min_x-1,0] = min_x
unwrap_xyz_fix[unwrap_xyz_fix[...,0]>max_x+1,0] = max_x
unwrap_xyz_fix[unwrap_xyz_fix[...,1]<min_y-1,1] = min_y
unwrap_xyz_fix[unwrap_xyz_fix[...,1]>max_y+1,1] = max_y
unwrap_xyz_fix[unwrap_xyz_fix[...,2]<min_z-1,2] = min_z
unwrap_xyz_fix[unwrap_xyz_fix[...,2]<min_z-1,2] = max_z
return unwrap_xyz_fix
def pad_unwrap_params_3D_spherical(unwrap_xyz, pad=10):
r""" Function to pad a single or multichannel 2D image in a spherical manner topologically such that the left/right sides are periodic extensions. The top is extended with a 180 degree flip, and the bottom is also extended with a 180 degree flip
Parameters
----------
unwrap_xyz :
an input (MxN) or (MxNxd) image to pad
pad : int
The uniform padding in the width and height
Returns
-------
unwrap_xyz_pad :
The padded image of dimensionality (M+2*pad x N+2*pad) or (M+2*pad x N+2*pad x d)
"""
import numpy as np
unwrap_xyz_pad = unwrap_xyz.copy()
# periodic in x
unwrap_xyz_pad = np.hstack([unwrap_xyz[:,-pad:],
unwrap_xyz,
unwrap_xyz[:,:pad]])
# flip and pad in x # but don't take the first and last!!!! else we have a discontinuity....
unwrap_xyz_pad = np.vstack([unwrap_xyz_pad[1:pad+1][:,::-1][::-1],
unwrap_xyz_pad,
unwrap_xyz_pad[-pad-1:-1][:,::-1][::-1]])
return unwrap_xyz_pad
def pad_unwrap_params_3D_spherical_depth(unwrap_depth_vals, pad=10, pad_depth=False, pad_depth_mode='edge'):
r""" Function to pad a topographic space coordinate set in a spherical manner topologically such that the left/right sides are periodic extensions. The top is extended with a 180 degree flip, and the bottom is also extended with a 180 degree flip
Optionally one can extend the depth (first channel) with the specified edge pad mode.
Parameters
----------
unwrap_depth_vals : array
an input (DxMxNxd) image to pad
pad : int
The uniform padding in the width and height i.e. M, N axis
pad_depth : bool
If True, pad the depth dimension (D) also by ``pad``
pad_depth_mode : str
if pad_depth is True, this specifies the handling of the padding. It should be one of the options in numpy.pad
Returns
-------
unwrap_depth_vals_pad :
The padded image of dimensionality (D x M+2*pad x N+2*pad x d) for pad_depth=False or (D+2*pad x M+2*pad x N+2*pad x d) for pad_depth=True
"""
# depth x m x n x ndim.
import numpy as np
# first pad in the horizontal then vertical ...
# pad horizontal.
unwrap_depth_vals_pad = np.concatenate([unwrap_depth_vals[:,:,-pad:],
unwrap_depth_vals,
unwrap_depth_vals[:,:,:pad]], axis=2)
# pad vertical.
unwrap_depth_vals_pad = np.concatenate([unwrap_depth_vals_pad[:,1:pad+1][:,::-1,::-1],
unwrap_depth_vals_pad,
unwrap_depth_vals_pad[:,-pad-1:-1][:,::-1,::-1]], axis=1)
if pad_depth:
# we must also pad in depth!.
unwrap_depth_vals_pad = np.pad(unwrap_depth_vals_pad, [[pad, pad], [0,0], [0,0], [0,0]], mode=pad_depth_mode)
return unwrap_depth_vals_pad
def compute_unwrap_params_normal_curvature(unwrap_depth_binary,
pad=10,
compute_curvature=True,
smooth_gradient=3,
smooth_curvature=3,
mask_gradient=False,
eps=1e-12):
r""" Function to pad a topographic space coordinate set in a spherical manner topologically such that the left/right sides are periodic extensions. The top is extended with a 180 degree flip, and the bottom is also extended with a 180 degree flip
Optionally one can extend the depth (first channel) with the specified edge pad mode.
Parameters
----------
unwrap_depth_vals : array
an input (DxMxNxd) image to pad
pad : int
The uniform padding in the width and height i.e. M, N axis
pad_depth : bool
If True, pad the depth dimension (D) also by ``pad``
pad_depth_mode : str
if pad_depth is True, this specifies the handling of the padding. It should be one of the options in numpy.pad
Returns
-------
unwrap_depth_vals_pad :
The padded image of dimensionality (D x M+2*pad x N+2*pad x d) for pad_depth=False or (D+2*pad x M+2*pad x N+2*pad x d) for pad_depth=True
"""
from ..Segmentation import segmentation as segmentation
if pad > 0:
unwrap_depth_binary_pad = pad_unwrap_params_3D_spherical_depth(unwrap_depth_binary[...,None],
pad=pad, pad_depth=True, pad_depth_mode='edge')
unwrap_depth_binary_pad = unwrap_depth_binary_pad[...,0]
else:
unwrap_depth_binary_pad = unwrap_depth_binary.copy()
if compute_curvature:
H_normal, sdf_vol_normal, sdf_vol = segmentation.mean_curvature_binary(unwrap_depth_binary_pad,
smooth=smooth_curvature,
mask=mask_gradient,
smooth_gradient=smooth_gradient,
eps=eps)
return unwrap_depth_binary_pad, H_normal, sdf_vol_normal, sdf_vol
else:
sdf_vol_normal, sdf_vol = segmentation.surf_normal_sdf(unwrap_depth_binary_pad,
return_sdf=True,
smooth_gradient=smooth_gradient,
eps=eps)
return unwrap_depth_binary_pad, sdf_vol_normal, sdf_vol
### add in the weighted filtering variant taking into account local mapping errors.
def smooth_unwrap_params_3D_spherical(unwrap_xyz,
sigma_window=15,
filter_func=None,
filter1d=True,
filter2d=False,
filterALS=True,
ALS_lam=None,
ALS_p=None,
ALS_iter=None):
r""" Applies image based smoothing techniques to smooth a (u,v) image parameterized (x,y,z) surface
Options include
- uniform 1d smoothing along x- and y- separately (filter1d=True)
- Gaussian 2D smoothing (filter2d=True)
- spline based smoothing (filterALS=True)
Only one of filter1d, filter2d and filterALS should be True
Parameters
----------
unwrap_xyz : array
an input (MxNxd) image to smooth
sigma_window : int
smoothing window in pixels
filter_func : array
specifies the ``weight`` in scipy.ndimage.filters.convolve1d for ``filter1d=True``. If filter_func=None, defaults to the uniform filter equivalent to taking the mean over the window ``2*sigma_window+1``
filter1d : bool
if True use scipy.ndimage.filters.convolve1d with the given weights, filter_func to filter the unwrapping coordinates.
filter2d : bool
if True, apply skimage.filters.gaussian with sigma=sigma_window
filterALS : bool
if True, asymmetric least squares is applied along independent x- and y- directions for smoothing with parameters given by ``ALS_lam, ALS_p and ALS_iter``. See :func:`unwrap3D.Analysis_Functions.timeseries.baseline_als`
ALS_lam : scalar
Controls the degree of smoothness in the baseline. The higher the smoother.
ALS_p : scalar
Controls the degree of smoothness in the baseline. The smaller the more asymmetric, the more the fitting biases towards the minimum value.
ALS_iter : int
The number of iterations to run the algorithm. Only a few iterations is required generally. This can generally be fixed.
Returns
-------
unwrap_xyz_filt :
the smoothed output (MxNxd) image
"""
from scipy.ndimage.filters import convolve1d
from skimage.filters import gaussian
def baseline_als(y, lam, p, niter=10):
from scipy import sparse
from scipy.sparse.linalg import spsolve
L = len(y)
D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in range(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
if filter_func is None:
# assume uniform
filter_func = np.ones(2*sigma_window+1);
filter_func = filter_func/float(np.sum(filter_func)) # normalize
unwrap_xyz_pad = pad_unwrap_params_3D_spherical(unwrap_xyz, pad=3*sigma_window) # we need to pad this more... to prevent edge effects...
if filter1d:
unwrap_xyz_x = convolve1d(unwrap_xyz_pad, weights=filter_func, axis=0)
unwrap_xyz_filt = convolve1d(unwrap_xyz_x, weights=filter_func, axis=1)
if filterALS:
# this idea works without fundamentally changing things -> so we should be able to run proxTV ....
# then we are going to filter.... if we set this too high ... we get moving average filter ( as the support of it is too high! )
unwrap_xyz_x = np.array([ np.array([baseline_als(unwrap_xyz_pad[ii,:,ch], lam=ALS_lam, p=ALS_p, niter=ALS_iter) for ii in range(len(unwrap_xyz_pad))]) for ch in range(unwrap_xyz_pad.shape[-1])]) # rows.
unwrap_xyz_x = unwrap_xyz_x.transpose(1,2,0)
unwrap_xyz_filt = np.array([ np.array([baseline_als(unwrap_xyz_x[:,ii,ch], lam=ALS_lam, p=ALS_p, niter=ALS_iter) for ii in range(unwrap_xyz_pad.shape[1])]) for ch in range(unwrap_xyz_pad.shape[-1])])
unwrap_xyz_filt = unwrap_xyz_filt.transpose(2,1,0)
if filter2d:
unwrap_xyz_filt = np.array([gaussian(unwrap_xyz_pad[...,ch], sigma=sigma_window, preserve_range=True) for ch in np.arange(unwrap_xyz_pad.shape[-1])])
unwrap_xyz_filt = unwrap_xyz_filt.transpose(1,2,0)
unwrap_xyz_filt = unwrap_xyz_filt[3*sigma_window:-3*sigma_window].copy() # because of extra padding.
unwrap_xyz_filt = unwrap_xyz_filt[:,3*sigma_window:-3*sigma_window].copy()
return unwrap_xyz_filt
def smooth_unwrap_params_3D_spherical_SmoothN(unwrap_xyz,
S=100,
isrobust=True,
pad_size=None):
r""" Applies the Whittaker smoother, smoothN of David Garcia to smooth a (u,v) image parameterized (x,y,z) surface. This is effectively a spline based smoothing
Parameters
----------
unwrap_xyz : (UxVx3) array
the input image to smooth
S : scalar
controls the extent of smoothing, the higher the more smoothing.
isrobust : bool
if True, runs the filtering in robust mode
pad_size : int
if specified, pads the image by the given size else pads the image by replicating itself.
Returns
-------
mesh_smooth : (UxVx3) array
the smoothed output image
"""
from ..Image_Functions.smoothn import smoothn
if pad_size is None:
# pad the mesh.....
unwrap_xyz_pad = np.hstack([unwrap_xyz, unwrap_xyz, unwrap_xyz]) # this pad is correct.
unwrap_xyz_pad = np.vstack([unwrap_xyz_pad[1:][::-1,::-1],
unwrap_xyz_pad,
unwrap_xyz_pad[:-1][::-1,::-1]])
else:
unwrap_xyz_pad = pad_unwrap_params_3D_spherical(unwrap_xyz, pad=pad_size)
# mesh_smooth_x,s,exitflag,Wtot = smoothn(unwrap_xyz_pad[...,0], s=S, isrobust=isrobust)
# mesh_smooth_y,s,exitflag,Wtot = smoothn(unwrap_xyz_pad[...,1], s=S, isrobust=isrobust)
# mesh_smooth_z,s,exitflag,Wtot = smoothn(unwrap_xyz_pad[...,2], s=S, isrobust=isrobust)
mesh_smooth,s,exitflag,Wtot = smoothn(unwrap_xyz_pad, s=S, isrobust=isrobust)
# mesh_smooth = np.dstack([mesh_smooth_x,
# mesh_smooth_y,
# mesh_smooth_z])
if pad_size is None:
mesh_smooth = mesh_smooth[len(unwrap_xyz)-1:-len(unwrap_xyz)+1]
mesh_smooth = mesh_smooth[:,unwrap_xyz.shape[1]:-unwrap_xyz.shape[1]]
else:
mesh_smooth = mesh_smooth[pad_size:-pad_size].copy()
mesh_smooth = mesh_smooth[:,pad_size:-pad_size].copy()
return mesh_smooth
def impute_2D_spherical(img, method='linear', pad_size=None, blank_pixels=None):
r""" Imputes an image with spherical boundary conditions using interpolation
Parameters
----------
img : (UxV) array
the input image to impute with missing pixels indicated by np.isnan (by default)
method : str
interpolation method, one of the possible option specified in scipy.interpolate.griddata. Linear interpolation is used by default
pad_size : int
if specified, pads the image by the given size else pads the image by replicating itself fully
blank : scalar
if specified, the alternative pixel intensity used to label the pixels to be imputed. By default we use np.isnan
Returns
-------
fill_interp : (UxV) array
the imputed image
"""
import scipy.interpolate as scinterpolate
import numpy as np
# prepad.
if pad_size is None:
# pad the mesh.....
img_pad = np.hstack([img, img, img]) # this pad is correct.
img_pad = np.vstack([img_pad[1:][::-1,::-1],
img_pad,
img_pad[:-1][::-1,::-1]])
else:
img_pad = pad_unwrap_params_3D_spherical(img, pad=pad_size)
YY, XX = np.indices(img_pad.shape)
if blank_pixels is None:
valid_mask = np.logical_not(np.isnan(img_pad))
else:
valid_mask = np.logical_not(img_pad==blank_pixels)
YYXX = np.vstack([YY[valid_mask],
XX[valid_mask]]).T
fill_interp = scinterpolate.griddata(YYXX,
img_pad[valid_mask],
(YY, XX), method=method, fill_value=np.nan)
if pad_size is None:
M, N = img.shape[:2]
fill_interp = fill_interp[M:-M].copy() # crop out the row
fill_interp = fill_interp[:,N:-N].copy() # crop out the col
else:
fill_interp = fill_interp[pad_size:-pad_size].copy()
fill_interp = fill_interp[:,pad_size:-pad_size].copy()
return fill_interp
def find_principal_axes_uv_surface(uv_coords, pts_weights, map_to_sphere=True, sort='ascending', return_pts=False):
""" Find the principal axes of a uv parametrized surface with given pixel weights.
Parameters
----------
uv_coords : (UxVx3) array
the input image specifying the uv unwrapped (x,y,z) surface to find the principal axis of in original Cartesian (x,y,z) space
pts_weights : (UxV) array
the positive weights at each pixel, specifying its relative importance in the computation of the principal axes
map_to_sphere : bool
if True, the unit sphere coordinate i.e. spherical parametrization of the uv grid is used instead of the actual (x,y,z) coordinate positions to compute principal axes. This enables geometry-independent computation useful for e.g. getting directional alignment based only on surface intensity
sort : 'ascending' or 'descending'
the sorting order of the eigenvectors in terms of the absolute value of the respective eigenvalues
return_pts : bool
if True, return the demeaned points used to compute the principal axes
Returns
-------
w : (3,) array
the sorted eigenvalues of the three principal eigenvectors
v : (3,3) array
the sorted eigenvectors of the corresponding eigenvalues
pts_demean : (UxVx3) array
the demeaned points used for doing the principal components analysis
See Also
--------
:func:`unwrap3D.Mesh.meshtools.find_principal_axes_surface_heterogeneity` :
Equivalent for finding the principal eigenvectors when give a surface mesh of unordered points.
"""
import numpy as np
from ..Geometry import geometry as geometry
pts = uv_coords.reshape(-1, uv_coords.shape[-1])
pts_weights = pts_weights.ravel()
if map_to_sphere:
# we replace the pts with that of the unit sphere (x,y,z)
m, n = uv_coords.shape[:2]
psi_theta_grid_ref = geometry.img_2_angles(m,n)
pts_demean = geometry.sphere_from_img_angles(psi_theta_grid_ref.reshape(-1,psi_theta_grid_ref.shape[-1]))
else:
# demean
pts_mean = np.mean(pts, axis=0)
pts_demean = pts - pts_mean[None,:]
# unweighted version.
pts_demean_ = pts_demean * pts_weights[:,None] / float(np.sum(pts_weights))
pts_cov = np.cov(pts_demean_.T) # 3x3 matrix #-> expect symmetric.
w, v = np.linalg.eigh(pts_cov)
# sort large to small.
if sort=='descending':
w_sort = np.argsort(np.abs(w))[::-1]
if sort=='ascending':
w_sort = np.argsort(np.abs(w))
w = w[w_sort]
v = v[:,w_sort]
if return_pts:
pts_demean = pts_demean.reshape(uv_coords.shape)
return w, v, pts_demean
else:
return w, v
##### unwrap_params_rotate, integrating the beltrami coefficient optimization.
def unwrap_params_rotate_coords(unwrap_params,
rot_matrix,
invert_transform=True,
method='spline',
cast_uint8=False,
optimize=False,
h_range=[0.1,5],
eps=1e-12):
r""" Given a (u,v) parametrization of an (x,y,z) surface. This function derives the corresponding (u,v) parametrization for an arbitrary rotation of the (x,y,z) surface by rotating the spherical parametrization and interpolating without needing to completely do a new spherical parametrization.
Parameters
----------
unwrap_params : (UxVx3) array
the input image specifying the uv unwrapped (x,y,z) surface
rot_matrix : (4x4) array
the specified rotation given as a 4x4 homogeneous rotation matrix
invert_transform : bool
if True, the rotation matrix is applied inverted to get the corresponding coordinates forming the new (u,v) parametrization. This should be set to true if the rotation_matrix is the forward transformation that rotates the current surface to the new surface.
method : str
the interpolation method. Either of 'spline' to use scipy.interpolate.RectBivariateSpline or one of those available for scipy.interpolate.RegularGridInterpolator
optimize : bool
if True, the aspect ratio of the image will be optimized to minimize metric distortion based on the Beltrami coefficient, see :func:`unwrap3D.Unzipping.unzip.beltrami_coeff_uv_opt`
h_range : 2-tuple
a list of aspect ratios to search for the optimal aspect ratio when optimize=True
eps : scalar
a small number for numerical stability
Returns
-------
xy_rot : (M,N,2)
the (u,v) coordinates of the input unwrap_params that form the new (u,v) of the rotated surface. The size (M,N) will be the same as input if optimize=False.
unwrap_params_new : (M,N,3)
the new uv unwrapped (x,y,z) surface coordinates denoting the rotated surface.
h_opt : scalar
the optimal aspect ratio found within the given ``h_range`` which minimizes the Beltrami coefficient, if ``optimize=True``. The new size is (U, int(h_opt*U), 3)
"""
import numpy as np
from ..Geometry import geometry as geometry
from ..Image_Functions.image import map_intensity_interp2
# from LightSheet_Analysis.Geometry import meshtools
# from LightSheet_Analysis.Geometry.geometry import compute_surface_distance_ref
"""
1. define the uv grid of the reference sphere.
"""
m, n = unwrap_params.shape[:2]
psi_theta_grid_ref = geometry.img_2_angles(m,n)
"""
2. define the reference xyz of the unit sphere for pullback.
"""
sphere_xyz = geometry.sphere_from_img_angles(psi_theta_grid_ref.reshape(-1,psi_theta_grid_ref.shape[-1]))
sphere_xyz_grid = sphere_xyz.reshape((m,n,-1))
"""
3. apply the inverse intended rotation matrix to the reference sphere.
# rot_matrix is 4x4, so is just the inverse
"""
if invert_transform==True:
T_matrix = np.linalg.inv(rot_matrix)
else:
T_matrix = rot_matrix.copy()
sphere_xyz_grid_rot = T_matrix.dot(np.vstack([sphere_xyz_grid.reshape(-1,sphere_xyz_grid.shape[-1]).T,
np.ones(len(sphere_xyz_grid.reshape(-1,sphere_xyz_grid.shape[-1])))]))[:sphere_xyz_grid.shape[-1]]
sphere_xyz_grid_rot = sphere_xyz_grid_rot.T
sphere_xyz_grid_rot = sphere_xyz_grid_rot.reshape(sphere_xyz_grid.shape) # this gives new (x,y,z) coordinates relating to the reference.
# pull down now the transformed angles
psi_theta_grid_ref_rot = geometry.img_angles_from_sphere(sphere_xyz_grid_rot.reshape(-1,sphere_xyz_grid_rot.shape[-1]))
psi_theta_grid_ref_rot = psi_theta_grid_ref_rot.reshape((m, n, psi_theta_grid_ref.shape[-1]))
# instead what we wdo is following https://github.com/henryseg/spherical_image_editing/blob/master/sphere_transforms_numpy.py
# we turn the angles into x,y coordinates! then use normal rectangular interpolation !.
xy_rot = geometry.angles_2_img(psi_theta_grid_ref_rot, (m,n)) # this is the new grid.
"""
4. we now do the reinterpolation of scalars.
"""
# s is only used in the case of smoothing for spline based.
unwrap_params_new = np.array([map_intensity_interp2(xy_rot[...,::-1].reshape(-1, xy_rot.shape[-1]), grid_shape=(m,n), I_ref=unwrap_params[...,ch], method=method, cast_uint8=cast_uint8, s=0).reshape((m,n)) for ch in np.arange(unwrap_params.shape[-1])])
unwrap_params_new = unwrap_params_new.transpose([1,2,0])
"""
5. we should add in the beltrami coefficient optimization for the new view.
"""
if optimize:
h_opt, unwrap_params_new = beltrami_coeff_uv_opt(unwrap_params_new, h_range=h_range, eps=eps, apply_opt=True) # optimize and return this.
return xy_rot, unwrap_params_new, h_opt
else:
return xy_rot, unwrap_params_new
def beltrami_coeff_uv_opt(surface_uv_params, h_range=[0.1,5], eps=1e-12, apply_opt=True):
r""" Find the optimal image aspect ratio to minimise the Beltrami coefficient which is a measure of metric distortion for a (u,v) parametrized (x,y,z) surface
See https://en.wikipedia.org/wiki/Beltrami_equation
Parameters
----------
surface_uv_params : (UxVx3) array
the input image specifying the uv unwrapped (x,y,z) surface
h_range : 2-tuple
specifies the [min, max] scaling factor of image width relative to height to search for the minimal Beltrami Coefficient
eps : scalar
small number for numerical stability
apply_opt : bool
if True, additionally return the resized surface as a second output
Returns
-------
h_opt : scalar
the optimal scaling factor within the specified h_range
surface_uv_params_resize_opt : (U x W x 3)
if apply_opt=True, the found aspect ratio is applied to the input image where the new width W is int(h_opt)*V.
"""
from scipy.optimize import fminbound
import skimage.transform as sktform
import numpy as np
m, n = surface_uv_params.shape[:2]
def opt_score(h):
# surface_unwrap_params_rot_resize = np.array([sktform.resize(surface_unwrap_params_rot[...,ch], (int(h*n),n), preserve_range=True) for ch in range(surface_unwrap_params_rot.shape[-1])])
surface_uv_params_resize = np.array([sktform.resize(surface_uv_params[...,ch], (m, int(h*m)), preserve_range=True) for ch in range(surface_uv_params.shape[-1])])
surface_uv_params_resize = surface_uv_params_resize.transpose(1,2,0)
beltrami_coeff = beltrami_coeff_uv(surface_uv_params_resize, eps=eps)
score = np.nanmean(np.abs(beltrami_coeff)**2) # using mean works.
return score
h_opt = fminbound(opt_score, h_range[0], h_range[1]);
if apply_opt:
surface_uv_params_resize_opt = np.array([sktform.resize(surface_uv_params[...,ch], (m, int(h_opt*m)), preserve_range=True) for ch in range(surface_uv_params.shape[-1])])
surface_uv_params_resize_opt = surface_uv_params_resize_opt.transpose(1,2,0)
return h_opt, surface_uv_params_resize_opt
else:
return h_opt
def beltrami_coeff_uv(surface_uv_params, eps=1e-12):
r""" Computes the Beltrami coefficient, a measure of uniform metric distortion given a (u,v) parametrized (x,y,z) surface
See https://en.wikipedia.org/wiki/Beltrami_equation for mathematical definition
Parameters
----------
surface_uv_params : (U,V,3) array
the input image specifying the uv unwrapped (x,y,z) surface
eps : scalar
small number for numerical stability
Returns
-------
mu : (U,V) array
Complex array giving the Beltrami coefficient at each (u,v) pixel position
"""
# https://en.wikipedia.org/wiki/Beltrami_equation, return np.sum(np.abs(beltrami_coefficient(np.hstack([square_x[:,None],h*square_y[:,None]]),f,v))**2)
from skimage.transform import resize
import numpy as np
# compute according to wikipedia....
dS_du = np.gradient(surface_uv_params, axis=0);
dXdu = dS_du[...,0].copy()
dYdu = dS_du[...,1].copy()
dZdu = dS_du[...,2].copy()
dS_dv = np.gradient(surface_uv_params, axis=1);
dXdv = dS_dv[...,0].copy()
dYdv = dS_dv[...,1].copy()
dZdv = dS_dv[...,2].copy()
E = dXdu**2 + dYdu**2 + dZdu**2;
G = dXdv**2 + dYdv**2 + dZdv**2;
F = dXdu*dXdv + dYdu*dYdv + dZdu*dZdv;
mu = (E - G + 2 * 1j * F) / ((E + G + 2.*np.sqrt(E*G - F**2))+eps);
return mu
def gradient_uv(surface_uv_params, eps=1e-12, pad=False):
r""" Compute the Jacobian of the uv parametrized (x,y,z) surface i.e. :math:`\partial S/\partial u` and `\partial S/\partial v`
Parameters
----------
surface_uv_params : (UxVx3) array
the input image giving the uv unwrapped (x,y,z) surface
eps : scalar
small numerical value for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
Returns
-------
dS_du : (UxVx3) array
:math:`\partial S/\partial u`, the change in the (x,y,z) surface coordinates in the direction of image u- axis (horizontal)
dS_dv : (UxVx3) array
:math:`\partial S/\partial v`, the change in the (x,y,z) surface coordinates in the direction of image v- axis (vertical)
"""
# if pad then wrap, else use the gradient.
if pad:
surface_uv_params_ = np.hstack([surface_uv_params,
surface_uv_params[:,1][:,None]])
surface_uv_params_ = np.vstack([surface_uv_params_,
surface_uv_params_[-2][None,::-1]])
dS_du = surface_uv_params_[:-1,1:] - surface_uv_params_[:-1,:-1]
dS_dv = surface_uv_params_[1:,:-1] - surface_uv_params_[:-1,:-1]
else:
dS_du = np.gradient(surface_uv_params, axis=1);
dS_dv = np.gradient(surface_uv_params, axis=0);
return dS_du, dS_dv
def gradient_uv_depth(depth_uv_params, eps=1e-12, pad=False):
r""" Compute the Jacobian of the topography (d,u,v) parametrized (x,y,z) volume i.e. :math:`\partial V/\partial d`, :math:`\partial V/\partial u` and :math:`\partial V/\partial v`
Parameters
----------
depth_uv_params : (DxUxVx3) array
the input volume image giving the topography (d,u,v) unwrapped (x,y,z) volume
eps : scalar
small numerical value for numerical stability
pad : bool
if True, spherically pads by 1 pixel depth, top and right to compute 1st order finite differences, if False use np.gradient to compute central differences
Returns
-------
dV_dd : (DxUxVx3) array
:math:`\partial V/\partial d`, the change in the (x,y,z) volume coordinates in the direction of image d- axis (depth)
dV_du : (DxUxVx3) array
:math:`\partial V/\partial u`, the change in the (x,y,z) volume coordinates in the direction of image u- axis (horizontal)
dV_dv : (DxUxVx3) array
:math:`\partial V/\partial v`, the change in the (x,y,z) volume coordinates in the direction of image v- axis (vertical)
"""
# if pad then wrap, else use the gradient.
if pad:
depth_uv_params_ = np.vstack([depth_uv_params,
depth_uv_params[-1][None,:]])
dV_dd = depth_uv_params_[1:] - depth_uv_params_[:-1] # difference in d
depth_uv_params_ = np.dstack([depth_uv_params,
depth_uv_params[:,:,-1][:,:,None,:]])
dV_du = depth_uv_params_[:,:,1:] - depth_uv_params_[:,:,:-1] # difference in d
depth_uv_params_ = np.hstack([depth_uv_params,
depth_uv_params[:,-2][:,None,::-1,:]])
dV_dv = depth_uv_params_[:,1:] - depth_uv_params_[:,:-1]
else:
dV_dd = np.gradient(depth_uv_params, axis=0);
dV_du = np.gradient(depth_uv_params, axis=2);
dV_dv = np.gradient(depth_uv_params, axis=1);
return dV_dd, dV_du, dV_dv
def conformality_error_uv(surface_uv_params, eps=1e-12, pad=False):
r""" Compute the Quasi-conformal error for the uv parametrized (x,y,z) surface which is defined by the ratio of the largest to the smallest singular values of the Jacobian (see :func:`unwrap3D.Unzipping.unzip.gradient_uv`)
.. math ::
\mathcal{Q} = |\sigma_{max}| / |\sigma_{min}|
where :math:`\sigma_{min}` and :math:`\sigma_{max}` denote the smaller and larger of the eigenvalues of :math:`J^T J`, where :math:`J` is the Jacobian matrix of the surface with respect to (u,v).
Parameters
----------
surface_uv_params : (UxVx3) array
the input image giving the uv unwrapped (x,y,z) surface
eps : scalar
small numerical value for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
Returns
-------
stretch_factor : (UxV) array
The quasi-conformal error at each pixel
mean_stretch_factor : scalar
The area weighted mean quasi-conformal error summarising the overall conformal error for the surface
"""
# this is just the gradient area.
import numpy as np
dS_du, dS_dv = gradient_uv(surface_uv_params, eps=eps, pad=pad)
# compile the jacobian.
Jac = np.concatenate([dS_du[None,...],
dS_dv[None,...]], axis=0)
Jac = Jac.transpose(1,2,3,0) # transpose.
Jac2 = np.matmul(Jac.transpose(0,1,3,2), Jac)
stretch_eigenvalues, stretch_eigenvectors = np.linalg.eigh(Jac2) # compute J_T.dot(J) which is the first fundamental form.
stretch_factor = np.sqrt(np.max(np.abs(stretch_eigenvalues), axis=-1) / np.min(np.abs(stretch_eigenvalues), axis=-1)) # since this was SVD decomposition.
# compute the overall distortion factor, mean conformality error
areas3D = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
mean_stretch_factor = np.nansum(areas3D*stretch_factor / (float(np.nansum(areas3D))))
return stretch_factor, mean_stretch_factor
def surface_area_uv(surface_uv_params, eps=1e-12, pad=False):
r""" Compute the total surface area of the unwrapped (u,v) parametrized surface using differential calculus.
Assuming the parametrization is continuous, the differential element area for a pixel is the area of a differential rectangular element which can be written as a cross-product of the gradient vectors,
.. math ::
A_{pixel} &= \left\|\frac{\partial S}{\partial u}\right\|\left\|\frac{\partial S}{\partial v}\right\| \\
&= \left\|\frac{\partial S}{\partial u} \times \frac{\partial S}{\partial v}\right\|
where :math:`\times` is the vector cross product
Parameters
----------
surface_uv_params : (UxVx3) array
the input image giving the uv unwrapped (x,y,z) surface
eps : scalar
small numerical value for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
Returns
-------
dS_dudv : (UxV) array
The surface area of each pixel
total_dS_dudv : scalar
the total summed surface area of all pixels
"""
import numpy as np
dS_du, dS_dv = gradient_uv(surface_uv_params, eps=eps, pad=pad)
# area of the original surface.
dS_dudv = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
total_dS_dudv = np.nansum(dS_dudv)
return dS_dudv, total_dS_dudv
# add total volume for a topogarphy space.
def volume_uv(depth_uv_params, eps=1e-12, pad=False):
r""" Compute the total volume of the unwrapped (d,u,v) parametrized volume using differential calculus.
Assuming the parametrization is continuous, the differential element element for a pixel is the volume of a differential parallelpiped element which can be written as a triple-product of the gradient vectors,
.. math ::
V_{pixel} &= \left\|\frac{\partial V}{\partial d}\right\|\left\|\frac{\partial V}{\partial u}\right\|\left\|\frac{\partial V}{\partial v}\right\| \\
&= \left\|\frac{\partial V}{\partial d} \cdot \frac{\partial V}{\partial u} \times \frac{\partial V}{\partial v} \right\|
where :math:`\cdot` is the vector dot product and :math:`\times` is the vector cross product
Parameters
----------
depth_uv_params : (DxUxVx3) array
the input image giving the topography (d,u,v) unwrapped (x,y,z) surface
eps : scalar
small numerical value for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
Returns
-------
dV : (DxUxV) array
The volume of each pixel
Volume : scalar
the total summed volume of all pixels
"""
import numpy as np
dV_dd, dV_du, dV_dv = gradient_uv_depth(depth_uv_params, eps=eps, pad=pad)
# volume of the original surface.
dV = np.cross(dV_du, dV_dv, axis=-1)
dV = np.nansum(dV_dd * dV, axis=-1)
dV = np.linalg.norm(dV, axis=-1)# finally taking the magniude.
Volume = np.nansum(dV)
return dV, Volume
def area_distortion_uv(surface_uv_params, eps=1e-12, pad=False):
r""" Compute the area distortion given a (u,v) parameterized (x,y,z) surface, :math:`S`. The area distortion factor, :math:`\lambda` is defined as the normalised surface area measured in (u,v) divided by the normalised surface area in (x,y,z)
.. math ::
\lambda &= \frac{dudv/\sum_{uv}dudv}{dS/\sum dS} \\
Parameters
----------
surface_uv_params : (UxVx3) array
the input image giving the uv unwrapped (x,y,z) surface
eps : scalar
small number for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
"""
# this is just the gradient area.
import numpy as np
dS_du, dS_dv = gradient_uv(surface_uv_params, eps=eps, pad=pad)
# area of the original surface.
dS_dudv = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
dS_dudv = dS_dudv / np.nansum(dS_dudv)
# area of a dudv element of unit area divided evenly. 1/(UV)
dudv = 1./float(dS_dudv.shape[0]*dS_dudv.shape[1])
area_distortion = np.abs( dudv / dS_dudv )
return area_distortion
# add total volume distortion for a topogarphy space.
def volume_distortion_duv(depth_uv_params, eps=1e-12, pad=False):
r""" Compute the volume distortion given a (d,u,v) parameterized (x,y,z) surface, :math:`V`. The volume distortion factor, :math:`\lambda_{V}` is defined as the normalised volume measured in (d,u,v) divided by the normalised volume in (x,y,z)
.. math ::
\lambda_{V} &= \frac{dd du dv/\sum_{duv}dd du dv}{dV/\sum dV} \\
Parameters
----------
depth_uv_params : (DxUxVx3) array
the input image giving the (d,u,v) unwrapped (x,y,z) surface
eps : scalar
small number for numerical stability
pad : bool
if True, spherically pads by 1 pixel top and right to compute 1st order finite differences, if False using np.gradient to compute central differences
"""
# this is just the gradient area.
import numpy as np
dV_dd, dV_du, dV_dv = gradient_uv_depth(depth_uv_params, eps=eps, pad=pad)
# volume of the original surface.
dV_dddudv = np.cross(dV_du, dV_dv, axis=-1)
dV_dddudv = np.nansum(dV_dd * dV_dddudv, axis=-1)
dV_dddudv = np.linalg.norm(dV_dddudv, axis=-1)# finally taking the magniude.
dV_dddudv = dV_dddudv / np.nansum(dV_dddudv) # normalise the original surface volume.
# area of a dddudv element of unit volume divided evenly. 1/(DUV)
dddudv = 1./float(dV_dddudv.shape[0]*dV_dddudv.shape[1]*dV_dddudv.shape[2]) # normalised current volume
volume_distortion = np.abs( dddudv / dV_dddudv )
return volume_distortion
| 58,212 | 47.269486 | 299 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Unzipping/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/plotting.py
|
import pylab as plt
def set_axes_equal(ax: plt.Axes):
r"""Set 3D plot axes to equal scale.
Make axes of 3D plot have equal scale so that spheres appear as
spheres and cubes as cubes. Required since `ax.axis('equal')`
and `ax.set_aspect('equal')` don't work on 3D.
Parameters
----------
ax : Maptlolib axes object
3D Matplotlib axis to adjust
Returns
-------
None
"""
import numpy as np
limits = np.array([
ax.get_xlim3d(),
ax.get_ylim3d(),
ax.get_zlim3d(),
])
origin = np.mean(limits, axis=1)
radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))
_set_axes_radius(ax, origin, radius)
return []
def _set_axes_radius(ax, origin, radius):
r"""Set 3D plot axes limits to origin +/- radius.
This helper is used in set_axes_equal to ensure correct aspect ratio of 3D plots.
Parameters
----------
ax : Maptlolib axes object
3D Matplotlib axis to adjust
origin: (x,y,z) tuple of position
the center coordinate to set the axis limits
radius: scalar
the isotropic distance around origin to limit the 3D plot view to.
Returns
-------
None
"""
x, y, z = origin
ax.set_xlim3d([x - radius, x + radius])
ax.set_ylim3d([y - radius, y + radius])
ax.set_zlim3d([z - radius, z + radius])
return []
| 1,422 | 22.327869 | 86 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/imshowpair.py
|
def imshowpair(im1,im2, ax=None):
r""" Combines two potentially different sized grayscale images into one image.
Parameters
----------
im1 : (M1,N1) grayscale numpy array
input image 1
im2 : (M2,N2) grayscale numpy array
input image 2
ax : Matplotlib axes object
optional axis to display the image
Returns
-------
img : (M_max,N_max,3) numpy array
the combined image of im1 and im2, where M_max=max(M_1, M_2), and N_max=(N_1,N_2) are the largest row and column dimensions of im1, im2. The images are automatically centered in the output.
"""
from skimage.exposure import rescale_intensity
import pylab as plt
import numpy as np
dtype = type(im1.ravel()[0]) # check the data type
shape1 = np.array(im1.shape)
shape2 = np.array(im2.shape)
img_shape = np.max(np.vstack([shape1,shape2]), axis=0)
img = np.zeros((img_shape[0], img_shape[1], 3), dtype=dtype)
offset1x = (img_shape[0] - shape1[0]) // 2; offset1y = (img_shape[1]-shape1[1]) // 2;
offset2x = (img_shape[0] - shape2[0]) // 2; offset2y = (img_shape[1]-shape2[1]) // 2;
# display centered images.
img[offset1x:offset1x+shape1[0],offset1y:offset1y+shape1[1],0] = im1
img[offset2x:offset2x+shape2[0],offset2y:offset2y+shape2[1],1] = im2
if ax is not None:
ax.imshow(rescale_intensity(img))
return img
def checkerboard_imgs(im1, im2, grid=(10,10)):
r""" generate a checkerboard montage of two 2D images, useful for checking misalignment when registering two images.
Parameters
----------
im1 : (M,N) grayscale or (M,N,3) color image as numpy array
input image 1
im2 : (M,N) grayscale or (M,N,3) color image as numpy array
input image 2
grid : (int,int) tuple
specifies the number of rows and number of columns in the gridding of the checkerboard.
Returns
-------
im : (M,N,3) numpy array
the checkerboard combined image of im1 and im2.
"""
import numpy as np
import pylab as plt
# im1, im2 are grayscale or rgb images only.
if len(im1.shape) == 2:
# grayscale image.
rows, cols = im1.shape
if len(im1.shape) == 3:
# rgb image.
rows, cols, _ = im1.shape
# set up return image
im = np.zeros((rows, cols, 3))
# create the checkerboard mask.
check_rows = np.linspace(0, rows, grid[0]+1).astype(np.int)
check_cols = np.linspace(0, cols, grid[1]+1).astype(np.int)
checkerboard = np.zeros((rows,cols))
for i in range(grid[0]):
if np.mod(i,2) == 0:
even = 0
else:
even = 1
for j in range(grid[1]):
r = [check_rows[i], check_rows[i+1]]
c = [check_cols[j], check_cols[j+1]]
checkerboard[r[0]:r[1], c[0]:c[1]] = even
if even == 0:
even = 1
else:
even = 0
ones = np.array(np.where(checkerboard==1)).T
zeros = np.array(np.where(checkerboard==0)).T
if len(im1.shape) == 2:
# grayscale image.
im[ones[:,0], ones[:,1], 0] = im1[ones[:,0], ones[:,1]]
im[zeros[:,0], zeros[:,1], 1] = im2[zeros[:,0], zeros[:,1]]
if len(im1.shape) == 3:
# rgb image.
im[ones[:,0], ones[:,1], :] = im1[ones[:,0], ones[:,1], :]
im[zeros[:,0], zeros[:,1], :] = im2[zeros[:,0], zeros[:,1], :]
return im
| 3,585 | 30.734513 | 198 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/volume_img.py
|
import numpy as np
def montage_vol_proj(vol, proj_fn=np.max):
r"""Given a 3D grayscale volumetric imageand a projection function such as np.max, generates projected views onto x-y, x-z, y-z and montages them into one view.
Parameters
----------
vol : (M,N,L) numpy array
input grayscale volumetric image
proj_fn : Python function
this is any suitable projection function that allows the call format, proj_fn(vol, axis=0) to generate a 2D projection image.
Returns
-------
montage_img : (N+M, L+L) 2D numpy array
montaged 2D image which puts [top left] view_12, [top right] view_02, [bottom left] view_01
"""
mm, nn, ll = vol.shape
proj12 = proj_fn(vol, axis=0)
proj02 = proj_fn(vol, axis=1)
proj01 = proj_fn(vol, axis=2)
vol_new = np.zeros((proj12.shape[0]+proj01.shape[0], proj12.shape[1]+proj02.shape[1]))
vol_new[:proj12.shape[0], :proj12.shape[1]] = proj12.copy()
vol_new[:proj02.shape[0], proj12.shape[1]:] = proj02.copy()
vol_new[proj12.shape[0]:, :proj01.shape[1]] = proj01.copy()
return vol_new
| 1,123 | 33.060606 | 166 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/grid_img.py
|
def viz_grid(im_array, shape=None, cmap='gray', figsize=(10,10)):
r""" given an array of images, plots them montage style in matplotlib
Parameters
----------
im_array : n_img x n_rows x n_cols (x 3) grayscale or color numpy array
array of n_img images to display
shape : (i,j) integer tuple
specifys the number of images to display row- and column- wise, if not set, will try np.sqrt, and make as square a panel as possible.
cmap : string
optional specification of a named matplotlib colormap to apply to view the image.
figsize : (int,int) tuple
specify the figsize in matplotlib plot, implicitly controlling viewing resolution
Returns
-------
(fig, ax): figure and ax handles
returned for convenience for downstream accessing of plot elements.
"""
import pylab as plt
import numpy as np
n_imgs = len(im_array)
if shape is not None:
nrows, ncols = shape
else:
nrows = int(np.ceil(np.sqrt(n_imgs)))
ncols = nrows
color=True
if len(im_array.shape) == 3:
color=False
if len(im_array.shape) == 4 and im_array.shape[-1]==1:
color=False
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
for i in range(nrows):
for j in range(ncols):
im_index = i*ncols + j
if im_index<n_imgs:
if color:
ax[i,j].imshow(im_array[im_index])
else:
ax[i,j].imshow(im_array[im_index], cmap=cmap)
# switch off all gridlines.
ax[i,j].axis('off')
ax[i,j].grid('off')
return (fig, ax)
| 1,745 | 28.59322 | 141 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Visualisation/colors.py
|
def get_colors(inp, colormap, vmin=None, vmax=None, bg_label=None):
r""" Maps a given numpy input array with the specified Matplotlib colormap with optional specified minimum and maximum values. For an array that is integer such as that from multi-label segmentation, bg_label helps specify the background class which will automatically be mapped to a background color of [0,0,0,0]
Parameters
----------
inp : numpy array
input n-d array to color
colormap : matplotlib.cm colormap object
colorscheme to apply e.g. cm.Spectral, cm.Reds, cm.coolwarm_r
vmin : int/float
specify the optional value to map as the minimum boundary of the colormap
vmax : int/float
specify the optional value to map as the maximum boundary of the colormap
bg_label: int
for an input array that is integer such as a segmentation mask, specify which integer label to mark as background. These values will all map to [0,0,0,0]
Returns
-------
colored : numpy array
the colored version of input as RGBA, the 4th being the alpha. colors are specified as floats in range 0.-1.
"""
import pylab as plt
norm = plt.Normalize(vmin, vmax)
colored = colormap(norm(inp))
if bg_label is not None:
colored[inp==bg_label] = 0 # make these all black!
return colored
| 1,328 | 38.088235 | 314 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Analysis_Functions/topography.py
|
from ..Mesh import meshtools as meshtools
from ..Segmentation import segmentation as segmentation
from ..Unzipping import unzip as uzip
from ..Image_Functions import image as image_fn
def uv_depth_pts3D_to_xyz_pts3D( uv_pts3D, uv_depth_params):
r""" Linear Interpolation of the corresponding (x,y,z) coordinates given query (d,u,v) topography coordinates where the injective map (d,u,v) -> (x,y,z) is given by uv_depth_params.
Parameters
----------
uv_pts3D : (Nx3) array
the topography, (d,u,v) coordinate at N positions for which original (x,y,z) coordinates is desired
uv_depth_params : (D,U,V,3) array
the lookup table mapping the uniform (D,U,V) grid to (x,y,z) in original shape space
Returns
-------
xyz_pts3D : (Nx3) array
The corresponding (x,y,z) coordinates into the space indexed by uv_depth_params.
"""
import numpy as np
uv_pts3D_ = uv_pts3D.copy()
uv_pts3D_[...,0] = np.clip(uv_pts3D[:,0], 0, uv_depth_params.shape[0]-1)
uv_pts3D_[...,1] = np.clip(uv_pts3D[:,1], 0, uv_depth_params.shape[1]-1)
uv_pts3D_[...,2] = np.clip(uv_pts3D[:,2], 0, uv_depth_params.shape[2]-1)
xyz_pts3D = np.array([image_fn.map_intensity_interp3(uv_pts3D_,
grid_shape=uv_depth_params.shape[:-1],
I_ref=uv_depth_params[...,ch]) for ch in np.arange(uv_depth_params.shape[-1])])
xyz_pts3D = xyz_pts3D.T.copy()
return xyz_pts3D
def estimate_base_topography_uv_img(depth_binary):
r""" Given a binary in topography space, this function attempts to derive a 1-to-1 height map of the basal surface by projecting straight lines in d at every (u,v) pixel position to find contiguous stretches of intracellular space. The basal surface is given by the highest d in the longest stretch of each (u,v) position
The resulting height map is intended to be used for downstream processing.
Parameters
----------
depth_binary : (DxUxV) array
a binary volume in topography space where 1 indicates intracellular space and 0 is background ( extracellular )
Returns
-------
heigh_func : (UxV) array
a grayscale image with intensity = to the height coordinate in d i.e. we express height as a function of (u,v) position, height = f(u,v)
"""
import numpy as np
m, n = depth_binary.shape[1:]
heigh_func = np.zeros((m,n))
YY,XX = np.indices((m,n))
for ii in np.arange(m)[:]:
for jj in np.arange(n)[:]:
# iterate over this and parse the column the longest contig.
data = depth_binary[:,ii,jj] > 0
valid = np.arange(len(data))[data > 0] # convert to index.
# break into contigs
contigs = []
# contigs_nearest_mesh_distance = []
contig = []
for jjj in np.arange(len(valid)): # iterate over the sequence.
if jjj == 0:
contig.append(valid[jjj])
else:
if len(contig)>0:
diff = valid[jjj] - contig[-1]
if diff == 1:
contig.append(valid[jjj])
else:
# we should wrap this up. in a function now.
# finish a contig.
# print(contig)
contigs.append(contig)
# query_contig_pt = np.hstack([contig[-1], ii, jj])
# print(query_contig_pt)
# query_contig_pt_distance = np.min(np.linalg.norm(topography_mesh_pts-query_contig_pt[None,:], axis=-1))
# contigs_nearest_mesh_distance.append(query_contig_pt_distance)
contig=[valid[jjj]] # start a new one.
else:
contig.append(valid[jjj]) # extend cuyrrent.
if len(contig) > 0 :
contigs.append(contig)
# query_contig_pt = np.hstack([contig[-1], ii, jj])
# query_contig_pt_distance = np.min(np.linalg.norm(topography_mesh_pts-query_contig_pt[None,:], axis=-1))
# contigs_nearest_mesh_distance.append(query_contig_pt_distance)
contig = []
# filter by distance then take the maximum!.
# contigs = [contigs[kkk] for kkk in np.arange(len(contigs)) if contigs_nearest_mesh_distance[kkk]<10.] # within a minimum threshold.
max_contig = contigs[np.argmax([len(cc) for cc in contigs])] # we assume we take the longest contig.
heigh_func[ii,jj] = max_contig[-1]
heigh_func = np.dstack([heigh_func, YY, XX])
return heigh_func
def penalized_smooth_topography_uv_img(height_func,
ds=4,
padding_multiplier=4,
method='ALS',
lam=1,
p=0.25,
niter=10,
uv_params=None):
r""" Applies extended 2D asymmetric least squares regression to smooth a topography surface given as a height image, that is where the surface has been parameetrized 1-to-1 with (u,v), :math:`d=f(u,v)`
Parameters
----------
height_func : (UxV) array
an input topography surface given as a height image such that d=f(u,v)
ds : int
isotropic downsampling factor of the original image, used for imposing additional smoothness + computational efficiency
padding_multiplier : scalar
this specifies the padding size as a scalar multiple, 1/padding_multiplier of the downsampled image. It is used to soft enforce spherical bounds.
method : str
one of
'ALS' : str
Basic asymmetric least squares algorithm, see :func:`unwrap3D.Analysis_Functions.topography.baseline_als_Laplacian`
'airPLS' : str
adaptive iteratively reweighted Penalized Least Squares algorithm, see :func:`unwrap3D.Analysis_Functions.topography.baseline_airPLS2D`
lam : scalar
Controls the degree of smoothness in the baseline
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
niter : int
The number of iterations to run the algorithm. Only a few iterations is required generally.
uv_params : (DxUxV,3) array
the lookup table mapping the uniform (D,U,V) grid to (x,y,z) in original shape space. If provided the smoothness regularization will take into account the metric distortion.
Returns
-------
out : (UxV) array
a smoothened output topography surface given as a height image such that d=f(u,v)
"""
import skimage.transform as sktform
import numpy as np
from sklearn.feature_extraction.image import grid_to_graph
import scipy.sparse as spsparse
output_shape = np.hstack(height_func.shape)
height_binary_ds = sktform.resize(height_func,
output_shape=(output_shape//ds).astype(np.int),
preserve_range=True);
# this will be used to rescale.
height_binary_ds_max = height_binary_ds.max()
height_binary_ds = height_binary_ds / float(height_binary_ds_max)
if uv_params is not None:
uv_params_ds = sktform.resize(uv_params,
output_shape=np.hstack([(output_shape//ds).astype(np.int), uv_params.shape[-1]]),
preserve_range=True);
# use padding to help regularize.
padding = (height_binary_ds.shape[0]//padding_multiplier)//2 * 2+1 # this is just to make it odd!.
# circular padding!.
height_binary_ds = np.hstack([height_binary_ds[:,-padding:],
height_binary_ds,
height_binary_ds[:,:padding]])
height_binary_ds = np.vstack([np.rot90(height_binary_ds[1:padding+1],2),
height_binary_ds,
np.rot90(height_binary_ds[-1-padding:-1],2)])
if uv_params is not None:
uv_params_ds = np.hstack([uv_params_ds[:,-padding:],
uv_params_ds,
uv_params_ds[:,:padding]])
uv_params_ds = np.vstack([np.rot90(uv_params_ds[1:padding+1],2),
uv_params_ds,
np.rot90(uv_params_ds[-1-padding:-1],2)])
"""
build a graph to use the laplacian - this assumes equal weights.
"""
if uv_params is None:
# build the equal weight Laplacian matrix.
img_graph = grid_to_graph(height_binary_ds.shape[0], height_binary_ds.shape[1])
L = spsparse.spdiags(np.squeeze(img_graph.sum(axis=1)), 0, img_graph.shape[0], img_graph.shape[1]) - img_graph # degree - adjacency matrix.
L = L.tocsc()
else:
# build the weighted Laplacian matrix using the inverse edge length weights.
L = meshtools.get_inverse_distance_weight_grid_laplacian(uv_params_ds, grid_pts=uv_params_ds)
L = L.tocsc()
if method == 'ALS':
out = baseline_als_Laplacian(height_binary_ds.ravel(), L, lam=lam, p=p, niter=niter) # because there was an issue # seems like the best thing would be to do some smooth estimated fitting through...!
out = out.reshape(height_binary_ds.shape)
out = out[padding:-padding,padding:-padding].copy()
out = sktform.resize(out, output_shape=height_func.shape) * height_binary_ds_max
if method == 'airPLS':
out = baseline_airPLS2D(height_binary_ds.ravel(), L, lam=lam, p=p, niter=niter)
out = out.reshape(height_binary_ds.shape)
out = out[padding:-padding,padding:-padding].copy()
out = sktform.resize(out, output_shape=height_func.shape) * height_binary_ds_max
return out
def baseline_als_Laplacian(y, D, lam, p, niter=10):
r""" Estimates a 1D baseline signal :math:`z=g(x_1,x_2,...,x_n)` to a 1D input signal :math:`y=f(x_1,x_2,...,x_n)` parametrized by :math:`n` dimensions using asymmetric least squares. It can also be used for generic applications where a multidimensional image requires smoothing.
Specifically the baseline signal, :math:`z` is the solution to the following optimization problem
.. math::
z = arg\,min_z \{w(y-z)^2 + \lambda\sum(\Delta z)^2\}
where :math:`y` is the input signal, :math:`\Delta z` is the 2nd derivative or Laplacian operator, :math:`\lambda` is the smoothing regularizer and :math:`w` is an asymmetric weighting
.. math::
w_i =
\Biggl \lbrace
{
p ,\text{ if }
{y_i>z_i}
\atop
1-p, \text{ otherwise }
}
Parameters
----------
signal : 1D signal
The 1D signal to estimate a baseline signal.
D : (NxN) sparse Laplacian matrix
the Laplacian matrix for the signal which captures the multidimensional structure of the signal e.g. the grid graph for a 2D or 3D image or the cotangent laplacian for a mesh.
lam : scalar
Controls the degree of smoothness in the baseline
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
niter: int
The number of iterations to run the algorithm. Only a few iterations is required generally.
Returns
-------
z : 1D numpy array
the estimated 1D baseline signal
"""
from scipy import sparse
from scipy.sparse.linalg import spsolve
import numpy as np
L = len(y)
# D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in range(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
def baseline_airPLS2D(y, D, lam=100, p=1, niter=15):
r""" Estimates a 1D baseline signal :math:`z=g(x_1,x_2,...,x_n)` to a 1D input signal :math:`y=f(x_1,x_2,...,x_n)` parametrized by :math:`n` dimensions using Adaptive iteratively reweighted penalized least squares for baseline fitting. It can also be used for generic applications where a multidimensional image requires smoothing.
Specifically the baseline signal, :math:`z` is the solution to the following optimization problem
.. math::
z = arg\,min_z \{w(y-z)^2 + \lambda\sum(\Delta z)^2\}
where :math:`y` is the input signal, :math:`\Delta z` is the 2nd derivative or Laplacian operator, :math:`\lambda` is the smoothing regularizer and :math:`w` is an asymmetric weighting
.. math::
w_i =
\Biggl \lbrace
{
0 ,\text{ if }
{y_i\ge z_i}
\atop
e^{t(y_i-z_i)/|\textbf{d}|}, \text{ otherwise }
}
where the vector :math:`\textbf{d}` consists of negative elements of the subtraction, :math:`y - z` and :math:`t` is the iteration number.
Instead of constant weights in airPLS, the weight :math:`w` is adaptively weighted for faster convergence.
Parameters
----------
signal : 1D signal
The 1D signal to estimate a baseline signal.
D : (NxN) sparse Laplacian matrix
the Laplacian matrix for the signal which captures the multidimensional structure of the signal e.g. the grid graph for a 2D or 3D image or the cotangent laplacian for a mesh.
lam : scalar
Controls the degree of smoothness in the baseline
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
niter: int
The number of iterations to run the algorithm. Only a few iterations is required generally.
Returns
-------
z : 1D numpy array
the estimated 1D baseline signal
"""
import numpy as np
import scipy.sparse as spsparse
from scipy.sparse import csc_matrix, eye, diags
from scipy.sparse.linalg import spsolve
L = len(y)
w=np.ones(L) # equal weights initially
for i in range(1,niter+1):
W = spsparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = spsolve(Z, w*y)
d=y-z # difference between original and the estimated baseline
# w = p * (y > z) + (1-p) * (y < z) update in the original
dssn=np.abs(d[d<0].sum())
if(dssn<0.001*(abs(y)).sum() or i==niter):
if(i==niter): print('WARING max iteration reached!')
break
w[d>=0]=0 # d>0 means that this point is part of a peak, so its weight is set to 0 in order to ignore it
w[d<0]=np.exp(i*np.abs(d[d<0])/dssn)
w[0]=np.exp(i*(d[d<0]).max()/dssn)
w[-1]=w[0]
return z
def segment_topography_vol_curvature_surface(vol_curvature,
vol_binary_mask,
depth_ksize=1,
smooth_curvature_sigma=[1],
seg_method='kmeans',
n_samples=10000,
n_classes=3,
random_state=0,
scale_feats=False):
r""" Segment protrusions on the unwrapped topography using multiscale mean curvature features.
The multiscale comes from extracting the `mean curvature <https://en.wikipedia.org/wiki/Mean_curvature>`_, :math:`H` computed as the divergence of the normalised gradient vectors of the signed distance function, :math:`\Phi`
.. math::
H = -\frac{1}{2}\nabla\cdot\left( \frac{\nabla \Phi}{|\nabla \Phi|}\right)
and creating a multi-feature vector concatenating the smoothed :math:`H` after Gaussian smoothing with different :math:`\sigma` as specified by smooth_curvature_sigma
Parameters
----------
vol_curvature : (MxNxL) numpy array
the curvature computed using the definition above using the normalised gradient vector of the signed distance transform of the binary volume
vol_binary_mask : (MxNxL) numpy array
the topography binary volume from which the vol_curvature was determined form
depth_ksize : scalar
the width of a ball morphological operator for extracting a binary mask of a thin shell of thickness 2 x depth_ksize capturing the topographic volume surface to be segmented.
smooth_curvature_sigma: list of scalars
The list of N :math:`\sigma`'s which the vol_curvature is smoothed with to generate a N-vector :math:`[H_{\sigma_1},H_{\sigma_2}\cdots H_{\sigma_N}]` to describe the local surface topography of a voxel
seg_method : str
one of two clustering methods
kmeans :
`K-Means <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html>`_ clustering algorithm
gmm :
`Gaussian mixture model <https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture>`_ algorithm with full covariances
n_samples : int
the number of random sampled point to fit clustering on for computational efficiency
n_classes :int
the number of clusters desired
random_state : int
a number to fix the random seed for reproducible clustering.
scale_feats : bool
if set, the features are standard scaled prior to clustering. For mean curvature feats we find setting this seemed to make the clustering worse.
Returns
-------
depth_binary_mask, H_binary_depth_clusters : (MxNxL), (MxNxL) numpy array
depth_binary_mask : (MxNxL) numpy array
Binary mask of a shell of the topographic surface
H_binary_depth_clusters : (MxNxL) numpy array
Integer array where background is 0 and, integers refer to the different clusters and arranged such that they reflect increasing mean curvature.
"""
import numpy as np
import skimage.morphology as skmorph
import scipy.ndimage as ndimage
# curvature only makes sense relative to a binary surface.
depth_binary_mask = np.logical_and(skmorph.binary_dilation(vol_binary_mask>0, skmorph.ball(depth_ksize)),
np.logical_not(skmorph.binary_erosion(vol_binary_mask>0, skmorph.ball(depth_ksize))))
if len(smooth_curvature_sigma) == 1:
vol_curvature_smooth = depth_binary_mask*ndimage.gaussian_filter(vol_curvature, sigma=smooth_curvature_sigma[0])
if vol_height is not None:
vol_curvature_smooth = np.concatenate([vol_curvature_smooth[...,None],
vol_height[...,None]], axis=-1)
else:
vol_curvature_smooth = vol_curvature_smooth[...,None] # augment.
# if seg_method == 'kmeans':
# H_binary_depth_all_clusters = segmentation.multi_level_kmeans_thresh((vol_curvature_smooth[depth_binary_mask>0])[None,None,:,None],
# n_classes=n_classes, n_samples=n_samples, random_state=random_state, scale=scale_feats)
# if seg_method == 'gmm':
# H_binary_depth_all_clusters = segmentation.multi_level_gaussian_thresh((vol_curvature_smooth[depth_binary_mask>0])[None,None,:,None],
# n_classes=n_classes, n_samples=n_samples, random_state=random_state, scale=scale_feats)
else:
vol_curvature_smooth = np.array([depth_binary_mask*ndimage.gaussian_filter(vol_curvature, sigma=sigma) for sigma in smooth_curvature_sigma])
vol_curvature_smooth = vol_curvature_smooth.transpose(1,2,3,0) # put this in the last dimension!.
if vol_height is not None:
vol_curvature_smooth = np.concatenate([vol_curvature_smooth, vol_height[...,None]], axis=-1)
if seg_method == 'kmeans':
H_binary_depth_all_clusters = segmentation.multi_level_kmeans_thresh((vol_curvature_smooth[depth_binary_mask>0])[None,None,:,:],
n_classes=n_classes, n_samples=n_samples, random_state=random_state, scale=scale_feats)
if seg_method == 'gmm':
H_binary_depth_all_clusters = segmentation.multi_level_gaussian_thresh((vol_curvature_smooth[depth_binary_mask>0])[None,None,:,:],
n_classes=n_classes, n_samples=n_samples, random_state=random_state, scale=scale_feats)
# put these back into the volume!
H_binary_depth_all_clusters = np.squeeze(H_binary_depth_all_clusters)
# relabel the cluster labels in increasing curvature.
mean_curvature_cls = np.hstack([np.nanmean((vol_curvature_smooth[depth_binary_mask>0])[H_binary_depth_all_clusters==lab,0]) for lab in np.unique(H_binary_depth_all_clusters)])
# conduct relabelling in the order of mean_curvature_cls.
new_cluster_labels = np.argsort(mean_curvature_cls)
H_binary_depth_all_clusters_ = np.zeros_like(H_binary_depth_all_clusters)
for new_lab, old_lab in enumerate(new_cluster_labels):
H_binary_depth_all_clusters_[H_binary_depth_all_clusters==old_lab] = new_lab
H_binary_depth_all_clusters = H_binary_depth_all_clusters_.copy()
H_binary_depth_clusters = np.zeros(vol_curvature.shape, dtype=np.int32) # use int!.
H_binary_depth_clusters[depth_binary_mask==1] = H_binary_depth_all_clusters + 1 # add 1 as these curvature clusters are not background!.
return depth_binary_mask, H_binary_depth_clusters
def remove_topography_segment_objects_binary( vol_clusters, minsize=100, uv_params_depth=None):
r""" Removes small connected components in the binary image input either by the number of voxels or if provided the mapping to the original space, on the apparent number of voxels after geometric correction.
Parameters
----------
vol_clusters : (D,U,V) array
a binary volume
minsize : scalar
the minimum size, any connected components less than this is removed
uv_params_depth : (D,U,V,3) array
the lookup table mapping the uniform (D,U,V) grid to (x,y,z) in original shape space, if provided the minsize is computed for (x,y,z) space not the current (d,u,v) space
Returns
-------
vol_clusters_new : (D,U,V) array
a binary volume where size of connected components with > minsize removed.
"""
import numpy as np
import skimage.measure as skmeasure
vol_clusters_new = vol_clusters.copy()
vol_clusters_label = skmeasure.label(vol_clusters) # run connected component analysis
# measure the properties
props = skmeasure.regionprops(vol_clusters_label)
if uv_params_depth is None:
props_size = np.hstack([re.area for re in props]) # min_size = 100
remove_labels = np.setdiff1d(vol_clusters_label, 0)[props_size<minsize] # should this be applied in 3D ? or just in the image?
for lab in remove_labels:
vol_clusters_new[vol_clusters_label==lab] = 0 # set to 0 / bg
else:
unique_labels = np.setdiff1d(np.unique(vol_clusters_label), 0)
if len(unique_labels) > 0:
# we are going to compute the actual volume using differential calculus.
dV_dd = np.gradient(uv_params_depth, axis=0)
dV_dy = np.gradient(uv_params_depth, axis=1)
dV_dx = np.gradient(uv_params_depth, axis=2)
dVol = np.abs(np.nansum(np.cross(dV_dx, dV_dy, axis=-1) * dV_dd, axis=-1))
print(dVol.shape)
remove_labels = []
for lab in unique_labels:
vol_mask = vol_clusters_label==lab
vol_mask_area = np.nansum(dVol[vol_mask>0])
if vol_mask_area < minsize:
remove_labels.append(lab)
for lab in remove_labels:
vol_clusters_new[vol_clusters_label==lab] = 0 # set to 0 / bg
return vol_clusters_new
def prop_labels_watershed_depth_slices(topo_depth_clusters, depth_binary, rev_order=True, expand_labels_2d=2):
r""" Propagate semantic labels volumetrically from surface labels in topography space using marker-seeded watershed slice-by-slice with markers seeded from surface and from top to bottom (or bottom to top).
This function is used to propagate surface labels into the volume so as to obtain realistic volumizations of protrusion instance segmentations when mapped back to (x.y.z) space.
Parameters
----------
topo_depth_clusters : (MxNxL) numpy array
integer labelled volume where background voxels = 0 and unique integers > 0 represent unique connected objects.
depth_binary : (MxNxL) numpy array
the topography binary volume defining the voxels that needs semantic labeling
rev_order : bool
if True, reverses the scan direction to go from top to bottom instead of bottom to top (default)
expand_labels_2d: int
a preprocessing expansion of input topo_depth_clusters, to better guide the in-plane watershed propagation.
Returns
-------
topo_depth_clusters_ : (MxNxL) numpy array
new integer labelled volume where background voxels = 0 and unique integers > 0 represent unique connected objects.
"""
import numpy as np
import scipy.ndimage as ndimage
import skimage.segmentation as sksegmentation
D = len(topo_depth_clusters)
if rev_order == True:
topo_depth_clusters_ = topo_depth_clusters[::-1].copy()
depth_binary_ = depth_binary[::-1].copy() # might want to keep as 0 labels? # how to prevent flow? # we can use piecewise cuts? to approx?
else:
topo_depth_clusters_ = topo_depth_clusters.copy()
depth_binary_ = depth_binary.copy() # might want to keep as 0 labels? # how to prevent flow? # we can use piecewise cuts? to approx?
for dd in np.arange(D):
dtform_2D = ndimage.distance_transform_edt(depth_binary_[dd]>0)
if dd == 0:
label_dd = topo_depth_clusters_[dd].copy()
label_dd_watershed = sksegmentation.watershed(-dtform_2D,
markers=sksegmentation.expand_labels(label_dd, distance=expand_labels_2d),
mask=depth_binary_[dd]>0) # labels = watershed(-distance, markers, mask=image)
topo_depth_clusters_[dd] = label_dd_watershed.copy()
# if dd>0:
else:
label_dd = topo_depth_clusters_[dd].copy()
joint_mask = np.logical_and(depth_binary_[dd]>0, depth_binary_[dd-1]>0) # get the join
# same time there has to be a value.
joint_mask = np.logical_and(joint_mask, topo_depth_clusters_[dd-1]>0)
if np.sum(joint_mask) > 0:
label_dd[joint_mask] = (topo_depth_clusters_[dd-1][joint_mask]).copy() # then copy the vals.
label_dd_watershed = sksegmentation.watershed(-dtform_2D,
markers=sksegmentation.expand_labels(label_dd, distance=expand_labels_2d),
mask=depth_binary_[dd]>0) # labels = watershed(-distance, markers, mask=image)
topo_depth_clusters_[dd] = label_dd_watershed.copy()
if rev_order:
topo_depth_clusters_ = topo_depth_clusters_[::-1].copy()
return topo_depth_clusters_
def inpaint_topographical_height_image(vol_labels_binary,
pre_smooth_ksize=1,
post_smooth_ksize=3,
background_height_thresh=None,
inpaint_method='Telea',
inpaint_radius=1,
spherical_pad=True):
r""" Given a topographical binary where 1 at (d,u,v) denotes the cell describe the cell surface as a height map where :math:`d=f(u,v)` and 'holes' are represented with :math:`d\le h_{thresh}`, where :math:`h_{thresh}` is a minimal height threshold, use image inpainting to 'infill' the holes to obtain a complete surface.
Parameters
----------
vol_labels_binary : (MxNxL) numpy array
unwrapped topographic binary volume
pre_smooth_ksize : (MxNxL) numpy array
gaussian :math:`\sigma` for presmoothing the height image
post_smooth_ksize : scalar
gaussian :math:`\sigma` for postsmoothing the inpainted height image
background_height_thresh: scalar
all (u,v) pixels with height less than the specified threshold (:math:`d\le h_{thresh}`) is marked as 'holes' for inpainting
inpaint_method : str
one of two classical inpainting methods implemented in `OpenCV <https://docs.opencv.org/3.4/df/d3d/tutorial_py_inpainting.html>`_.
'Telea' :
Uses Fast Marching method of `Telea et al. <https://docs.opencv.org/3.4/d7/d8b/group__photo__inpaint.html#gga8c5f15883bd34d2537cb56526df2b5d6a892824c38e258feb5e72f308a358d52e>`_.
'NS' :
Uses Navier-Stokes method of `Bertalmio et al. <https://docs.opencv.org/3.4/d7/d8b/group__photo__inpaint.html#gga8c5f15883bd34d2537cb56526df2b5d6a892824c38e258feb5e72f308a358d52e>`_.
spherical_pad : int
the number of pixels to spherically pad, to soft-mimic the closed spherical boundary conditions in original (x,y,z) space
Returns
-------
infill_height : (UxV) numpy array
Inpainted height image representing the hole-completed topographic surface
(background_height, infill_mask) :
background_height : (UxV) numpy array
Height image of the input surface
infill_mask : (UxV) numpy array
Binary image where 1 denotes the region to be infilled
"""
import numpy as np
import cv2
import skimage.morphology as skmorph
import scipy.ndimage as ndimage
background_height_coords = np.argwhere(vol_labels_binary>0)
background_height = np.zeros(vol_labels_binary.shape[1:]) # build the image.
background_height[background_height_coords[:,1],
background_height_coords[:,2]] = background_height_coords[:,0] # assuming the 1st = height.
# mark the infill mask.
if pre_smooth_ksize is not None:
if background_height_thresh is None:
infill_mask = skmorph.binary_dilation(background_height<1, skmorph.disk(pre_smooth_ksize))
else:
infill_mask = skmorph.binary_dilation(background_height<background_height_thresh, skmorph.disk(pre_smooth_ksize))
# for rescaling purposes.
background_height_max = background_height.max()
if inpaint_method == 'Telea':
infill_height = cv2.inpaint(np.uint8(255*background_height/background_height_max), np.uint8(255*infill_mask), inpaint_radius, cv2.INPAINT_TELEA)
if inpaint_method == 'NS':
infill_height = cv2.inpaint(np.uint8(255*background_height/background_height_max), np.uint8(255*infill_mask), inpaint_radius, cv2.INPAINT_NS)
infill_height = infill_height/255. * background_height_max
if spherical_pad:
# we need to ensure that things connect linearly # a quick fix is to set left equal to right and the top and bottom to the mean with minimal changes.
infill_height_ = infill_height.copy()
infill_height_[0,:] = np.nanmean(infill_height[0,:])
infill_height_[-1,:] = np.nanmean(infill_height[-1,:])
infill_height_[:,-1] = infill_height_[:,0].copy()
infill_height = infill_height_.copy()
if post_smooth_ksize is not None:
infill_height = ndimage.gaussian_filter(infill_height, sigma=post_smooth_ksize) # maybe a regulariser is a better smoother...
return infill_height, (background_height, infill_mask)
def mask_volume_dense_propped_labels_with_height_image(vol_labels, height_map,
ksize=1,
min_size=500,
connectivity=2,
keep_largest=False):
r""" This function uses a hole-completed basal surface such as that from :func:`unwrap3D.Analysis_Functions.topography.inpaint_topographical_height_image` to isolate only the protrusions from a volume-dense volumization such as the output from :func:`unwrap3D.Analysis_Functions.topography.prop_labels_watershed_depth_slices`
Parameters
----------
vol_labels : (MxNxL) numpy array
integer labelled volume where background voxels = 0 and unique integers > 0 represent unique connected objects.
height_map : (MxN) numpy array
height image at every (u,v) pixel position specifying the basal surface :math:`d=f(u,v)` such that all voxels in vol_labels with coordinates :math:`d_{uv}\le d` will be set to a background label of 0
ksize : int
Optional morphological dilation of the binary surface specified by height map with a ball kernel of radius ksize. Can be used to control the extent of exclusion of the basal surface.
Set this parameter to None to not do morphological processing.
min_size: scalar
The minimum size of connected components to keep after masking
connectivity : int
specifies the connectivity of voxel neighbors. If 1, the 6-connected neighborhood, if 2, the full 26-connected neighborhood including the diagonals
keep_largest : bool
if True, for labels that end up disconnected after the masking, retain only the largest connected region.
Returns
-------
vol_labels_new : (MxNxL) numpy array
the non excluded integer labelled volume where background voxels = 0 and unique integers > 0 represent unique connected objects.
infill_height_mask : (MxN) numpy array
the exclusion volume specified by height_map after optional ksize morphological dilation.
"""
import numpy as np
import skimage.morphology as skmorph
# use the height to mask out all invalid volumes...
# depth_height = depth_mesh.vertices[:,0].reshape(H_binary_.shape[1:])
ZZ, _, _ = np.indices(vol_labels.shape)
if ksize is not None:
infill_height_mask = np.logical_not(skmorph.binary_dilation(np.logical_not(ZZ >= height_map), skmorph.ball(ksize)))
else:
infill_height_mask = ZZ >= height_map
# apply mask.
vol_labels_new = vol_labels*infill_height_mask
# postprocess - keep only the largest component in each cluster label!
keep_mask = skmorph.remove_small_objects(vol_labels_new>0, min_size=min_size, connectivity=connectivity)
vol_labels_new = vol_labels_new*keep_mask # apply the mask.
if keep_largest:
# suppressing this should be faster.
# for each label we should only have 1 connected component!
vol_labels_new = segmentation.largest_component_vol_labels(vol_labels_new, connectivity=connectivity)
return vol_labels_new, infill_height_mask
| 35,882 | 50.334764 | 336 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Analysis_Functions/timeseries.py
|
def linear_fit(x,y):
r""" Ordinary linear least regressions fit to a 1d array of x and y data
Parameters
----------
x : numpy array
the independent variable
y : numpy array
the dependent variable
Returns
-------
opts : ``LinregressResult`` instance
The return value is an object with the following attributes
slope : float
Slope of the regression line.
intercept : float
Intercept of the regression line.
rvalue : float
The Pearson correlation coefficient. The square of ``rvalue``
is equal to the coefficient of determination.
pvalue : float
The p-value for a hypothesis test whose null hypothesis is
that the slope is zero, using Wald Test with t-distribution of
the test statistic.
stderr : float
Standard error of the estimated slope (gradient), under the
assumption of residual normality.
intercept_stderr : float
Standard error of the estimated intercept, under the assumption
of residual normality.
"""
from scipy.stats import linregress
opts = linregress(x,y)
return opts
def exponential_decay_correction_time(signal, time_subset=None, f_scale=100., loss_type='soft_l1'):
r""" Corrects the mean intensities of an input video by fitting an exponential decay curve. The exponential is of the mathematical form
.. math::
y = Ae^{Bt} + C
where A, B, C are constants, t is time and y the signal.
Robust regression is used for fitting. See https://scipy-cookbook.readthedocs.io/items/robust_regression.html for more information.
Parameters
----------
signal : 1D numpy array
The 1D signal to fit an exponential function.
time_subset : 1D numpy array
A 1D array to mask the fitting to specific contiguous timepoints
f_scale : float
The regularisation parameter in the robust fitting
loss_type: str
One of the 5 robust loss types available in scipy, https://scipy-cookbook.readthedocs.io/items/robust_regression.html
Returns
-------
correction_factor : 1D numpy array
the multiplication factor at each timepoint to correct the signal
(res_robust.x, robust_y) : 2-tuple
res_robust.x returns the fitted model coefficients for reuse,
robust_y is the prediction of the signal using the fitted model coefficients
See Also
--------
unwrap3D.Analysis_Functions.timeseries.baseline_correction_time :
Use weighted least squares to estimate a baseline signal that can be used for correction
"""
from scipy.stats import linregress
from scipy.optimize import least_squares
import numpy as np
I_vid = signal.copy()
if time_subset is None:
# use the full
I_time = np.arange(len(I_vid))
I_time_subset = I_time.copy()
I_vid_subset = I_vid.copy()
else:
I_time = np.arange(len(I_vid))
I_time_subset = I_time[time_subset].copy()
I_vid_subset = I_vid[time_subset].copy()
# fit equation. y =A*e^(-Bt)
log_I_vid = np.log(I_vid_subset)
slope, intercept, r_value, p_value, std_err = linregress(I_time_subset, log_I_vid)
# initial fit.
A = np.exp(intercept)
B = slope
# refined robust fitting.
def exp_decay(t,x):
return (x[0] * np.exp(x[1] * t) + x[2])
# def exp_decay_line(t,x):
# return (x[0] * np.exp(x[1] * (t+x[3])) + x[2]) # exp + linear. (rather than this.... might be more correct to be a switch.... )
def res(x, t, y):
# return exp_decay(t,x) - y
return exp_decay(t,x) - y
x0 = [A, B, 0] #, 0]
# print(x0)
res_robust = least_squares(res, x0, loss=loss_type, f_scale=f_scale, args=(I_time_subset, I_vid_subset))
"""
applying the fitted now on the proper sequence.
"""
robust_y = exp_decay(I_time, res_robust.x)
correction_factor = float(robust_y[0]) / robust_y
return correction_factor, (res_robust.x, robust_y)
def baseline_correction_time(signal, p=0.1, lam=1, niter=10):
r""" Corrects the mean signal using weighted least square means regression to infer a baseline signal.
Specifically we estimate the baseline signal, :math:`z` as the solution to the following optimization problem
.. math::
z = arg\,min_z \{w(y-z)^2 + \lambda\sum(\Delta z)^2\}
where :math:`y` is the input signal, :math:`\Delta z` is the 2nd derivative, :math:`\lambda` is the smoothing regularizer and :math:`w` is an asymmetric weighting
.. math::
w =
\Biggl \lbrace
{
p ,\text{ if }
{y>z}
\atop
1-p, \text{ otherwise }
}
Parameters
----------
signal : 1D numpy array
The 1D signal to estimate a baseline signal.
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
lam : scalar
Controls the degree of smoothness in the baseline
niter: int
The number of iterations to run the algorithm. Only a few iterations is required generally.
Returns
-------
correction_factor : 1D numpy array
the multiplication factor at each timepoint to correct the signal
(baseline, corrected) : 2-tuple of 1D numpy array
baseline is the inferred smooth baseline signal,
corrected is the multiplicatively corrected signal using the estimated correction factor from the baseline
See Also
--------
unwrap3D.Analysis_Functions.timeseries.baseline_als :
The weighted least squares method used to estimate the baseline
"""
from scipy.stats import linregress
from scipy.optimize import least_squares
import numpy as np
I_vid = signal
baseline = baseline_als(I_vid, lam=lam, p=p, niter=niter)
correction_factor = float(I_vid[0]) / baseline
corrected = I_vid * correction_factor
return correction_factor, (baseline, corrected)
def baseline_als(y, lam, p, niter=10):
r""" Estimates a baseline signal using asymmetric least squares. It can also be used for generic applications where a 1D signal requires smoothing.
Specifically the baseline signal, :math:`z` is the solution to the following optimization problem
.. math::
z = arg\,min_z \{w(y-z)^2 + \lambda\sum(\Delta z)^2\}
where :math:`y` is the input signal, :math:`\Delta z` is the 2nd derivative, :math:`\lambda` is the smoothing regularizer and :math:`w` is an asymmetric weighting
.. math::
w =
\Biggl \lbrace
{
p ,\text{ if }
{y>z}
\atop
1-p, \text{ otherwise }
}
Parameters
----------
signal : 1D numpy array
The 1D signal to estimate a baseline signal.
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
lam : scalar
Controls the degree of smoothness in the baseline
niter: int
The number of iterations to run the algorithm. Only a few iterations is required generally.
Returns
-------
z : 1D numpy array
the estimated 1D baseline signal
See Also
--------
unwrap3D.Analysis_Functions.timeseries.baseline_correction_time :
Application of this method to estimate a baseline for a 1D signal and correct the signal e.g. for photobleaching
unwrap3D.Analysis_Functions.timeseries.decompose_nonlinear_time_series :
Application of this method to decompose a 1D signal into smooth baseline + high frequency fluctuations.
"""
from scipy import sparse
from scipy.sparse.linalg import spsolve
import numpy as np
L = len(y)
D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in range(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
def fit_spline(x,y, smoothing=None):
r""" Fitting a univariate smoothing spline to x vs y univariate data curve
Parameters
----------
x : (N,) array
the 1d x- variables
y : (N,) array
the 1d y- variables
smoothing : scalar
Optional control of smoothing, higher gives more smoothing. If None, it is automatically set based on standard deviation of y.
Returns
-------
x, y_norm, interp_s : list of (N,) arrays
the 1d x- variables, normalised maximum normalized y_norm=y/y_max variables used to fit and interp_s the smooth y curve
spl : scipy spline instance object
the interpolating spline object fitted on x, y_norm
"""
from scipy.interpolate import UnivariateSpline
import numpy as np
max_y = np.max(y)
y_norm = y/float(max_y)
if smoothing is None:
spl = UnivariateSpline(x, y_norm, s=2*np.std(y_))
else:
spl = UnivariateSpline(x, y_norm, s=smoothing)
interp_s = max_y*spl(x)
return (x, y_norm, interp_s), spl
def decompose_nonlinear_time_series(y, lam, p, niter=10, padding=None):
r""" Decomposes a given signal into smooth + residual components. The smooth signal is estimated using asymmetric least squares.
Parameters
----------
y : 1D numpy array
The input 1D signal to decompose
lam : scalar
Controls the degree of smoothness in the baseline
p : scalar
Controls the degree of asymmetry in the weighting. p=0.5 is the same as smoothness regularized least mean squares.
niter: int
The number of iterations to run the algorithm. Only a few iterations is required generally.
padding: int
Padding window to dampen boundary conditions. If None, the entire signal is used for padding otherwise the specified window is used to pad.
Reflecting boundary conditions are used for padding.
Returns
-------
z : 1D numpy array
the estimated 1D baseline signal
"""
import numpy as np
if padding is None:
y_ = np.hstack([y[::-1], y, y[::-1]])
y_base = baseline_als(y_, lam=lam, p=p, niter=niter)
y_base = y_base[len(y):-len(y)]
else:
y_ = np.hstack([y[::-1][-padding:], y, y[::-1][:padding]])
y_base = baseline_als(y_, lam=lam, p=p, niter=niter)
y_base = y_base[padding:-padding]
return y_base, y-y_base
def xcorr(x, y=None, norm=True, eps=1e-12):
r""" Computes the discrete crosscorrelation of two read 1D signals as defined by
.. math::
c_k = \sum_n x_{n+k} \cdot y_n
If norm=True, :math:`\hat{x}=\frac{x-\mu}{\sigma}` and :math:`\hat{y}=\frac{y-\mu}{\sigma}` is normalised and the zero-normalised autocorrelation is computed,
.. math::
c_k = \frac{1}{T}\sum_n \hat{x}_{n+k} \cdot \hat{y}_n
where :math:`T` is the length of the signal :math:`x`
Parameters
----------
x : 1D numpy array
The input 1D signal
y : 1D numpy array
The optional second 1D signal. If None, the autocorrelation of x is computed.
norm : bool
If true, the normalized autocorrelation is computed such that all values are in the range [-1.,1.]
eps : scalar
small constant to prevent zero division when norm=True
Returns
-------
result : 1D numpy array
the 1-sided autocorrelation if y=None, or the full cross-correlation otherwise
Notes
-----
The definition of correlation above is not unique and sometimes correlation
may be defined differently. Another common definition is:
.. math::
c'_k = \sum_n x_{n} \cdot {y_{n+k}}
which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
"""
import numpy as np
if norm:
a = (x - np.nanmean(x)) / (np.nanstd(x) * len(x) + eps)
if y is not None:
b = (y - np.nanmean(y)) / (np.nanstd(y) + eps)
else:
b = a.copy()
else:
a = x.copy()
if y is not None:
b = y.copy()
b = x.copy()
result = np.correlate(a, b, mode=mode) # this is not normalized!.
if y is None:
# return the 1-sided autocorrelation.
result = result[result.size // 2:]
return result
def xcorr_timeseries_set_1d(timeseries_array1, timeseries_array2=None, norm=True, eps=1e-12, stack_final=False):
r""" Computes the discrete crosscorrelation of two read 1D signals as defined by
.. math::
c_k = \sum_n x_{n+k} \cdot y_n
If norm=True, :math:`\hat{x}=\frac{x-\mu}{\sigma}` and :math:`\hat{y}=\frac{y-\mu}{\sigma}` is normalised and the zero-normalised autocorrelation is computed,
.. math::
c_k = \frac{1}{T}\sum_n \hat{x}_{n+k} \cdot \hat{y}_n
where :math:`T` is the length of the signal :math:`x`
given two arrays or lists of 1D signals. The signals in the individual arrays need not have the same temporal length. If they do, by setting stack_final=True, the result can be returned as a numpy array else will be returned as a list
Parameters
----------
timeseries_array1 : array_like of 1D signals
A input list of 1D signals
timeseries_array2 : array_like of 1D signals
An optional second 1D signal set. If None, the autocorrelation of each timeseries in timeseries_array1 is computed.
norm : bool
If true, the normalized autocorrelation is computed such that all values are in the range [-1.,1.]
eps : scalar
small constant to prevent zero division when norm=True
stack_final : bool
if timeseries_array1 or timeseries_array2 are numpy arrays with individual signals within of equal temoporal length, setting this flag to True, will return a numpy array else returns a list of cross-correlation curves
Returns
-------
xcorr_out : array_list of 1D numpy array
the 1-sided autocorrelation if y=None, or the full cross-correlation otherwise
Notes
-----
The definition of correlation above is not unique and sometimes correlation
may be defined differently. Another common definition is:
.. math::
c'_k = \sum_n x_{n} \cdot {y_{n+k}}
which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
"""
import numpy as np
compute_xcorr=True
if timeseries_array2 is None:
timeseries_array2 = timeseries_array1.copy() # create a copy.
compute_xcorr=False
xcorr_out = []
for ii in np.arange(len(timeseries_array1)):
timeseries_ii_1 = timeseries_array1[ii].copy()
timeseries_ii_2 = timeseries_array2[ii].copy()
if compute_xcorr:
xcorr_timeseries_ii = xcorr(timeseries_ii_1, y=timeseries_ii_2, norm=norm, eps=eps)
else:
xcorr_timeseries_ii = xcorr(timeseries_ii_1, y=None, norm=norm, eps=eps)
xcorr_out.append(xcorr_timeseries_ii)
if stack_final:
xcorr_out = np.vstack(xcorr_out)
return xcorr_out
else:
return xcorr_out
def stack_xcorr_curves(xcorr_list):
r""" Compiles a list of cross-correlation curves of different temporal lengths with NaN representing missing values assuming the midpoint of each curves is time lag = 0
Parameters
----------
xcorr_list : list of 1D arrays
A input list of 1D cross-correlation curves of different lengths
Returns
-------
out_array : numpy array
a compiled N x T matrix, where N is the number of curves, and T is the length of the longest curve.
"""
import numpy as np
N = [len(xx) for xx in xcorr_list]
size = np.max(N)
out_array = np.zeros((len(xcorr_list), size)); out_array[:] = np.nan
for jj in np.arange(len(xcorr_list)):
xcorr = xcorr_list[jj].copy()
out_array[jj,size//2-len(xcorr)//2:size//2+len(xcorr)//2+1] = xcorr.copy()
return out_array
def spatialcorr_k_neighbors(timeseries_array, k_graph, norm=True, eps=1e-12):
r""" Computes the spatial correlation of timeseries for a defined number of steps away. That is it assumes the distance has been pre-discretised and the k_graph represents the relevant neighbors at different distance steps away for a timeseries.
Parameters
----------
timeseries_array : (NxT) of 1D timeseries
A input list of 1D cross-correlation curves of different lengths
k_graph : N x (adjacency list of neighbors)
adjacency list of each timeseries for N radial spatial steps
norm : bool
if True, returns the zero-normalised correlation coefficient in [-1.,1.]
eps : scalar
small constant to prevent zero division when norm=True
Returns
-------
vertex_means_pearsonr : 1d numpy array
The average spatial correlation over all timeseries at the given spatial steps away
"""
import numpy as np
z_norm = timeseries_array.copy()
if norm:
z_norm = (z_norm-np.nanmean(z_norm, axis=1)[:,None]) / (np.nanstd(z_norm, axis=1)[:,None]+eps)
adj_list = list(k_graph)
##### too much memory usage.
# N_adj_list = np.hstack([len(aa) for aa in adj_list])
# adj_list_pad = -np.ones((len(N_adj_list), np.max(N_adj_list)), dtype=np.int32)
# for vv_ii in np.arange(len(adj_list)):
# adj_list_pad[vv_ii, :len(adj_list[vv_ii])] = adj_list[vv_ii]
# series1 = z_norm[adj_list_pad].copy()
# series1_mask = np.ones(adj_list_pad.shape, dtype=bool); series1_mask[adj_list_pad==-1] = 0
# vertex_means_pearsonr = np.nanmean(z_norm[:,None,:] * series1, axis=-1)
# vertex_means_pearsonr = np.nansum(vertex_means_pearsonr*series1_mask, axis=1) / N_adj_list
# all_ring_corrs.append(vertex_means_pearsonr)
vertex_means_pearsonr = []
# iterate over each vertex.
for vv_ii in np.arange(len(adj_list)): # this is likely the longest loop - we can paralellize this if we pad....
# series0 = z_norm[vv_ii].copy() # if norm.
# series1 = z_norm[adj_list[vv_ii]].copy()
# corrs = np.hstack([spstats.pearsonr(series0, ss)[0] for ss in series1])
# vertex_means_pearsonr.append(np.nanmean(corrs))
# # hard code this to make this fast.
# # definition being Sxy / SxxSyy
# # https://stackabuse.com/calculating-pearson-correlation-coefficient-in-python-with-numpy/
series0 = z_norm[vv_ii].copy(); series0 = (series0 - np.nanmean(series0)) / (np.nanstd(series0) + eps)
series1 = z_norm[adj_list[vv_ii]].copy(); series1 = (series1 - np.nanmean(series1, axis=1)[:,None]) / (np.nanstd(series1, axis=1)[:,None] + eps)
Sxy = np.nanmean(series0[None,:] * series1, axis=1)
SxxSxy = np.nanstd(series0) * np.nanstd(series1, axis=1)
corrs = Sxy / (SxxSxy + 1e-12)
vertex_means_pearsonr.append(np.nanmean(corrs))
vertex_means_pearsonr = np.hstack(vertex_means_pearsonr)
return vertex_means_pearsonr
| 17,506 | 31.907895 | 246 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Analysis_Functions/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Utility_Functions/file_io.py
|
def read_czifile(czi_file, squeeze=True):
r""" Reads the data of a simple .czi microscope stack into a numpy array using the lightweight czifile library
Parameters
----------
czifile : filepath
path of the .czi file to read
squeeze : bool
specify whether singleton dimensions should be collapsed out
Returns
-------
image_arrays : numpy array
image stored in the .czi
"""
import numpy as np
from czifile import CziFile
with CziFile(czi_file) as czi:
image_arrays = czi.asarray()
if squeeze:
image_arrays = np.squeeze(image_arrays)
return image_arrays
def mkdir(directory):
r"""Recursively creates all directories if they do not exist to make the folder specifed by 'directory'
Parameters
----------
directory : folderpath
path of the folder to create
"""
import os
if not os.path.exists(directory):
os.makedirs(directory)
return []
def get_basename(pathname, ext):
r"""helper to return the base file name minus the extension given an absolute or relative filepath location
e.g. This function will return from a filepath, '../long_file_location/filename.tif', the file name minus the extension, 'filename'
Parameters
----------
pathname : filepath
filepath to parse the file name from
ext : string
extension of the file format e.g. .tif, .png, .docx
Returns
-------
basename : string
the name of the file minus extension and location information
"""
import os
basename = os.path.split(pathname)[-1].split(ext)[0]
return basename
def read_demons_matlab_tform( tform_file, volshape, keys=['u', 'v', 'w']):
r"""helper for reading Matlab generated xyz demons deformation fields accounting for the difference in array convention.
Parameters
----------
tform_file : .mat (Matlab v5.4 format)
filepath to the .mat of the saved deformation field saved from Matlab
volshape : (M,N,L) tuple
shape of the original volume, the deformation fields correspond to. This shape is used to rescale any downsampled deformation fields to the original size using linear interpolation.
keys : list of strings
the variable names in the saved .mat corresponding to the x-, y-, z- direction deformation within Matlab
Returns
-------
w : (M,N,L) numpy array
the 'x' deformation in Python tiff image reading convention
v : (M,N,L) numpy array
the 'y' deformation in Python tiff image reading convention
u : (M,N,L) numpy array
the 'z' deformation in Python tiff image reading convention
"""
import scipy.io as spio
import skimage.transform as sktform
tform_obj = spio.loadmat(tform_file) # this assumes matlab v5.4 format
u = (tform_obj[keys[0]]).astype(np.float32).transpose(2,0,1)
v = (tform_obj[keys[1]]).astype(np.float32).transpose(2,0,1)
w = (tform_obj[keys[2]]).astype(np.float32).transpose(2,0,1)
scaling_factor = np.hstack(volshape).astype(np.float32) / np.hstack(u.shape)
# transform this remembering to cast to float32.
u = sktform.resize((u*scaling_factor[0]).astype(np.float32), volshape, preserve_range=True).astype(np.float32)
v = sktform.resize((v*scaling_factor[2]).astype(np.float32), volshape, preserve_range=True).astype(np.float32)
w = sktform.resize((w*scaling_factor[1]).astype(np.float32), volshape, preserve_range=True).astype(np.float32)
return w,v,u
def save_array_to_nifti(data, savefile):
r""" Saves a given numpy array to a nifti format using the nibabel library. The main use is for exporting volumes to annotate in ITKSnap.
Parameters
----------
data : numpy array
input volume image
savefile : string
filepath to save the output to, user should include the extension in this e.g. .nii.gz for compressed nifty
"""
import nibabel as nib
import numpy as np
img = nib.Nifti1Image(data, np.eye(4))
nib.save(img, savefile)
return []
| 4,215 | 28.900709 | 190 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Utility_Functions/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Utility_Functions/stack.py
|
def bounding_box(mask3D):
r""" Given a binary mask in 3D, locate the xyz corners of the tightest bounding box without geometric transformation.
Parameters
----------
mask3D : (M,N,L) binary np.bool array
3D binary image to compute the bounding box coordinates for
Returns
-------
bbox : [x1,y1,z1,x2,y2,z2] 1d numpy array
3D bounding box of the given object specified by the 'top left' (x1,y1,z1) and 'bottom right' (x2,y2,z2) corners in 3D
"""
import numpy as np
coords = np.argwhere(mask3D>0).T
min_x, max_x = np.min(coords[:,0]), np.max(coords[:,0])
min_y, max_y = np.min(coords[:,1]), np.max(coords[:,1])
min_z, max_z = np.min(coords[:,2]), np.max(coords[:,2])
bbox = np.hstack([min_x, min_y, min_z, max_x, max_y, max_z])
return bbox
def expand_bounding_box(bbox3D, clip_limits, border=50, border_x=None, border_y=None, border_z=None):
r""" Given a bounding box specified with 'top left' (x1,y1,z1) and 'bottom right' (x2,y2,z2) corners in 3D, return another such bounding box with asymmetrically expanded limits
Parameters
----------
bbox3D : [x1,y1,z1,x2,y2,z2] 1d numpy array
original 3D bounding box specified by the 'top left' (x1,y1,z1) and 'bottom right' (x2,y2,z2) corners in 3D
clip_limits : (M,N,L) integer tuple
the maximum bounds corresponding to the volumetric image size
border : int
the default single scalar for expanding a bounding box, it is overridden in select directions by setting border_x, border_y, border_z the 1st, 2nd, 3rd axes respectively.
border_x : int
the expansion in the 1st axis
border_y : int
the expansion in the 2nd axis
border_z : int
the expansion in the 3rd axis
Returns
-------
bbox : [x1,y1,z1,x2,y2,z2] 1d numpy array
the coordinates of the expanded 3D bounding box specified by the 'top left' (x1,y1,z1) and 'bottom right' (x2,y2,z2) corners in 3D
"""
import numpy as np
clip_x, clip_y, clip_z = clip_limits
new_bounds = np.zeros_like(bbox3D)
for i in range(len(new_bounds)):
if i==0:
if border_x is not None:
new_bounds[i] = np.clip(bbox3D[i]-border_x, clip_x[0], clip_x[1])
else:
new_bounds[i] = np.clip(bbox3D[i]-border, clip_x[0], clip_x[1])
if i==3:
if border_x is not None:
new_bounds[i] = np.clip(bbox3D[i]+border_x, clip_x[0], clip_x[1])
else:
new_bounds[i] = np.clip(bbox3D[i]+border, clip_x[0], clip_x[1])
if i==1:
if border_y is not None:
new_bounds[i] = np.clip(bbox3D[i]-border_y, clip_y[0], clip_y[1])
else:
new_bounds[i] = np.clip(bbox3D[i]-border, clip_y[0], clip_y[1])
if i==4:
if border_y is not None:
new_bounds[i] = np.clip(bbox3D[i]+border_y, clip_y[0], clip_y[1])
else:
new_bounds[i] = np.clip(bbox3D[i]+border, clip_y[0], clip_y[1])
if i==2:
if border_z is not None:
new_bounds[i] = np.clip(bbox3D[i]-border_z, clip_z[0], clip_z[1])
else:
new_bounds[i] = np.clip(bbox3D[i]-border, clip_z[0], clip_z[1])
if i==5:
if border_z is not None:
new_bounds[i] = np.clip(bbox3D[i]+border_z, clip_z[0], clip_z[1])
else:
new_bounds[i] = np.clip(bbox3D[i]+border, clip_z[0], clip_z[1])
return new_bounds
def crop_img_2_box(volume, bbox3D):
r""" crop a given 3D volumetric image given a 3D cropping bounding box. Bounding boxes are clipped internally to the size of the volume.
Parameters
----------
volume : (M,N,L) numpy array
3D image to crop
bbox3D : [x1,y1,z1,x2,y2,z2] 1d numpy array
3D cropping bounding box specified by the 'top left' (x1,y1,z1) and 'bottom right' (x2,y2,z2) corners in 3D
Returns
-------
cropped : cropped numpy array
volume[x1:x2,y1:y2,z1:z2]
"""
import numpy as np
x1,y1,z1,x2,y2,z2 = bbox3D
M, N, L = volume.shape
x1 = np.clip(x1, 0, M-1)
x2 = np.clip(x2, 0, M-1)
y1 = np.clip(y1, 0, N-1)
y2 = np.clip(y2, 0, N-1)
z1 = np.clip(z1, 0, L-1)
z2 = np.clip(z2, 0, L-1)
cropped = volume[x1:x2,y1:y2,z1:z2]
return cropped
| 4,547 | 33.984615 | 181 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Segmentation/segmentation.py
|
import numpy as np
def smooth_vol(vol, ds=4, smooth=5, method='gaussian'):
r""" Smoothing particularly a 3D volume image with large Gaussian kernels or Median filters is extremely slow. This function combines downsampling of the original volume image with smaller kernel smoothing on the downsampled image before upsampling to do significantly faster smoothing for large arrays.
Parameters
----------
vol : array
input image
ds : int
the downsampling factor, the downsampled shape will have size ``vol.shape//ds``
smooth : scalar
the size of smoothing; ``sigma`` for scipy.ndimage.gaussian_filter or ``size`` for scipy.ndimage.median_filter
Returns
-------
smoothed image, the same size as the input
"""
from skimage.filters import gaussian
from scipy.ndimage import gaussian_filter, median_filter
import skimage.transform as sktform
import numpy as np
small = sktform.resize(vol, np.array(vol.shape)//ds, preserve_range=True)
if method == 'gaussian':
small = gaussian_filter(small, sigma=smooth)
if method == 'median':
small = median_filter(small, size=smooth)
return sktform.resize(small, np.array(vol_binary.shape), preserve_range=True)
def largest_component_vol(vol_binary, connectivity=1):
r""" Given a binary segmentation, return only the largest connected component of the given connectivity
Parameters
----------
vol : array
input binary image
connectivity : 1 or 2
if 1, the local 4-neighbors for 2D or 6-neighbors for 3D.
if 2, the local 8-neighbors for 2D or 26-neighbors for 3D.
Returns
-------
vol_binary : array
output binary image same size as input retaining only the largest connected component
"""
from skimage.measure import label, regionprops
import numpy as np
vol_binary_labelled = label(vol_binary, connectivity=connectivity)
# largest component.
vol_binary_props = regionprops(vol_binary_labelled)
vol_binary_vols = [re.area for re in vol_binary_props]
vol_binary = vol_binary_labelled == (np.unique(vol_binary_labelled)[1:][np.argmax(vol_binary_vols)])
return vol_binary
def largest_component_vol_labels(vol_labels, connectivity=1, bg_label=0):
r""" Given a multi-label integer image, return for each unique label, the largest connected component such that 1 label, 1 connected area. Useful to enforce the spatial uniqueness of a label.
Parameters
----------
vol_labels : array
input multi-label integer image
connectivity : 1 or 2
if 1, the local 4-neighbors for 2D or 6-neighbors for 3D.
if 2, the local 8-neighbors for 2D or 26-neighbors for 3D.
bg_label : 0
the integer label of background non-object areas
Returns
-------
vol_labels_new : array
output multi-label integer image where every unique label is associated with only one connected region.
"""
import numpy as np
# now do a round well each only keeps the largest component.
uniq_labels = np.setdiff1d(np.unique(vol_labels), bg_label)
vol_labels_new = vol_labels.copy()
for lab in uniq_labels:
mask = vol_labels == lab
mask = largest_component_vol(mask, connectivity=connectivity)
vol_labels_new[mask>0] = lab # put this.
return vol_labels_new
def get_bbox_binary_2D(mask, feature_img=None, prop_nan=True):
r""" Given a 2D binary image, return the largest bounding box described in terms of its top left and bottom right coordinate positions. If given the corresponding feature_img, compute the average feature vector describing the contents inside the bounding box and concatenate this with the bounding box coordinates for downstream applications.
This function is primarily useful for describing a region of interest with a bounding box for downstream tracking, classification and clustering applications.
Parameters
----------
mask : array
input binary image
feature_img : array
if not None, should be a ``mask.shape + (F,)`` array, where F is the number of features for which we would like the average (using mean) over any detected bounding box to append to the bounding box coordinates to be returned
prop_nan : bool
if True, when no valid bounding box can be detected e.g. for a 1 pixel only binary area, the bounding box coordinates and associated features (if specified) are subsituted for by ``np.nan``. Otherwise, the empty list [] is returned. This flag is useful for downstream applications where a regular sized array may be required.
Returns
-------
bbox : (N,) array
the bounding box described by its top-left (x1,y1) and bottom right (x2,y2) coordinates given as a 1d array of x1,y1,x2,y2 concatenated if specified by the mean feature vector
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.get_bbox_labels_2D` :
this function does the same for multi-label segmentation images
"""
import numpy as np
yyxx = np.argwhere(mask>0)
yy = yyxx[:,0]
xx = yyxx[:,1]
x1 = np.min(xx)
x2 = np.max(xx)
y1 = np.min(yy)
y2 = np.max(yy)
if x2>x1 and y2>y1:
if feature_img is not None:
features_box = np.hstack([np.nanmean(ff[mask>0]) for ff in feature_img])
# features_box = np.nanmean(feature_img[mask>0], axis=-1) # average over the last dimension.
bbox = np.hstack([x1,y1,x2,y2, features_box])
else:
bbox = np.hstack([x1,y1,x2,y2])
else:
if prop_nan:
if feature_img is not None:
bbox = np.hstack([np.nan, np.nan, np.nan, np.nan, np.nan*np.ones(feature_img.shape[-1])])
else:
bbox = np.hstack([np.nan, np.nan, np.nan, np.nan])
else:
bbox = []
return bbox
def get_bbox_labels_2D(label_img, feature_img=None, prop_nan=True, bg_label=0, split_multi_regions=False):
r""" Given a 2D multi-label image, iterate over each unique foreground labelled regions and return the bounding boxes described in terms of its top left and bottom right coordinate positions and label. If given the corresponding feature_img, compute the average feature vector describing the contents inside the bounding box and concatenate this with the bounding box coordinates for downstream applications.
This function is useful for describing regions of interest with a bounding box for downstream tracking, classification and clustering applications.
Parameters
----------
label_img : array
input multi-labeled image
feature_img : array
if not None, should be a ``label_img.shape + (F,)`` array, where F is the number of features for which we would like the average (using mean) over any detected bounding box to append to the bounding box coordinates to be returned
prop_nan : bool
if True, when no valid bounding box can be detected e.g. for a 1 pixel only area, the bounding box coordinates and associated features (if specified) are subsituted for by ``np.nan``. Otherwise, the empty list [] is returned. This flag is useful for downstream applications where a regular sized array may be required.
bg_label : int
the integer label marking background regions
split_multi_regions : bool
if True, this function will derive generate a bounding box for each disconnected region with the same label
Returns
-------
bboxes : list(array) of (N,) arrays
all the detected bounding boxes for all labelled regions where each bounding box is described by the region label and its top-left (x1,y1) and bottom right (x2,y2) coordinates given as a 1d array of label, x1,y1,x2,y2 concatenated if specified by the mean feature vector. The return will be a regular 2-d numpy array if prop_nan is True, otherwise if one region did not detect a valid bounding box the result would be a list of arrays
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.get_bbox_binary_2D` :
this function does the same for binary segmentation images
"""
import numpy as np
import skimage.measure as skmeasure
bboxes = []
for lab in np.setdiff1d(np.unique(label_img), bg_label):
mask = label_img==lab
if split_multi_regions==True:
# if split then we do a separate connected components
labelled_mask = skmeasure.label(mask, connectivity=2) #
uniq_regions = np.setdiff1d(np.unique(labelled_mask),0)
for region in uniq_regions:
mask_region = labelled_mask==region
bbox = get_bbox_binary_2D(mask_region, feature_img=feature_img)
if len(bbox) > 0:
bboxes.append(np.hstack([lab, bbox]))
else:
bbox = get_bbox_binary_2D(mask, feature_img=feature_img)
if len(bbox) > 0:
bboxes.append(np.hstack([lab, bbox]))
if len(bboxes)>0:
bboxes = np.vstack(bboxes)
return bboxes
# crops an image box given an image or given a binary
def crop_box_3D(im, thresh=None, pad=50):
r""" Derive the 3D bounding box given a volume intensity image or a volume binary image with optional additional padding. The input image is only specified if a constant scalar threshold, ``thresh`` is provided.
Parameters
----------
im : array
input image
thresh : scalar
if None, the input image will be assumed binary and the bounding box will be determined by the largest connected component. If not None, the image is first binarised with ``im>=thresh``.
pad : int
the isotropic padding to expand the found bounding box in all xyz-directions
Returns
-------
bbox : (6,) array
the bounding box described by its top-left (x1,y1,z1) and bottom right (x2,y2,z2) coordinates concatenated as a vector [x1,y1,z1,x2,y2,z2]
"""
import numpy as np
l,m,n = im.shape
if thresh is not None:
binary = im>=thresh
else:
binary = im.copy() # the input is already binarised.
binary = largest_component_vol(binary)
# min_zz, min_yy, min_xx, max_zz, max_yy, max_xx = bounding_box(binary)
ZZ, YY, XX = np.indices(binary.shape)
min_zz = np.min(ZZ[binary])
max_zz = np.max(ZZ[binary])
min_yy = np.min(YY[binary])
max_yy = np.max(YY[binary])
min_xx = np.min(XX[binary])
max_xx = np.max(XX[binary])
min_zz = np.clip(min_zz - pad, 0, l-1)
max_zz = np.clip(max_zz + pad, 0, l-1)
min_yy = np.clip(min_yy - pad, 0, m-1)
max_yy = np.clip(max_yy + pad, 0, m-1)
min_xx = np.clip(min_xx - pad, 0, n-1)
max_xx = np.clip(max_xx + pad, 0, n-1)
bbox = np.hstack([min_zz, min_yy, min_xx, max_zz, max_yy, max_xx])
return bbox
def segment_vol_thresh( vol, thresh=None, postprocess=True, post_ksize=3):
r""" Basic image segmentation based on automatic binary Otsu thresholding or a specified constant threshold with simple morphological postprocessing
Parameters
----------
vol : array
the input image to segment on intensity
thresh : scalar
if None, determine the constant threshold using Otsu binary thresholding else the binary is given by ``vol >= thresh``
postprocess : bool
if True, the largest connected component is retained, small holes are closed with a disk (2D) or ball kernel (3D) of radius given by ``post_ksize`` and finally the resulting binary is binary filled.
post_ksize : int
the size of the kernel to morphologically close small holes of ``postprocess=True``
Returns
-------
im_binary : array
the final binary segmentation image
im_thresh : scalar
the intensity threshold used
"""
from skimage.filters import threshold_otsu
import skimage.morphology as skmorph
from scipy.ndimage.morphology import binary_fill_holes
if thresh is None:
im_thresh = threshold_otsu(vol.ravel())
else:
im_thresh = thresh
im_binary = vol >= im_thresh
if postprocess:
im_binary = largest_component_vol(im_binary) # ok. here we keep only the largest component. -> this is crucial to create a watertight segmentation.
if len(vol.shape) == 3:
im_binary = skmorph.binary_closing(im_binary, skmorph.ball(post_ksize))
if len(vol.shape) == 2:
im_binary = skmorph.binary_closing(im_binary, skmorph.disk(post_ksize))
im_binary = binary_fill_holes(im_binary) # check there is no holes!
# return the volume and the threshold.
return im_binary, im_thresh
# also create a multi-level threshold? algorithm.
def multi_level_gaussian_thresh(vol, n_classes=3, n_samples=10000, random_state=None, scale=False):
r""" Segments an input volume image into n_classes using bootstrapped Gaussian mixture model (GMM) clustering. This allows multi-dimensional features and not just intensity to be used for segmentation. The final clustering will result in larger/smoother clusters than K-means.
Parameters
----------
vol : array
the 3D input image or 4D feature image to segment
n_classes : int
the number of desired clusters
n_samples : int
the number of randomly sampled pixels to fit the GMM
random_state : int
if not None, uses this number as the fixed random seed
scale : bool
if True, standard scales input features before GMM fitting, see `scipy.preprocessing.StandardScaler <https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html>`_
Returns
-------
labels_ : array
the final clustered image as a multi-label volume image, clusters are sorted in increasing order of the 1st feature by default
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.multi_level_kmeans_thresh` :
The K-Means clustering equivalent
"""
from sklearn.mixture import GaussianMixture
import numpy as np
model = GaussianMixture(n_components=n_classes, random_state=random_state)
volshape = vol.shape[:3]
if len(vol.shape) > 3:
vals = vol.reshape(-1,vol.shape[-1])
else:
vals = vol.ravel()[:,None]
if random_state is not None:
np.random.seed(random_state) # make this deterministic!.
random_select = np.arange(len(vals))
np.random.shuffle(random_select)
# if applying scale we need to do standard scaling of features.
if scale:
from sklearn.preprocessing import StandardScaler
vals = StandardScaler().fit_transform(vals) # apply the standard scaling of features prior to
X = vals[random_select[:n_samples]] # random sample to improve inference time.
model.fit(X)
if len(vol.shape) > 3:
labels_means = model.means_[:,0].ravel()
else:
labels_means = model.means_.ravel()
labels_order = np.argsort(labels_means)
labels = model.predict(vals)
labels_ = np.zeros_like(labels)
for ii, lab in enumerate(labels_order):
labels_[labels==lab] = ii
labels_ = labels_.reshape(volshape)
return labels_
def multi_level_kmeans_thresh(vol, n_classes=3, n_samples=10000, random_state=None, scale=False):
r""" Segments an input volume image into n_classes using bootstrapped K-Means clustering. This allows multi-dimensional features and not just intensity to be used for segmentation. The final clustering will result in smaller/higher-frequency clusters than Gaussian mixture models.
Parameters
----------
vol : array
the 3D input image or 4D feature image to segment
n_classes : int
the number of desired clusters
n_samples : int
the number of randomly sampled pixels to fit the K-Means
random_state : int
if not None, uses this number as the fixed random seed
scale : bool
if True, standard scales input features before GMM fitting, see `scipy.preprocessing.StandardScaler <https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html>`_
Returns
-------
labels_ : array
the final clustered image as a multi-label volume image, clusters are sorted in increasing order of the 1st feature by default
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.multi_level_gaussian_thresh` :
The Gaussian Mixture Model clustering equivalent
"""
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import numpy as np
model = KMeans(n_clusters=n_classes, init='k-means++', random_state=random_state)
volshape = vol.shape[:3]
if len(vol.shape) > 3:
vals = vol.reshape(-1,vol.shape[-1])
else:
vals = vol.ravel()[:,None]
if random_state is not None:
np.random.seed(random_state) # make this deterministic!.
# vals = StandardScaler().fit_transform(vals)
random_select = np.arange(len(vals))
np.random.shuffle(random_select)
if scale:
from sklearn.preprocessing import StandardScaler
vals = StandardScaler().fit_transform(vals)
X = vals[random_select[:n_samples]]
model.fit(X)
if len(vol.shape) > 3:
labels_means = model.cluster_centers_[:,0].ravel()
else:
labels_means = model.cluster_centers_.ravel()
labels_order = np.argsort(labels_means)
labels = model.predict(vals)
labels_ = np.zeros_like(labels)
for ii, lab in enumerate(labels_order):
labels_[labels==lab] = ii
labels_ = labels_.reshape(volshape)
return labels_
def sdf_distance_transform(binary, rev_sign=True, method='edt'):
r""" Compute the signed distance function (SDF) of the shape specified by the input n-dimensional binary image. Signed distance function enables shape to be captured as a continuous function which is highly advantageous for shape arithmetic and machine learning applications.
see https://en.wikipedia.org/wiki/Signed_distance_function for more details on the SDF.
Parameters
----------
binary : array
input n-dimensional binary image
rev_sign : bool
if True, reverses the sign of the computed signed distance function. When this is True, the inside of the shape is +ve distances and -ve distances is the outside of the shape
method : str
specifies the method used to compute the distance transform
'edt' : str
This is the Euclidean distance transform computed with scipy.ndimage.distance_transform_edt
'fmm' : str
This is the geodesic distance transform computed with `scikit-fmm <https://github.com/scikit-fmm/scikit-fmm>`_ library
Returns
-------
res : array
the signed distance function, the same size as the input where the contours of the input binary has a distance of 0.
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.get_label_distance_transform` :
The multi-label equivalent but here we compute just the one-sided interior distance transform.
"""
import numpy as np
pos_binary = binary.copy()
neg_binary = np.logical_not(pos_binary)
if method == 'edt':
from scipy.ndimage import distance_transform_edt
res = distance_transform_edt(neg_binary) * neg_binary - (distance_transform_edt(pos_binary) - 1) * pos_binary
if method =='fmm':
import skmm
res = skmm.distance(neg_binary) * neg_binary - (skmm.distance(pos_binary) - 1) * pos_binary
if rev_sign:
res = res * -1
return res
def get_label_distance_transform(labelled, bg_label=0, normalise=False, rev_sign=False, method='edt'):
r""" Compute the distance function for each label of the input multi-labelled image. The distance function captures the shape as a continuous function which is used to express for example multiple cell instances in a single image for deep learning instance-level segmenters.
see https://en.wikipedia.org/wiki/Distance_transform for more details on the distance transform
see https://en.wikipedia.org/wiki/Signed_distance_function for more details on the signed distance function
Parameters
----------
labelled : array
input n-dimensional multi-labelled image
bg_label : int
the integer label of the background areas
normalise : bool
if True, normalizes the distance transform of each label by dividing by the maximum distance
rev_sign : bool
if True, reverses the sign of the computed signed distance function. When this is True, the inside of the shape is +ve distances and -ve distances is the outside of the shape
method : str
specifies the method used to compute the distance transform
'edt' : str
This is the Euclidean distance transform computed with scipy.ndimage.distance_transform_edt
'fmm' : str
This is the geodesic distance transform computed with `scikit-fmm <https://github.com/scikit-fmm/scikit-fmm>`_ library
Returns
-------
dist_tform : array
the distance transform of each labelled region with the same size as the input
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.sdf_distance_transform` :
The binary equivalent computing the double-sided interior and exterior signed distance transform.
"""
import numpy as np
if method == 'edt':
from scipy.ndimage import distance_transform_edt
dist_fnc = distance_transform_edt
if method == 'fmm':
import skfmm
dist_fnc = skfmm.distance
# iterate over all unique_labels.
uniq_labels = np.setdiff1d(np.unique(labelled), bg_label)
dist_tform = np.zeros(labelled.shape, dtype=np.float64)
for lab in uniq_labels:
binary_mask = labelled == lab
dist = dist_fnc(binary_mask)
if rev_sign:
dist = dist * -1
if normalise:
dist = dist / np.nanmax(dist)
dist_tform[binary_mask>0] = dist[binary_mask>0].copy()
return dist_tform
def gradient_watershed2D_binary(binary,
gradient_img=None,
smooth_sigma=1,
smooth_gradient=1,
delta=.5,
n_iter=10,
min_area=5,
eps=1e-12,
thresh_factor=None,
mask=None,
return_tracks=False,
interp_bool=False):
r""" Parses the instance level segmentation implicitly given as an input binary or a vector field.
The algorithm works as an inverse watershed.
Step 1: a grid of points is seeds on the image
Step 2: points are propagated for n_iter according to the gradient_img, condensing towards cell centers implicitly implied by the gradient image.
Step 3: individual cluster centers are found by binarisation and connected component, removing objects < min_area
result is an integer image the same size as binary.
Parameters
----------
binary : (MxN) numpy array
input binary image defining the voxels that need labeling
gradient_img : (MxNx2) numpy array
This is a gradient field such as that from applying np.array(np.gradient(img)).transpose(1,2,0) where img is a potential such as a distance transform or probability map.
smooth_sigma : scalar
controls the catchment area for identifying distinct cells at the final propagation position. Smaller smooth_sigma leads to more oversegmentation.
smooth_gradient : scalar
the isotropic sigma value controlling the Gaussian smoothing of the gradient field. More smoothing results in more cells grouped together
delta: scalar
the voxel size to propagate grid points per iteration. Related to the stability. If too small takes too long. If too large, might not converge. if delta=1, takes a 1 voxel step.
n_iter: int
the number of iterations to run. (To do: monitor convergence and break early to improve speed)
min_area: scalar
volume of cells < min_area are removed.
eps: float
a small number for numerical stability
thresh_factor: scalar
The final cells are identified by thresholding on a threshold mean+thresh_factor*std. Thresh_factor controls what is an object prior to connected components analysis
mask: (MxN) numpy array
optional binary mask to gate the region to parse labels for.
return_tracks : bool
if True, return the grid point trajectories
interp_bool : bool
if True, interpolate the gradient field when advecting at the cost of speed. If False, point positions are clipped and this is much faster.
Returns
-------
cell_seg_connected_original : (MxN)
an integer image where each unique int > 0 relates to a unique object such that object 1 is retrieved by cell_seg_connected_original==1.
tracks : Nx2
if return_tracks=True, returns as a second argument, the tracks of the initial seeded grid points to its final position
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.gradient_watershed3D_binary` :
Equivalent for 3D images
"""
import scipy.ndimage as ndimage
import numpy as np
import skimage.morphology as skmorph
import pylab as plt
import skimage.measure as skmeasure
import skimage.segmentation as sksegmentation
from tqdm import tqdm
def interp2(query_pts, grid_shape, I_ref, method='linear', cast_uint8=False):
import numpy as np
from scipy.interpolate import RegularGridInterpolator
spl = RegularGridInterpolator((np.arange(grid_shape[0]),
np.arange(grid_shape[1])),
I_ref, method=method, bounds_error=False, fill_value=0)
I_query = spl((query_pts[...,0],
query_pts[...,1]))
if cast_uint8:
I_query = np.uint8(I_query)
return I_query
# compute the signed distance transform
if gradient_img is not None:
sdf_normals = gradient_img.transpose(2,0,1) # use the supplied gradients!
sdf_normals = sdf_normals * binary[None,...]
else:
sdf_normals, sdf_binary = surf_normal_sdf(binary, smooth_gradient=smooth_gradient, eps=eps, norm_vectors=True)
sdf_normals = sdf_normals * binary[None,...]
# print(sdf_normals.shape)
grid = np.zeros(binary.shape, dtype=np.int32)
pts = np.argwhere(binary>0) # (N,ndim)
# print(pts.shape)
# plt.figure(figsize=(10,10))
# plt.imshow(binary)
# plt.plot(pts[:,1], pts[:,0], 'r.')
# plt.show()
tracks = [pts]
for ii in tqdm(np.arange(n_iter)):
pt_ii = tracks[-1].copy()
if interp_bool:
pts_vect_ii = np.array([interp2(pt_ii, binary.shape, I_ref=sdf_normals[ch], method='linear', cast_uint8=False) for ch in np.arange(len(sdf_normals))]).T
else:
pts_vect_ii = np.array([sdf_normals[ch][pt_ii[:,0].astype(np.int), pt_ii[:,1].astype(np.int)] for ch in np.arange(len(sdf_normals))]).T
pts_vect_ii = pts_vect_ii / (np.linalg.norm(pts_vect_ii, axis=-1)[:,None] + 1e-12)
pt_ii_next = pt_ii + delta*pts_vect_ii
pt_ii_next[:,0] = np.clip(pt_ii_next[:,0], 0, binary.shape[0]-1)
pt_ii_next[:,1] = np.clip(pt_ii_next[:,1], 0, binary.shape[1]-1)
tracks.append(pt_ii_next)
# plt.figure(figsize=(10,10))
# plt.imshow(binary)
# plt.plot(pt_ii_next[:,1], pt_ii_next[:,0], 'r.')
# plt.show()
tracks = np.array(tracks)
"""
a radius neighbor graph or kNN graph here may be much more optimal here.... or use hdbscan?
"""
# parse ...
votes_grid_acc = np.zeros(binary.shape)
votes_grid_acc[(tracks[-1][:,0]).astype(np.int),
(tracks[-1][:,1]).astype(np.int)] += 1. # add a vote.
# smooth to get a density (fast KDE estimation)
votes_grid_acc = ndimage.gaussian_filter(votes_grid_acc, sigma=smooth_sigma)
if thresh_factor is not None:
if mask is not None:
votes_grid_binary = votes_grid_acc >np.mean(votes_grid_acc[mask]) + thresh_factor*np.std(votes_grid_acc[mask])
else:
votes_grid_binary = votes_grid_acc >np.mean(votes_grid_acc) + thresh_factor*np.std(votes_grid_acc)
else:
votes_grid_binary = votes_grid_acc > np.mean(votes_grid_acc) # just threshold over the mean.
cell_seg_connected = skmeasure.label(votes_grid_binary, connectivity=1) # use the full conditional
cell_uniq_regions = np.setdiff1d(np.unique(cell_seg_connected),0)
if len(cell_uniq_regions)>0:
props = skmeasure.regionprops(cell_seg_connected)
areas = np.hstack([re.area for re in props])
invalid_areas = cell_uniq_regions[areas<=min_area]
for invalid in invalid_areas:
cell_seg_connected[cell_seg_connected==invalid] = 0
if cell_seg_connected.max() > 0:
cell_seg_connected = sksegmentation.relabel_sequential(cell_seg_connected)[0]
cell_seg_connected_original = np.zeros_like(cell_seg_connected)
cell_seg_connected_original[(pts[:,0]).astype(np.int),
(pts[:,1]).astype(np.int)] = cell_seg_connected[(tracks[-1][:,0]).astype(np.int),
(tracks[-1][:,1]).astype(np.int)]
if mask is not None:
cell_seg_connected[mask == 0] = 0
# plt.figure(figsize=(10,10))
# plt.imshow(cell_seg_connected)
# plt.show()
# plt.figure(figsize=(10,10))
# plt.imshow(cell_seg_connected_original)
# plt.show()
if return_tracks:
return cell_seg_connected_original, tracks
else:
return cell_seg_connected_original
def gradient_watershed3D_binary(binary,
gradient_img=None,
smooth_sigma=1,
smooth_gradient=1,
delta=1,
n_iter=100,
min_area=5,
eps=1e-12,
thresh_factor=None,
mask=None,
return_tracks=False,
interp_bool=False):
r""" Parses the instance level segmentation implicitly given as an input binary or a vector field.
The algorithm works as an inverse watershed.
Step 1: a grid of points is seeds on the image
Step 2: points are propagated for n_iter according to the gradient_img, condensing towards cell centers implicitly implied by the gradient image.
Step 3: individual cluster centers are found by binarisation and connected component, removing objects < min_area
result is an integer image the same size as binary.
Parameters
----------
binary : (MxNxL) numpy array
input binary image defining the voxels that need labeling
gradient_img : (MxNxLx3) numpy array
This is a gradient field such as that from applying np.array(np.gradient(img)).transpose(1,2,3,0) where img is a potential such as a distance transform or probability map.
smooth_sigma : scalar
controls the catchment area for identifying distinct cells at the final propagation position. Smaller smooth_sigma leads to more oversegmentation.
smooth_gradient : scalar
the isotropic sigma value controlling the Gaussian smoothing of the gradient field. More smoothing results in more cells grouped together
delta: scalar
the voxel size to propagate grid points per iteration. Related to the stability. If too small takes too long. If too large, might not converge. if delta=1, takes a 1 voxel step.
n_iter: int
the number of iterations to run. (To do: monitor convergence and break early to improve speed)
min_area: scalar
volume of cells < min_area are removed.
eps: float
a small number for numerical stability
thresh_factor: scalar
The final cells are identified by thresholding on a threshold mean+thresh_factor*std. Thresh_factor controls what is an object prior to connected components analysis
mask: (MxNxL) numpy array
optional binary mask to gate the region to parse labels for.
return_tracks : bool
if True, return the grid point trajectories
interp_bool : bool
if True, interpolate the gradient field when advecting at the cost of speed. If False, point positions are clipped and this is much faster.
Returns
-------
cell_seg_connected_original : (MxNxL)
an integer image where each unique int > 0 relates to a unique object such that object 1 is retrieved by cell_seg_connected_original==1.
tracks : Nx3
if return_tracks=True, returns as a second argument, the tracks of the initial seeded grid points to its final position
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.gradient_watershed2D_binary` :
Equivalent for 2D images
"""
import scipy.ndimage as ndimage
import numpy as np
import skimage.morphology as skmorph
import pylab as plt
import skimage.measure as skmeasure
import skimage.segmentation as sksegmentation
from tqdm import tqdm
def interp3(query_pts, grid_shape, I_ref, method='linear', cast_uint8=False):
from scipy.interpolate import RegularGridInterpolator
from scipy import ndimage
spl_3 = RegularGridInterpolator((np.arange(grid_shape[0]),
np.arange(grid_shape[1]),
np.arange(grid_shape[2])),
I_ref, method=method, bounds_error=False, fill_value=0)
I_query = spl_3((query_pts[...,0],
query_pts[...,1],
query_pts[...,2]))
if cast_uint8:
I_query = np.uint8(I_query)
return I_query
if gradient_img is not None:
sdf_normals = gradient_img.transpose(3,0,1,2) # use the supplied gradients!
sdf_normals = sdf_normals * binary[None,...]
else:
# compute the signed distance transform
sdf_normals, sdf_binary = surf_normal_sdf(binary, smooth_gradient=smooth_gradient, eps=eps, norm_vectors=True)
sdf_normals = sdf_normals * binary[None,...]
grid = np.zeros(binary.shape, dtype=np.int32)
pts = np.argwhere(binary>0) # (N,ndim)
tracks = [pts]
for ii in tqdm(np.arange(n_iter)):
pt_ii = tracks[-1].copy()
if interp_bool:
pts_vect_ii = np.array([interp3(pt_ii, binary.shape, I_ref=sdf_normals[ch], method='linear', cast_uint8=False) for ch in np.arange(len(sdf_normals))]).T
else:
pts_vect_ii = np.array([sdf_normals[ch][pt_ii[:,0].astype(np.int), pt_ii[:,1].astype(np.int), pt_ii[:,2].astype(np.int)] for ch in np.arange(len(sdf_normals))]).T
pts_vect_ii = pts_vect_ii / (np.linalg.norm(pts_vect_ii, axis=-1)[:,None] + 1e-12)
pt_ii_next = pt_ii + delta*pts_vect_ii
# clip to volume bounds
pt_ii_next[:,0] = np.clip(pt_ii_next[:,0], 0, binary.shape[0]-1)
pt_ii_next[:,1] = np.clip(pt_ii_next[:,1], 0, binary.shape[1]-1)
pt_ii_next[:,2] = np.clip(pt_ii_next[:,2], 0, binary.shape[2]-1)
tracks[-1] = pt_ii_next # overwrite
# plt.figure(figsize=(10,10))
# plt.imshow(binary.max(axis=0))
# plt.plot(pt_ii_next[:,2],
# pt_ii_next[:,1], 'r.')
# plt.show()
tracks = np.array(tracks)
# parse ...
votes_grid_acc = np.zeros(binary.shape)
votes_grid_acc[(tracks[-1][:,0]).astype(np.int),
(tracks[-1][:,1]).astype(np.int),
(tracks[-1][:,2]).astype(np.int)] += 1. # add a vote.
# smooth to get a density (fast KDE estimation)
votes_grid_acc = ndimage.gaussian_filter(votes_grid_acc, sigma=smooth_sigma)
if thresh_factor is not None:
if mask is not None:
votes_grid_binary = votes_grid_acc >np.mean(votes_grid_acc[mask]) + thresh_factor*np.std(votes_grid_acc[mask])
else:
votes_grid_binary = votes_grid_acc >np.mean(votes_grid_acc) + thresh_factor*np.std(votes_grid_acc)
else:
votes_grid_binary = votes_grid_acc > np.mean(votes_grid_acc) # just threshold over the mean.
cell_seg_connected = skmeasure.label(votes_grid_binary, connectivity=2)
cell_uniq_regions = np.setdiff1d(np.unique(cell_seg_connected),0)
if len(cell_uniq_regions)>0:
props = skmeasure.regionprops(cell_seg_connected)
areas = np.hstack([re.area for re in props])
invalid_areas = cell_uniq_regions[areas<=min_area]
for invalid in invalid_areas:
cell_seg_connected[cell_seg_connected==invalid] = 0
if cell_seg_connected.max() > 0:
cell_seg_connected = sksegmentation.relabel_sequential(cell_seg_connected)[0]
cell_seg_connected_original = np.zeros_like(cell_seg_connected)
cell_seg_connected_original[(pts[:,0]).astype(np.int),
(pts[:,1]).astype(np.int),
(pts[:,2]).astype(np.int)] = cell_seg_connected[(tracks[-1][:,0]).astype(np.int),
(tracks[-1][:,1]).astype(np.int),
(tracks[-1][:,2]).astype(np.int)]
if mask is not None:
cell_seg_connected[mask == 0] = 0
# plt.figure(figsize=(10,10))
# plt.imshow(cell_seg_connected.max(axis=0))
# plt.show()
# plt.figure(figsize=(10,10))
# plt.imshow(cell_seg_connected_original.max(axis=0))
# plt.show()
if return_tracks:
return cell_seg_connected_original, tracks
else:
return cell_seg_connected_original
def surf_normal_sdf(binary, smooth_gradient=None, eps=1e-12, norm_vectors=True):
r""" Given an input binary compute the signed distance function with positive distances for the shape interior and the gradient vector field of the signed distance function. The gradient vector field passes through the boundaries of the binary at normal angles.
Parameters
----------
binary : array
input n-dimensional binary image
smooth_gradient : scalar
if not None, Gaussian smoothes the gradient vector field with ``sigma=smooth_gradient``
eps : scalar
small value for numerical stabilty
norm_vectors : bool
if True, normalise the gradient vector field such that all vectors have unit magnitude
Returns
-------
sdf_vol_normal : array
the gradient vector field of the signed distance function of the binary
sdf_vol : array
the signed distance function of the binary, with positive distances denoting the interior and negative distances the exterior
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.sdf_distance_transform` :
For computing just the signed distance function
"""
import numpy as np
import scipy.ndimage as ndimage
sdf_vol = sdf_distance_transform(binary, rev_sign=True) # so that we have it pointing outwards!.
# compute surface normal of the signed distance function.
sdf_vol_normal = np.array(np.gradient(sdf_vol))
# smooth gradient
if smooth_gradient is not None: # smoothing needs to be done before normalization of magnitude.
sdf_vol_normal = np.array([ndimage.gaussian_filter(sdf, sigma=smooth_gradient) for sdf in sdf_vol_normal])
if norm_vectors:
sdf_vol_normal = sdf_vol_normal / (np.linalg.norm(sdf_vol_normal, axis=0)[None,:]+eps)
return sdf_vol_normal, sdf_vol
def edge_attract_gradient_vector(binary,
return_sdf=True,
smooth_gradient=None,
eps=1e-12,
norm_vectors=True,
rev_sign=False):
r""" Given an input binary compute an edge aware signed distance function which pulls all points in the volume towards the boundary edge of the binary. The construction is based on computing the signed distance function.
Parameters
----------
binary : array
input n-dimensional binary image
return_sdf : bool
if True, return the signed distance function
smooth_gradient : scalar
if not None, Gaussian smoothes the gradient vector field with ``sigma=smooth_gradient``
eps : scalar
small value for numerical stabilty
norm_vectors : bool
if True, normalise the gradient vector field such that all vectors have unit magnitude
rev_sign : bool
if True, create the opposite edge repelling field
Returns
-------
sdf_vol_vector : array
the edge attracting or edge repelling gradient vector field of the signed distance function of the binary
sdf_vol : array
the signed distance function of the binary, with positive distances denoting the interior and negative distances the exterior
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.surf_normal_sdf` :
Similar gradient vector field, but pulls every point in the volume towards a central point within the binary
"""
import numpy as np
import scipy.ndimage as ndimage
pos_binary = binary.copy()
neg_binary = np.logical_not(pos_binary)
sdf_vol_vector, sdf_vol = surf_normal_sdf(binary,
smooth_gradient=smooth_gradient,
eps=eps,
norm_vectors=norm_vectors)
# now we can invert the vectors....
sdf_vol_vector = (-sdf_vol_vector) * pos_binary[None,...] + (sdf_vol_vector) * neg_binary[None,...]
return sdf_vol_vector, sdf_vol
def mean_curvature_field(sdf_normal):
r""" Compute the mean curvature given a vector field, :math:`V`. This is defined as
.. math::
H = -\frac{1}{2}\nabla\cdot\left( V\right)
The output is a scalar field. The vector dimension is the first axis.
Parameters
----------
sdf_normal : array
input (d,) + n-dimensional gradient field
Returns
-------
H : array
output n-dimensional divergence
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.mean_curvature_binary` :
Function wraps this function to compute the mean curvature given a binary
"""
def divergence(f):
import numpy as np
"""
Computes the divergence of the vector field f, corresponding to dFx/dx + dFy/dy + ...
:param f: List of ndarrays, where every item of the list is one dimension of the vector field
:return: Single ndarray of the same shape as each of the items in f, which corresponds to a scalar field
"""
num_dims = len(f)
return np.ufunc.reduce(np.add, [np.gradient(f[i], axis=i) for i in range(num_dims)])
# add the negative so that it is consistent with a positive distance tranform for the internal!
H = -.5*(divergence(sdf_normal))# total curvature is the divergence of the normal.
return H
def mean_curvature_binary(binary, smooth=3, mask=True, smooth_gradient=None, eps=1e-12):
r""" All in one function to compute the signed distance function, :math:`\Phi`, its normalised gradient field, :math:`\nabla\Phi /|\nabla\Phi|` and the mean curvature defined as
.. math::
H = -\frac{1}{2}\nabla\cdot\left( \frac{\nabla \Phi}{|\nabla \Phi|}\right)
The output is a scalar field.
Parameters
----------
binary : array
input n-dimensional binary image
smooth : scalar
the sigma of the Gaussian smoother for smoothing the computed mean curvature field and the width of the derived surface mask if ``mask=True``
mask : bool
if True, the mean curvature is restricted to the surface captured by binary derived internally as a thin shell of width ``smooth``. Non surface values will then be returned as np.nan
smooth_gradient : scalar
if not None, Gaussian smoothes the gradient vector field with the provided sigma value before computing mean curvature
eps : scalar
small number for numerics
Returns
-------
H_normal : array
output n-dimensional mean curvature
sdf_vol_normal : array
(n,) + n-dimensional gradient of the signed distance function. The first axis is the vectors.
sdf_vol : array
n-dimensional signed distance function
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.mean_curvature_field` :
for the computation of mean curvature where the input vector field is the normalised gradient vector the binary signed distance function.
"""
import skimage.morphology as skmorph
import scipy.ndimage
import numpy as np
sdf_vol_normal, sdf_vol = surf_normal_sdf(binary, smooth_gradient=smooth_gradient, eps=eps)
H_normal = mean_curvature_field(sdf_vol_normal)
if smooth is not None:
H_normal = scipy.ndimage.gaussian_filter(H_normal, sigma=smooth)
if mask:
# do we really need to pass an additional mask here?
mask_outer = skmorph.binary_dilation(binary, skmorph.ball(smooth))
mask_inner = skmorph.binary_erosion(binary, skmorph.ball(smooth))
mask_binary = np.logical_and(mask_outer, np.logical_not(mask_inner))
H_normal[mask_binary==0] = np.nan
return H_normal, sdf_vol_normal, sdf_vol
def extract_2D_contours_img_and_curvature(binary, presmooth=None, k=4, error=0.1):
r""" Given an input binary image, extract the largest closed 2D contour and compute the curvature at every point of the curve using splines.
It is assumed there is only 1 region, 1 contour.
Parameters
----------
binary : (MxN) image
input 2D binary image
presmooth : scalar
if not None, smoothes the binary before running ``skimage.measure.find_contours`` with an isolevel of 0.5 to extract the 2D contour otherwise no smoothing is applied and we extract at isolevel of 0.
k : int
the polynomial order of the interpolating spline used for computing line curvature
error : scalar
The allowed error in the spline fitting. Controls the smoothness of the fitted spline. The larger the error, the more smooth the fitting and curvature value variation.
Returns
-------
contour : (N,2) array
array of xy coordinates of the contour line
contour_prime : (N,2) array
array of the 1st derivative of the contour line
contour_prime_prime : (N,2) array
array of the 2nd derivative of the contour line
kappa : (N,) array
array of the line curvature values at each point on the contour
orientation : angle in radians
the orientation of the region
See Also
--------
:func:`unwrap3D.Segmentation.segmentation.curvature_splines` :
Function used to compute line curvature
"""
import skimage.measure as skmeasure
import scipy.ndimage as ndimage
if presmooth:
binary_smooth = ndimage.gaussian_filter(binary*1, sigma=presmooth)
contour = skmeasure.find_contours(binary_smooth, 0.5)[0]
# contour = contour[np.argmax([len(cc) for cc in contour])] # largest
else:
binary_smooth = binary.copy()
contour = skmeasure.find_contours(binary_smooth, 0)[0]
# contour = contour[np.argmax([len(cc) for cc in contour])] # largest
orientation = skmeasure.regionprops(binary*1)[0].orientation # this is the complementary angle
orientation = np.pi/2. - orientation
contour = contour[:,::-1].copy() # to convert to x-y convention
# refine this with errors.
(x,y), (x_prime, y_prime), (x_prime_prime, y_prime_prime), kappa = curvature_splines(contour[:,0], y=contour[:,1], k=k, error=error)
contour = np.vstack([x,y]).T
contour_prime = np.vstack([x_prime,y_prime]).T
contour_prime_prime = np.vstack([x_prime_prime,y_prime_prime]).T
return contour, contour_prime, contour_prime_prime, kappa, orientation
# curvature of line using spline fitting.
def curvature_splines(x, y=None, k=4, error=0.1):
r"""Calculate the signed curvature of a 2D curve at each point using interpolating splines.
Parameters
----------
x,y : numpy.array(dtype=float) shape (n_points,)
or
y=None and
x is a numpy.array(dtype=complex) shape (n_points, )
In the second case the curve is represented as a np.array
of complex numbers.
k : int
The order of the interpolating spline
error : float
The admisible error when interpolating the splines
Returns
-------
[x_, y_] : list of [(n_points,), (n_points,)] numpy.array(dtype=float)
the x, y coordinates of the interpolating spline where curvature was evaluated.
[x_prime, y_prime] : list of [(n_points,), (n_points,)] numpy.array(dtype=float)
the x, y first derivatives of the interpolating spline
[x_prime_prime,y_prime_prime] : list of [(n_points,), (n_points,)] numpy.array(dtype=float)
the x, y second derivatives of the interpolating spline
curvature: numpy.array shape (n_points,)
The line curvature at each (x,y) point
"""
from scipy.interpolate import UnivariateSpline
# handle list of complex case
if y is None:
x, y = x.real, x.imag
t = np.arange(x.shape[0])
std = error * np.ones_like(x)
fx = UnivariateSpline(t, x, k=k, w=1 / np.sqrt(std))
fy = UnivariateSpline(t, y, k=k, w=1 / np.sqrt(std))
# fx = UnivariateSpline(t, x, k=k, s=smooth)
# fy = UnivariateSpline(t, y, k=k, s=smooth)
x_ = fx(t)
y_ = fy(t)
x_prime = fx.derivative(1)(t)
x_prime_prime = fx.derivative(2)(t)
y_prime = fy.derivative(1)(t)
y_prime_prime = fy.derivative(2)(t)
curvature = (x_prime * y_prime_prime - y_prime* x_prime_prime) / np.power(x_prime** 2 + y_prime** 2, 3. / 2)
# return [x_, y_], [xˈ, yˈ], curvature
return [x_, y_], [x_prime, y_prime], [x_prime_prime,y_prime_prime], curvature
def reorient_line(xy):
r""" Convenience function to reorient a given xy line to be anticlockwise orientation using the sign of the vector area
Parameters
----------
xy : (n_points,2) array
The input contour in xy coordinates
Returns
-------
xy_reorient : (n_points,2) array
The reoriented input contour in xy coordinates
"""
# mean_xy = np.mean(xy, axis=0)
# xy_ = xy - mean_xy[None,:]
# angle = np.arctan2(xy_[:,1], xy_[:,0])
# # angle_diff = np.mean(angle[1:] - angle[:-1]) # which way to go. # is this the correct way to average?
# angle_diff = np.mean(np.sign(angle[1:] - angle[:-1])) # correct assumption -> this average was key.
from ..Geometry import geometry as geom
area = geom.polyarea_2D(xy)
if np.sign(area) < 0:
xy_orient = xy[::-1].copy()
return xy_orient
else:
xy_orient = xy.copy()
return xy_orient
| 52,509 | 41.346774 | 442 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Segmentation/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Geometry/geometry.py
|
import numpy as np
def squicircle(uv, _epsilon = 0.0000000001):
r""" Compute the squicircle mapping unit disk coordinates to the square on [-1,1]x[-1,1]
see 'Analytical Methods for Squaring the Disc' - https://arxiv.org/abs/1509.06344
Parameters
----------
uv_ : (n_vertices,2) array
the coordinates of the the disk to square
_epsilon : scalar
small scalar for numerical stability
Returns
-------
square : (n_vertices,2) array
the coordinates of the corresponding square on [-1,1]x[-1,1]
"""
import numpy as np
#_fgs_disc_to_square
u = uv[:,0].copy()
v = uv[:,1].copy()
x = u.copy()
y = v.copy()
u2 = u * u
v2 = v * v
r2 = u2 + v2
uv = u * v
fouru2v2 = 4.0 * uv * uv
rad = r2 * (r2 - fouru2v2)
sgnuv = np.sign(uv)
sgnuv[uv==0.0] = 0.0
sqrto = np.sqrt(0.5 * (r2 - np.sqrt(rad)))
y[np.abs(u) > _epsilon] = (sgnuv / u * sqrto)[np.abs(u) > _epsilon]
x[np.abs(v) > _epsilon] = (sgnuv / v * sqrto)[np.abs(v) > _epsilon]
square = np.vstack([x,y]).T
return square
def elliptical_nowell(uv):
r""" Compute the elliptical of Nowell mapping unit disk coordinates to the square on [-1,1]x[-1,1]
see 'Analytical Methods for Squaring the Disc' - https://arxiv.org/abs/1509.06344
Parameters
----------
uv : (n_vertices,2) array
the coordinates of the the disk to square
Returns
-------
square : (n_vertices,2) array
the coordinates of the corresponding square on [-1,1]x[-1,1]
"""
import numpy as np
u = uv[:,0].copy()
v = uv[:,1].copy()
x = .5*np.sqrt(2.+2.*u*np.sqrt(2) + u**2 - v**2) - .5*np.sqrt(2.-2.*u*np.sqrt(2) + u**2 - v**2)
y = .5*np.sqrt(2.+2.*v*np.sqrt(2) - u**2 + v**2) - .5*np.sqrt(2.-2.*v*np.sqrt(2) - u**2 + v**2)
# there is one nan.
nan_select = np.isnan(x)
# check the nan in the original
x[nan_select] = np.sign(u[nan_select]) # map to 1 or -1
y[nan_select] = np.sign(v[nan_select])
square = np.vstack([x,y]).T
return square
def isotropic_scale_pts(pts, scale):
r""" Isotropic scaling of points with respect to the centroid.
Parameters
----------
pts : (nxd) array
an nxd matrix of d-dimension coordinates where d=2 for 2D and d=3 for 3D
Returns
-------
pts_ : (nxd) array
the rescaled coordinates
"""
pts_ = pts.reshape(-1,pts.shape[-1])
centroid = np.nanmean(pts_[pts_[:,0]>0], axis=0)
pts_diff = pts_ - centroid[None,:]
pts_ = centroid[None,:] + pts_diff*scale
pts_[pts_[:,0]==0] = 0 # don't get it?
pts_ = pts_.reshape(pts.shape)
return pts_
def rotmatrix3D_to_4D(rot_matrix3D):
r""" Convert a 3x3 transformation matrix on [x,y,z] to 4x4 transformation matrix in homogeneous coordinates operating on [x,y,z,1]
Parameters
----------
rot_matrix3D: (3x3) array
a general 3D transformation matrix
.. math::
T = \begin{bmatrix}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{32} & a_{33}
\end{bmatrix}
Returns
-------
rot_matrix: (4x4) array
the corresponding 4x4 homogeneous transformation matrix
.. math::
T' = \begin{bmatrix}
a_{11} & a_{12} & a_{13} & 0\\
a_{21} & a_{22} & a_{23} & 0\\
a_{31} & a_{32} & a_{33} & 0\\
0 & 0 & 0 & 1
\end{bmatrix}
"""
import numpy as np
rot_matrix = np.eye(4,4)
rot_matrix[:3,:3] = rot_matrix3D.copy()
return rot_matrix
def rot_pts_xyz(pts, rot_matrix, mean_pts=None, demean_pts=True):
r""" Rotate 3D points Given homogeneous 4x4 rotation matrix
Parameters
----------
pts : (nx3) array
an nx3 matrix of 3D (x,y,z) coordinates
rot_matrix : (4x4) array
a homogeneous 4x4 matrix which captures affine + translation transformation specified by A (3x3 top left submatrix) and (3x1 rightmost submatrix) respectively.
.. math::
\textbf{x}' = A\textbf{x} + T
mean_pts : (3,) array
a 3D vector specifying the designed centroid of affine transformation
demean_pts : bool
if True, the rotation matrix is applied with respect to the given mean_pts. If mean_pts=None, it is inferred as the mean (x,y,z) coordinate of the input points.
Returns
-------
rot_pts : (nx3) array
an nx3 matrix of the rotated 3D (x,y,z) coordinates
"""
if demean_pts:
if mean_pts is not None:
pts_ = pts - mean_pts[None,:]
else:
mean_pts = np.nanmean(pts, axis=0)
pts_ = pts - mean_pts[None,:]
else:
pts_ = pts.copy()
# homogeneous
pts_ = np.hstack([pts_,
np.ones(len(pts_))[:,None]])
rot_pts = rot_matrix.dot(pts_.T)[:3].T
if demean_pts:
rot_pts = rot_pts + mean_pts[None,:] # add back the mean.
return rot_pts
# functions to map uv image grid to sphere grid.
def img_2_angles(m,n):
r""" Given an (m,n) image compute the corresponding polar, :math:`\theta` and azimuthal, :math:`\phi` angles of the unit sphere for each pixel position such that :math:`(0,\lfloor n/2 \rfloor)` maps to the South pole and :math:`(m-1,\lfloor n/2 \rfloor)` maps to the North pole of the unit sphere
Given an image specifying the cartesian space, :math:`U\times V: [0,n]\times[0,m]`,
the corresponding angle space is, :math:`\phi\times \theta: [-\pi,\pi]\times[-\pi,0]`
Parameters
----------
m : int
the height of the image
n : int
the width of the image
Returns
-------
psi_theta_grid : (mxnx2) array
the corresponding :math:`(\phi,\theta)` coordinates for each :math:`(u,v)` image coordinate. ``psi_theta_grid[:,:,0]`` is :math:`\phi`, ``psi_theta_grid[:,:,1]`` is :math:`\theta`.
"""
import numpy as np
psi, theta = np.meshgrid(np.linspace(-np.pi, np.pi, n),
np.linspace(-np.pi, 0, m)) # elevation, rotation.
psi_theta_grid = np.dstack([psi, theta])
return psi_theta_grid
def img_pts_2_angles(pts2D, shape):
r""" Given select :math:`(u,v)` image coordinates of an :math:`m\times n` pixel image compute the corresponding (azimuthal, polar), :math:`(\phi,\theta)` coordinates with the convention that :math:`(0,\lfloor n/2 \rfloor)` maps to the South pole and :math:`(m-1,\lfloor n/2 \rfloor)` maps to the North pole of the unit sphere
.. math::
\phi &= -\pi + \frac{u}{n-1}\cdot 2\pi\\
\theta &= -\pi + \frac{v}{m-1} \cdot \pi\\
Parameters
----------
m : int
the height of the image
n : int
the width of the image
Returns
-------
psi_theta_angles : (nx2) array
the array of :math:`(\theta,\phi)` coordinates
"""
import numpy as np
m, n = shape
psi = pts2D[...,0]/float(n-1)*2*np.pi + (-np.pi) # transforms the x coordinate
theta = pts2D[...,1]/float(m-1)*np.pi + (-np.pi) # transforms the y coordinate
psi_theta_angles = np.vstack([psi, theta]).T
return psi_theta_angles
def angles_2_img(psi_theta_angles, shape):
r""" Given select (azimuthal, polar), :math:`(\phi,\theta)` coordinates find the corresponding :math:`(u,v)` image coordinates of an :math:`m\times n` pixel image with the convention that :math:`(0,\lfloor n/2 \rfloor)` maps to the South pole and :math:`(m-1,\lfloor n/2 \rfloor)` maps to the North pole of the unit sphere
.. math::
u &= \frac{\phi-(-\pi)}{2\pi}\cdot (n-1)\\
v &= \frac{\theta-(-\pi)}{\pi}\cdot (m-1)\\
Parameters
----------
psi_theta_angles : array
last dimension is 2 where ``psi_theta_grid[:,:,0]`` is :math:`\phi`, ``psi_theta_grid[:,:,1]`` is :math:`\theta`.
shape : (m,n) tuple
the height, width of the image grid
Returns
-------
xy_out : array
last dimension is 2 where ``xy_out[:,:,0]`` is :math:`u`, ``xy_out[:,:,1]`` is :math:`v`.
"""
import numpy as np
m, n = shape
x = (psi_theta_angles[...,0] - (-np.pi)) / (2*np.pi)*(n-1) #compute fraction
y = (psi_theta_angles[...,1] - (-np.pi)) / (np.pi)*(m-1)
xy_out = np.zeros(psi_theta_angles.shape)
xy_out[...,0] = x.copy()
xy_out[...,1] = y.copy()
return xy_out
def sphere_from_img_angles(psi_theta_angles):
r""" Given select (azimuthal, polar), :math:`(\phi,\theta)` coordinates compute the corresponding :math:`(x,y,z)` cartesian coordinates of the unit sphere.
.. math::
x &= \sin\theta\cos\phi\\
y &= \sin\theta\sin\phi\\
z &= \cos\theta
Parameters
----------
psi_theta_angles : (n,2) array
last dimension is 2 where ``psi_theta_grid[:,:,0]`` is :math:`\phi`, ``psi_theta_grid[:,:,1]`` is :math:`\theta`.
Returns
-------
xyz : (n,3) array
the :math:`(x,y,z)` cartesian coordinates on the unit sphere.
"""
import numpy as np
x = psi_theta_angles[:,0] # psi
y = psi_theta_angles[:,1] # theta
xyz = np.vstack([np.sin(y)*np.cos(x), np.sin(y)*np.sin(x), np.cos(y)]).T
return xyz
def img_angles_from_sphere(xyz3D):
r""" Given select :math:`(x,y,z)` cartesian coordinates of the unit sphere find the (azimuthal, polar), :math:`(\phi,\theta)` coordinates
.. math::
\phi &= -\cos^{-1}{z}\\
\theta &= -\tan^{-1}{-\frac{y}{x}}
with appropriate transformation so that
.. math::
\phi &\in [-\pi,\pi]\\
\theta &\in [-\pi,0]
Parameters
----------
xyz3D : (n,3) array
(x,y,z) coordinates
Returns
-------
psitheta : (n,2) array
the :math:`(\phi,\theta)` azimuthal, polar coordinates
"""
import numpy as np
theta = np.arccos(xyz3D[...,2]) * -1
theta[theta==0] = 0
psi = np.arctan2(xyz3D[...,1], -xyz3D[...,0]) * -1
psi[psi==0] = 0
# restrict into the interval [-pi,0] x [-pi,pi]
theta[theta<np.pi] = theta[theta<np.pi] + np.pi
theta[theta>0] = theta[theta>0] - np.pi
psi[psi<np.pi] = psi[psi<np.pi] + 2*np.pi
psi[psi>np.pi] = psi[psi>np.pi] - 2*np.pi
psitheta = np.vstack([psi,theta]).T
return psitheta
# this is for rotating the volume -> not actually needed.
def rot_pts_z(pts, angle, mean_pts=None, demean_pts=True):
r""" Rotate 3D points around the z-axis given angle in radians
Parameters
----------
pts : (nx3) array
an nx3 matrix of 3D (x,y,z) coordinates
angle : scalar
rotation angle around the z-axis given in radians
mean_pts : (3,) array
a 3D vector specifying the designed centroid of affine transformation
demean_pts : bool
if True, the rotation matrix is applied with respect to the given mean_pts. If mean_pts=None, it is inferred as the mean (x,y,z) coordinate of the input points.
Returns
-------
pts_new : (nx3) array
an nx3 matrix of the rotated 3D (x,y,z) coordinates
"""
matrix = np.array([[np.cos(angle), -np.sin(angle), 0],
[np.sin(angle), np.cos(angle), 0],
[0, 0, 1]])
if demean_pts:
if mean_pts is not None:
mean_pts = np.nanmean(pts, axis=0)
pts_ = pts - mean_pts[None,:]
else:
pts_ = pts.copy()
pts_new = matrix.dot(pts.T)
if demean_pts:
pts_new = pts_new + mean_pts[None,:] # add back the mean.
pts_new = pts_new.T
return pts_new
def rot_pts_y(pts, angle, mean_pts=None, demean_pts=True):
r""" Rotate 3D points around the y-axis given angle in radians
Parameters
----------
pts : (nx3) array
an nx3 matrix of 3D (x,y,z) coordinates
angle : scalar
rotation angle around the y-axis given in radians
mean_pts : (3,) array
a 3D vector specifying the designed centroid of affine transformation
demean_pts : bool
if True, the rotation matrix is applied with respect to the given mean_pts. If mean_pts=None, it is inferred as the mean (x,y,z) coordinate of the input points.
Returns
-------
pts_new : (nx3) array
an nx3 matrix of the rotated 3D (x,y,z) coordinates
"""
matrix = np.array([[np.cos(angle), 0, np.sin(angle)],
[0, 1, 0],
[-np.sin(angle), 0, np.cos(angle)]])
if demean_pts:
if mean_pts is not None:
mean_pts = np.nanmean(pts, axis=0)
pts_ = pts - mean_pts[None,:]
else:
pts_ = pts.copy()
pts_new = matrix.dot(pts.T)
if demean_pts:
pts_new = pts_new + mean_pts[None,:] # add back the mean.
pts_new = pts_new.T
return pts_new
def rot_pts_x(pts, angle, mean_pts=None, demean_pts=True):
r""" Rotate 3D points around the x-axis given angle in radians
Parameters
----------
pts : (nx3) array
an nx3 matrix of 3D (x,y,z) coordinates
angle : scalar
rotation angle around the x-axis given in radians
mean_pts : (3,) array
a 3D vector specifying the designed centroid of affine transformation
demean_pts : bool
if True, the rotation matrix is applied with respect to the given mean_pts. If mean_pts=None, it is inferred as the mean (x,y,z) coordinate of the input points.
Returns
-------
pts_new : (nx3) array
an nx3 matrix of the rotated 3D (x,y,z) coordinates
"""
matrix = np.array([[1, 0, 0],
[0, np.cos(angle), -np.sin(angle)],
[0, np.sin(angle), np.cos(angle)]])
if demean_pts:
if mean_pts is not None:
mean_pts = np.nanmean(pts, axis=0)
pts_ = pts - mean_pts[None,:]
else:
pts_ = pts.copy()
pts_new = matrix.dot(pts.T)
if demean_pts:
pts_new = pts_new + mean_pts[None,:] # add back the mean.
pts_new = pts_new.T
return pts_new
def get_rotation_x(theta):
r""" Construct the homogeneous 4x4 rotation matrix to rotate :math:`\theta` radians around the x-axis
.. math::
R_x(\theta) = \begin{bmatrix}
1 & 0 & 0 & 0\\
0 & \cos\theta & -\sin\theta & 0 \\
0 & \sin\theta & \cos\theta & 0 \\
0 & 0 & 0 & 1
\end{bmatrix}
Parameters
----------
theta : scalar
rotatiion angle in radians
Returns
-------
R_x : (4x4) array
the 4x4 homogeneous rotation matrix around the x-axis
"""
R_x = np.zeros((4,4))
R_x[-1:] = np.array([0,0,0,1])
R_x[:-1,:-1] = np.array([[1,0,0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]])
return R_x
def get_rotation_y(theta):
r""" Construct the homogeneous 4x4 rotation matrix to rotate :math:`\theta` radians around the y-axis
.. math::
R_y(\theta) = \begin{bmatrix}
\cos\theta & 0 & \sin\theta & 0\\
0 & 1 & 0 & 0 \\
-\sin\theta & 0 & \cos\theta & 0 \\
0 & 0 & 0 & 1
\end{bmatrix}
Parameters
----------
theta : scalar
rotatiion angle in radians
Returns
-------
R_y : (4x4) array
the 4x4 homogeneous rotation matrix around the y-axis
"""
R_y = np.zeros((4,4))
R_y[-1:] = np.array([0,0,0,1])
R_y[:-1,:-1] = np.array([[np.cos(theta), 0, np.sin(theta)],
[0, 1, 0],
[-np.sin(theta), 0, np.cos(theta)]])
return R_y
def get_rotation_z(theta):
r""" Construct the homogeneous 4x4 rotation matrix to rotate :math:`\theta` radians around the z-axis
.. math::
R_z(\theta) = \begin{bmatrix}
\cos\theta & -\sin\theta & 0 & 0\\
\sin\theta & \cos\theta & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1
\end{bmatrix}
Parameters
----------
theta : scalar
rotation angle in radians
Returns
-------
R_z : (4x4) array
the 4x4 homogeneous rotation matrix around the z-axis
"""
R_z = np.zeros((4,4))
R_z[-1:] = np.array([0,0,0,1])
R_z[:-1,:-1] = np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
return R_z
def rotation_matrix_xyz(angle_x,angle_y, angle_z, center=None, imshape=None):
r""" Construct the composite homogeneous 4x4 rotation matrix to rotate :math:`\theta_x` radians around the x-axis, :math:`\theta_y` radians around the y-axis,
:math:`\theta_z` radians around the z-axis, with optional specification of rotation center. One of ``center`` or ``imshape`` must be specified to fix the center of rotation.
The individual rotations are composited functionally in the order of x- then y- then z- rotations.
.. math::
R(\theta_x,\theta_y,\theta_z) = R_z(R_y(R_x)))
We then add the translation to put the output coordinates to the specified center :math:`T=(\bar{x},\bar{y},\bar{z})` after rotation. If ``center`` not specified then :math:`T=(0,0,0)`.
.. math::
A = \begin{pmatrix}
R &\bigm \| & T \\
\textbf{0} &\bigm \|& 1
\end{pmatrix}
For rotating a volumetric image we must first decenter before applying :math:`A`. The decentering translation matrix is
.. math::
A' = \begin{pmatrix}
\textbf{I} &\bigm \| & T' \\
\textbf{0} &\bigm \|& 1
\end{pmatrix}
where :math:`T'=(-\bar{x}',-\bar{y}',-\bar{z}')` and :math:`(\bar{x}',\bar{y}',\bar{z})` is either ``center`` or ``imshape``/2.
The final one-step transformation matrix is given by left matrix multiplication and this is what this function returns
.. math::
T_{final} = AA'
Parameters
----------
angle_x : scalar
x-axis rotation angle in radians
angle_x : scalar
x-axis rotation angle in radians
angle_x : scalar
x-axis rotation angle in radians
center : (x,y,z) array
centroid of the final rotated volume
imshape : (m,n,l) array
size of the volume transform will be applied to.
Returns
-------
T : (4x4) array
the composite 4x4 homogeneous rotation matrix
"""
import numpy as np
affine_x = get_rotation_x(angle_x)
affine_y = get_rotation_y(angle_y) # the top has coordinates (r, np.pi/2. 0)
affine_z = get_rotation_z(angle_z)
affine = affine_z.dot(affine_x.dot(affine_y))
if center is not None:
affine[:-1,-1] = center
if imshape is not None:
decenter = np.eye(4); decenter[:-1,-1] = [-imshape[0]//2, -imshape[1]//2, -imshape[2]//2]
else:
decenter = np.eye(4); decenter[:-1,-1] = -center
T = affine.dot(decenter)
return T
def shuffle_Tmatrix_axis_3D(Tmatrix, new_axis):
r""" Utility function to shift a 4x4 transformation matrix to conform to transposition of [x,y,z] coordinates. This is useful for example when converting between Python and Matlab where Matlab adopts a different convention in the specification of their transformation matrix.
Parameters
----------
Tmatrix : 4x4 array
4x4 homogeneous transformation matrix
new_axis : array-like
an array specifying the permutation of the (x,y,z) coordinate axis e.g. [1,0,2], [2,0,1]
Returns
-------
Tmatrix_new : 4x4 array
the corresponding 4x4 homogeneous transformation matrix matching the permutation of (x,y,z) specified by `new_axis`
"""
Tmatrix_new = Tmatrix[:3].copy()
Tmatrix_new = Tmatrix_new[new_axis,:] # flip rows first. (to flip the translation.)
Tmatrix_new[:,:3] = Tmatrix_new[:,:3][:,new_axis] #flip columns (ignoring translations)
Tmatrix_new = np.vstack([Tmatrix_new, [0,0,0,1]]) # make it homogeneous 4x4 transformation.
return Tmatrix_new
def rotate_vol(vol, angle, centroid, axis, check_bounds=True):
r""" Utility function to rotate a volume image around a given centroid, around a given axis specified by one of 'x', 'y', 'z' with the angle specified in degrees. If check_bounds is True, the output volume size will be appropriately determined to ensure the content is not clipped else it will return the rotated volume with the same size as the input
The rotation currently uses Dipy library.
Parameters
----------
vol : (MxNxL) array
input volume image
angle : scalar
rotation angle specified in degrees
centroid : (x,y,z) array
centroid of rotation specified as a vector
axis : str
one of x-, y-, z- independent axis of rotation
'x' :
x-axis rotation
'y' :
y-axis rotation
'z' :
z-axis rotation
check_bounds : bool
if True, the output volume will be resized to fit image contents
Returns
-------
vol_out : (MxNxL) array
the rotated volume image
"""
rads = angle/180.*np.pi
if axis == 'x':
rot_matrix = get_rotation_x(rads)
if axis == 'y':
rot_matrix = get_rotation_y(rads)
if axis == 'z':
rot_matrix = get_rotation_z(rads)
im_center = np.array(vol.shape)//2
rot_matrix[:-1,-1] = np.array(centroid)
decenter = np.eye(4); decenter[:-1,-1] = -np.array(im_center)
T = rot_matrix.dot(decenter)
# print(T)
if check_bounds:
vol_out = apply_affine_tform(vol, T,
sampling_grid_shape=None,
check_bounds=True,
contain_all=True,
codomain_grid_shape=None,
domain_grid2world=None,
codomain_grid2world=None,
sampling_grid2world=decenter)
else:
vol_out = apply_affine_tform(vol, T,
sampling_grid_shape=vol.shape)
return vol_out
def rotate_volume_xyz(vol, vol_center, angle_x, angle_y, angle_z, use_im_center=True, out_shape=None):
r""" Utility function to rotate a volume image around a given centroid, and different angles specified in degrees around x-, y-, z- axis. This function doesn't check bounds but allows a specification of the final shape.
The rotation currently uses Dipy library. The rotation will be applied in the order of x-, y-, then z-
Parameters
----------
vol : (MxNxL) array
input volume image
vol_center : (x,y,z) array
centroid of rotation specified as a vector
angle_x : scalar
x-axis rotation in degrees
angle_y : scalar
y-axis rotation in degrees
angle_z : scalar
z-axis rotation in degrees
use_im_center : bool
if True, rotate about the image center instead of the specified vol_center
out_shape : (m,n,l) tuple
shape of the final output volume which can be different from vol.shape
Returns
-------
rot_mat : 4x4 array
the rotation matrix applied
vol_out : (MxNxL) array
the final rotated volume
"""
import numpy as np
angle_x = angle_x/180. * np.pi
angle_y = angle_y/180. * np.pi
angle_z = angle_z/180. * np.pi
# construct the correction matrix and transform the image.
imshape = vol.shape
if use_im_center:
rot_mat = rotation_matrix_xyz(-angle_x, -angle_y, -angle_z, vol_center, imshape)
else:
rot_mat = rotation_matrix_xyz(-angle_x, -angle_y, -angle_z, vol_center) # negative angle is to match the pullback nature of getting intensities.
if out_shape is None:
vol_out = apply_affine_tform(vol, rot_mat, sampling_grid_shape=imshape)
else:
vol_out = apply_affine_tform(vol, rot_mat, sampling_grid_shape=out_shape)
return rot_mat, vol_out
def apply_affine_tform(volume, matrix, sampling_grid_shape=None, check_bounds=False, contain_all=False, domain_grid_shape=None, codomain_grid_shape=None, domain_grid2world=None, codomain_grid2world=None, sampling_grid2world=None):
r""" Given a homogeneous transformation matrix, creates an affine transform matrix and use Dipy library to apply the transformation.
see https://dipy.org/documentation/1.1.1./reference/dipy.align/ for more info on parameters.
Parameters
----------
volume : (MxNxL) array
input volume image
matrix : 4x4 array
the homogeneous transformation matrix
sampling_grid_shape : (m,n,l) tuple
the shape of the input volume
check_bounds : bool
if true check if the final shape needs to be modified to avoid clipping the pixels from the input
contain_all : bool
if true the final shape is specified avoid clipping of any of the pixels from the input
domain_grid_shape : bool
if True, rotate about the image center instead of the specified vol_center
codomain_grid_shape : (m,n,l) tuple
the shape of the default co-domain sampling grid. When transform_inverse is called to transform an image, the resulting image will have this shape, unless a different sampling information is provided. If None (the default), then the sampling grid shape must be specified each time the transform_inverse method is called.
domain_grid2world : 4x4 array
the grid-to-world transform associated with the domain grid. If None (the default), then the grid-to-world transform is assumed to be the identity.
codomain_grid2world : 4x4 array
the grid-to-world transform associated with the co-domain grid. If None (the default), then the grid-to-world transform is assumed to be the identity.
sampling_grid2world : 4x4 array
the grid-to-world transform associated with the sampling grid (specified by sampling_grid_shape, or by default self.codomain_shape). If None (the default), then the grid-to-world transform is assumed to be the identity.
Returns
-------
out : (MxNxL) array
the final rotated volume
Notes
-----
The various domain, codomain etc. are mostly relevant in MRI applications where there is discrepancy between world coordinates and image coordinates. For all practical purposes, user can just pass ``volume``, ``matrix``, ``sampling_shape``, ``check_bounds`` and ``contain_all``.
"""
import numpy as np
from dipy.align.imaffine import AffineMap
if domain_grid_shape is None:
domain_grid_shape = volume.shape
if codomain_grid_shape is None:
codomain_grid_shape = volume.shape
if check_bounds:
if contain_all:
in_out_corners, out_shape, tilt_tf_ = compute_transform_bounds(domain_grid_shape, matrix, contain_all=True)
else:
in_out_corners, out_shape = compute_transform_bounds(domain_grid_shape, matrix, contain_all=False)
tilt_tf_ = None
# print out_shape
affine_map = AffineMap(matrix,
domain_grid_shape=domain_grid_shape, domain_grid2world=domain_grid2world,
codomain_grid_shape=codomain_grid_shape, codomain_grid2world=codomain_grid2world)
if check_bounds:
out = affine_map.transform(volume, sampling_grid_shape=out_shape, sampling_grid2world=tilt_tf_)
else:
out = affine_map.transform(volume, sampling_grid_shape=sampling_grid_shape, sampling_grid2world=sampling_grid2world)
return out
def compute_transform_bounds(im_shape, tf, contain_all=True):
r""" This helper function is used by :func:`MicroscopySuite.Geometry.geometry.apply_affine_tform` to determine the minimum output size of the final volume image to avoid clipping pixels in the original after the application of a given transformation matrix
Parameters
----------
im_shape : (M,N,L) array
shape of the volume image
tf : 4x4 array
the homogeneous transformation matrix
contain_all : bool
specifies whether all of the original input volume pixels must be captured.
Returns
-------
in_out_corners : 8x3 array
the 8 corner points of the box containing the transformed input shape under tf
out_shape
the new size of the image.
tf_mod : 4x4 array
only returned if contain_all = True. This is a hack translation shift correction to make dipy play nice when the transformed coordinates is negative but we want to keep the full input volume in the final output.
"""
def general_cartesian_prod(objs):
import itertools
import numpy as np
out = []
for element in itertools.product(*objs):
out.append(np.array(element))
out = np.vstack(out)
return out
import numpy as np
obj = [[0, ii-1] for ii in list(im_shape)] # remember to be -1
in_box_corners = general_cartesian_prod(obj)
# unsure whether its left or right multiplication ! - i believe this should be the left multiplcation i,e, pts x tf.
out_box_corners = tf.dot(np.vstack([in_box_corners.T, np.ones(in_box_corners.shape[0])[None,:]]))[:-1].T
in_out_corners = (in_box_corners, out_box_corners)
if contain_all:
out_shape = np.max(out_box_corners, axis=0) - np.min(out_box_corners, axis=0)
out_shape = (np.rint(out_shape)).astype(np.int)
# to shift the thing, we need to change the whole world grid!.
mod_tf = np.min(out_box_corners, axis=0) # what is the required transformation parameters to get the shape in line? # double check? in terms of point clouds?
tf_mod = np.eye(4)
tf_mod[:-1,-1] = mod_tf
# this adjustment needs to be made in a left handed manner!.
# here we probably need to create an offset matrix then multiply this onto the tf_ which is a more complex case.... of transformation? # to avoid sampling issues.
return in_out_corners, out_shape, tf_mod
else:
out_shape = np.max(out_box_corners,axis=0) # this should touch the edges now right? #- np.min(out_box_corners,axis=0) # not quite sure what dipy tries to do ?
out_shape = (np.rint(out_shape)).astype(np.int)
return in_out_corners, out_shape
def xyz_2_spherical(x,y,z, center=None):
r""" General Cartesian, :math:`(x,y,z)` to Spherical, :math:`(r,\theta,\phi)` coordinate transformation where :math:`\theta` is the polar or elevation angle and :math:`\phi` the aziumthal or circular rotation angle.
.. math::
r &= \sqrt{\hat{x}^2+\hat{y}^2+\hat{z}^2}\\
\theta &= \cos^{-1}\frac{\hat{z}}{r} \\
\phi &= \tan^{-1}\frac{\hat{y}}{\hat{x}}
where :math:`\hat{x}=x-\bar{x}`, :math:`\hat{y}=y-\bar{y}`, :math:`\hat{z}=z-\bar{z}` are the demeaned :math:`(x,y,z)` coordinates.
Parameters
----------
x : array
x-coordinate
y : array
y-coordinate
z : array
z-coordinate
center : (x,y,z) vector
the centroid coordinate, :math:`(\bar{x}, \bar{y}, \bar{z})`, if center=None, the mean of the input :math:`(x, y, z)` is computed
Returns
-------
r : array
radial distance
polar : array
polar angle, :math:`\theta`
azimuthal : array
azimuthal angle, :math:`\phi`
"""
if center is None:
center = np.hstack([np.mean(x), np.mean(y), np.mean(z)])
x_ = x - center[0]
y_ = y - center[1]
z_ = z - center[2]
r = np.sqrt(x_**2+y_**2+z_**2)
polar = np.arccos(z_/r) # normal circular rotation (longitude)
azimuthal = np.arctan2(y_,x_) # elevation (latitude)
return r, polar, azimuthal
def spherical_2_xyz(r, polar, azimuthal, center=None):
r""" General Cartesian, :math:`(x,y,z)` to Spherical, :math:`(r,\theta,\phi)` coordinate transformation where :math:`\theta` is the polar or elevation angle and :math:`\phi` the aziumthal or circular rotation angle.
.. math::
x &= r\sin\theta\cos\phi + \bar{x}\\
y &= r\sin\theta\sin\phi + \bar{y}\\
z &= r\cos\theta + \bar{z}
where :math:`(\bar{x}, \bar{y}, \bar{z})` is the provided mean of :math:`(x,y,z)` coordinates. If ``center`` is not specified the origin :math:`(0, 0, 0)` is used.
Parameters
----------
r : array
radial distance
polar : array
polar angle, :math:`\theta`
azimuthal : array
azimuthal angle, :math:`\phi`
center : (x,y,z) vector
the centroid coordinate, :math:`(\bar{x}, \bar{y}, \bar{z})`, if center=None, the centroid is taken to be the origin :math:`(0, 0, 0)`
Returns
-------
x : array
x-coordinate
y : array
y-coordinate
z : array
z-coordinate
"""
if center is None:
center = np.hstack([0, 0, 0])
x = r*np.sin(polar)*np.cos(azimuthal)
y = r*np.sin(polar)*np.sin(azimuthal)
z = r*np.sin(polar)
x = x + center[0]
y = y + center[1]
z = z + center[2]
return x,y,z
def xyz_2_longlat(x,y,z, center=None):
r""" General Cartesian, :math:`(x,y,z)` to geographical longitude latitude, :math:`(r,\phi,\lambda)` coordinate transformation used in cartographic projections
.. math::
r &= \sqrt{\hat{x}^2+\hat{y}^2+\hat{z}^2}\\
\phi &= \sin^{-1}\frac{\hat{z}}{r} \\
\lambda &= \tan^{-1}\frac{\hat{y}}{\hat{x}}
where :math:`\hat{x}=x-\bar{x}`, :math:`\hat{y}=y-\bar{y}`, :math:`\hat{z}=z-\bar{z}` are the demeaned :math:`(x,y,z)` coordinates.
Parameters
----------
x : array
x-coordinate
y : array
y-coordinate
z : array
z-coordinate
center : (x,y,z) vector
the centroid coordinate, :math:`(\bar{x}, \bar{y}, \bar{z})`, if center=None, the mean of the input :math:`(x, y, z)` is computed
Returns
-------
r : array
radial distance
latitude : array
latitude angle, :math:`\lambda`
longitude : array
longitude angle, :math:`\phi`
"""
if center is None:
center = np.hstack([np.mean(x), np.mean(y), np.mean(z)])
x_ = x - center[0]
y_ = y - center[1]
z_ = z - center[2]
r = np.sqrt(x_**2+y_**2+z_**2)
latitude = np.arcsin(z_/r) # normal circular rotation (longitude)
longitude = np.arctan2(y_,x_) # elevation (latitude)
return r, latitude, longitude
def latlong_2_spherical(r,lat,long):
r""" Conversion from geographical longitude latitude, :math:`(r,\lambda,\phi)` to Spherical, :math:`(r,\theta,\phi)` coordinates
.. math::
r &= r\\
\theta &= \phi + \pi/2\\
\phi &= \lambda
see:
https://vvvv.org/blog/polar-spherical-and-geographic-coordinates
Parameters
----------
r : array
radial distance
long : array
longitude angle, :math:`\lambda`
lat : array
latitude angle, :math:`\phi`
Returns
-------
r : array
radial distance
polar : array
polar angle, :math:`\theta`
azimuthal : array
azimuthal angle, :math:`\phi`
"""
polar = lat + np.pi/2.
azimuthal = long
return r, polar, azimuthal
def spherical_2_latlong(r, polar, azimuthal):
r""" Conversion from Spherical, :math:`(r,\theta,\phi)` to geographical longitude latitude, :math:`(r,\lambda,\phi)` coordinates
.. math::
r &= r\\
\phi &= \theta - \pi/2\\
\lambda &= \phi
see:
https://vvvv.org/blog/polar-spherical-and-geographic-coordinates
Parameters
----------
r : array
radial distance
polar : array
polar angle, :math:`\theta`
azimuthal : array
azimuthal angle, :math:`\phi`
Returns
-------
r : array
radial distance
lat : array
latitude angle, :math:`\lambda`
long : array
longitude angle, :math:`\phi`
"""
lat = polar - np.pi/2.
long = azimuthal
return r, lat, long
def map_gnomonic(r, lon, lat, lon0=0, lat0=0):
r""" Gnomonic map projection of geographical longitude latitude coordinates to :math:`(x,y)` image coordinates
The gnomonic projection is a nonconformal map projection obtained by projecting points :math:`P_1` on the surface of a sphere from a sphere's center O to a point :math:`P` in a plane that is tangent to another point :math:`S` on the sphere surface. In a gnomonic projection, great circles are mapped to straight lines. The gnomonic projection represents the image formed by a spherical lens, and is sometimes known as the rectilinear projection.
The transformation equations for the plane tangent at the point :math:`S` having latitude phi and longitude lambda for a projection with central longitude :math:`\lambda_0` and central latitude :math:`\phi_0` are given by
.. math::
x &= r\cdot\frac{\cos\phi\sin(\lambda-\lambda_0)}{\cos c}\\
y &= r\cdot\frac{\cos\phi_0\sin\theta - \sin\phi_0\cos\phi\cos(\lambda-\lambda_0)}{\cos c}
where :math:`c` is the angular distance of the point :math:`(x,y)` from the center of the projection given by
.. math::
\cos c= \sin\phi_0\sin_\phi + \cos\phi_0\cos\phi\cos(\lambda-\lambda_0)
see :
https://mathworld.wolfram.com/GnomonicProjection.html
Parameters
----------
r : array
radial distance
lon : array
longitude angle, :math:`\lambda`
lat : array
latitude angle, :math:`\phi`
lon0 : scalar
central longitude
lat0 : scalar
central latitude
Returns
-------
x : array
x-coordinate in the plane
y : array
y-coordinate in the plane
"""
cos_c = np.sin(lat0)*np.sin(lat) + np.cos(lat0)*np.cos(lat)*np.cos(lon-lon0)
x = r*np.cos(lat)*np.sin(lon-lon0) / cos_c
y = r*(np.cos(lat0)*np.sin(lat) - np.sin(lat0)*np.cos(lat)*np.cos(lon-lon0))/ cos_c
return x, y
def azimuthal_ortho_proj3D(latlong, pole='pos'):
r"""Orthographic azimuthal or perspective projection of sphere onto a tangent plane. This is just the straight line projection in spherical coordinates to the plane and strictly projects a hemisphere. Clipping must be applied to prevent overlap specified by the `pole` parameter.
.. math::
x &= r\cos\phi\cos\lambda\\
y &= r\cos\phi\sin\lambda
see :
https://en.wikipedia.org/wiki/Orthographic_map_projection
Parameters
----------
latlong : list of arrays
list of `[r, lat, long]` coordinates
pole : str
if 'pos', the hemisphere specified by `lat <= 0` is projected else the hemisphere with `lat >= 0` is mapped
Returns
-------
x_select : array
the x-coordinate of input points from the chosen hemisphere
y_select : array
the y-coordinate of input points from the chosen hemisphere
select : array
binary mask specifying which of the input points were mapped to the plane
"""
r, lat, long = latlong
x = r*np.cos(lat)*np.cos(long)
y = r*np.cos(lat)*np.sin(long)
# determine clipping points
if pole == 'pos':
select = lat <= 0
else:
select = lat >= 0
x_select = x[select]
y_select = y[select]
return x_select, y_select, select
def azimuthal_equidistant(latlong, lat0=0, lon0=0):
r""" The azimuthal equidistance projection preserves radial distance emanating from the central point of the projection. It is neither equal-area nor conformal.
Let :math:`\phi_0` and :math:`\lambda_0` be the latitude and longitude of the center of the projection, then the transformation equations are given by
.. math::
x &= k'\cos\phi\sin(\lambda-\lambda_0)\\
y &= k'[\cos\phi_0\sin\phi-\sin\phi_0\cos\phi\cos(\lambda-\lambda_0)]
where,
.. math::
k' = \frac{c}{\sin c}
and :math:`c` is the angular distance of the point :math:`(x,y)` from the center of the projection given by
.. math::
\cos c= \sin\phi_0\sin_\phi + \cos\phi_0\cos\phi\cos(\lambda-\lambda_0)
see :
https://mathworld.wolfram.com/AzimuthalEquidistantProjection.html
Parameters
----------
latlong : list of arrays
list of `[r, lat, long]` coordinates
lat0 : scalar
central latitude
lon0 : scalar
central longitude
Returns
-------
x : array
x-coordinate in the plane
y : array
y-coordinate in the plane
"""
r, lat, lon = latlong
cos_c = np.sin(lat1)*np.sin(lat) + np.cos(lat1)*np.cos(lat)*np.cos(lon-lon0)
c = np.arccos(cos_c)
k_ = c/np.sin(c)
x_p = k_ * np.cos(lat) * np.sin(lon-lon0)
y_p = k_ * (np.cos(lat1)*np.sin(lat) - np.sin(lat1)*np.cos(lat)*np.cos(lon-lon0))
x = r*x_p
y = r*y_p
return x, y
def stereographic(u):
r""" Function which both stereographic projection of 3D unit sphere points to the 2D plane and from the 2D plane back to the sphere depending on the dimensionality of the input.
Mathematically the transformations are
From 2D plane to 3D sphere
.. math::
(u,v) \rightarrow \left( \frac{2u}{1+u^2+v^2}, \frac{2v}{1+u^2+v^2}, \frac{-1+u^2+v^2}{1+u^2+v^2}\right)
From 3D sphere to 2D plane
.. math::
(x,y,z) \rightarrow \left( \frac{x}{1-z}, \frac{y}{1-z}\right)
Parameters
----------
u : (N,) complex array or (N,2) array for plane or (N,3) for sphere points
the plane or sphere points. If coordinate dimensions is 3, assumes the 3D sphere points and the return will be the 2D plane points after stereographic projection
Returns
-------
v : (N,2) array of plane or (N,3) array of sphere points
"""
# % STEREOGRAPHIC Stereographic projection.
# % v = STEREOGRAPHIC(u), for N-by-2 matrix, projects points in plane to sphere
# % ; for N-by-3 matrix, projects points on sphere to plane
import numpy as np
if u.shape[-1] == 1:
u = np.vstack([np.real(u), np.imag(u)])
x = u[:,0].copy()
y = u[:,1].copy()
if u.shape[-1] < 3:
z = 1 + x**2 + y**2;
v = np.vstack([2*x / z, 2*y / z, (-1 + x**2 + y**2) / z]).T;
else:
z = u[:,2].copy()
v = np.vstack([x/(1.-z), y/(1.-z)]).T
return v
def fix_improper_rot_matrix_3D(rot_matrix):
r""" All rotational matrices are orthonormal, however only those with determinant = +1 constitute pure rotation matrices. Matrices with determinant = -1 involve a flip. This function is used to test a given 3x3 rotation matrix and if determinant = -1 make it determinant = + 1 by appropriately flipping the columns.
Parameters
----------
rot_matrix : 3x3 array
input rotation matrix of determinant = -1 or +1
Returns
-------
rot_matrix_fix : 3x3 matrix
a proper rotation matrix with determinant = +1
Notes
-----
Without loss of generality, we can turn an improper 3x3 rotation matrix into its proper equivalent by comparing sign with the +x, +y, +z axis.
Given a 3x3 rotation matrix, the function searches the 1st column vector and checks the x-component is positive i.e. in the same direction as the +x axis, if not it flips all the first column components by multiplying by -1. It then checks the second column component which should be alignment with the +y axis. The third vector by definition must be orthogonal to the first two therefore it does not need to be checked and is directly found by the cross-product.
"""
import numpy as np
if np.sign(np.linalg.det(rot_matrix)) < 0:
rot_matrix_fix = rot_matrix.copy()
for ii in np.arange(rot_matrix.shape[1]-1):
if np.sign(rot_matrix[ii,ii]) >= 0:
# nothing
pass
else:
rot_matrix_fix[:,ii] = -1*rot_matrix[:,ii]
last = np.cross(rot_matrix_fix[:,0], rot_matrix_fix[:,1])
last = last / (np.linalg.norm(last) + 1e-12)
rot_matrix_fix[:,-1] = last.copy()
return rot_matrix_fix
else:
rot_matrix_fix = rot_matrix.copy()
return rot_matrix_fix
def resample_vol_intensity_rotation(img, rot_matrix_fwd,
mean_ref=None,
mean_ref_out=None,
pts_ref=None,
pad=None,
out_shape=None,
max_lims_out=None,
min_lims_out=None):
r""" Utility function to rotate a volume image given a general affine transformation matrix. Options are provided to specify the center of rotation of the input and volume center in the output which may be differ to prevent clipping.
Unlike rotate_vol, this function does not require Dipy and is more flexible to tune.
Parameters
----------
img : (MxNxL) array
input volume image
rot_matrix_fwd : 4x4 array
the desired transformation matrix
mean_ref : (x,y,z) array
if specified, the centroid of rotation specified as a vector, to rotate the initial volume
mean_ref_out : (x,y,z) array
if specified, the centroid of rotation specified as a vector, to center the final output volume
pad : int
if pad is not None, this function will then compute the exact bounds of rotation to enable padding. If pad=None a volume the same size as input is returned.
out_shape : (M,N,L) tuple
specifies the desired output shape of the rotated volume, this will only be taken into account if pad is not None.
max_lims_out : (M,N,L) tuple
the maximum coordinate in each axis in the final rotated volume, if not specified it will be auto-inferred as the minimum bounding box
min_lims_out : (M,N,L) tuple
the minimum coordinate in each axis in the final rotated volume, if not specified it will be auto-inferred as the minimum bounding box
Returns
-------
img_pullback : (MxNxL) array
the final transformed volume image
mean_pts_img : (x,y,z) array
the centroid of the final transformed volume image
(min_lims, max_lims) : (3-tuple, 3-tuple)
returned only if pad is not None. These specify the real minimum and maximum of the coordinate bounding box when the forward transform is applied. The final volume is of shape equal to difference in these if the `out_shape` was not specified by the user.
"""
def map_intensity_interp3(query_pts, grid_shape, I_ref, method='linear', cast_uint8=False):
# interpolate instead of discretising to avoid artifact.
from scipy.interpolate import RegularGridInterpolator
#ZZ,XX,YY = np.indices(im_array.shape)
spl_3 = RegularGridInterpolator((np.arange(grid_shape[0]),
np.arange(grid_shape[1]),
np.arange(grid_shape[2])),
I_ref, method=method, bounds_error=False, fill_value=0)
I_query = spl_3((query_pts[...,0],
query_pts[...,1],
query_pts[...,2]))
if cast_uint8:
I_query = np.uint8(I_query)
return I_query
import numpy as np
if pts_ref is None:
XX, YY, ZZ = np.indices(img.shape) # get the full coordinates.
pts_ref = np.vstack([XX.ravel(),
YY.ravel(),
ZZ.ravel()]).T
if mean_ref is None:
mean_ref = np.nanmean(pts_ref,axis=0)
# # compute the forward transform to determine the bounds.
# forward_pts_tform = rot_matrix_fwd.dot((pts_ref-mean_ref[None,:]).T).T + mean_ref[None,:]
if pad is None:
# then we use the same volume size as the img.
rot_matrix_pulldown = np.linalg.inv(rot_matrix_fwd)
XX, YY, ZZ = np.indices(img.shape)
pts_img_orig = np.vstack([XX.ravel(),
YY.ravel(),
ZZ.ravel()]).T
if mean_ref_out is None:
mean_pts_img = np.nanmean(pts_img_orig, axis=0)
else:
mean_pts_img = mean_ref_out.copy()
pts_img_orig = rot_matrix_pulldown.dot((pts_img_orig-mean_pts_img[None,:]).T).T + mean_ref[None,:] # demean with respect to own coordinates, but mean_ref...
img_pullback = map_intensity_interp3(pts_img_orig,
img.shape,
I_ref=img, method='linear',
cast_uint8=False)
img_pullback = img_pullback.reshape(img.shape) # reshape to the correct shape.
# interpolate the original image.!
return img_pullback, mean_pts_img
else:
rot_matrix_pulldown = np.linalg.inv(rot_matrix_fwd)
# compute the forward transform to determine the bounds.
forward_pts_tform = rot_matrix_fwd.dot((pts_ref-mean_ref[None,:]).T).T + mean_ref[None,:]
if min_lims_out is None:
min_lims = np.nanmin(forward_pts_tform, axis=0)
else:
min_lims = min_lims_out.copy()
if max_lims_out is None:
max_lims = np.nanmax(forward_pts_tform, axis=0)
else:
max_lims = max_lims_out.copy()
# the range of the max-min gives the size of the volume + the padsize. (symmetric padding.)
# points then linearly establish correspondence.
# this vectorial represntation allows asymmetric handling.
print(min_lims, max_lims)
min_lims = min_lims.astype(np.int) - np.hstack(pad)
max_lims = (np.ceil(max_lims)).astype(np.int) + np.hstack(pad)
# we need to create new cartesian combination of datapoints.
if out_shape is None:
l, m, n = max_lims - min_lims
else:
l, m, n = out_shape
ll, mm, nn = np.indices((l,m,n))
# map this to 0-1 scale and reverse (xx - a) / (a-b) for general (a,b) intervals.
XX = ll/float(l) * (max_lims[0] - min_lims[0]) + min_lims[0]
YY = mm/float(m) * (max_lims[1] - min_lims[1]) + min_lims[1]
ZZ = nn/float(n) * (max_lims[2] - min_lims[2]) + min_lims[2]
pts_img_orig = np.vstack([XX.ravel(),
YY.ravel(),
ZZ.ravel()]).T
if mean_ref_out is None:
mean_pts_img = np.nanmean(forward_pts_tform, axis=0)
else:
mean_pts_img = mean_ref_out.copy()
pts_img_orig = rot_matrix_pulldown.dot((pts_img_orig-mean_pts_img[None,:]).T).T + mean_ref[None,:] # demean with respect to own coordinates, but mean_ref...
img_pullback = map_intensity_interp3(pts_img_orig,
img.shape,
I_ref=img, method='linear',
cast_uint8=False)
img_pullback = img_pullback.reshape((l,m,n)) # reshape to the correct shape.
return img_pullback, mean_pts_img, (min_lims, max_lims)
def minimum_bounding_rectangle(points):
r"""
Find the smallest bounding rectangle for a set of points.
Returns a set of points representing the corners of the bounding box.
code taken from https://gis.stackexchange.com/questions/22895/finding-minimum-area-rectangle-for-given-points
Parameters
----------
points: (nx2) array
an nx2 matrix of coordinates
Returns
-------
rval: (4x2) array
a 4x2 matrix of the coordinates specify the corners of the bounding box.
"""
from scipy.ndimage.interpolation import rotate
import numpy as np
from scipy.spatial import ConvexHull
pi2 = np.pi/2.
# get the convex hull for the points
hull_points = points[ConvexHull(points).vertices]
# calculate edge angles
edges = np.zeros((len(hull_points)-1, 2))
edges = hull_points[1:] - hull_points[:-1]
angles = np.zeros((len(edges)))
angles = np.arctan2(edges[:, 1], edges[:, 0])
angles = np.abs(np.mod(angles, pi2))
angles = np.unique(angles)
# find rotation matrices
# XXX both work
rotations = np.vstack([
np.cos(angles),
np.cos(angles-pi2),
np.cos(angles+pi2),
np.cos(angles)]).T
# rotations = np.vstack([
# np.cos(angles),
# -np.sin(angles),
# np.sin(angles),
# np.cos(angles)]).T
rotations = rotations.reshape((-1, 2, 2))
# apply rotations to the hull
rot_points = np.dot(rotations, hull_points.T)
# find the bounding points
min_x = np.nanmin(rot_points[:, 0], axis=1)
max_x = np.nanmax(rot_points[:, 0], axis=1)
min_y = np.nanmin(rot_points[:, 1], axis=1)
max_y = np.nanmax(rot_points[:, 1], axis=1)
# find the box with the best area
areas = (max_x - min_x) * (max_y - min_y)
best_idx = np.argmin(areas)
# return the best box
x1 = max_x[best_idx]
x2 = min_x[best_idx]
y1 = max_y[best_idx]
y2 = min_y[best_idx]
r = rotations[best_idx]
rval = np.zeros((4, 2))
rval[0] = np.dot([x1, y2], r)
rval[1] = np.dot([x2, y2], r)
rval[2] = np.dot([x2, y1], r)
rval[3] = np.dot([x1, y1], r)
return rval
def polyarea_2D(xy):
r""" compute the signed polygon area of a closed xy curve
Parameters
----------
xy : (N,2)
coordinates of the closed curve.
Returns
-------
signed_area : scalar
signed area, where a negative means the contour is clockwise instead of positive anticlockwise convention
"""
# check whether the last is the same as the first point.
check = sum([xy[0][ch]==xy[-1][ch] for ch in range(xy.shape[1])])
if check == xy.shape[1]:
# then the first = last point.
p = xy[:-1].copy()
else:
p = xy.copy()
signed_area = 0.5*(np.dot(p[:,0], np.roll(p[:,1],1)) - np.dot(p[:,1], np.roll(p[:,0],1))) # shoelace formula
return signed_area
def fit_1d_spline_and_resample(pts,
smoothing=1,
k=3,
n_samples=1000,
periodic=False):
r""" Fits a Parametric spline to given n-dimensional points using splines.
This function allows enforcement of periodicity in the points e.g. when the points are part of a closed contour. A common application is to fit a curve to spatial points coming from a geometric line object.
Parameters
----------
pts : (N,d)
d-dimension point cloud sampled from a line
smoothing : scalar
controls the degree of smoothing. if 0, spline will interpolate. The higher the more smoothing
k : int
order of the interpolating polynomial spline
n_samples : int
the number of samples points to equisample from the final fitted spline
periodic : bool
If True, enforce periodic or closure of the fitted spline. This is required for example when the input points come from a circle
Returns
-------
tck, u : tuple
(t,c,k) a tuple containing the vector of knots, the B-spline coefficients, and the degree of the spline. see ``scipy.interpolate.splprep``. To interpolate with this spline we can use ``scipy.interpolate.splev`` such as
pts_out : (n_samples, d)
the resampled points based on the fitted spline
.. code-block:: python
import scipy.interpolate as interpolate
import numpy as np
u_fine = np.linspace(0, 1, n_samples) # sample from 0-1 of the parameter t
pts_out = interpolate.splev(u_fine, tck)
"""
from scipy import interpolate
import numpy as np
# 1. fitting.
if periodic == True:
tck, u = interpolate.splprep(pts, per=1, k=k, s=smoothing)
else:
tck, u = interpolate.splprep(pts, k=k, s=smoothing)
# 2 reinterpolation.
u_fine = np.linspace(0, 1, n_samples)
pts_out = interpolate.splev(u_fine, tck)
return (tck, u), pts_out
| 57,256 | 33.265111 | 469 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Registration/registration.py
|
"""
This module implements various different registration algorithms
"""
# these that are commented out should now be incorporated into individual functions below
# from ..Utility_Functions import file_io as fio
# from ..Visualisation import imshowpair as imshowpair
# from ..Geometry import geometry as geom
# from transforms3d.affines import decompose44, compose
import numpy as np
def matlab_affine_register(fixed_file, moving_file, save_file, reg_config, multiscale=False):
r""" Use Python-Matlab interface to conduct affine registration. The transformed image is saved to file to bypass speed bottleneck in transferring Matlab to Python
Parameters
----------
fixed_file : filepath
the filepath of the image to be used as reference for registration.
moving_file : filepath
the filepath of the image to be registered to the fixed image.
save_file : filepath
the output filepath to save the registered image of the moving_file
reg_config : dict
Python dict specifying the parameters for running the registration. See :func:`unwrap3D.Parameters.params.affine_register_matlab` for the parameters required to be set.
multiscale : bool
if True, do multiscale registration given by the ``register3D_intensity_multiscale`` script, otherwise run the ``register3D_rigid_faster`` script.
Returns
-------
transform : 4x4 array
the forward homogeneous transformation matrix to map fixed to moving.
im1 : array
return the fixed image as numpy array from fixed_file if ``reg_config['return_img']!=1``. if ``reg_config['return_img']==1``, the transform is directly applied within Matlab and the result saved to save_file
im2_ : array
return the transformed moving image after applying the transform as a numpy array if ``reg_config['return_img']!=1``. if ``reg_config['return_img']==1``, the transform is directly applied within Matlab and the result saved to save_file
"""
import matlab.engine
import scipy.io as spio
import skimage.io as skio
from transforms3d.affines import decompose44, compose
from ..Geometry import geometry as geom
eng = matlab.engine.start_matlab()
if reg_config['view'] is not None:
# use initialisation.
initial_tf = reg_config['initial_tf']
# decompose the initialisation to comply with Matlab checks. # might be better ways to do this?
T,R,Z,S = decompose44(initial_tf) # S is shear!
if reg_config['type'] == 'similarity':
# initialise with just rigid instead -> checks on this normally are too stringent.
affine = compose(T, R, np.ones(3), np.zeros(3)) # the similarity criteria too difficult for matlab
if reg_config['type'] == 'rigid':
affine = compose(T, R, np.ones(3), np.zeros(3))
if reg_config['type'] == 'translation':
affine = compose(T, np.eye(3), np.ones(3), np.zeros(3))
if reg_config['type'] == 'affine':
affine = initial_tf.copy()
# save the tform as temporary for matlab to read.
spio.savemat('tform.mat', {'tform':affine}) # transpose for matlab
if multiscale == False:
transform = eng.register3D_rigid_faster(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 1, reg_config['downsample'],
reg_config['modality'], reg_config['max_iter'],
reg_config['type'],
reg_config['return_img'],
nargout=1)
else:
transform = eng.register3D_intensity_multiscale(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 1, reg_config['downsample'],
reg_config['modality'], reg_config['max_iter'],
reg_config['type'],
reg_config['return_img'],
nargout=1)
else:
if multiscale == False:
transform = eng.register3D_rigid_faster(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 0, reg_config['downsample'],
reg_config['modality'], reg_config['max_iter'],
reg_config['type'],
reg_config['return_img'],
nargout=1)
else:
# print('multiscale')
# convert to matlab arrays.
levels = matlab.double(reg_config['downsample'])
warps = matlab.double(reg_config['max_iter'])
transform = eng.register3D_intensity_multiscale(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 0, levels,
reg_config['modality'], warps,
reg_config['type'],
reg_config['return_img'],
nargout=1)
transform = np.asarray(transform)
if reg_config['return_img']!= 1:
# then the transform is applied within python
im1 = skio.imread(fixed_file)
im2 = skio.imread(moving_file)
im2_ = np.uint8(geom.apply_affine_tform(im2.transpose(2,1,0),
np.linalg.inv(transform),
np.array(im1.shape)[[2,1,0]]))
im2_ = im2_.transpose(2,1,0) # flip back
return transform, im1, im2_
else:
return transform
# add multiscale capability
def matlab_group_register_batch(dataset_files, ref_file, in_folder, out_folder, reg_config, reset_ref_steps=0, multiscale=True, debug=False):
r""" Temporal affine registration of an entire video using Matlab call.
Parameters
----------
dataset_files : list of files
list of img files arranged in increasing temporal order
ref_file : str
filepath of the initial reference file for registration.
in_folder : str
specifies the parent folder of the dataset_files. This string is replaced with the out_folder string in order to generate the save paths for the registered timepoints.
reg_config : dict
Python dict specifying the parameters for running the registration. See :func:`unwrap3D.Parameters.params.affine_register_matlab` for the parameters required to be set.
reset_ref_steps : int
if reset_ref_steps > 0, uses every nth registered file as the reference. default of 0 = fixed reference specified by ref_file, whilst 1 = sequential
multiscale : bool
if True, do multiscale registration given by the ``register3D_intensity_multiscale`` script, otherwise run the ``register3D_rigid_faster`` script.
debug : bool
if True, will plot for every timepoint the 3 mid-slices in x-y, y-z, x-z to qualitatively check registration. Highly recommended for checking parameters.
Returns
-------
tforms : array
the compiled 4x4 transformation matrices between all successive timepoints
tformfile : str
the filepath to the saved transforms
"""
import matlab.engine
import scipy.io as spio
import os
import shutil
import pylab as plt
from tqdm import tqdm
import skimage.io as skio
from ..Visualisation import imshowpair as imshowpair
from ..Geometry import geometry as geom
from ..Utility_Functions import file_io as fio
# start matlab engine.
eng = matlab.engine.start_matlab()
fio.mkdir(out_folder) # check output folder exists.
tforms = []
ref_files = []
# difference is now fixed_file is always the same one.
fixed_file = ref_file
all_save_files = np.hstack([f.replace(in_folder, out_folder) for f in dataset_files])
for i in tqdm(range(len(dataset_files))):
moving_file = dataset_files[i]
save_file = all_save_files[i]
if multiscale:
# print('multiscale')
levels = matlab.double(reg_config['downsample'])
warps = matlab.double(reg_config['max_iter'])
transform = eng.register3D_intensity_multiscale(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 0, levels,
reg_config['modality'], warps,
reg_config['type'],
reg_config['return_img'],
nargout=1)
else:
transform = eng.register3D_rigid_faster(str(fixed_file), str(moving_file), str(save_file),
'tform.mat', 0, reg_config['downsample'],
reg_config['modality'], reg_config['max_iter'],
reg_config['type'],
reg_config['return_img'],
nargout=1)
transform = np.asarray(transform) # (z,y,x)
tforms.append(transform)
ref_files.append(fixed_file) # which is the reference used.
# if reg_config['return_img'] != 1: # this is too slow and disabled.
im1 = skio.imread(fixed_file)
im2 = skio.imread(moving_file)
im2_ = np.uint8(geom.apply_affine_tform(im2.transpose(2,1,0), np.linalg.inv(transform), sampling_grid_shape=np.array(im1.shape)[[2,1,0]]))
im2_ = im2_.transpose(2,1,0) # flip back
# fio.save_multipage_tiff(im2_, save_file)
skio.imsave(save_file, im2_)
if debug:
# visualize all three possible cross sections for reference and checking.
fig, ax = plt.subplots(nrows=1, ncols=2)
imshowpair(ax[0], im1[im1.shape[0]//2], im2[im2.shape[0]//2])
imshowpair(ax[1], im1[im1.shape[0]//2], im2_[im2_.shape[0]//2])
fig, ax = plt.subplots(nrows=1, ncols=2)
imshowpair(ax[0], im1[:,im1.shape[1]//2], im2[:,im2.shape[1]//2])
imshowpair(ax[1], im1[:,im1.shape[1]//2], im2_[:,im2_.shape[1]//2])
fig, ax = plt.subplots(nrows=1, ncols=2)
imshowpair(ax[0], im1[:,:,im1.shape[2]//2], im2[:,:,im2.shape[2]//2])
imshowpair(ax[1], im1[:,:,im1.shape[2]//2], im2_[:,:,im2_.shape[2]//2])
plt.show()
if reset_ref_steps > 0:
# change the ref file.
if np.mod(i+1, reset_ref_steps) == 0:
fixed_file = save_file # change to the file you just saved.
# save out tforms into a .mat file.
tformfile = os.path.join(out_folder, 'tforms-matlab.mat')
tforms = np.array(tforms)
ref_files = np.hstack(ref_files)
spio.savemat(tformfile, {'tforms':tforms,
'ref_files':ref_files,
'in_files':dataset_files,
'out_files':all_save_files,
'reg_config':reg_config})
return tforms, tformfile
def COM_2d(im1, im2):
r""" Compute the center of mass between two images, im1 and im2 based solely on binary Otsu Thresholding. This can be used to compute the rough translational displacement.
Parameters
----------
im1 : array
n-dimension image 1
im2 : array
n-dimension image 2
Returns
-------
com1 : array
n-dimension center of mass coordinates of image 1
com2 :
n-dimension center of mass coordinates of image 2
"""
from scipy.ndimage.measurements import center_of_mass
from scipy.ndimage.morphology import binary_fill_holes
from skimage.filters import threshold_otsu
mask1 = binary_fill_holes(im1>=threshold_otsu(im1))
mask2 = binary_fill_holes(im2>=threshold_otsu(im2))
com1 = center_of_mass(mask1)
com2 = center_of_mass(mask2)
return com1, com2
# function to join two volume stacks
def simple_join(stack1, stack2, cut_off=None, blend=True, offset=10, weights=[0.7,0.3]):
r""" Joins two volumetric images, stack1 and stack2 in the first dimension by direct joining or linear weighting constrained to +/- offset to the desired ``cut_off`` slice number.
The constrained linear blending within the interval :math:`[x_c-\Delta x, x_c + \Delta x]` is given by
.. math::
I =
\Biggl \lbrace
{
w_2\cdot I_1 + w_1\cdot I_2 ,\text{ if }
{x\in [x_c, x_c + \Delta x]}
\atop
w_1\cdot I_1 + w_2\cdot I_2, \text{ if }
{x\in [x_c-\Delta x, x_c]}
}
where :math:`x_c` denotes the ``cut_off`` point. The weight reversal enables asymmetric weights to be define once but used twice.
Parameters
----------
stack1 : (MxNxL) array
volume image whose intensities will dominant in the first dimension when < ``cut_off``
stack2 : (MxNxL) array
volume image whose intensities will dominant in the first dimension when > ``cut_off``
cut_off : int
the slice number of the first dimension where the transition from stack2 to stack1 will occur
blend : bool
if blend==True, the join occurs directly at the cut_off point with simple array copying and there is no blending. If True then the linear blending as described occurs around the cut_off point.
offset : int
the +/- slice numbers around the cut_off to linearly blend the intensities of stack1 and stack2 for a smoother effect.
weights : 2 vector array
:math:`w_1=` ``weights[0]`` and :math:`w_2=` ``weights[1]``. The sum of weights should be 1.
Returns
-------
the blended image of the same image dimension
"""
if cut_off is None:
cut_off = len(stack1) // 2
if blend:
combined_stack = np.zeros_like(stack1)
combined_stack[:cut_off-offset] = stack1[:cut_off-offset]
combined_stack[cut_off-offset:cut_off] = weights[0]*stack1[cut_off-offset:cut_off]+weights[1]*stack2[cut_off-offset:cut_off]
combined_stack[cut_off:cut_off+offset] = weights[1]*stack1[cut_off:cut_off+offset]+weights[0]*stack2[cut_off:cut_off+offset]
combined_stack[cut_off+offset:] = stack2[cut_off+offset:]
else:
combined_stack = np.zeros_like(stack1)
combined_stack[:cut_off] = stack1[:cut_off]
combined_stack[cut_off:] = stack2[cut_off:]
return combined_stack
def sigmoid_join(stack1, stack2, cut_off=None, gradient=200, shape=1, debug=False):
r""" Joins two volumetric images, stack1 and stack2 in the first dimension using a sigmoid type blending function. Both stacks are assumed to be the same size.
The sigmoid has the following mathematical expression
.. math::
w_2 &= \frac{1}{\left( 1+e^{-\text{grad} (x - x_c)} \right)^{1/\text{shape}}} \\
w_1 &= 1 - w_2
where :math:`x_c` denoting the ``cut_off``.
The blended image is then the weighted sum
.. math::
I_{blend} = w_1\cdot I_1 + w_2\cdot I_2
see https://en.wikipedia.org/wiki/Generalised_logistic_function
Parameters
----------
stack1 : (MxNxL) array
volume image whose intensities will dominant in the first dimension when < ``cut_off``
stack2 : (MxNxL) array
volume image whose intensities will dominant in the first dimension when > ``cut_off``
cut_off : int
the slice number of the first dimension where the transition from stack2 to stack1 will occur
gradient : scalar
controls the sharpness of the transition between the two stacks
shape : scalar
controls the shape of the sigmoid, in particular introduces asymmetry in the shape
debug : bool
if True, will use Matplotlib to plot the computed sigmoid weights for checking.
Returns
-------
the blended image of the same image dimension
"""
if cut_off is None:
cut_off = len(stack1) // 2
def generalised_sigmoid( stack1, cut_off=cut_off, shape=shape, grad=gradient):
x = np.arange(0,stack1.shape[0])
weights2 = 1./((1+np.exp(-grad*(x - cut_off)))**(1./shape))
weights1 = 1. - weights2
return weights1, weights2
weights1, weights2 = generalised_sigmoid( stack1, cut_off=cut_off, shape=shape, grad=gradient)
if debug:
import pylab as plt
plt.figure()
plt.plot(weights1, label='1')
plt.plot(weights2, label='2')
plt.legend()
plt.show()
return stack1*weights1[:,None,None] + stack2*weights2[:,None,None]
def nonregister_3D_demons_matlab(infile1, infile2, savefile, savetransformfile, reg_config):
r""" This function uses Matlab's imregdemons function to run Demon's registration. The result is directly saved to disk.
Parameters
----------
infile1 : str
filepath of the reference static image
infile2 : str
filepath of the moving image to register to the fixed image
savefile : str
filepath to save the transformed moving image to
savetransformfile : str
filepath to save the displacement field to
reg_config : dict
parameters to pass to imregdemons. see :func:`unwrap3D.Parameters.params.demons_register_matlab`
Returns
-------
return_val : int
return value of 1 if Matlab execution was successful and completed
"""
import matlab.engine
eng = matlab.engine.start_matlab()
print(reg_config['level'], reg_config['warps'])
# alpha = matlab.single(reg_config['alpha'])
# level = matlab.double(reg_config['level'])
level = float(reg_config['level'])
warps = matlab.double(reg_config['warps'])
smoothing = float(reg_config['alpha'])
# add in additional options for modifying.
return_val = eng.nonrigid_register3D_demons(str(infile1), str(infile2), str(savefile),
str(savetransformfile),
level, warps, smoothing)
return return_val
def warp_3D_demons_tfm(infile, savefile, transformfile, downsample, direction=1):
r""" This function warps the input image file according to the deformation field specified in transformfile and saves the result in savefile.
If direction == 1 warp in the same direction else if direction == -1 in the reverse direction.
Parameters
----------
infile : str
filepath of the image to transform
savefile : str
filepath of transformed result
transformfile : str
filepath to the displacement field transform
downsample : int
this parameter specifies the highest level of downsampling the displacement field came from i.e. if the displacement field is the same size as the image then downsample=1. If the displacement field was generated at a scale 4x smaller than the input image then specify downsample=4 here.
The displacment field will be rescaled by this factor before applying to the input image.
direction : 1 or -1
if 1, warps the image in the same direction of the diplacement field. If -1 warps the image in the reverse direction of the displacement field
Returns
-------
return_val : int
if 1, the process completed successfully in Matlab
"""
import matlab.engine
eng = matlab.engine.start_matlab()
return_val = eng.warp_3D_demons(str(infile), str(savefile), str(transformfile), int(downsample), direction)
return return_val
def warp_3D_demons_matlab_tform_scipy(im, tformfile, direction='F', pad=20):
r""" Python-based warping of Matlab imregdemons displacement fields adjusting for the difference in coordinate convention.
Parameters
----------
im : (MxNxL) array
input 3D volumetric image to warp
tformfile : str
filepath to the displacement field transform
direction : 'F' or 'B'
if 'F' warps im in the forwards direction specified by the displacement field or if 'B' warps im in the backwards direction.
pad : int
optional isotropic padding applied to every image dimension before warping
Returns
-------
im_interp : (MxNxL) array
the warped 3D volumetric image
"""
import numpy as np
from scipy.ndimage import map_coordinates
from ..Utility_Functions import file_io as fio
dx,dy,dz = fio.read_demons_matlab_tform(tformfile, im.shape)
# print(dx.max(), dx.min())
im_ = im.copy()
if pad is not None:
im_ = np.pad(im_, [[pad,pad] for i in range(len(im_.shape))], mode='constant') # universally pad the volume by the edge values.
dx = np.pad(dx, [[pad,pad] for i in range(len(dx.shape))], mode='constant') # universally pad the volume by the edge values.
dy = np.pad(dy, [[pad,pad] for i in range(len(dy.shape))], mode='constant') # universally pad the volume by the edge values.
dz = np.pad(dz, [[pad,pad] for i in range(len(dz.shape))], mode='constant') # universally pad the volume by the edge values.
im_interp = warp_3D_displacements_xyz(im_, dx, dy, dz, direction=direction)
return im_interp
def warp_3D_displacements_xyz(im, dx, dy, dz, direction='F', ret_xyz=False, mode='nearest'):
r""" Warps an image with a 3D displacement field specified by arrays, optionally returning the corresponding coordinates where the image intensities were interpolated from in the image
Parameters
----------
im : (MxNxL) array
the input 3D volume image
dx : (MxNxL) array
the displacements in x-direction (first image axis)
dy : (MxNxL) array
the displacements in y-direction (second image axis)
dz : (MxNxL) array
the displacements in z-direction (third image axis)
direction : 'F' or 'B'
if 'F' warp image in the same direction as specified by (dx,dy,dz) or if 'B' warp image in the opposite direction of (-dx,-dy,-dz)
ret_xyz : bool
if True, return as a second output the x-, y- and z- coordinates in ``im`` where ``im_interp`` intensities were interpolated at
mode : str
one of the boundary modes specified as ``mode`` argument in `scipy.map_coordinates <https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html>`_
Returns
-------
im_interp : (MxNxL) array
the transformed image
[XX, YY, ZZ] : list of arrays
the x-, y- and z- coordinates of same array shape as im where ``im_interp`` intensities were taken from ``im``
"""
from scipy.ndimage import map_coordinates
import numpy as np
XX, YY, ZZ = np.indices(im.shape) # set up the interpolation grid.
if direction == 'F':
XX = XX + dx
YY = XX + dy
ZZ = ZZ + dz
if direction == 'B':
XX = XX - dx
YY = YY - dy
ZZ = ZZ - dz
im_interp = map_coordinates(im,
np.vstack([(XX).ravel().astype(np.float32),
(YY).ravel().astype(np.float32),
(ZZ).ravel().astype(np.float32)]), prefilter=False, order=1, mode=mode) # note the mode here refers to the boundary handling.
im_interp = im_interp.reshape(im.shape)
if ret_xyz:
return im_interp, [XX,YY,ZZ]
else:
return im_interp
def warp_3D_displacements_xyz_pts(pts3D, dxyz, direction='F'):
r""" Convenience function for warping forward or backward a 3D point cloud given the displacement field
If direction == 'F', the new points, :math:`(x',y',z')` are
.. math::
(x',y',z') = (x+dx, y+dy, z+dz)
If direction == 'B', the new points, :math:`(x',y',z')` are
.. math::
(x',y',z') = (x-dx, y-dy, z-dz)
Parameters
----------
pts3D : array
n-dimensional array with last dimension of size 3 for (x,y,z)
dxyz : array
n-dimensional array with last dimension of size 3 for (dx,dy,dz)
direction : 'F' or 'B'
if 'F' warp points in the same direction as specified by (dx,dy,dz) or if 'B' warp image in the opposite direction of (-dx,-dy,-dz)
Returns
-------
pts3D_warp : array
n-dimensional array with last dimension of size 3 for the new (x,y,z) coordinates after warping
"""
if direction == 'F':
pts3D_warp = pts3D + dxyz
if direction == 'B':
pts3D_warp = pts3D - dxyz
return pts3D_warp
def warp_3D_transforms_xyz(im, tmatrix, direction='F', ret_xyz=False):
r""" Warps a volume image with the given affine transformation matrix forward or reverse with trilinear interpolation, returning if specified the corresponding (x,y,z) grid points
Parameters
----------
im : (MxNxL) array
the input 3D volume image
tmatrix : (4x4) array
the homogeneous affine 3D transformation matrix
direction : 'F' or 'B'
if 'F' warp image with tmatrix or if 'B' warp image with the matrix inverse of tmatrix
ret_xyz : bool
if True, return as a second output the xyz- coordinates in ``im`` where ``im_interp`` intensities were interpolated at
Returns
-------
im_interp : (MxNxL) array
the transformed image
xyz_ : list of arrays
the xyz- coordinates of same array shape as im where ``im_interp`` intensities were taken from ``im``
"""
import numpy as np
from scipy.ndimage import map_coordinates
XX, YY, ZZ = np.indices(im.shape) # set up the interpolation grid.
xyz = np.vstack([(XX).ravel().astype(np.float32),
(YY).ravel().astype(np.float32),
(ZZ).ravel().astype(np.float32),
np.ones(len(ZZ.ravel()), dtype=np.float32)])
if direction == 'F':
xyz_ = tmatrix.dot(xyz)
if direction == 'B':
xyz_ = (np.linalg.inv(tmatrix)).dot(xyz)
im_interp = map_coordinates(im,
xyz_[:3], prefilter=False, order=1, mode='nearest')
im_interp = im_interp.reshape(im.shape)
# return also the coordinates that it maps to
if ret_xyz:
return im_interp, xyz_
else:
return im_interp
def warp_3D_transforms_xyz_pts(pts3D, tmatrix, direction='F'):
r""" Convenience function for warping forward or backward a 3D point cloud given an affine transform matrix
Parameters
----------
pts3D : array
n-dimensional array with last dimension of size 3 for (x,y,z)
tmatrix : (4x4) array
the homogeneous affine 3D transformation matrix
direction : 'F' or 'B'
if 'F' warp points with ``tmatrix`` or if 'B' warp points with the reverse transformation given by``np.linalg.inv(tmatrix)``, the matrix inverse
Returns
-------
pts3D_warp : array
n-dimensional array with last dimension of size 3 for the new (x,y,z) coordinates after warping
"""
import numpy as np
# first make homogeneous coordinates.
xyz = np.vstack([(pts3D[...,0]).ravel().astype(np.float32),
(pts3D[...,1]).ravel().astype(np.float32),
(pts3D[...,2]).ravel().astype(np.float32),
np.ones(len(pts3D[...,0].ravel()), dtype=np.float32)])
if direction == 'F':
xyz_ = tmatrix.dot(xyz)
if direction == 'B':
xyz_ = (np.linalg.inv(tmatrix)).dot(xyz)
pts3D_warp = (xyz_[:3].T).reshape(pts3D.shape)
return pts3D_warp
def warp_3D_transforms_xyz_similarity(im, translation=[0,0,0], rotation=np.eye(3), zoom=[1,1,1], shear=[0,0,0], center_tform=True, direction='F', ret_xyz=False, pad=50):
r""" Warps a volume image forward or reverse where the transformation matrix is explicitly given by the desired translation, rotation, zoom and shear matrices, returning if specified the corresponding (x,y,z) grid points and optional padding
Parameters
----------
im : (MxNxL) array
the input 3D volume image
translation : (3,) array
the global (dx,dy,dz) translation vector
rotation : (3x3) array
the desired rotations given as a rotation matrix
zoom : (3,) array
the independent scaling factor in x-, y-, z- directions
shear : (3,) array
the shearing factor in x-, y-, z- directions
center_tform : bool
if true, the transformation will be applied preserving ``im_center``
direction : 'F' or 'B'
if 'F' warp points with the specified transformation or if 'B' warp points by the reverse transformation
ret_xyz : bool
if True, return as a second output the xyz- coordinates in ``im`` where ``im_interp`` intensities were interpolated at
pad : int
if not None, the input image is prepadded with the same number of pixels given by ``pad`` in all directions before transforming
Returns
-------
im_interp : (MxNxL) array
the transformed image
xyz_ : list of arrays
the xyz- coordinates of same array shape as im where ``im_interp`` intensities were taken from ``im``
"""
"""
This function is mainly to test how to combine the coordinates with transforms.
pad enables an optional padding of the image.
"""
from scipy.ndimage import map_coordinates
from transforms3d.affines import compose
import numpy as np
# compose the 4 x 4 homogeneous matrix.
tmatrix = compose(translation, rotation, zoom, shear)
im_ = im.copy()
if pad is not None:
im_ = np.pad(im_, [[pad,pad] for i in range(len(im.shape))], mode='constant') # universally pad the volume by the edge values.
if center_tform:
im_center = np.array(im_.shape)//2
tmatrix[:-1,-1] = tmatrix[:-1,-1] + np.array(im_center)
decenter = np.eye(4); decenter[:-1,-1] = -np.array(im_center)
tmatrix = tmatrix.dot(decenter)
XX, YY, ZZ = np.indices(im_.shape) # set up the interpolation grid.
xyz = np.vstack([(XX).ravel().astype(np.float32),
(YY).ravel().astype(np.float32),
(ZZ).ravel().astype(np.float32),
np.ones(len(ZZ.ravel()), dtype=np.float32)])
if direction == 'F':
xyz_ = tmatrix.dot(xyz)
if direction == 'B':
xyz_ = (np.linalg.inv(tmatrix)).dot(xyz)
# needs more memory % does this actually work?
im_interp = map_coordinates(im_,
xyz_[:3], prefilter=False, order=1, mode='nearest')
im_interp = im_interp.reshape(im_.shape)
if ret_xyz:
# additional return of the target coordinates.
return im_interp, xyz_
else:
return im_interp
def warp_3D_transforms_xyz_similarity_pts(pts3D, translation=[0,0,0], rotation=np.eye(3), zoom=[1,1,1], shear=[0,0,0], center_tform=True, im_center=None, direction='F'):
r""" Convenience function for warping forward or backward a 3D point cloud where the transformation matrix is explicitly given by the desired translation, rotation, zoom and shear matrices
Parameters
----------
pts3D : array
n-dimensional array with last dimension of size 3 for (x,y,z)
translation : (3,) array
the global (dx,dy,dz) translation vector
rotation : (3x3) array
the desired rotations given as a rotation matrix
zoom : (3,) array
the independent scaling factor in x-, y-, z- directions
shear : (3,) array
the shearing factor in x-, y-, z- directions
center_tform : bool
if true, the transformation will be applied preserving ``im_center``
im_center : (3,) array
if None, the mean of ``pt3D`` in x-, y-, z- is taken as ``im_center`` and takes effect only if ``center_tform=True``
direction : 'F' or 'B'
if 'F' warp points with the specified transformation or if 'B' warp points by the reverse transformation
Returns
-------
pts3D_warp : array
n-dimensional array with last dimension of size 3 for the new (x,y,z) coordinates after warping
"""
from transforms3d.affines import compose
# compose the 4 x 4 homogeneous matrix.
tmatrix = compose(translation, rotation, zoom, shear)
if center_tform:
if im_center is None:
im_center = np.hstack([np.nanmean(pts3D[...,ch]) for ch in pts3D.shape[-1]])
# im_center = np.array(im.shape)//2
tmatrix[:-1,-1] = tmatrix[:-1,-1] + np.array(im_center)
decenter = np.eye(4); decenter[:-1,-1] = -np.array(im_center)
tmatrix = tmatrix.dot(decenter)
# first make homogeneous coordinates.
xyz = np.vstack([(pts3D[...,0]).ravel().astype(np.float32),
(pts3D[...,1]).ravel().astype(np.float32),
(pts3D[...,2]).ravel().astype(np.float32),
np.ones(len(pts3D[...,0].ravel()), dtype=np.float32)])
if direction == 'F':
xyz_ = tmatrix.dot(xyz)
if direction == 'B':
xyz_ = (np.linalg.inv(tmatrix)).dot(xyz)
pts3D_warp = (xyz_[:3].T).reshape(pts3D.shape)
return pts3D_warp
def smooth_and_resample(image, shrink_factors, smoothing_sigmas):
""" Utility function used in :func:`unwrap3D.Registration.registration.multiscale_demons` for generating multiscale image pyramids for registration based on the SimpleITK library
see SimpleITK notebooks, https://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/66_Registration_Demons.html
Parameters
----------
image : SimpleITK image
The image we want to resample.
shrink_factors : scalar or array
Number(s) greater than one, such that the new image's size is original_size/shrink_factor.
smoothing_sigma(s): scalar or array
Sigma(s) for Gaussian smoothing, this is in physical units, not pixels.
Returns
-------
image_resample : SimpleITK image
Image which is a result of smoothing the input and then resampling it using the given sigma(s) and shrink factor(s).
"""
import SimpleITK as sitk
import numpy as np
if np.isscalar(shrink_factors):
shrink_factors = [shrink_factors]*image.GetDimension()
if np.isscalar(smoothing_sigmas):
smoothing_sigmas = [smoothing_sigmas]*image.GetDimension()
smoothed_image = sitk.SmoothingRecursiveGaussian(image, smoothing_sigmas)
original_spacing = image.GetSpacing()
original_size = image.GetSize()
new_size = [int(sz/float(sf) + 0.5) for sf,sz in zip(shrink_factors,original_size)]
new_spacing = [((original_sz-1)*original_spc)/(new_sz-1)
for original_sz, original_spc, new_sz in zip(original_size, original_spacing, new_size)]
image_resample = sitk.Resample(smoothed_image, new_size, sitk.Transform(),
sitk.sitkLinear, image.GetOrigin(),
new_spacing, image.GetDirection(), 0.0,
image.GetPixelID())
return image_resample
def multiscale_demons(registration_algorithm,
fixed_image, moving_image, initial_transform = None,
shrink_factors=None, smoothing_sigmas=None):
r""" Run the given registration algorithm in a multiscale fashion. The original scale should not be given as input as the
original images are implicitly incorporated as the base of the pyramid.
We use the algorithm here to run demons registration in multiscale hence the name.
see SimpleITK notebooks, https://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/66_Registration_Demons.html
Parameters
----------
registration_algorithm : SimpleITK algorithm instance
Any registration algorithm in `SimpleITK <https://simpleitk.readthedocs.io/en/master/filters.html>`_ that has an Execute(fixed_image, moving_image, displacement_field_image) method.
fixed_image: SimpleITK image
This is the reference image. Resulting transformation maps points from this image's spatial domain to the moving image spatial domain.
moving_image : SimpleITK image
This is the image to register to the fixed image. Resulting transformation maps points from the fixed_image's spatial domain to this image's spatial domain.
initial_transform : SimpleITK transform
Any SimpleITK transform, used to initialize the displacement field.
shrink_factors : list of lists or scalars
Shrink factors relative to the original image's size. When the list entry, shrink_factors[i], is a scalar the same factor is applied to all axes.
When the list entry is a list, shrink_factors[i][j] is applied to axis j. This allows us to specify different shrink factors per axis. This is useful
in the context of microscopy images where it is not uncommon to have unbalanced sampling such as a 512x512x8 image. In this case we would only want to
sample in the x,y axes and leave the z axis as is: [[[8,8,1],[4,4,1],[2,2,1]].
smoothing_sigmas : list of lists or scalars
Amount of smoothing which is done prior to resmapling the image using the given shrink factor. These are in physical (image spacing) units.
Returns
-------
SimpleITK.DisplacementFieldTransform
"""
import SimpleITK as sitk
import numpy as np
# Create image pyramid in a memory efficient manner using a generator function.
# The whole pyramid never exists in memory, each level is created when iterating over
# the generator.
def image_pair_generator(fixed_image, moving_image, shrink_factors, smoothing_sigmas):
end_level = 0
start_level = 0
if shrink_factors is not None:
end_level = len(shrink_factors)
for level in range(start_level, end_level):
f_image = smooth_and_resample(fixed_image, shrink_factors[level], smoothing_sigmas[level])
m_image = smooth_and_resample(moving_image, shrink_factors[level], smoothing_sigmas[level])
yield(f_image, m_image)
yield(fixed_image, moving_image)
# Create initial displacement field at lowest resolution.
# Currently, the pixel type is required to be sitkVectorFloat64 because
# of a constraint imposed by the Demons filters.
if shrink_factors is not None:
original_size = fixed_image.GetSize()
original_spacing = fixed_image.GetSpacing()
s_factors = [shrink_factors[0]]*len(original_size) if np.isscalar(shrink_factors[0]) else shrink_factors[0]
df_size = [int(sz/float(sf) + 0.5) for sf,sz in zip(s_factors,original_size)]
df_spacing = [((original_sz-1)*original_spc)/(new_sz-1)
for original_sz, original_spc, new_sz in zip(original_size, original_spacing, df_size)]
else:
df_size = fixed_image.GetSize()
df_spacing = fixed_image.GetSpacing()
if initial_transform:
initial_displacement_field = sitk.TransformToDisplacementField(initial_transform,
sitk.sitkVectorFloat64,
df_size,
fixed_image.GetOrigin(),
df_spacing,
fixed_image.GetDirection())
else:
initial_displacement_field = sitk.Image(df_size, sitk.sitkVectorFloat64, fixed_image.GetDimension())
initial_displacement_field.SetSpacing(df_spacing)
initial_displacement_field.SetOrigin(fixed_image.GetOrigin())
# Run the registration.
# Start at the top of the pyramid and work our way down.
for f_image, m_image in image_pair_generator(fixed_image, moving_image, shrink_factors, smoothing_sigmas):
initial_displacement_field = sitk.Resample (initial_displacement_field, f_image)
initial_displacement_field = registration_algorithm.Execute(f_image, m_image, initial_displacement_field)
return sitk.DisplacementFieldTransform(initial_displacement_field)
def SITK_multiscale_affine_registration(vol1, vol2,
imtype=16,
p12=None,
rescale_intensity=True,
centre_tfm_model='geometry',
tfm_type = 'rigid',
metric='Matte',
metric_numberOfHistogramBins=16,
sampling_intensity_method='random',
MetricSamplingPercentage=0.1,
shrink_factors = [1],
smoothing_sigmas = [0],
optimizer='gradient',
optimizer_params=None,
eps=1e-12):
r""" Main function to affine register two input volumes using SimpleITK library in a multiscale manner.
Affine registration includes the following transformations
- rigid (rotation + translation)
- iso_similarity (isotropic scale + rigid)
- aniso_similarity (anisotropic scale + rigid)
- affine (skew + aniso_similarity)
see SimpleITK notebooks, https://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/61_Registration_Introduction_Continued.html
Parameters
----------
vol1 : (MxNxL) array
reference volume given as a Numpy array
vol2 : (MxNxL) array
volume to register to vol2, given as a Numpy array
imtype : int
specifies the -bit of the image e.g. 8-bit, 16-bit etc. Used to normalize the intensity if ``rescale_intensity=False``
p12 : (p1,p2) tuple
if provided, vol1 and vol2 are constract enhanced using percentage intensity normalization
rescale_intensity : bool
if True, does min-max scaling of image intensities in the two volumes independently before registering. This follows percentage intensity normalization if specified.
centre_tfm_model : str
specifies the initial centering model. This is one of two options. For microscopy, we find 'geometry' has less jitter and is best.
tfm_type : str
Type of affine transform from 4. The more complex, the longer the registration.
'rigid' :
rotation + translation
'iso_similarity' :
isotropic scale + rotation + translation
'aniso_similarity' :
anisotropic scale + rotation + translation
'affine' :
skew + scale + rotation + translation
metric : str
This parameter is currently not used. Matte's mutual information ('Matte') is used by default as it offers the best metric for fluorescence imaging and multimodal registration.
metric_numberOfHistogramBins : int,
The number of histogram bins to compute mutual information. Higher bins may allow finer registration but also adds more intensity noise. Smaller bins is more robust to intensity variations but may not be as discriminative.
sampling_intensity_method : str
This parameter is currently not used. 'random' is on by default. Evaluating the metric of registration is too expensive for the full image, thus we need to sample. Random is good since it avoids consistently evaluating the same grid points.
MetricSamplingPercentage : scalar,
Number betwen 0-1 specifying the fraction of image voxels to evaluate the cost per registration iteration. Usually want to keep this fairly low for speed.
shrink_factors : list of lists or scalars
Shrink factors relative to the original image's size. When the list entry, shrink_factors[i], is a scalar the same factor is applied to all axes.
When the list entry is a list, shrink_factors[i][j] is applied to axis j. This allows us to specify different shrink factors per axis. This is useful
in the context of microscopy images where it is not uncommon to have unbalanced sampling such as a 512x512x8 image. In this case we would only want to
sample in the x,y axes and leave the z axis as is: [[[8,8,1],[4,4,1],[2,2,1]].
smoothing_sigmas : list of lists or scalars
Amount of smoothing which is done prior to resmapling the image using the given shrink factor. These are in pixel units.
optimizer : str
The optimization algorithm used to find the parameters.
'gradient' :
uses regular gradient descent. registration_method.SetOptimizerAsGradientDescent
'1+1_evolutionary' :
uses 1+1 evolutionary which is default in Matlab. registration_method.SetOptimizerAsOnePlusOneEvolutionary
optimizer_params : dict
Python dictionary-like specification of the optimization parameters. See :func:`unwrap3D.Parameters.params.gradient_descent_affine_reg` for setting up gradient descent (Default) and
:func:`unwrap3D.Parameters.params.evolutionary_affine_reg` for setting up the evolutionary optimizer
eps : scalar
small number for numerical precision
Returns
-------
SimpleITK.Transform
"""
import SimpleITK as sitk
def imadjust(vol, p1, p2):
import numpy as np
from skimage.exposure import rescale_intensity
# this is based on contrast stretching and is used by many of the biological image processing algorithms.
p1_, p2_ = np.percentile(vol, (p1,p2))
vol_rescale = rescale_intensity(vol, in_range=(p1_,p2_))
return vol_rescale
import numpy as np
if p12 is None:
im1_ = vol1.copy()
im2_ = vol2.copy()
# no contrast stretching
if rescale_intensity == False:
im1_ = im1_ / (2**imtype - 1)
im2_ = im2_ / (2**imtype - 1)
else:
im1_ = (im1_ - im1_.min()) / (im1_.max() - im1_.min() + eps)
im2_ = (im2_ - im2_.min()) / (im2_.max() - im2_.min() + eps)
else:
# contrast stretching
im1_ = imadjust(vol1, p12[0], p12[1])
im2_ = imadjust(vol2, p12[0], p12[1])
if rescale_intensity == False:
im1_ = im1_ / (2**imtype - 1)
im2_ = im2_ / (2**imtype - 1)
else:
im1_ = (im1_ - im1_.min()) / (im1_.max() - im1_.min() + eps)
im2_ = (im2_ - im2_.min()) / (im2_.max() - im2_.min() + eps)
### main analysis scripts.
v1 = sitk.GetImageFromArray(im1_, isVector=False)
v2 = sitk.GetImageFromArray(im2_, isVector=False)
# a) initial transform
# translation.
if centre_tfm_model=='geometry':
translation_mode = sitk.CenteredTransformInitializerFilter.GEOMETRY
if centre_tfm_model=='moments':
translation_mode = sitk.CenteredTransformInitializerFilter.MOMENTS
# if tfm_type == 'translation':
# transform_mode = sitk.TranslationTransform(3)
# these are the built in transforms without additional modification.
if tfm_type == 'rigid':
transform_mode = sitk.Euler3DTransform()
if tfm_type == 'iso_similarity':
transform_mode = sitk.Similarity3DTransform()
if tfm_type == 'aniso_similarity':
transform_mode = sitk.ScaleVersor3DTransform() # this version allows anisotropic scaling
if tfm_type == 'affine':
# transform_mode = sitk.AffineTransform(3) # this is a generic that requires setting.
transform_mode = sitk.ScaleSkewVersor3DTransform() # this is anisotropic + skew
initial_transform = sitk.CenteredTransformInitializer(v1,
v2,
transform_mode, # this is where we change the transform
translation_mode)
# a) Affine registration transform
# Select a different type of affine registration
# multiscale rigid.
registration_method = sitk.ImageRegistrationMethod()
# Similarity metric settings.
registration_method.SetMetricAsMattesMutualInformation(numberOfHistogramBins=metric_numberOfHistogramBins)
# key for making it fast. (subsampling, don't use all the pixels)
if sampling_intensity_method == 'random':
registration_method.SetMetricSamplingStrategy(registration_method.RANDOM)
registration_method.SetMetricSamplingPercentage(MetricSamplingPercentage)
registration_method.SetInterpolator(sitk.sitkLinear) # use this to help resampling the intensity at each iteration.
# Optimizer settings. # put these settings in a dedicated params file?
if optimizer == 'gradient':
registration_method.SetOptimizerAsGradientDescent(learningRate=optimizer_params['learningRate'],
numberOfIterations=optimizer_params['numberOfIterations'], # increase this.
convergenceMinimumValue=optimizer_params['convergenceMinimumValue'],
convergenceWindowSize=optimizer_params['convergenceWindowSize'],
estimateLearningRate=registration_method.EachIteration)
if optimizer == '1+1_evolutionary':
registration_method.SetOptimizerAsOnePlusOneEvolutionary(numberOfIterations=optimizer_params['numberOfIterations'],
epsilon=optimizer_params['epsilon'],
initialRadius= optimizer_params['initialRadius'],
growthFactor= optimizer_params['growthFactor'],
shrinkFactor= optimizer_params['shrinkFactor']
)
registration_method.SetOptimizerScalesFromIndexShift()
# set the multiscale registration parameters here.
registration_method.SetShrinkFactorsPerLevel(shrinkFactors = shrink_factors) # use just the one scale.
registration_method.SetSmoothingSigmasPerLevel(smoothingSigmas=smoothing_sigmas) # don't filter.
registration_method.SetInitialTransform(initial_transform, inPlace=False)
tfm = registration_method.Execute(sitk.Cast(v1, sitk.sitkFloat32),
sitk.Cast(v2, sitk.sitkFloat32))
# if tfm_type == 'affine':
# # refit with the above params.
# tfm_affine = sitk.AffineTransform(3)
# tfm_affine.SetMatrix(tfm.GetMatrix())
# tfm_affine.SetTranslation(tfm.GetTranslation())
# tfm_affine.SetCenter(tfm.GetCenter())
# registration_method.SetInitialTransform(tfm_affine, inPlace=False)
# tfm = registration_method.Execute(sitk.Cast(v1, sitk.sitkFloat32),
# sitk.Cast(v2, sitk.sitkFloat32))
return tfm
# to do: define helper script to wrap the main preprocessing steps for demons registration of two volumetric images.
def SITK_multiscale_demons_registration(vol1, vol2,
imtype=16,
p12=(2,99.8),
rescale_intensity=True,
centre_tfm_model='geometry',
demons_type='diffeomorphic',
n_iters = 25,
smooth_displacement_field = True,
smooth_alpha=.8,
shrink_factors = [2.,1.],
smoothing_sigmas = [1.,1.],
eps=1e-12):
r""" Main function to register two input volumes using Demon's registration algorithm in the SimpleITK library in a multiscale manner.
see SimpleITK notebooks, https://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/66_Registration_Demons.html
Parameters
----------
vol1 : (MxNxL) array
reference volume given as a Numpy array
vol2 : (MxNxL) array
volume to register to vol2, given as a Numpy array
imtype : int
specifies the -bit of the image e.g. 8-bit, 16-bit etc. Used to normalize the intensity if ``rescale_intensity=False``
p12 : (p1,p2) tuple
if provided, vol1 and vol2 are constract enhanced using percentage intensity normalization
rescale_intensity : bool
if True, does min-max scaling of image intensities in the two volumes independently before registering. This follows percentage intensity normalization if specified.
centre_tfm_model : str
specifies the initial centering model. This is one of two options. For microscopy, we find 'geometry' has less jitter and is best.
'geometry': str
uses sitk.CenteredTransformInitializerFilter.GEOMETRY. This computes the geometrical center independent of intensity.
'moments': str
uses sitk.CenteredTransformInitializerFilter.MOMENTS. This computes the geometrical center of mass of the volume based on using image intensity as a weighting.
demons_type : str
One of two demon's filters in SimpleITK.
'diffeomorphic' : str
sitk.DiffeomorphicDemonsRegistrationFilter(). This implements the diffeomorphic demons approach of [1]_ to penalise foldovers in the warp field and is more biologically plausible
'symmetric' : str
sitk.FastSymmetricForcesDemonsRegistrationFilter(). This implements the symmetric forces of [2]_. The idea is that in general the warp field of registering vol2 to vol1 and vice versa is not quite the same. in Symmetric forces demon the learning takes the average of these two warp fields to ensure symmetry preservation.
shrink_factors : list of lists or scalars
Shrink factors relative to the original image's size. When the list entry, shrink_factors[i], is a scalar the same factor is applied to all axes.
When the list entry is a list, shrink_factors[i][j] is applied to axis j. This allows us to specify different shrink factors per axis. This is useful
in the context of microscopy images where it is not uncommon to have unbalanced sampling such as a 512x512x8 image. In this case we would only want to
sample in the x,y axes and leave the z axis as is: [[[8,8,1],[4,4,1],[2,2,1]].
smoothing_sigmas : list of lists or scalars
Amount of smoothing which is done prior to resmapling the image using the given shrink factor. These are in pixel units.
eps : scalar
small number for numerical precision
Returns
-------
SimpleITK.DisplacementFieldTransform
References
----------
.. [1] Vercauteren et al. "Diffeomorphic demons: Efficient non-parametric image registration." NeuroImage 45.1 (2009): S61-S72.
.. [2] Avants et al. "Symmetric diffeomorphic image registration with cross-correlation: evaluating automated labeling of elderly and neurodegenerative brain." Medical image analysis 12.1 (2008): 26-41.
"""
import SimpleITK as sitk
def imadjust(vol, p1, p2):
import numpy as np
from skimage.exposure import rescale_intensity
# this is based on contrast stretching and is used by many of the biological image processing algorithms.
p1_, p2_ = np.percentile(vol, (p1,p2))
vol_rescale = rescale_intensity(vol, in_range=(p1_,p2_))
return vol_rescale
import numpy as np
if p12 is None:
im1_ = vol1.copy()
im2_ = vol2.copy()
# no contrast stretching
if rescale_intensity == False:
im1_ = im1_ / (2**imtype - 1)
im2_ = im2_ / (2**imtype - 1)
else:
im1_ = (im1_ - im1_.min()) / (im1_.max() - im1_.min() + eps)
im2_ = (im2_ - im2_.min()) / (im2_.max() - im2_.min() + eps)
else:
# contrast stretching
im1_ = imadjust(vol1, p12[0], p12[1])
im2_ = imadjust(vol2, p12[0], p12[1])
if rescale_intensity == False:
im1_ = im1_ / (2**imtype - 1)
im2_ = im2_ / (2**imtype - 1)
else:
im1_ = (im1_ - im1_.min()) / (im1_.max() - im1_.min() + eps)
im2_ = (im2_ - im2_.min()) / (im2_.max() - im2_.min() + eps)
### main analysis scripts.
v1 = sitk.GetImageFromArray(im1_, isVector=False)
v2 = sitk.GetImageFromArray(im2_, isVector=False)
# a) initial transform
# translation.
if centre_tfm_model=='geometry':
translation_mode = sitk.CenteredTransformInitializerFilter.GEOMETRY
if centre_tfm_model=='moments':
translation_mode = sitk.CenteredTransformInitializerFilter.MOMENTS
initial_transform = sitk.CenteredTransformInitializer(v1,
v2,
sitk.Euler3DTransform(),
translation_mode)
# a) demons transform (best to have corrected out any rigid transforms a priori)
# Select a Demons filter and configure it.
if demons_type == 'diffeomorphic':
demons_filter = sitk.DiffeomorphicDemonsRegistrationFilter() # we should use this version.
if demons_type == 'symmetric':
demons_filter = sitk.FastSymmetricForcesDemonsRegistrationFilter()
# set the number of iterations
demons_filter.SetNumberOfIterations(n_iters) # 5 for less. # long time for 20?
# Regularization (update field - viscous, total field - elastic).
demons_filter.SetSmoothDisplacementField(smooth_displacement_field)
demons_filter.SetStandardDeviations(smooth_alpha)
# run the registration and return the final transform parameters
final_tfm = multiscale_demons(registration_algorithm=demons_filter,
fixed_image = v1,
moving_image = v2,
initial_transform = initial_transform,
shrink_factors = shrink_factors, # did have 2 here. -> test, can we separate the # do at the same scale.
smoothing_sigmas = smoothing_sigmas) # set smoothing very low, since we want it to zone in on interesting features.
# check again how this is parsed .
return final_tfm
# define helper scripts to transform new volumes given a deformation.
def transform_img_sitk(vol, tfm):
r""" One-stop function for applying any SimpleITK transform to an input image. Linear interpolation is used.
Parameters
----------
vol: array
input image as a numpy array
tfm: SimpleITK.Transform
A simpleITK transform instance such as that resulting from using the simpleITK registration functions in this module.
Returns
-------
v_transformed : array
resulting image after applying the given transform to the input, returned as a numpy array
"""
import SimpleITK as sitk
v = sitk.GetImageFromArray(vol, isVector=False)
v_transformed = sitk.Resample(v,
v,
tfm, # this should work with all types of transforms.
sitk.sitkLinear,
0.0,
v.GetPixelID())
v_transformed = sitk.GetArrayFromImage(v_transformed) # back to numpy format.
return v_transformed
# here we need to add functions for reading and writing SITK transforms, and converting a numpy array to diplacemeent field to take into advantage of SITK image resampling.
| 52,919 | 39.73903 | 324 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Registration/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Tracking/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Tracking/tracking.py
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 15 16:50:05 2022
@author: felix
"""
from ..Utility_Functions import file_io as fio
import numpy as np
# is there a quick way to compute the occupied bbox density.
def remove_very_large_bbox(boxes, shape, thresh=0.5, aspect_ratio=None, method='density', max_density=4, mode='fast', return_ind=False):
from sklearn.metrics.pairwise import pairwise_distances
if method == 'density':
boxes_ = boxes.copy()
keep_ind = np.arange(len(boxes_))
if aspect_ratio is not None:
w = boxes[:,2] - boxes[:,0]
h = boxes[:,3] - boxes[:,1]
wh = np.vstack([w,h])
aspect_w_h = np.max(wh, axis=0) / (np.min(wh, axis=0) + .1)
boxes_ = boxes_[aspect_w_h<=aspect_ratio]
keep_ind = keep_ind[aspect_w_h<=aspect_ratio]
box_density = np.zeros(shape)
bbox_coverage = np.zeros(len(boxes_))
box_centroids_x = np.clip((.5*(boxes_[:,0] + boxes_[:,2])).astype(np.int), 0, shape[1]-1).astype(np.int)
box_centroids_y = np.clip((.5*(boxes_[:,1] + boxes_[:,3])).astype(np.int), 0, shape[0]-1).astype(np.int)
if mode == 'fast':
box_centroids = np.vstack([box_centroids_x, box_centroids_y]).T
box_centroids_r = np.sqrt((boxes_[:,2]-boxes_[:,0])*(boxes_[:,3]-boxes_[:,1])/np.pi +.1)
box_centroids_distance = pairwise_distances(box_centroids)
bbox_coverage = np.nansum(box_centroids_distance<=box_centroids_r[:,None], axis=1)
else:
# box_density[box_centroids_y, box_centroids_x] += 1
for cent_ii in np.arange(len(box_centroids_x)):
cent_x = box_centroids_x[cent_ii]
cent_y = box_centroids_y[cent_ii]
box_density[int(cent_y), int(cent_x)] += 1
for box_ii, box in enumerate(boxes_):
x1, y1, x2, y2 = box
x1 = np.clip(int(x1), 0, shape[1]-1)
y1 = np.clip(int(y1), 0, shape[0]-1)
x2 = np.clip(int(x2), 0, shape[1]-1)
y2 = np.clip(int(y2), 0, shape[0]-1)
bbox_coverage[box_ii] = np.nansum(box_density[int(y1):int(y2),
int(x1):int(x2)])
# print(bbox_coverage)
if return_ind == False:
return boxes_[bbox_coverage<=max_density]
else:
return boxes_[bbox_coverage<=max_density], keep_ind[bbox_coverage<=max_density]
if method == 'area':
areas_box = []
area_shape = float(np.prod(shape))
# print(area_shape)
for box in boxes:
x1, y1, x2, y2 = box
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
area_box = (y2-y1)*(x2-x1)
areas_box.append(area_box)
areas_box = np.hstack(areas_box)
areas_box_frac = areas_box / float(area_shape)
return boxes[areas_box_frac<=thresh]
def Eval_dense_optic_flow(prev, present, params):
r""" Computes the optical flow using Farnebacks Method
Parameters
----------
prev : numpy array
previous frame, m x n image
present : numpy array
current frame, m x n image
params : Python dict
a dict object to pass all algorithm parameters. Fields are the same as that in the opencv documentation, https://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html. Our recommended starting values:
* params['pyr_scale'] = 0.5
* params['levels'] = 3
* params['winsize'] = 15
* params['iterations'] = 3
* params['poly_n'] = 5
* params['poly_sigma'] = 1.2
* params['flags'] = 0
Returns
-------
flow : finds the displacement field between frames, prev and present such that :math:`\mathrm{prev}(y,x) = \mathrm{next}(y+\mathrm{flow}(y,x)[1], x+\mathrm{flow}(y,x)[0])` where (x,y) is the cartesian coordinates of the image.
"""
import numpy as np
import warnings
import cv2
# Check version of opencv installed, if not 3.0.0 then issue alert.
# if '3.0.0' in cv2.__version__ or '3.1.0' in cv2.__version__:
# Make the image pixels into floats.
prev = prev.astype(np.float)
present = present.astype(np.float)
if cv2.__version__.split('.')[0] == '3' or cv2.__version__.split('.')[0] == '4':
flow = cv2.calcOpticalFlowFarneback(prev, present, None, params['pyr_scale'], params['levels'], params['winsize'], params['iterations'], params['poly_n'], params['poly_sigma'], params['flags'])
if cv2.__version__.split('.')[0] == '2':
flow = cv2.calcOpticalFlowFarneback(prev, present, pyr_scale=params['pyr_scale'], levels=params['levels'], winsize=params['winsize'], iterations=params['iterations'], poly_n=params['poly_n'], poly_sigma=params['poly_sigma'], flags=params['flags'])
# print(flow.shape)
return flow
def rescale_intensity_percent(img, intensity_range=[2,98]):
from skimage.exposure import rescale_intensity
import numpy as np
p2, p98 = np.percentile(img, intensity_range)
img_ = rescale_intensity(img, in_range=(p2,p98))
return img_
# add in optical flow.
def extract_optflow(vid, optical_flow_params, rescale_intensity=True, intensity_range=[2,98]):
# uses CV2 built in farneback ver. which is very fast and good for very noisy and small motion
import cv2
from skimage.exposure import rescale_intensity
import numpy as np
from tqdm import tqdm
vid_flow = []
n_frames = len(vid)
for frame in tqdm(np.arange(len(vid)-1)):
frame0 = rescale_intensity_percent(vid[frame], intensity_range=intensity_range)
frame1 = rescale_intensity_percent(vid[frame+1], intensity_range=intensity_range)
flow01 = Eval_dense_optic_flow(frame0, frame1,
params=optical_flow_params)
vid_flow.append(flow01)
vid_flow = np.array(vid_flow).astype(np.float32) # to save some space.
return vid_flow
def predict_new_boxes_flow_tf(boxes, flow):
from skimage.transform import estimate_transform, matrix_transform, SimilarityTransform
from skimage.measure import ransac
import numpy as np
flow_x = flow[:,:,0]
flow_y = flow[:,:,1]
new_boxes_tf = []
tfs = []
for box in boxes:
x1,y1,x2,y2 = box
x1 = int(x1); y1 =int(y1); x2=int(x2); y2 =int(y2); # added, weirdly ...
# how to take into account the change in size (scale + translation ? very difficult. )
flow_x_patch = flow_x[y1:y2, x1:x2].copy()
flow_y_patch = flow_y[y1:y2, x1:x2].copy()
nrows_, ncols_ = flow_x_patch.shape
# threshold_the mag
mag_patch = np.sqrt(flow_x_patch ** 2 + flow_y_patch ** 2)
select = mag_patch > 0
# select = np.ones(mag_patch.shape) > 0
pix_X, pix_Y = np.meshgrid(range(ncols_), range(nrows_))
if np.sum(select) == 0:
# if we cannot record movement in the box just append the original ?
tfs.append([])
new_boxes_tf.append([x1,y1,x2,y2])
else:
src_x = pix_X[select].ravel(); dst_x = src_x + flow_x_patch[select]
src_y = pix_Y[select].ravel(); dst_y = src_y + flow_y_patch[select]
src = np.hstack([src_x[:,None], src_y[:,None]])
dst = np.hstack([dst_x[:,None], dst_y[:,None]])
# estimate the transformation.
matrix = estimate_transform('similarity', src[:,[0,1]], dst[:,[0,1]])
tf_scale = matrix.scale; tf_offset = matrix.translation
# print tf_scale, tf_offset
if np.isnan(tf_scale):
tfs.append(([]))
new_boxes_tf.append([x1,y1,x2,y2])
else:
x = .5*(x1+x2); w = x2-x1
y = .5*(y1+y2); h = y2-y1
x1_tf_new = x + tf_offset[0] - w*tf_scale/2.
y1_tf_new = y + tf_offset[1] - h*tf_scale/2.
x2_tf_new = x1_tf_new + w*tf_scale
y2_tf_new = y1_tf_new + h*tf_scale
# print x1_tf_new
tfs.append(matrix)
new_boxes_tf.append([x1_tf_new, y1_tf_new, x2_tf_new, y2_tf_new])
new_boxes_tf = np.array(new_boxes_tf)
return tfs, new_boxes_tf
# this version is just over the boxes. given voc format.
def bbox_iou_corner_xy(bboxes1, bboxes2):
import numpy as np
"""
computes the distance matrix between two sets of bounding boxes.
Args:
bboxes1: shape (total_bboxes1, 4)
with x1, y1, x2, y2 point order.
bboxes2: shape (total_bboxes2, 4)
with x1, y1, x2, y2 point order.
p1 *-----
| |
|_____* p2
Returns:
Tensor with shape (total_bboxes1, total_bboxes2)
with the IoU (intersection over union) of bboxes1[i] and bboxes2[j]
in [i, j].
"""
x11, y11, x12, y12 = bboxes1[:,0], bboxes1[:,1], bboxes1[:,2], bboxes1[:,3]
x21, y21, x22, y22 = bboxes2[:,0], bboxes2[:,1], bboxes2[:,2], bboxes2[:,3]
x11 = x11[:,None]; y11 = y11[:,None]; x12=x12[:,None]; y12=y12[:,None]
x21 = x21[:,None]; y21 = y21[:,None]; x22=x22[:,None]; y22=y22[:,None]
xI1 = np.maximum(x11, np.transpose(x21))
xI2 = np.minimum(x12, np.transpose(x22))
yI1 = np.maximum(y11, np.transpose(y21))
yI2 = np.minimum(y12, np.transpose(y22))
inter_area = np.maximum((xI2 - xI1), 0.) * np.maximum((yI2 - yI1), 0.)
bboxes1_area = (x12 - x11) * (y12 - y11)
bboxes2_area = (x22 - x21) * (y22 - y21)
union = (bboxes1_area + np.transpose(bboxes2_area)) - inter_area
# some invalid boxes should have iou of 0 instead of NaN
# If inter_area is 0, then this result will be 0; if inter_area is
# not 0, then union is not too, therefore adding a epsilon is OK.
return inter_area / (union+0.0001)
def bbox_tracks_2_array(vid_bbox_tracks, nframes, ndim):
import numpy as np
N_tracks = len(vid_bbox_tracks)
vid_bbox_tracks_all_array = np.zeros((N_tracks, nframes, ndim))
vid_bbox_tracks_all_array[:] = np.nan
vid_bbox_tracks_prob_all_array = np.zeros((N_tracks, nframes))
vid_bbox_tracks_prob_all_array[:] = np.nan
for ii in np.arange(N_tracks):
tra_ii = vid_bbox_tracks[ii]
tra_ii_times = np.array([tra_iii[0] for tra_iii in tra_ii])
tra_ii_boxes = np.array([tra_iii[-1] for tra_iii in tra_ii]) # boxes is the last array.
tra_ii_prob = np.array([tra_iii[1] for tra_iii in tra_ii])
vid_bbox_tracks_all_array[ii,tra_ii_times] = tra_ii_boxes.copy()
vid_bbox_tracks_prob_all_array[ii,tra_ii_times] = tra_ii_prob.copy()
return vid_bbox_tracks_prob_all_array, vid_bbox_tracks_all_array
def bbox_scalar_2_array(vid_scalar_tracks, nframes):
import numpy as np
N_tracks = len(vid_scalar_tracks)
vid_scalar_tracks_all_array = np.zeros((N_tracks, nframes))
vid_scalar_tracks_all_array[:] = np.nan
for ii in np.arange(N_tracks):
tra_ii = vid_scalar_tracks[ii]
tra_ii_times = np.array([tra_iii[0] for tra_iii in tra_ii])
tra_ii_vals = np.array([tra_iii[1] for tra_iii in tra_ii])
vid_scalar_tracks_all_array[ii,tra_ii_times] = tra_ii_vals.copy()
return vid_scalar_tracks_all_array
def unpad_bbox_tracks(all_uniq_tracks, pad, shape, nframes, aspect_ratio=3):
import numpy as np
# define the bounds.
bounds_x = [0, shape[1]-1]
bounds_y = [0, shape[0]-1]
all_uniq_bbox_tracks_new = []
for tra_ii in np.arange(len(all_uniq_tracks)):
all_uniq_tracks_ii = all_uniq_tracks[tra_ii]
# all_track_labels_ii = track_labels[tra_ii]
all_uniq_bbox_track_ii = []
for jj in np.arange(len(all_uniq_tracks_ii)):
tra = all_uniq_tracks_ii[jj]
# tra_label = all_track_labels_ii[jj][-1]
tp, conf, bbox = tra
x1, y1, x2, y2 = bbox
x1 = np.clip(x1, 0, shape[1]-1+2*pad)
x2 = np.clip(x2, 0, shape[1]-1+2*pad)
y1 = np.clip(y1, 0, shape[0]-1+2*pad)
y2 = np.clip(y2, 0, shape[0]-1+2*pad)
x1_= x1-pad
y1_= y1-pad
x2_ = x2-pad
y2_ = y2-pad
# print(x1_, x2_, y1_, y2_)
"""
This is more complex ...
if y < 0 or y > shape[0], then we have to flip x coordinate and flip y-coordinate.
# test this inversion ! ######## ---> for a fixed timepoint, just to double ceck we are getting the correct alogrithm. !.
"""
# left top
if y1_ < bounds_y[0] and (x1_ < bounds_x[0]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = -1 * y1_ # flip y
# x1_ = (bounds_x[1]+1*pad + x1_) - bounds_x[1] # flip x axis.
x1_ = bounds_x[0] - x1_
if y2_ < bounds_y[0] and (x2_ < bounds_x[0]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = -1 * y2_
# x2_ = (bounds_x[1]+1*pad + x2_) - bounds_x[1] # flip x axis.
x2_ = bounds_x[0] - x2_
# middle top # this is ok
if y1_ < bounds_y[0] and (x1_ >= bounds_x[0] and x1_ <= bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = -1 * y1_
x1_ = bounds_x[1] - x1_ # flip x axis.
if y2_ < bounds_y[0] and (x2_ >= bounds_x[0] and x2_ <= bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = -1 * y2_
x2_ = bounds_x[1] - x2_ # flip x axis.
# right top
if y1_ < bounds_y[0] and (x1_ > bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = -1 * y1_ # flip y
x1_ = bounds_x[1] - (x1_ - bounds_x[1])
if y2_ < bounds_y[0] and (x2_ > bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = -1 * y2_
x2_ = bounds_x[1] - (x2_ - bounds_x[1])
# middle left
if (y1_ >= bounds_y[0] and y1_ <= bounds_y[1]) and (x1_ < bounds_x[0]):
# simply shift the x1_ back
x1_ = x1_ + (bounds_x[1]+1)
if (y2_ >= bounds_y[0] and y2_ <= bounds_y[1]) and (x2_ < bounds_x[0]):
x2_ = x2_ + (bounds_x[1]+1)
# middle right
if (y1_ >= bounds_y[0] and y1_ <= bounds_y[1]) and (x1_ > bounds_x[1]):
# simply shift the x1_ back
x1_ = x1_ - (bounds_x[1]+1)
if (y2_ >= bounds_y[0] and y2_ <= bounds_y[1]) and (x2_ > bounds_x[1]):
# simply shift the x1_ back
x2_ = x2_ - (bounds_x[1]+1)
# left bottom
if y1_ > bounds_y[1] and (x1_ < bounds_x[0]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = bounds_y[1] + (bounds_y[1] - y1_) # flipping at the other end.
# x1_ = (bounds_x[1]+1*p-d + x1_) - bounds_x[1] # flip x axis.
x1_ = bounds_x[0] - x1_
if y2_ > bounds_y[1] and (x2_ < bounds_x[0]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = bounds_y[1] + (bounds_y[1] - y2_) # flipping at the other end.
x2_ = bounds_x[0] - x2_
# x2_ = (bounds_x[1]+1*pad + x2_) - bounds_x[1]
# x2_ = x2_ - (bounds_x[1]+1)
# middle bottom
if y1_ > bounds_y[1] and (x1_ >= bounds_x[0] and x1_ <= bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = bounds_y[1] + (bounds_y[1] - y1_) # flipping at the other end.
x1_ = bounds_x[1] - x1_ # flip x axis.
if y2_ > bounds_y[1] and (x2_ >= bounds_x[0] and x2_ <= bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = bounds_y[1] + (bounds_y[1] - y2_) # flipping at the other end.
x2_ = bounds_x[1] - x2_ # flip x axis.
# right bottom
if y1_ > bounds_y[1] and (x1_ > bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y1_ = bounds_y[1] + (bounds_y[1] - y1_) # flipping at the other end.
# x1_ = x1_ - (bounds_x[1]+1*pad) + bounds_x[1] # flip x axis.
x1_ = bounds_x[1] - (x1_ - bounds_x[1])
if y2_ > bounds_y[1] and (x2_ > bounds_x[1]):
# then we flip the x axis and flip the y coordinate into the shape. (=180 rotation)
y2_ = bounds_y[1] + (bounds_y[1] - y2_) # flipping at the other end.
# x2_ = x2_ - (bounds_x[1]+1*pad) + bounds_x[1] # flip x axis.
x2_ = bounds_x[1] - (x2_ - bounds_x[1])
"""
need a accuracy test for the designated label if the label is not the background label!.
"""
# we check the sign change here! to know if we need to modify.
w1_ = (x2_ - x1_) # x2 must be higher? if negative that means x1 needs to be shifted back.
h1_ = (y2_ - y1_) # if negative means y1 needs to be shifted
# print(w1_, h1_, (x1_,y1_,x2_,y2_))
if w1_ < 0:
# we have to shift but dunno which way.
x1_test = np.clip(x1_ - (bounds_x[1]), 0, bounds_x[1])
x2_test = np.clip(x2_ + (bounds_x[1]), 0, bounds_x[1])
area_x1_test = np.abs(x2_ - x1_test) * np.abs(y2_-y1_)
area_x2_test = np.abs(x2_test - x1_) * np.abs(y2_-y1_)
if area_x1_test > area_x2_test:
x1_ = x1_test
else:
x2_ = x2_test
if h1_ < 0:
# y1_ = np.clip(y1_ - (bounds_y[1]+1), 0, bounds_y[1])
# y2_ = np.clip(y2_ + (bounds_y[1]+1), 0, bounds_y[1])
# we have to shift but dunno which way.
y1_test = np.clip(y1_ - (bounds_y[1]), 0, bounds_y[1]) # make y1 smaller or
y2_test = np.clip(y2_ + (bounds_y[1]), 0, bounds_y[1]) # make y2 bigger
area_y1_test = np.abs(y2_ - y1_test) * np.abs(x2_ - x1_)
area_y2_test = np.abs(y2_test - y1_) * np.abs(x2_ - x1_)
if area_y1_test > area_y2_test:
y1_ = y1_test
else:
y2_ = y2_test
bbox_new = np.hstack([x1_, y1_, x2_, y2_])
all_uniq_bbox_track_ii.append([tp, conf, bbox_new])
all_uniq_bbox_tracks_new.append(all_uniq_bbox_track_ii)
# convert this !.
# compile into a numpy array and send this out too
_, all_uniq_bbox_tracks_array_new = bbox_tracks_2_array(all_uniq_bbox_tracks_new, nframes=nframes, ndim=4)
all_uniq_bbox_tracks_centroids_xy_new = np.array([.5*(all_uniq_bbox_tracks_array_new[...,0] + all_uniq_bbox_tracks_array_new[...,2]),
.5*(all_uniq_bbox_tracks_array_new[...,1] + all_uniq_bbox_tracks_array_new[...,3])])
return all_uniq_bbox_tracks_new, all_uniq_bbox_tracks_array_new, all_uniq_bbox_tracks_centroids_xy_new
def assign_label_detection_to_track_frame_by_frame(bbox_array_time, bbox_detections_time, min_iou=.25):
"""
bbox_array_time: N_tracks x N_frames x 4
bbox_detections_time: N_frames list
"""
import numpy as np
from scipy.optimize import linear_sum_assignment
n_tracks, n_frames, _ = bbox_array_time.shape
bbox_array_time_labels = np.zeros((n_tracks, n_frames), dtype=np.float64) # initialise to background!.
bbox_array_time_labels[:] = np.nan # initialise to empty
# iterate over time
for tt in np.arange(n_frames)[:]:
# reference
bbox_frame_tt = bbox_detections_time[tt].copy()
bbox_labels_tt = bbox_frame_tt[:,0].copy()
bbox_labels_bbox = bbox_frame_tt[:,1:5].copy()
tracks_bboxes = bbox_array_time[:,tt].copy()
non_nan_select = np.logical_not(np.isnan(tracks_bboxes[:,0])) # just test the one coordinate. # only these need to be given a label!.
tracks_bboxes_bbox = tracks_bboxes[non_nan_select>0].copy()
labels_non_nan_select = np.zeros(len(tracks_bboxes_bbox), dtype=np.int) # preinitialise
# build the iou cost matrix. between rows: tracks and cols: the frame boxes.
iou_matrix = bbox_iou_corner_xy(tracks_bboxes_bbox,
bbox_labels_bbox)
iou_matrix = np.clip(1.-iou_matrix, 0, 1) # to make it a dissimilarity matrix.
# solve the pairing problem.
ind_ii, ind_jj = linear_sum_assignment(iou_matrix)
# threshold as the matching is maximal.
iou_ii_jj = iou_matrix[ind_ii, ind_jj].copy()
keep = iou_ii_jj <= (1-min_iou) # keep those with a minimal distance.
# keep = iou_ii_jj <= dist_thresh
ind_ii = ind_ii[keep>0];
ind_jj = ind_jj[keep>0]
labels_non_nan_select[ind_ii] = bbox_labels_tt[ind_jj].copy()
# copy back into the labels.
bbox_array_time_labels[non_nan_select>0, tt] = labels_non_nan_select.copy() # copy these assignments in now.
return bbox_array_time_labels
def compute_labeled_to_unlabeled_track(track_label_array):
import numpy as np
n_tracks, n_frames = track_label_array.shape
track_counts = []
for tra_ii in np.arange(n_tracks):
tra_label = track_label_array[tra_ii].copy()
valid = np.logical_not(np.isnan(tra_label))
num_valid = np.sum(valid)
valid_labels = tra_label[valid].astype(np.int)
num_nonzeros = np.sum(valid_labels > 0)
track_counts.append([num_valid, num_nonzeros, float(num_nonzeros) / num_valid, n_frames])
track_counts = np.vstack(track_counts)
return track_counts
def moving_average_bbox_tracks(list_tracks, avg_func=np.nanmean, winsize=3, min_winsize_prop=0.1, pad_mode='edge', *args):
import numpy as np
list_tracks_smooth = []
for tra_ii in np.arange(len(list_tracks)):
track_ii = np.array(list_tracks[tra_ii]) # numpy array
winsize_track = winsize
if winsize/float(len(track_ii)) < min_winsize_prop:
# then reduce the winsize smoothing!.
winsize_track = np.maximum(3, int(len(track_ii)*min_winsize_prop))
track_ii_pad = np.pad(track_ii, [[winsize_track//2, winsize_track//2], [0,0]], mode=pad_mode, *args)
track_ii_smooth = np.vstack([avg_func(track_ii_pad[tt:tt+winsize_track], axis=0) for tt in np.arange(len(track_ii))])
list_tracks_smooth.append(track_ii_smooth)
return list_tracks_smooth
# using optical flow to implement a predictive tracker for blebs.
def track_bleb_bbox(vid_flow, # flow is already computed.
vid_bboxes, # bbox files for each frame only !.
vid=None, # only for visualisation purposes.
iou_match=.25,
ds_factor = 1,
wait_time=10,
min_aspect_ratio=3,
max_dense_bbox_cover=8,
min_tra_len_filter=5,
min_tra_lifetime_ratio = .1,
to_viz=True,
remove_eccentric_bbox=False,
saveanalysisfolder=None):
"""
uses optical flow and registration as a predictor to improve tracking over occlusion.
# we should preserve the bbox coordinates + the given probability from yolo..... that way we can always do further processing?
"""
import numpy as np
import seaborn as sns
import pylab as plt
import os
from tqdm import tqdm
from scipy.optimize import linear_sum_assignment
"""
initial setting up.
"""
im_shape = vid_flow[0].shape[:2]
nframes = len(vid_flow)+1 # the number of frames in the video.
if saveanalysisfolder is not None:
print('saving graphics in folder: ', saveanalysisfolder)
# saveanalysisfolder_movie = os.path.join(saveanalysisfolder, 'track_boundaries'); mkdir(saveanalysisfolder_movie);
saveanalysisfolder_movie_bbox = os.path.join(saveanalysisfolder, 'track_bbox');
mkdir(saveanalysisfolder_movie_bbox);
# =============================================================================
# BBox Tracks
# =============================================================================
# terminated_vid_cell_tracks = []
terminated_vid_bbox_tracks = []
terminated_check_match_bbox_tracks = []
vid_bbox_tracks = [] # this is to keep track of the actual bbox we use, including inferred.
vid_bbox_tracks_last_time = [] # record when the last time a proper match was made.
vid_match_check_bbox_tracks = []
# =============================================================================
# build up the tracks dynamically now, frame by frame dynamically , with a track waiting time before termination.
# ============================================================================
for ii in tqdm(np.arange(nframes-1)[:]):
"""
if working set is empty or otherwise, then add to working set.
"""
# add these to the working tracks.
if ii == 0 or len(vid_bbox_tracks)==0:
# bboxfile_ii = vid_bboxes[ii]
"""
swap this element out.
"""
# prob_ii, boxes_ii = load_bbox_frame_voc( vid[0], bboxfile_ii) # modify this here!.
boxes_ii = vid_bboxes[ii].copy()
# set prob dependent on the size of the boxes. (if 5D then take the first as a measure of objectness else assume 1.)
if boxes_ii.shape[-1] == 4:
prob_ii = np.ones(len(boxes_ii))
else:
prob_ii = boxes_ii[:,0].copy()
boxes_ii = boxes_ii[:,1:].copy()
boxes_ii = boxes_ii / float(ds_factor)
# clip
boxes_ii[:,0] = np.clip(boxes_ii[:,0], 0, im_shape[1]-1)
boxes_ii[:,1] = np.clip(boxes_ii[:,1], 0, im_shape[0]-1)
boxes_ii[:,2] = np.clip(boxes_ii[:,2], 0, im_shape[1]-1)
boxes_ii[:,3] = np.clip(boxes_ii[:,3], 0, im_shape[0]-1)
# remove all boxes that are have an area 1 pixels or less.
boxes_ii_w = boxes_ii[:,2] - boxes_ii[:,0]
boxes_ii_h = boxes_ii[:,3] - boxes_ii[:,1]
boxes_ii = boxes_ii[boxes_ii_w*boxes_ii_h>0]
# suppress implausible.
if remove_eccentric_bbox:
boxes_ii, keep_ind_ii = remove_very_large_bbox(boxes_ii,
im_shape,
thresh=0.5,
aspect_ratio = 3, # we don't expect it to be very long.
method='density',
max_density=max_dense_bbox_cover,
mode='fast',
return_ind=True)
else:
keep_ind_ii = np.ones(len(boxes_ii))>0
assert(len(boxes_ii) == len(keep_ind_ii)) # keep a check here.
prob_ii = prob_ii[keep_ind_ii]
for jj in np.arange(len(boxes_ii)):
vid_bbox_tracks.append([[ii, prob_ii[jj], boxes_ii[jj]]]) # add the prob in as another entry here.
vid_bbox_tracks_last_time.append(ii) # update with current time.
vid_match_check_bbox_tracks.append([[ii, 1]]) # update with the current time., this is just to select whether this box was propagated or found in the original detections.
"""
load the current working set of tracks.
"""
# 1) check for track termination
# get the last timepoint.
boxes_ii_track_time = np.hstack(vid_bbox_tracks_last_time)
# check if any of the box tracks need to be terminated.
track_terminate = boxes_ii_track_time < ii - wait_time
track_terminate_id = np.arange(len(track_terminate))[track_terminate]
if len(track_terminate_id)>0:
# update the relevant info.
for idd in track_terminate_id:
#update
terminated_vid_bbox_tracks.append(vid_bbox_tracks[idd][:-wait_time-1])
terminated_check_match_bbox_tracks.append(vid_match_check_bbox_tracks[idd][:-wait_time-1])
# terminated_vid_cell_tracks_properties.append(vid_cell_tracks_properties[idd][:-wait_time-1])
# # reform the working set.
# vid_cell_tracks = [vid_cell_tracks[jjj] for jjj in np.arange(len(vid_cell_tracks)) if jjj not in track_terminate_id] # i guess this is to keep track of actual cell ids that we segmented.
vid_bbox_tracks = [vid_bbox_tracks[jjj] for jjj in np.arange(len(vid_bbox_tracks)) if jjj not in track_terminate_id] # this is to keep track of the actual bbox we use, including inferred.
# vid_cell_tracks_properties = [vid_cell_tracks_properties[jjj] for jjj in np.arange(len(vid_cell_tracks_properties)) if jjj not in track_terminate_id]
vid_bbox_tracks_last_time = [vid_bbox_tracks_last_time[jjj] for jjj in np.arange(len(vid_bbox_tracks_last_time)) if jjj not in track_terminate_id]
vid_match_check_bbox_tracks = [vid_match_check_bbox_tracks[jjj] for jjj in np.arange(len(vid_match_check_bbox_tracks)) if jjj not in track_terminate_id]
# load the current version of the boxes.
boxes_ii_track = np.array([bb[-1][-1] for bb in vid_bbox_tracks]) # the bboxes to consider.
boxes_ii_track_prob = np.array([bb[-1][1] for bb in vid_bbox_tracks])
boxes_ii_track_time = np.array([bb[-1][0] for bb in vid_bbox_tracks]) # the time of the last track.
"""
Infer the next frame boxes from current boxes using optical flow.
"""
boxes_ii_track_pred = []
for jjj in np.arange(len(boxes_ii_track)):
"""
Predict using the flow the likely position of boxes.
"""
new_tfs, boxes_ii_pred = predict_new_boxes_flow_tf(boxes_ii_track[jjj][None,:],
vid_flow[boxes_ii_track_time[jjj]])
# clip
boxes_ii_pred[:,0] = np.clip(boxes_ii_pred[:,0], 0, im_shape[1]-1)
boxes_ii_pred[:,1] = np.clip(boxes_ii_pred[:,1], 0, im_shape[0]-1)
boxes_ii_pred[:,2] = np.clip(boxes_ii_pred[:,2], 0, im_shape[1]-1)
boxes_ii_pred[:,3] = np.clip(boxes_ii_pred[:,3], 0, im_shape[0]-1)
boxes_ii_track_pred.append(boxes_ii_pred[0])
boxes_ii_track_pred = np.array(boxes_ii_track_pred)
"""
load the next frame boxes. which are the candidates.
"""
# bboxfile_jj = vid_bboxes[ii+1]
# prob_jj, boxes_jj = load_bbox_frame_voc( vid[ii+1],
# bboxfile_jj)
boxes_jj = vid_bboxes[ii+1].copy();
# set prob dependent on the size of the boxes. (if 5D then take the first as a measure of objectness else assume 1.)
if boxes_jj.shape[-1] == 4:
prob_jj = np.ones(len(boxes_jj))
else:
prob_jj = boxes_jj[:,0].copy()
boxes_jj = boxes_jj[:,1:].copy()
boxes_jj = boxes_jj/float(ds_factor)
# clip
boxes_jj[:,0] = np.clip(boxes_jj[:,0], 0, im_shape[1]-1)
boxes_jj[:,1] = np.clip(boxes_jj[:,1], 0, im_shape[0]-1)
boxes_jj[:,2] = np.clip(boxes_jj[:,2], 0, im_shape[1]-1)
boxes_jj[:,3] = np.clip(boxes_jj[:,3], 0, im_shape[0]-1)
# remove all boxes that are have an area 1 pixels or less.
boxes_jj_w = boxes_jj[:,2] - boxes_jj[:,0]
boxes_jj_h = boxes_jj[:,3] - boxes_jj[:,1]
boxes_jj = boxes_jj[boxes_jj_w*boxes_jj_h>0]
# suppress implausible.
if remove_eccentric_bbox:
boxes_jj, keep_ind_jj = remove_very_large_bbox(boxes_jj,
im_shape,
thresh=0.5,
aspect_ratio = 3, # we don't expect it to be very long.
method='density',
max_density=max_dense_bbox_cover,
mode='fast', return_ind=True)
else:
keep_ind_jj = np.ones(len(boxes_jj))>0
prob_jj = prob_jj[keep_ind_jj]
"""
build the association matrix and match boxes based on iou.
"""
iou_matrix = bbox_iou_corner_xy(boxes_ii_track_pred,
boxes_jj);
iou_matrix = np.clip(1.-iou_matrix, 0, 1) # to make it a dissimilarity matrix.
# solve the pairing problem.
ind_ii, ind_jj = linear_sum_assignment(iou_matrix)
# threshold as the matching is maximal.
iou_ii_jj = iou_matrix[ind_ii, ind_jj].copy()
keep = iou_ii_jj <= (1-iou_match)
# keep = iou_ii_jj <= dist_thresh
ind_ii = ind_ii[keep>0];
ind_jj = ind_jj[keep>0]
"""
Update the trajectories.
"""
# update first the matched.
for match_ii in np.arange(len(ind_ii)):
# vid_cell_tracks[ind_ii[match_ii]].append([ii+1, ind_jj[match_ii]]) # i guess this is to keep track of actual cell ids that we segmented.
vid_bbox_tracks[ind_ii[match_ii]].append([ii+1, prob_jj[ind_jj[match_ii]], boxes_jj[ind_jj[match_ii]]]) # this is to keep track of the actual bbox we use, including inferred.
# vid_cell_tracks_properties[ind_ii[match_ii]].append([ii+1, masks_jj_properties[ind_jj[match_ii]]]) # append the properties of the next time point.
vid_bbox_tracks_last_time[ind_ii[match_ii]] = ii+1 # let this be a record of the last time a 'real' segmentation was matched, not one inferred from optical flow.
# vid_mask_tracks_last[ind_ii[match_ii]] = masks_jj[...,ind_jj[match_ii]] # retain just the last masks thats relevant for us.
# vid_mask_tracks_last[ind_ii[match_ii]] = boxes_jj[ind_jj[match_ii]]
vid_match_check_bbox_tracks[ind_ii[match_ii]].append([ii+1, 1]) # success, append 0
no_match_ind_ii = np.setdiff1d(np.arange(len(boxes_ii_track_pred)), ind_ii)
no_match_ind_jj = np.setdiff1d(np.arange(len(boxes_jj)), ind_jj)
for idd in no_match_ind_ii:
# these tracks already exist so we just add to the existant tracks.
# vid_cell_tracks[idd].append([ii+1, -1]) # i guess this is to keep track of actual cell ids that we segmented.
vid_bbox_tracks[idd].append([ii+1, boxes_ii_track_prob[idd], boxes_ii_track_pred[idd]]) # this is to keep track of the actual bbox we use, including inferred.
# vid_cell_tracks_properties[idd].append([ii+1, properties_ii_track_pred[idd]])
# vid_bbox_tracks_last_time[idd] = ii+1 # let this be a record of the last time a 'real' segmentation was matched, not one inferred from optical flow.
# vid_mask_tracks_last[idd] = boxes_ii_track_pred[idd] # retain just the last masks thats relevant for us.
vid_match_check_bbox_tracks[idd].append([ii+1, 0]) # no success, append 0
for idd in no_match_ind_jj:
# these tracks don't exsit yet so we need to create new tracks.
# vid_cell_tracks.append([[ii+1, idd]]) # i guess this is to keep track of actual cell ids that we segmented.
vid_bbox_tracks.append([[ii+1, prob_jj[idd], boxes_jj[idd]]]) # this is to keep track of the actual bbox we use, including inferred.
# vid_cell_tracks_properties.append([[ii+1, masks_jj_properties[idd]]])
vid_bbox_tracks_last_time.append(ii+1) # let this be a record of the last time a 'real' segmentation was matched, not one inferred from optical flow.
# vid_mask_tracks_last.append(masks_jj[...,idd]) # retain just the last masks thats relevant for us.
# vid_mask_tracks_last.append(boxes_jj[idd])
vid_match_check_bbox_tracks.append([[ii+1, 1]])
# =============================================================================
# Combine the tracks togther
# =============================================================================
vid_bbox_tracks_all = terminated_vid_bbox_tracks + vid_bbox_tracks # combine
vid_match_checks_all = terminated_check_match_bbox_tracks + vid_match_check_bbox_tracks
# =============================================================================
# Compute some basic track properties for later filtering.
# =============================================================================
vid_bbox_tracks_all_lens = np.hstack([len(tra) for tra in vid_bbox_tracks_all])
vid_bbox_tracks_all_start_time = np.hstack([tra[0][0] for tra in vid_bbox_tracks_all])
print(vid_bbox_tracks_all_lens)
print(vid_bbox_tracks_all_start_time)
vid_bbox_tracks_lifetime_ratios = vid_bbox_tracks_all_lens / (len(vid_flow) - vid_bbox_tracks_all_start_time).astype(np.float)
# =============================================================================
# Turn into a proper array of n_tracks x n_time x 4 or 5....
# =============================================================================
vid_bbox_tracks_prob_all_array, vid_bbox_tracks_all_array = bbox_tracks_2_array(vid_bbox_tracks_all, nframes=nframes, ndim=boxes_ii.shape[1])
vid_match_checks_all_array = bbox_scalar_2_array(vid_match_checks_all, nframes=nframes)
# =============================================================================
# Apply the given filtering parameters for visualization else it will be messy.
# =============================================================================
if to_viz:
fig, ax = plt.subplots()
ax.scatter(vid_bbox_tracks_all_start_time,
vid_bbox_tracks_all_lens,
c=vid_bbox_tracks_lifetime_ratios,
vmin=0,
vmax=1, cmap='coolwarm')
plt.show()
# keep filter
keep_filter = np.logical_and(vid_bbox_tracks_all_lens>=min_tra_len_filter,
vid_bbox_tracks_lifetime_ratios>=min_tra_lifetime_ratio)
keep_ids = np.arange(len(vid_bbox_tracks_all_lens))[keep_filter]
plot_vid_bbox_tracks_all = vid_bbox_tracks_all_array[keep_ids].copy()
plot_colors = sns.color_palette('hls', len(plot_vid_bbox_tracks_all))
# print(len(plot_vid_bbox_tracks_all), len(vid_bbox_tracks_all_array))
# iterate over time.
for frame_no in np.arange(nframes):
fig, ax = plt.subplots(figsize=(5,5))
plt.title('Frame: %d' %(frame_no+1))
if vid is not None:
vid_overlay = vid[frame_no].copy()
else:
vid_overlay = np.zeros(im_shape)
ax.imshow(vid_overlay, cmap='gray')
for ii in np.arange(len(plot_vid_bbox_tracks_all))[:]:
bbox_tra_ii = plot_vid_bbox_tracks_all[ii][frame_no] # fetch it at this point in time.
if ~np.isnan(bbox_tra_ii[0]):
# then there is a valid bounding box.
x1,y1,x2,y2 = bbox_tra_ii
ax.plot( [x1,x2,x2,x1,x1],
[y1,y1,y2,y2,y1], lw=1, color = plot_colors[ii])
ax.set_xlim([0, im_shape[1]-1])
ax.set_ylim([im_shape[0]-1, 0])
plt.axis('off')
plt.grid('off')
if saveanalysisfolder is not None:
fig.savefig(os.path.join(saveanalysisfolder_movie_bbox, 'Frame-%s.png' %(str(frame_no).zfill(3))), bbox_inches='tight')
plt.show()
plt.close(fig)
# spio.savemat(savematfile,
# {'boundaries':organoid_boundaries,
# 'initial_seg': seg0_grab,
# 'motion_source_map': spixels_B_motion_sources,
# 'seg_pts': organoid_segs_pts})
# return organoid_boundaries, organoid_segs_pts
return vid_bbox_tracks_prob_all_array, vid_bbox_tracks_all, vid_bbox_tracks_all_array, vid_match_checks_all_array, (vid_bbox_tracks_all_lens, vid_bbox_tracks_all_start_time, vid_bbox_tracks_lifetime_ratios)
def tracks2Darray_to_3Darray(tracks2D_time, uv_params_time):
from ..Unzipping import unzip_new as uzip
import numpy as np
m, n = uv_params_time.shape[1:-1]
n_tracks, n_time, _ = tracks2D_time.shape
tracks3D_time = np.zeros((n_tracks, n_time, 3))
tracks3D_time[:] = np.nan
for tt in np.arange(n_time):
# iterate over frame
uv_params = uv_params_time[tt].copy()
tracks2D_tt = tracks2D_time[:,tt].copy()
# only interpolate for non nan vals.
val_track = np.logical_not(np.isnan(tracks2D_tt[:,0]))
pts2D = tracks2D_tt[val_track>0].copy()
pts2D[...,0] = np.clip(pts2D[...,0], 0, n-1) # this assumes x,y...
pts2D[...,1] = np.clip(pts2D[...,1], 0, m-1)
# is this interpolation bad?
pts3D = np.array([uzip.map_intensity_interp2(pts2D[:,::-1],
grid_shape=(m,n),
I_ref=uv_params[...,ch],
method='linear',
cast_uint8=False, s=0) for ch in np.arange(uv_params.shape[-1])]).T
tracks3D_time[val_track>0, tt, :] = pts3D.copy()
return tracks3D_time
# =============================================================================
# Add some track postprocessing support namely removal of all nan tracks and non-max suppression amongst tracks. (operating purely on bboxes!)
# =============================================================================
def calculate_iou_matrix_time(box_arr1, box_arr2, eps=1e-9):
import numpy as np
x11 = box_arr1[...,0]; y11 = box_arr1[...,1]; x12 = box_arr1[...,2]; y12 = box_arr1[...,3]
x21 = box_arr2[...,0]; y21 = box_arr2[...,1]; x22 = box_arr2[...,2]; y22 = box_arr2[...,3]
m,n = x11.shape
# # n_tracks x n_time.
# flip this.
x11 = x11.T; y11 = y11.T; x12 = x12.T; y12 = y12.T
x21 = x21.T; y21 = y21.T; x22 = x22.T; y22 = y22.T
xA = np.maximum(x11[...,None], x21[:,None,:])
yA = np.maximum(y11[...,None], y21[:,None,:])
xB = np.minimum(x12[...,None], x22[:,None,:])
yB = np.minimum(y12[...,None], y22[:,None,:])
interArea = np.maximum((xB - xA + eps), 0) * np.maximum((yB - yA + eps), 0)
boxAArea = (x12 - x11 + eps) * (y12 - y11 + eps)
boxBArea = (x22 - x21 + eps) * (y22 - y21 + eps)
# iou = interArea / (boxAArea + np.transpose(boxBArea) - interArea)
iou = interArea / (boxAArea[...,None] + boxBArea[:,None,:] - interArea)
# # iou = iou.reshape((m,n))
return iou
# replace with iou bbox_tracks
def iou_boundary_tracks(tra_1, tra_2):
import numpy as np
n_pts = len(tra_1)
iou_time = np.zeros(n_pts)
for ii in range(n_pts):
tra_1_ii = tra_1[ii]
tra_2_ii = tra_2[ii]
if np.isnan(tra_1_ii[0,0]) or np.isnan(tra_2_ii[0,0]):
iou_time[ii] = np.nan
else:
x1, x2 = np.min(tra_1_ii[...,1]), np.max(tra_1_ii[...,1])
y1, y2 = np.min(tra_1_ii[...,0]), np.max(tra_1_ii[...,0])
x1_, x2_ = np.min(tra_2_ii[...,1]), np.max(tra_2_ii[...,1])
y1_, y2_ = np.min(tra_2_ii[...,0]), np.max(tra_2_ii[...,0])
bbox1 = np.hstack([x1,y1,x2,y2])
bbox2 = np.hstack([x1_,y1_,x2_,y2_])
print(bbox1, bbox2)
iou_12 = get_iou(bbox1, bbox2)
iou_time[ii] = iou_12
return iou_time
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x, y) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
Returns
-------
float
in [0, 1]
"""
if np.sum(bb1) < 1 and np.sum(bb2) < 1:
iou = 0
else:
bb1 = {'x1': bb1[0],
'y1': bb1[1],
'x2': bb1[2],
'y2': bb1[3]}
bb2 = {'x1': bb2[0],
'y1': bb2[1],
'x2': bb2[2],
'y2': bb2[3]}
# print(bb1)
# print(bb2)
# test for 0
# allow for collapsed boxes.
assert bb1['x1'] <= bb1['x2']
assert bb1['y1'] <= bb1['y2']
assert bb2['x1'] <= bb2['x2']
assert bb2['y1'] <= bb2['y2']
# determine the coordinates of the intersection rectangle
x_left = max(bb1['x1'], bb2['x1'])
y_top = max(bb1['y1'], bb2['y1'])
x_right = min(bb1['x2'], bb2['x2'])
y_bottom = min(bb1['y2'], bb2['y2'])
if x_right < x_left or y_bottom < y_top:
return 0.0
# The intersection of two axis-aligned bounding boxes is always an
# axis-aligned bounding box
intersection_area = (x_right - x_left) * (y_bottom - y_top)
# compute the area of both AABBs
bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1'])
bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1'])
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
assert iou >= 0.0
assert iou <= 1.0
return iou
def iou_bbox_tracks(tra_1, tra_2):
import numpy as np
n_pts = len(tra_1)
iou_time = np.zeros(n_pts)
for ii in range(n_pts):
tra_1_ii = tra_1[ii] # get the track at a particular timepoint should be 4
tra_2_ii = tra_2[ii]
if np.isnan(tra_1_ii[0,0]) or np.isnan(tra_2_ii[0,0]):
iou_time[ii] = np.nan # prop the nan onwards.
else:
x1, y1, x2, y2 = tra_1_ii
x1_, y1_, x2_, y2_ = tra_2_ii
# x1, x2 = np.min(tra_1_ii[...,1]), np.max(tra_1_ii[...,1])
# y1, y2 = np.min(tra_1_ii[...,0]), np.max(tra_1_ii[...,0])
# x1_, x2_ = np.min(tra_2_ii[...,1]), np.max(tra_2_ii[...,1])
# y1_, y2_ = np.min(tra_2_ii[...,0]), np.max(tra_2_ii[...,0])
bbox1 = np.hstack([x1,y1,x2,y2])
bbox2 = np.hstack([x1_,y1_,x2_,y2_])
# print(bbox1, bbox2)
iou_12 = get_iou(bbox1, bbox2)
iou_time[ii] = iou_12
return iou_time
def pairwise_iou_tracks(boundaries_list):
import itertools
import numpy as np
Ns = np.hstack([len(bb) for bb in boundaries_list]) # this is for dissecting IDs.
ind_ids = np.hstack([[str(jj)+'_'+str(ii) for jj in range(Ns[ii])] for ii in range(len(Ns))])
# stack all of them together.
all_boundaries = np.vstack(boundaries_list)
# print(all_boundaries.shape)
sim_matrix = np.zeros((len(all_boundaries), len(all_boundaries)))
shared_time_matrix = np.zeros((len(all_boundaries), len(all_boundaries)))
for i, j in itertools.combinations(range(len(all_boundaries)),2):
boundary_i = all_boundaries[i]
boundary_j = all_boundaries[j]
# iou_track = iou_boundary_tracks(boundary_i, boundary_j)
iou_track = iou_bbox_tracks(boundary_i, boundary_j)
sim_matrix[i,j] = np.nanmean(iou_track)
sim_matrix[j,i] = np.nanmean(iou_track)
shared_time_matrix[i,j] = ~np.isnan(iou_track).sum()
shared_time_matrix[j,i] = ~np.isnan(iou_track).sum()
return ind_ids, (sim_matrix, shared_time_matrix)
def pairwise_iou_tracks_fast(boundaries_list, eps=1e-9, return_bbox=False, avg_func=np.nanmean):
import numpy as np
import time
Ns = np.hstack([len(bb) for bb in boundaries_list]) # this is for dissecting IDs.
ind_ids = np.hstack([[str(jj)+'_'+str(ii) for jj in range(Ns[ii])] for ii in range(len(Ns))])
# stack all of them together.
all_boundaries = np.vstack(boundaries_list) # flatten all.
# # turn the boundaries into bbox.
# all_boundaries_bbox_xmin = np.min(all_boundaries[...,0], axis=-1)
# all_boundaries_bbox_xmax = np.max(all_boundaries[...,2], axis=-1)
# all_boundaries_bbox_ymin = np.min(all_boundaries[...,1], axis=-1)
# all_boundaries_bbox_ymax = np.max(all_boundaries[...,3], axis=-1)
# all_boundaries_bbox = np.concatenate([all_boundaries_bbox_xmin[...,None],
# all_boundaries_bbox_ymin[...,None],
# all_boundaries_bbox_xmax[...,None],
# all_boundaries_bbox_ymax[...,None]], axis=-1)
all_boundaries_bbox = all_boundaries.copy()
all_sim_matrix = calculate_iou_matrix_time(all_boundaries_bbox,
all_boundaries_bbox,
eps=eps)
sim_matrix = avg_func(all_sim_matrix, axis=0)
shared_time_matrix = np.sum(~np.isnan(all_sim_matrix), axis=0)
if return_bbox:
return ind_ids, (sim_matrix, shared_time_matrix), (all_boundaries_bbox, sim_matrix)
else:
return ind_ids, (sim_matrix, shared_time_matrix)
def unique_pts(a):
import numpy as np
# returns the unique rows of an array.
return np.vstack(list({tuple(row) for row in a}))
def get_id_cliques(id_list):
"""
given a list of identities, merges the common ids into a cluster/clique
"""
N = len(id_list)
cliques = [id_list[0]]
for ii in range(1, N):
id_list_ii = id_list[ii]
add_clique = True
for cc_i, cc in enumerate(cliques):
if len(np.intersect1d(id_list_ii, cc)) > 0:
cliques[cc_i] = np.unique(np.hstack([cc, id_list_ii]))
add_clique = False
break
if add_clique:
cliques.append(id_list_ii)
return cliques
# of the two versions, this is more useful because it ensures more temporal continuity.
def objectness_score_tracks_time(track, vid_score, mean_func=np.nanmean):
# give an image and a timepoint which the image corresponds to, to get the objectness score. default uses the first timepoint of the video.
from skimage.draw import polygon
img_shape = vid_score[0].shape
nframes = len(track)
scores = []
for frame in range(nframes):
coords = track[frame].copy()
print(coords)
if ~np.isnan(coords[0]):
x1,y1,x2,y2 = coords
coords = np.vstack([[y1,y1,y2,y2],
[x1,x2,x2,x1]])
rr,cc = polygon(coords[:,0],
coords[:,1], shape=img_shape)
score = mean_func(vid_score[frame][rr,cc])
scores.append(score)
else:
scores.append(0)
score = np.nanmean(scores)
return score
def track_iou_time(track, use_bbox=True):
"""
frame to frame iou score
"""
nframes = len(track)
first_diff_iou = []
for frame_no in np.arange(nframes-1):
tra_1 = track[frame_no]
tra_2 = track[frame_no+1]
if np.isnan(tra_1[0]) or np.isnan(tra_2[0]):
first_diff_iou.append(np.nan)
else:
if use_bbox:
x1, y1, x2, y2 = tra_1
x1_, y1_, x2_, y2_ = tra_2
# x1, x2 = np.min(tra_1[...,1]), np.max(tra_1[...,1])
# y1, y2 = np.min(tra_1[...,0]), np.max(tra_1[...,0])
# x1_, x2_ = np.min(tra_2[...,1]), np.max(tra_2[...,1])
# y1_, y2_ = np.min(tra_2[...,0]), np.max(tra_2[...,0])
bbox1 = np.hstack([x1,y1,x2,y2])
bbox2 = np.hstack([x1_,y1_,x2_,y2_])
# print(bbox1, bbox2)
iou_12 = get_iou(bbox1, bbox2)
first_diff_iou.append(iou_12)
first_diff_iou = np.hstack(first_diff_iou)
return first_diff_iou
# the following bypasses the need for point alignment along the tracks? by using area.
def smoothness_score_tracks_iou(track, mean_func=np.nanmean, second_order=False, use_bbox=True):
# get the second order track differences
# from skimage.draw import polygon
import numpy as np
first_diff_iou = track_iou_time(track, use_bbox=use_bbox)
if second_order:
second_diff_norm = np.gradient(first_diff_iou)
else:
second_diff_norm = first_diff_iou.copy()
# second_diff_norm = np.nanmean(second_diff_norm, axis=1) # obtain the mean over the boundaries., should we use median?
if second_order:
score = -mean_func(second_diff_norm) # this should be maxed for iou.
else:
score = mean_func(second_diff_norm)
return score
def nan_stability_score_tracks(track):
"""
simply the fraction of frames for which we were able to successfully track the object.
"""
len_track = float(len(track))
valid_track_times = np.sum(~np.isnan(track[:,0]))
score = valid_track_times / len_track
return score
def non_stable_track_suppression_filter(obj_vid,
org_tracks_list, # use the bbox directly.
track_overlap_thresh=0.25,
weight_nan=1., weight_smooth=0.1, max_obj_frames=5,
obj_mean_func=np.nanmean,
smoothness_mean_func=np.nanmean,
fast_comp=True,
debug_viz=False):
"""
Combines the utility codes above to filter the raw organoid boundary tracks. extends to single and multiple channels.
need to absolutely change this...
obj_vid: the metric to score objectness ....
"""
if debug_viz:
import pylab as plt
# 1. apply iou calculations pairwise between tracks to score overlap across channels
if fast_comp:
ind_ids, (sim_matrix, shared_time_matrix) = pairwise_iou_tracks_fast(org_tracks_list)
# detrend the diagonals.(which is self connections)
sim_matrix = sim_matrix - np.diag(np.diag(sim_matrix))
else:
ind_ids, (sim_matrix, shared_time_matrix) = pairwise_iou_tracks(org_tracks_list) # this concatenates all the tracks etc together, resolving all inter-, intra- overlaps
sim_matrix_ = sim_matrix.copy()
sim_matrix_[np.isnan(sim_matrix)] = 0 # replace any nan values which will not be useful.
# 2. detect overlaps and cliques (clusters of tracks that correspond to one dominant organoid)
tracks_overlap = np.where(sim_matrix_ >= track_overlap_thresh)
# print(tracks_overlap)
if len(tracks_overlap[0]) > 0:
# 2b. if there is any evidence of overlap! we collect this all together.
overlap_positive_inds = np.vstack(tracks_overlap).T
overlap_positive_inds = np.sort(overlap_positive_inds, axis=1)
# print(overlap_positive_inds)
# overlap_positive_inds = np.unique(overlap_positive_inds, axis=0) #remove duplicate rows.
overlap_positive_inds = unique_pts(overlap_positive_inds)
# merge these indices to identify unique cliques ... -> as those will likely be trying to track the same organoid.
cliq_ids = get_id_cliques(overlap_positive_inds)
# 3. clique resolution -> determining which organoid is actually being tracked, and which track offers best tracking performance on average from all candidates in the clique.
assigned_cliq_track_ids = [] # stores which of the tracks we should use from the overlapped channels.
for cc in cliq_ids[:]:
# iterate, use objectness score provided by the input vid, to figure out which organoid is being tracked.
ind_ids_cc = ind_ids[cc] # what are the possible ids here.
obj_score_cc = []
tra_stable_scores_cc = []
# in the order of organoid id and channel.
if debug_viz:
import seaborn as sns
ch_colors = sns.color_palette('Set1', len(org_tracks_list))
fig, ax = plt.subplots()
ax.imshow(obj_vid[0], alpha=0.5) # just visualise the first frame is enough.
for ind_ids_ccc in ind_ids_cc:
org_id, org_ch = ind_ids_ccc.split('_')
org_id = int(org_id)
org_ch = int(org_ch)
boundary_org = org_tracks_list[org_ch][org_id]
# this is the problem?
# objectness score for deciding the dominant organoid.
obj_score = objectness_score_tracks_time(boundary_org[:max_obj_frames],
obj_vid[:max_obj_frames,...,org_ch],
mean_func=obj_mean_func)
obj_score_cc.append(obj_score)
# stability score which is weighted on 2 factors. to determine which track.
nan_score = nan_stability_score_tracks(boundary_org)
# this should be a minimisation ..... !
# smooth_score = smoothness_score_tracks(boundary_org,
# mean_func=np.nanmean)
smooth_score = smoothness_score_tracks_iou(boundary_org,
mean_func=smoothness_mean_func)
tra_stable_scores_cc.append(weight_nan*nan_score+weight_smooth*smooth_score)
if debug_viz:
ax.set_title( 'org: %s, stable: %s' %(ind_ids_cc[np.argmax(obj_score_cc)],
ind_ids_cc[np.argmax(tra_stable_scores_cc)]))
plt.show()
# stack all the scores.
obj_score_cc = np.hstack(obj_score_cc)
tra_stable_scores_cc = np.hstack(tra_stable_scores_cc)
# decide on the organoid and track (argmax)
cliq_org_id_keep = ind_ids_cc[np.argmax(obj_score_cc)]
cliq_track_id_keep = ind_ids_cc[np.argmax(tra_stable_scores_cc)]
# save this out for processing.
assigned_cliq_track_ids.append([cliq_org_id_keep, cliq_track_id_keep])
# 4. new org_tracks_list production based on the filtered information.
org_tracks_list_out = []
for list_ii in range(len(org_tracks_list)):
org_tracks_list_ii = org_tracks_list[list_ii]
org_tracks_list_ii_out = []
for org_ii in range(len(org_tracks_list_ii)):
tra_int_id = str(org_ii)+'_'+str(list_ii) # create the string id lookup.
include_track = True
for cliq_ii in range(len(cliq_ids)):
ind_ids_cc = ind_ids[cliq_ids[cliq_ii]] # gets the clique members in string form -> is this organoid part of a clique.
if tra_int_id in ind_ids_cc:
include_track = False # do not automatically include.
# test is this the dominant organoid in the clique.
cliq_organoid_assign, cliq_organoid_assign_track = assigned_cliq_track_ids[cliq_ii] # get the assignment information of the clique.
if tra_int_id == cliq_organoid_assign:
# if this is the dominant organoid then we add the designated track.
org_id_tra_assign, org_ch_tra_assign = cliq_organoid_assign_track.split('_')
org_id_tra_assign = int(org_id_tra_assign); org_ch_tra_assign=int(org_ch_tra_assign)
org_tracks_list_ii_out.append(org_tracks_list[org_ch_tra_assign][org_id_tra_assign])
# do nothing otherwise -> exclude this organoid basically.
if include_track:
# directly include.
org_tracks_list_ii_out.append(org_tracks_list_ii[org_ii])
if len(org_tracks_list_ii_out) > 0:
# stack the tracks.
org_tracks_list_ii_out = np.array(org_tracks_list_ii_out)
org_tracks_list_out.append(org_tracks_list_ii_out)
else:
org_tracks_list_out = list(org_tracks_list)
# cleaned tracks, in the same input format as a list of numpy tracks for each channel.
return org_tracks_list_out
def non_maxlen_track_suppression_filter(obj_vid,
org_tracks_list, # use the bbox directly.
track_overlap_thresh=0.25,
max_obj_frames=5,
obj_mean_func=np.nanmean,
fast_comp=True,
debug_viz=False):
"""
Combines the utility codes above to filter the raw organoid boundary tracks. extends to single and multiple channels.
need to absolutely change this...
obj_vid: the metric to score objectness ....
"""
if debug_viz:
import pylab as plt
# 1. apply iou calculations pairwise between tracks to score overlap across channels - we only suppress. those that share a lot of overlap.
if fast_comp:
ind_ids, (sim_matrix, shared_time_matrix) = pairwise_iou_tracks_fast(org_tracks_list)
# detrend the diagonals.(which is self connections)
sim_matrix = sim_matrix - np.diag(np.diag(sim_matrix))
else:
ind_ids, (sim_matrix, shared_time_matrix) = pairwise_iou_tracks(org_tracks_list) # this concatenates all the tracks etc together, resolving all inter-, intra- overlaps
sim_matrix_ = sim_matrix.copy()
sim_matrix_[np.isnan(sim_matrix)] = 0 # replace any nan values which will not be useful.
# 2. detect overlaps and cliques (clusters of tracks that correspond to one dominant organoid)
tracks_overlap = np.where(sim_matrix_ >= track_overlap_thresh)
# print(tracks_overlap)
if len(tracks_overlap[0]) > 0:
# 2b. if there is any evidence of overlap! we collect this all together.
overlap_positive_inds = np.vstack(tracks_overlap).T
overlap_positive_inds = np.sort(overlap_positive_inds, axis=1)
# print(overlap_positive_inds)
# overlap_positive_inds = np.unique(overlap_positive_inds, axis=0) #remove duplicate rows.
overlap_positive_inds = unique_pts(overlap_positive_inds)
# merge these indices to identify unique cliques ... -> as those will likely be trying to track the same organoid.
cliq_ids = get_id_cliques(overlap_positive_inds)
# 3. clique resolution -> determining which organoid is actually being tracked, and which track offers best tracking performance on average from all candidates in the clique.
assigned_cliq_track_ids = [] # stores which of the tracks we should use from the overlapped channels.
for cc in cliq_ids[:]:
# iterate, use objectness score provided by the input vid, to figure out which organoid is being tracked.
ind_ids_cc = ind_ids[cc] # what are the possible ids here.
print(ind_ids_cc)
obj_score_cc = []
tra_stable_scores_cc = []
# in the order of organoid id and channel.
if debug_viz:
import seaborn as sns
ch_colors = sns.color_palette('Set1', len(org_tracks_list))
fig, ax = plt.subplots()
ax.imshow(obj_vid[0], alpha=0.5) # just visualise the first frame is enough.
for ind_ids_ccc in ind_ids_cc:
org_id, org_ch = ind_ids_ccc.split('_')
org_id = int(org_id)
org_ch = int(org_ch)
boundary_org = org_tracks_list[org_ch][org_id]
print(boundary_org)
# # this is the problem?
# # objectness score for deciding the dominant organoid.
# obj_score = [ np.logical_not(org_tra_frame[0]) for org_tra_frame in boundary_org]
# obj_score = np.sum(obj_score)
# obj_score_cc.append(obj_score) # pick the longest track.
obj_score = objectness_score_tracks_time(boundary_org[:],
obj_vid[...,org_ch],
mean_func=obj_mean_func)
obj_score_cc.append(obj_score)
# stability score which is weighted on 2 factors. to determine which track.
nan_score = nan_stability_score_tracks(boundary_org)
# # this should be a minimisation ..... !
# # smooth_score = smoothness_score_tracks(boundary_org,
# # mean_func=np.nanmean)
# smooth_score = smoothness_score_tracks_iou(boundary_org,
# mean_func=smoothness_mean_func)
# tra_stable_scores_cc.append(weight_nan*nan_score+weight_smooth*smooth_score)
tra_stable_scores_cc.append(nan_score)
if debug_viz:
ax.set_title( 'org: %s, stable: %s' %(ind_ids_cc[np.argmax(obj_score_cc)],
ind_ids_cc[np.argmax(obj_score_cc)]))
plt.show()
# stack all the scores.
obj_score_cc = np.hstack(obj_score_cc)
tra_stable_scores_cc = np.hstack(tra_stable_scores_cc)
print(obj_score_cc)
print(tra_stable_scores_cc)
print('===')
# decide on the organoid and track (argmax)
cliq_org_id_keep = ind_ids_cc[np.argmax(obj_score_cc)]
cliq_track_id_keep = ind_ids_cc[np.argmax(obj_score_cc)]
# save this out for processing.
assigned_cliq_track_ids.append([cliq_org_id_keep, cliq_track_id_keep])
# 4. new org_tracks_list production based on the filtered information.
org_tracks_list_out = []
for list_ii in range(len(org_tracks_list)):
org_tracks_list_ii = org_tracks_list[list_ii]
org_tracks_list_ii_out = []
for org_ii in range(len(org_tracks_list_ii)):
tra_int_id = str(org_ii)+'_'+str(list_ii) # create the string id lookup.
include_track = True
for cliq_ii in range(len(cliq_ids)):
ind_ids_cc = ind_ids[cliq_ids[cliq_ii]] # gets the clique members in string form -> is this organoid part of a clique.
if tra_int_id in ind_ids_cc:
include_track = False # do not automatically include.
# test is this the dominant organoid in the clique.
cliq_organoid_assign, cliq_organoid_assign_track = assigned_cliq_track_ids[cliq_ii] # get the assignment information of the clique.
if tra_int_id == cliq_organoid_assign:
# if this is the dominant organoid then we add the designated track.
org_id_tra_assign, org_ch_tra_assign = cliq_organoid_assign_track.split('_')
org_id_tra_assign = int(org_id_tra_assign); org_ch_tra_assign=int(org_ch_tra_assign)
org_tracks_list_ii_out.append(org_tracks_list[org_ch_tra_assign][org_id_tra_assign])
# do nothing otherwise -> exclude this organoid basically.
if include_track:
# directly include.
org_tracks_list_ii_out.append(org_tracks_list_ii[org_ii])
if len(org_tracks_list_ii_out) > 0:
# stack the tracks.
org_tracks_list_ii_out = np.array(org_tracks_list_ii_out)
org_tracks_list_out.append(org_tracks_list_ii_out)
else:
org_tracks_list_out = list(org_tracks_list)
# cleaned tracks, in the same input format as a list of numpy tracks for each channel.
return org_tracks_list_out
def filter_nan_tracks( boundary ):
"""
function removes all tracks that for the entire duration is only nan.
"""
import numpy as np
boundaries_out = []
for ii in range(len(boundary)):
tra = boundary[ii]
tra_len = len(tra)
n_nans = 0
for tra_tt in tra:
if np.isnan(tra_tt[0]):
n_nans+=1
if n_nans < tra_len:
boundaries_out.append(tra) # append the whole track
if len(boundaries_out) > 0:
boundaries_out = np.array(boundaries_out)
return boundaries_out
| 72,029 | 42.920732 | 256 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Parameters/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Parameters/params.py
|
"""
This module generates some general default parameter settings to help get started with certain functions with many parameters
"""
def optimesh_relaxation_config():
r""" parameters for doing CVT relaxation of meshes using the optimesh library
see https://pypi.org/project/optimesh/
"""
params = {}
params['relax_method'] = 'CVT (block-diagonal)'
params['tol'] = 1.0e-5
params['n_iters']=20
return params
# Farneback 2D optical flow
def farneback2D_optical_flow():
r""" parameters for extracting optical flow using Farneback method
see :func:`unwrap3D.Tracking.tracking.Eval_dense_optic_flow`
"""
params = {}
params['pyr_scale'] = 0.5
params['levels'] = 3
params['winsize'] = 15
params['iterations'] = 5
params['poly_n'] = 3
params['poly_sigma'] = 1.2
params['flags'] = 0
return params
def affine_register_matlab():
r""" specify parameters for running Matlab imregtform to do Affine registration
see :func:`unwrap3D.Registration.registration.matlab_affine_register` for registering two timepoints and
see :func:`unwrap3D.Registration.registration.matlab_group_register_batch` for registering a video with switching of reference images.
"""
params = {}
params['downsample'] = [16., 8., 4.], # the scales to do registration at. [16, 8, 4, 2, 1] will continue on 2x downsampled and original resolution.
params['modality'] = 'multimodal' # str specifying we want the multimodal registration option of imregtform
params['type'] = 'similarity' # type of transform
params['view'] = None
params['return_img'] = 1
return params
def demons_register_matlab():
r""" specify parameters for running Matlab imregdemons to do Demon's registration
see :func:`unwrap3D.Registration.registration.nonregister_3D_demons_matlab`
"""
params = {}
params['alpha'] = 0.1
params['levels'] = [8,4,2,1]
params['warps'] = [4,2,0,0]
return params
def gradient_descent_affine_reg():
r""" parameters for affine registration using simpleITK using Gradient Descent optimizer
see :func:`unwrap3D.Registration.registration.SITK_multiscale_affine_registration`
"""
params = {}
params['learningRate'] = 1
params['numberOfIterations'] = 500
params['convergenceMinimumValue'] = 1e-6
params['convergenceWindowSize'] = 10
return params
def evolutionary_affine_reg():
r""" parameters for affine registration using simpleITK using Evolutionary optimizer
see :func:`unwrap3D.Registration.registration.SITK_multiscale_affine_registration`
"""
params = {}
params['numberOfIterations'] = 100
params['epsilon'] = 1.5e-4
params['initialRadius'] = 6.25e-3
params['growthFactor'] = 1.01
params['shrinkFactor'] = -1.0
return params
# demons multiscale registration in simpleITK
| 2,926 | 31.164835 | 151 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Mesh/meshtools.py
|
from ..Geometry import geometry as geom
from ..Unzipping import unzip as uzip
def read_mesh(meshfile,
process=False,
validate=False,
keep_largest_only=False):
r""" Wrapper around trimesh.load_mesh such that the mesh is read exactly with the same vertices and face indexes by default. Additionally we introduce a convenient flag to keep just the largest mesh component
Parameters
----------
meshfile : filepath
input mesh of any common format, e.g. .obj, .ply, .dae, .stl, see https://trimsh.org/index.html
process : bool
If True, degenerate and duplicate faces will be removed immediately, and some functions will alter the mesh to ensure consistent results.
validate : bool
if True, Nan and Inf values will be removed immediately and vertices will be merged
keep_largest_only : bool
if True, keep only the largest connected component of the mesh, ignoring whether this is watertight or not
Returns
-------
mesh : trimesh.Trimesh or trimesh.Scene
loaded mesh geometry
"""
import trimesh
import numpy as np
mesh = trimesh.load_mesh(meshfile,
validate=validate,
process=process)
if keep_largest_only:
mesh_comps = mesh.split(only_watertight=False)
mesh = mesh_comps[np.argmax([len(cc.vertices) for cc in mesh_comps])]
return mesh
def create_mesh(vertices,faces,vertex_colors=None, face_colors=None):
r""" Wrapper around trimesh.Trimesh to create a mesh given the vertices, faces and optionally vertex colors or face colors.
Parameters
----------
vertices : (n_vertices,3) array
the vertices of the mesh geometry
faces : (n_faces,3) array
the 0-indexed integer indices indicating how vertices are joined together to form a triangle element
vertex_colors : (n_vertices,3) array
if provided, an array of the RGB color values per vertex
face_colors : (n_faces,3) array
if provided, an array of the RGB color values per face
Returns
-------
mesh : trimesh.Trimesh or trimesh.Scene
created mesh geometry with colors saved in mesh.visual.vertex_colors or mesh.visual.face_colors
"""
import trimesh
mesh = trimesh.Trimesh(vertices=vertices,
faces=faces,
process=False,
validate=False,
vertex_colors=vertex_colors,
face_colors=face_colors)
return mesh
def submesh(mesh,
faces_sequence,
mesh_face_attributes,
repair=True,
only_watertight=False,
min_faces=None,
append=False,**kwargs):
r""" Return a subset of a mesh. Function taken from the Trimesh library.
Parameters
------------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
only_watertight : bool
Only return submeshes which are watertight.
append : bool
Return a single mesh which has the faces appended, if this flag is set, only_watertight is ignored
Returns
----------
if append : Trimesh object
else list of Trimesh objects
"""
import copy
import numpy as np
def type_bases(obj, depth=4):
"""
Return the bases of the object passed.
"""
import collections
bases = collections.deque([list(obj.__class__.__bases__)])
for i in range(depth):
bases.append([i.__base__ for i in bases[-1] if i is not None])
try:
bases = np.hstack(bases)
except IndexError:
bases = []
# we do the hasattr as None/NoneType can be in the list of bases
bases = [i for i in bases if hasattr(i, '__name__')]
return np.array(bases)
def type_named(obj, name):
"""
Similar to the type() builtin, but looks in class bases
for named instance.
Parameters
------------
obj: object to look for class of
name : str, name of class
Returns
----------
named class, or None
"""
# if obj is a member of the named class, return True
name = str(name)
if obj.__class__.__name__ == name:
return obj.__class__
for base in type_bases(obj):
if base.__name__ == name:
return base
raise ValueError('Unable to extract class of name ' + name)
# evaluate generators so we can escape early
faces_sequence = list(faces_sequence)
if len(faces_sequence) == 0:
return []
# avoid nuking the cache on the original mesh
original_faces = mesh.faces.view(np.ndarray)
original_vertices = mesh.vertices.view(np.ndarray)
faces = []
vertices = []
normals = []
visuals = []
attributes = []
# for reindexing faces
mask = np.arange(len(original_vertices))
for index in faces_sequence:
# sanitize indices in case they are coming in as a set or tuple
index = np.asanyarray(index)
if len(index) == 0:
# regardless of type empty arrays are useless
continue
if index.dtype.kind == 'b':
# if passed a bool with no true continue
if not index.any():
continue
# if fewer faces than minimum
if min_faces is not None and index.sum() < min_faces:
continue
elif min_faces is not None and len(index) < min_faces:
continue
current = original_faces[index]
unique = np.unique(current.reshape(-1)) # unique points.
# redefine face indices from zero
mask[unique] = np.arange(len(unique))
normals.append(mesh.face_normals[index])
faces.append(mask[current])
vertices.append(original_vertices[unique])
attributes.append(mesh_face_attributes[index])
visuals.append(mesh.visual.face_subset(index))
if len(vertices) == 0:
return np.array([])
# we use type(mesh) rather than importing Trimesh from base
# to avoid a circular import
trimesh_type = type_named(mesh, 'Trimesh')
# generate a list of Trimesh objects
result = [trimesh_type(
vertices=v,
faces=f,
face_normals=n,
visual=c,
metadata=copy.deepcopy(mesh.metadata),
process=False) for v, f, n, c in zip(vertices,
faces,
normals,
visuals)]
result = np.array(result)
return result, attributes
def split_mesh(mesh,
mesh_face_attributes,
adjacency=None,
only_watertight=False,
engine=None, **kwargs):
r""" Split a mesh into multiple meshes from face connectivity taken from the Trimesh library. If only_watertight is true it will only return watertight meshes and will attempt to repair
single triangle or quad holes.
Parameters
----------
mesh : trimesh.Trimesh
only_watertight: bool
Only return watertight components
adjacency : (n, 2) int
Face adjacency to override full mesh
engine : str or None
Which graph engine to use
Returns
----------
meshes : (m,) trimesh.Trimesh
Results of splitting
meshes_attributes : (m,d) attributes.
associated splitted attributes.
"""
import trimesh
import numpy as np
# used instead of trimesh functions in order to keep it consistent with the splitting of mesh attributes.
if adjacency is None:
adjacency = mesh.face_adjacency
# if only watertight the shortest thing we can split has 3 triangles
if only_watertight:
min_len = 4
else:
min_len = 1
components = trimesh.graph.connected_components(
edges=adjacency,
nodes=np.arange(len(mesh.faces)),
min_len=min_len,
engine=engine)
meshes, meshes_attributes = submesh(mesh,
components,
mesh_face_attributes,
**kwargs)
return meshes, meshes_attributes
def decimate_resample_mesh(mesh, remesh_samples, predecimate=True):
r""" Downsample (decimate) and optionally resample the mesh to equilateral triangles.
Parameters
----------
mesh : trimesh.Trimesh
input mesh
remesh_samples : 0-1
fraction of the number of vertex points to target in size of the output mesh
predecimate : bool
if True, small edges are first collapsed using igl.decimate in the ``igl`` library
Returns
-------
mesh : trimesh.Trimesh
output mesh
"""
# this will for sure change the connectivity
import pyacvd
import pyvista as pv
import igl
import trimesh
if predecimate:
_, V, F, _, _ = igl.decimate(mesh.vertices, mesh.faces, int(.9*len(mesh.vertices))) # there is bug?
if len(V) > 0: # have a check in here to prevent break down.
mesh = trimesh.Trimesh(V, F, validate=True) # why no good?
# print(len(mesh.vertices))
mesh = pv.wrap(mesh) # convert to pyvista format.
clus = pyacvd.Clustering(mesh)
clus.cluster(int(remesh_samples*len(mesh.points))) # this guarantees a remesh is possible.
mesh = clus.create_mesh()
mesh = trimesh.Trimesh(mesh.points, mesh.faces.reshape((-1,4))[:, 1:4], validate=True) # we don't care. if change
# print(mesh.is_watertight)
return mesh
def upsample_mesh(mesh, method='inplane'):
r""" Upsample a given mesh using simple barycentric splittng ('inplane') or using 'loop', which slightly smoothes the output
Parameters
----------
mesh : trimesh.Trimesh
input mesh
method : str
one of 'inplane' or 'loop' allowed in igl.upsample
Returns
-------
mesh_out : trimesh.Trimesh
output mesh
"""
"""
inplane or loop
"""
import igl
import trimesh
if method =='inplane':
uv, uf = igl.upsample(mesh.vertices, mesh.faces)
if method == 'loop':
uv, uf = igl.loop(mesh.vertices, mesh.faces)
mesh_out = trimesh.Trimesh(uv, uf, validate=False, process=False)
return mesh_out
def upsample_mesh_and_vertex_vals(mesh, vals, method='inplane'):
r""" Upsample a given mesh using simple barycentric splittng ('inplane') or using 'loop', which slightly smoothes the output and also reinterpolate any associated vertex values for the new mesh
Parameters
----------
mesh : trimesh.Trimesh
input mesh
vals : (n_vertices, n_features)
vertex based values to also upsample
method : str
one of 'inplane' or 'loop' allowed in igl.upsample
Returns
-------
mesh_out : trimesh.Trimesh
output mesh
"""
"""
inplane only... vals is the same length as mesh vertices.
"""
import igl
import trimesh
import numpy as np
if method =='inplane':
uv, uf = igl.upsample(mesh.vertices, mesh.faces) # get the new vertex and faces.
if method == 'loop':
uv, uf = igl.loop(mesh.vertices, mesh.faces)
vals_new = np.zeros((len(uv), vals.shape[-1])); vals_new[:] = np.nan
max_ind_mesh_in = len(mesh.vertices)
vals_new[:max_ind_mesh_in] = vals.copy()
old_new_edge_list = igl.edges(uf) # use the new faces.
old_new_edge_list = old_new_edge_list[old_new_edge_list[:,0]<max_ind_mesh_in]
vals_new[old_new_edge_list[::2,1]] = .5*(vals_new[old_new_edge_list[::2,0]]+vals_new[old_new_edge_list[1::2,0]])
mesh_out = trimesh.Trimesh(uv, uf, validate=False, process=False)
return mesh_out, vals_new
def marching_cubes_mesh_binary(vol,
presmooth=1.,
contourlevel=.5,
remesh=False,
remesh_method='pyacvd',
remesh_samples=.5,
remesh_params=None,
predecimate=True,
min_mesh_size=40000,
keep_largest_only=True,
min_comp_size=20,
split_mesh=True,
upsamplemethod='inplane'):
r""" Mesh an input binary volume using Marching Cubes algorithm with optional remeshing to improve mesh quality
Parameters
----------
vol : trimesh.Trimesh
input mesh
presmooth : scalar
pre Gaussian smoothing with the specified sigma to get a better marching cubes mesh.
contourlevel :
isolevel to extract the Marching cubes mesh
remesh_method : str
one of 'pyacvd' or 'optimesh'.
'pyacvd' : str
pyacvd uses voronoidal clustering i.e. kmeans clustering to produce a uniformly remeshing, see https://github.com/pyvista/pyacvd
'optimesh' : str
if selected, this method aims to relax the mesh vertices to a more uniform state, see https://github.com/meshpro/optimesh. This doesn't change the number of vertices and so effect of this is limited and there is some changing of the input shape
remesh_samples : 0-1
fraction of the number of vertex points to target in size of the output mesh
remesh_params : dict
only for remesh_method='optimesh'. See :func:`unwrap3D.Parameters.params.optimesh_relaxation_config` for template of parameter settings
predecimate : bool
if True, collapse the small edges in the Marching Cubes output before remeshing
min_mesh_size : int
minimum number of vertices in the output mesh
keep_largest_only : bool
if True, check and keep only the largest mesh component
min_comp_size : int
if keep_largest_only=False, remesh=True and split_mesh=True, individual connected components of the mesh is checked and only those > min_comp_size are kept. This is crucial if the mesh is to be remeshed. The remeshing fraction is applied to all components equally. Without this check, there will be errors as some mesh components become zero.
split_mesh : bool
if True, runs connected component to filter out Marching cubes components that are too small (keep_largest_only=False) or keep only the largest (keep_largest_only=True) prior to remeshing
upsamplemethod : str
one of 'inplane' or 'loop' allowed in igl.upsample. This is called to meet the minimum number of vertices in the final mesh as specified in ``min_mesh_size``
Returns
-------
mesh : trimesh.Trimesh
output mesh
"""
from skimage.filters import gaussian
import trimesh
try:
from skimage.measure import marching_cubes_lewiner
except:
from skimage.measure import marching_cubes
import igl
import numpy as np
if presmooth is not None:
img = gaussian(vol, sigma=presmooth, preserve_range=True)
img = img / img.max() # do this.
else:
img = vol.copy()
try:
V, F, _, _ = marching_cubes_lewiner(img, level=contourlevel, allow_degenerate=False)
except:
V, F, _, _ = marching_cubes(img, level=contourlevel, method='lewiner', allow_degenerate=False)
mesh = trimesh.Trimesh(V,F, validate=True)
if split_mesh:
mesh_comps = mesh.split(only_watertight=False)
if keep_largest_only:
mesh = mesh_comps[np.argmax([len(cc.vertices) for cc in mesh_comps])]
else:
mesh_comps = [mm for mm in mesh_comps if len(mm.faces)>=min_comp_size] # keep a min_size else the remeshing doesn't work
# combine_mesh_components
mesh = trimesh.util.concatenate(mesh_comps)
# we need to recombine this
# mesh = mesh_comps[np.argmax([len(cc.vertices) for cc in mesh_comps])]
if remesh:
if remesh_method == 'pyacvd':
mesh = decimate_resample_mesh(mesh, remesh_samples, predecimate=predecimate)
# other remesh is optimesh which allows us to reshift the vertices (change the connections)
if remesh_method == 'optimesh':
if predecimate:
_, V, F, _, _ = igl.decimate(mesh.vertices,mesh.faces, int(.9*len(mesh.faces))) # decimates up to the desired amount of faces?
mesh = trimesh.Trimesh(V, F, validate=True)
mesh, _, mean_quality = relax_mesh( mesh, relax_method=remesh_params['relax_method'], tol=remesh_params['tol'], n_iters=remesh_params['n_iters']) # don't need the quality parameters.
# print('mean mesh quality: ', mean_quality)
mesh_check = len(mesh.vertices) >= min_mesh_size # mesh_min size is only applied here.!
while(mesh_check==0):
mesh = upsample_mesh(mesh, method=upsamplemethod)
mesh_check = len(mesh.vertices) >= min_mesh_size
return mesh
def measure_props_trimesh(mesh, main_component=True, clean=True):
r""" Compute basic statistics and properties of a given mesh
- is Convex : Yes/No
- is Volume : Yes/No - is it closed such that a volume can be computed
- is Watertight : Yes/No - is it closed such that a volume can be computed
- orientability : Yes/No - can all faces be oriented the same way. Mobius strips and Klein bottles are non-orientable
- Euler number : or Euler characteristic, :math:`\chi` #vertices - #edges + #faces
- Genus : :math:`(2-2\chi)/2` if orientable or :math:`2-\chi` if nonorientable
Parameters
----------
mesh : trimesh.Trimesh
input mesh
main_component : bool
if True, get the largest mesh component and compute statistics on this
clean : bool
if True, removes NaN and infs and degenerate and duplicate faces which may affect the computation of some of these statistics
Returns
-------
props : dict
A dictionary containing the metrics
'convex' : bool
'volume' : bool
'watertight' : bool
'orientability' : bool
'euler_number' : scalar
'genus' : scalar
"""
import trimesh
import numpy as np
# check
# make sure we do a split
if clean:
mesh_ = trimesh.Trimesh(mesh.vertices,
mesh.faces,
validate=True,
process=True)
else:
mesh_ = mesh.copy()
mesh_comps = mesh_.split(only_watertight=False)
main_mesh = mesh_comps[np.argmax([len(cc.vertices) for cc in mesh_comps])]
props = {}
props['convex'] = main_mesh.is_convex
props['volume'] = main_mesh.is_volume
props['watertight'] = main_mesh.is_watertight
props['orientability'] = main_mesh.is_winding_consistent
props['euler_number'] = main_mesh.euler_number
if main_mesh.is_winding_consistent:
# if orientable we can use the euler_number computation. see wolfram mathworld!.
genus = (2.-props['euler_number'])/2.# euler = 2-2g
else:
genus = (2.-props['euler_number'])
props['genus'] = genus
return props
def measure_triangle_props(mesh_, clean=True):
r""" Compute statistics regarding the quality of the triangle faces
Parameters
----------
mesh_ : trimesh.Trimesh
input mesh
clean : bool
if True, removes NaN and infs and degenerate and duplicate faces which may affect the computation of some of these statistics
Returns
-------
props : dict
A dictionary containing the metrics
'min_angle' : scalar
minimum internal triangle angle of faces in degrees
'avg_angle' : scalar
mean internal triangle angle of faces in degrees
'max_angle' :
maximum internal triangle angle of faces in degrees
'std_dev angle' :
standard devation of internal triangle angle of faces in degrees
'min_quality' :
minimum triangle quality. triangle quality is measured as 2*inradius/circumradius
'avg_quality' :
mean triangle quality. triangle quality is measured as 2*inradius/circumradius
'max_quality' :
maximum triangle quality. triangle quality is measured as 2*inradius/circumradius
'quality'
per face quality. triangle quality is measured as 2*inradius/circumradius
'angles' :
all internal face angles
"""
import numpy as np
import trimesh
import igl
if clean:
mesh = trimesh.Trimesh(mesh_.vertices,
mesh_.faces,
validate=True,
process=True)
else:
mesh = mesh_.copy()
# if use_igl:
angles = igl.internal_angles(mesh.vertices, mesh.faces)
q = 2.* igl.inradius(mesh.vertices, mesh.faces) / igl.circumradius(mesh.vertices, mesh.faces)# 2 * inradius / circumradius
# mesh_meshplex = meshplex.MeshTri(mesh.vertices, mesh.faces)
# angles = mesh_meshplex.angles / np.pi * 180.
# q = mesh_meshplex.q_radius_ratio
props = {}
props['min_angle'] = np.nanmin(angles) / np.pi * 180.
props['avg_angle'] = np.nanmean(angles) / np.pi * 180.
props['max_angle'] = np.nanmax(angles) / np.pi * 180.
props['std_dev_angle'] = np.nanstd(angles) / np.pi * 180.
props['min_quality'] = np.nanmin(q)
props['avg_quality'] = np.nanmean(q)
props['max_quality'] = np.nanmax(q)
props['quality'] = q
props['angles'] = angles
return props
def PCA_rotate_mesh(binary, mesh=None, mesh_contour_level=.5):
r""" Compute principal components of a given binary through extracting the surface mesh or a used specified surface mesh
Parameters
----------
binary : array
input binary image
mesh : trimesh.Trimesh
a user-specified surface mesh
mesh_contour_level : scalar
if only a binary is provided Marching cubes is used to extract a surface mesh at the isolevel given by ``mesh_contour_level``
Returns
-------
pca_model : scikit-learn PCA model instance
a fitted princial components model for the mesh. see sklearn.decomposition.PCA for attributes
mean_pts : (3,) array
the centroid of the surface mesh with which points were demeaned prior to PCA
"""
import numpy as np
from sklearn.decomposition import PCA
from skimage.measure import marching_cubes_lewiner
import igl
if mesh is not None:
# we don't have a given surface, instead we need to segment.
v = mesh.vertices.copy()
f = mesh.faces.copy()
else:
# if use_surface:
v, f, _, _ = marching_cubes_lewiner(binary, level=mesh_contour_level)
# else:
# pts = np.argwhere(binary>0)
# pts = np.vstack(pts)
barycenter = igl.barycenter(v,f)
weights = igl.doublearea(v, f)
# print(weights.shape)
# print(barycenter.shape)
mean_pts = np.nansum( (weights / float(np.sum(weights)))[:,None] * barycenter, axis=0)
pts_ = v - mean_pts[None,:]
pca_model = PCA(n_components=pts_.shape[-1], random_state=0, whiten=False)
pca_model.fit(pts_)
return pca_model, mean_pts
def voxelize_image_mesh_pts(mesh, pad=50, dilate_ksize=3, erode_ksize=1, vol_shape=None, upsample_iters_max=10, pitch=2):
r""" Given a surface mesh, voxelises the mesh to create a closed binary volume to enable for exampled signed distance function comparison and for repairing small holes
Parameters
----------
mesh : trimesh.Trimesh
input mesh
pad : int
integer isotropic pad to create a volume grid if vol_shape is not given
dilate_ksize : int
optional dilation of the voxelized volume with a ball kernel of specified radius to fill holes so that scipy.ndimage.morphology.binary_fill_holes will allow a complete volume to be otained
erode_ksize : int
optional erosion of the voxelized volume with a ball kernel of specified radius
vol_shape : (m,n,l) tuple
the size of the volume image to voxelize onto
upsample_iters_max : int
the maximum number of recursive mesh subdivisions to achieve the target pitch
pitch : scalar
target side length of each voxel, the mesh will be recursively subdivided up to the maximum number of iterations specified by ``upsample_iters_max`` until this is met.
Returns
-------
smooth_img_binary : (MxNxL) array
binary volume image
"""
# works only for meshs from images. so all coordinates are positive.
# this voxelizes the pts without need for an image.
import numpy as np
import skimage.morphology as skmorph
from scipy.ndimage.morphology import binary_fill_holes
import igl
vv = mesh.vertices.copy()
ff = mesh.faces.copy()
if vol_shape is None:
# mesh_pts = mesh.vertices.copy() + 1
longest_edge_length = igl.edge_lengths(vv,ff).max()
factor = longest_edge_length / float(dilate_ksize) / 2.
# print(factor)
if factor >= pitch / 2. :
# print('upsample')
# # then we can't get a volume even if watertight.
upsample_iters = int(np.rint(np.log2(factor)))
# print(upsample_iters)
upsample_iters = np.min([upsample_iters, upsample_iters_max])
vv, ff = igl.upsample(mesh.vertices, mesh.faces, upsample_iters)
mesh_pts = igl.barycenter(vv,ff) + 1
# determine the boundaries.
min_x, min_y, min_z = np.min(mesh_pts, axis=0)
max_x, max_y, max_z = np.max(mesh_pts, axis=0)
# pad = int(np.min([min_x, min_y, min_z])) # auto determine the padding based on this.
# new binary.
smooth_img_binary = np.zeros((int(max_x)+pad, int(max_y)+pad, int(max_z)+pad))
else:
# mesh_pts = mesh.vertices.copy() #+ .5
# mesh_pts = mesh.vertices.copy() + 1
longest_edge_length = igl.edge_lengths(vv,ff).max()
factor = longest_edge_length / float(dilate_ksize) / 2.
if factor >= pitch / 2. :
# then we can't get a volume even if watertight.
upsample_iters = int(np.rint(np.log2(factor)))
upsample_iters = np.min([upsample_iters, upsample_iters_max])
vv, ff = igl.upsample(mesh.vertices, mesh.faces, upsample_iters)
mesh_pts = igl.barycenter(vv,ff)
smooth_img_binary = np.zeros(vol_shape)
smooth_img_binary[mesh_pts[:,0].astype(np.int),
mesh_pts[:,1].astype(np.int),
mesh_pts[:,2].astype(np.int)] = 1
if dilate_ksize is not None:
smooth_img_binary = skmorph.binary_dilation(smooth_img_binary, skmorph.ball(dilate_ksize))
smooth_img_binary = binary_fill_holes(smooth_img_binary) # since we dilated before to create a full mesh. we inturn must erode.
if erode_ksize is not None:
smooth_img_binary = skmorph.binary_erosion(smooth_img_binary, skmorph.ball(erode_ksize))
return smooth_img_binary
def area_normalize_mesh(mesh, map_color=False, centroid='area'):
r""" Normalize the mesh vertices by subtracting the centroid and dividing by the square root of the total surface area.
Parameters
----------
mesh : trimesh.Trimesh
input mesh
map_color : bool
if True, copy across the vertex and face colors to the new normalised mesh
centroid : str
specifies the method for computing the centroid of the mesh. If 'area' the face area weighted centroid is computed from triangle barycenter. If 'points' the centroid is computed from triangle barycenters with no weighting
Returns
-------
mesh_out : trimesh.Trimesh
output normalized mesh
(v_mean, v_out_scale) : ((3,) array, scalar)
the computed centroid and scalar normalisation
"""
import igl
import trimesh
import numpy as np
v = mesh.vertices.copy()
f = mesh.faces.copy()
if centroid == 'area':
# this uses barycenters.
area_weights_v = (igl.doublearea(v,f)/2.)[:,None]
v_mean = np.nansum( area_weights_v/float(np.nansum(area_weights_v)) * igl.barycenter(v,f), axis=0)
if centroid == 'points':
v_mean = np.nanmean(igl.barycenter(v,f), axis=0) # 3*more barycenters
v_out = v - v_mean[None,:]
v_out_scale = float(np.sqrt(np.sum(igl.doublearea(v,f))/2.))
v_out = v_out / v_out_scale
if map_color:
mesh_out = trimesh.Trimesh(v_out, f, vertex_colors=mesh.visual.vertex_colors, face_colors=mesh.visual.face_colors, process=False, validate=False)
else:
mesh_out = trimesh.Trimesh(v_out, f, process=False, validate=False)
return mesh_out, (v_mean, v_out_scale)
def unit_sphere_normalize_mesh(mesh, map_color=False, centroid='area'):
r""" Normalize the mesh vertices by direct projection onto the unit sphere by normalising the displacement vector relative to the centroid
Parameters
----------
mesh : trimesh.Trimesh
input mesh
map_color : bool
if True, copy across the vertex and face colors to the new normalised mesh
centroid : str
specifies the method for computing the centroid of the mesh. If 'area' the face area weighted centroid is computed from triangle barycenter. If 'points' the centroid is computed from triangle barycenters with no weighting
Returns
-------
mesh_out : trimesh.Trimesh
output normalized mesh
(v_mean, v_out_scale) : ((3,) array, scalar)
the computed centroid and scalar normalisation
"""
import igl
import trimesh
import numpy as np
v = mesh.vertices.copy()
f = mesh.faces.copy()
if centroid == 'area':
# this uses barycenters.
area_weights_v = (igl.doublearea(v,f)/2.)[:,None]
v_mean = np.nansum( area_weights_v/float(np.nansum(area_weights_v)) * igl.barycenter(v,f), axis=0)
if centroid == 'points':
v_mean = np.nanmean(igl.barycenter(v,f), axis=0) # 3*more barycenters
v_out = v - v_mean[None,:]
v_out_scale = np.linalg.norm(v_out, axis=-1)
v_out = v_out / v_out_scale[:,None]
if map_color:
mesh_out = trimesh.Trimesh(v_out, f, vertex_colors=mesh.visual.vertex_colors, process=False, validate=False)
else:
mesh_out = trimesh.Trimesh(v_out, f, process=False, validate=False)
return mesh_out, (v_mean, v_out_scale)
def get_uv_grid_tri_connectivity(grid):
r""" Construct the vertex and faces indices to convert a (M,N,d) d-dimensional grid coordinates with spherical geometry to a triangle mesh where vertices=grid.ravel()[vertex_indices], faces=face_indices.
Parameters
----------
grid : (M,N) or (M,N,d) array
input (u,v) image used to construct vertex and face indices for
Returns
-------
vertex_indices_all : (N_all,3) array
specifies the flattened indices in the grid to form the vertices of the triangle mesh
triangles_all :
specifies the flattened indices in the grid to form the faces of the triangle mesh
"""
"""
grid should be odd
the first row is same point and degenerate.
the last row is same point and degenerate.
easier to build the vertex and face connectivity from scratch. in a non-degenerate way!.
"""
import numpy as np
import trimesh
m, n = grid.shape[:2]
interior_grid = grid[1:-1, :-1].copy()
img_grid_indices = np.arange(np.prod(grid.shape[:2])).reshape(grid.shape[:2])
# img_grid_indices_interior = img_grid_indices[1:-1, :-1].copy()
img_grid_indices_interior = np.arange(np.prod(grid[1:-1, :-1].shape[:2])).reshape(grid[1:-1, :-1].shape[:2]) # set these as the new indices.
M, N = img_grid_indices_interior.shape[:2]
# print(m,n)
vertex_indices_interior = (img_grid_indices[1:-1,:-1].ravel())
vertex_indices_north = img_grid_indices[0,n//2]
vertex_indices_south = img_grid_indices[-1,n//2]
vertex_indices_all = np.hstack([vertex_indices_interior,
vertex_indices_north,
vertex_indices_south]) # get all the vertex indices.
# build the interior grid periodic triangle connectivity.
img_grid_indices_main = np.hstack([img_grid_indices_interior,
img_grid_indices_interior[:,0][:,None]])
M, N = img_grid_indices_main.shape[:2]
# squares_main = np.vstack([img_grid_indices_main[:m-2, :n-1].ravel(),
# img_grid_indices_main[1:m-1, :n-1].ravel(),
# img_grid_indices_main[1:m-1, 1:n].ravel(),
# img_grid_indices_main[:m-2, 1:n].ravel()]).T
squares_main = np.vstack([img_grid_indices_main[:M-1, :N-1].ravel(),
img_grid_indices_main[1:M, :N-1].ravel(),
img_grid_indices_main[1:M, 1:N].ravel(),
img_grid_indices_main[:M-1, 1:N].ravel()]).T
# trianglulate the square and this is indexed in terms of the uv grid.
squares_main_triangles = trimesh.geometry.triangulate_quads(squares_main)
# now add the triangles that connect to the poles.
triangles_north_pole = np.vstack([ len(vertex_indices_interior)*np.ones(len(img_grid_indices_main[0][1:])),
img_grid_indices_main[0][1:],
img_grid_indices_main[0][:-1]]).T
triangles_south_pole = np.vstack([ img_grid_indices_main[-1][:-1],
img_grid_indices_main[-1][1:],
(len(vertex_indices_interior)+1)*np.ones(len(img_grid_indices_main[0][1:]))]).T
# compile all the triangles together.
triangles_all = np.vstack([squares_main_triangles[:,::-1],
triangles_north_pole,
triangles_south_pole]).astype(np.int)
# can determine the sign orientation using vector area.
# implement triangle orientation check to check orientation consistency?
return vertex_indices_all, triangles_all
def build_img_2d_edges(grid):
r""" Extract the 4-neighbor edge connectivity for a (M,N) 2D image, returning an array of the list of edge connections
Parameters
----------
grid : (M,N) image
input image of the width and height to get the edge connectivity between pixels
Returns
-------
e : (n_edges,2) array
the list of unique edges specified in terms of the flattened indices in the grid.
"""
import numpy as np
m, n = grid.shape[:2]
img_grid_indices = np.arange(np.prod(grid.shape[:2])).reshape(grid.shape[:2])
e1 = np.vstack([img_grid_indices[:m-1, :n-1].ravel(),
img_grid_indices[1:m, :n-1].ravel()]).T
e2 = np.vstack([img_grid_indices[1:m, :n-1].ravel(),
img_grid_indices[1:m, 1:n].ravel()]).T
e3 = np.vstack([img_grid_indices[1:m, 1:n].ravel(),
img_grid_indices[:m-1, 1:n].ravel()]).T
e4 = np.vstack([img_grid_indices[:m-1, 1:n].ravel(),
img_grid_indices[:m-1, :n-1].ravel()]).T
e = np.vstack([e1,e2,e3,e4]) # these should be the upper triangular matrix.
e = np.sort(e, axis=1)
e = np.unique(e, axis=0)
return e
def get_inverse_distance_weight_grid_laplacian(grid, grid_pts, alpha=0.1):
r""" Compute a sparse grid Laplacian matrix for 2D image based on inverse weighting of edge lengths. This allows to take into account the length distortion of grid points constructed from 2D unwrapping
Parameters
----------
grid : (M,N) image
input image of the width and height to get the edge connectivity between pixels
grid_pts : (M,N,d) image
input image with which to compute edge lengths based on the Euclidean distance of the d-features. e.g. this could be the bijective (u,v) <-> (x,y,z) unwrapping parameters where d=3.
alpha : scalar
a shape factor that controls the inverse distance weights. In short, this is a small pseudo-distance added to measured distances to avoid division by zero or infs.
Returns
-------
L : (MxN,MxN) array
the sparse grid Laplacian where edge connections factor into account the distance between ``grid_pts``
"""
import numpy as np
import scipy.sparse as spsparse
from sklearn.preprocessing import normalize
m, n = grid.shape[:2]
grid_pts_flat = grid_pts.reshape(-1, grid_pts.shape[-1])
elist = build_img_2d_edges(grid)
dist_edges = np.linalg.norm(grid_pts_flat[elist[:,0]] - grid_pts_flat[elist[:,1]], axis=-1)
# make into a vertex edge distance matrix.
n = len(grid_pts_flat)
D = spsparse.csr_matrix((dist_edges, (elist[:,0], elist[:,1])),
shape=(n,n))
D = D + D.transpose() # make symmetric! # this is still not correct? # this should make symmetric!.
# # D = spsparse.triu(D).tocsr()
D = normalize(D, axis=1, norm='l1') # should be computing the weights...
D = .5*(D + D.transpose()) # make symmetric!
D.data = 1./(alpha+D.data) # c.f. https://math.stackexchange.com/questions/4264675/handle-zero-in-inverse-distance-weighting
D = normalize(D, axis=1, norm='l1')
D = .5*(D + D.transpose()) # make symmetric!
# to convert to laplacian we can simply do D - A.
L = spsparse.spdiags(np.squeeze(D.sum(axis=1)), 0, D.shape[0], D.shape[1]) - D # degree - adjacency matrix.
L = L.tocsc()
return L
# this version doesn't support mesh laplacian if using the corresponding 3D coordinates because the first row and last row maps to the same point and generates the triangles. - use the above triangle version.
def get_uv_grid_quad_connectivity(grid, return_triangles=False, bounds='spherical'):
r""" Compute the quad and the triangle connectivity between pixels in a 2d grid with either spherical or no boundary conditions
Parameters
----------
grid : (M,N,d) image
input image of the width and height to get the pixel connectivity, N must be odd if bounds='spherical' due to the necessary rewrapping.
return_triangles : bool
if True, return in addition the triangle connectivity based on triangulation of the quad grid connectivity
bounds : str
string specifying the boundary conditions of the grid, either of 'spherical' or 'none'
'spherical' : str
this wraps the left to right side, pinches together the top and pinches together the bottom of the grid
'none' : str
this does no unwrapping and returns the grid connectivity of the image. This is the same as sklearn.feature_extraction.image.grid_to_graph
Returns
-------
all_squares : (N_squares,4) array
the 4-neighbor quad connectivity of flattened image indices
all_squares_to_triangles : (2*N_squares,3) array
the triangle connectivity of the flattened image indices. Each square splits into 2 triangles.
"""
import trimesh
import numpy as np
m, n = grid.shape[:2]
img_grid_indices = np.arange(np.prod(grid.shape[:2])).reshape(grid.shape[:2])
if bounds == 'spherical':
img_grid_indices_main = np.hstack([img_grid_indices, img_grid_indices[:,0][:,None]])
squares_main = np.vstack([img_grid_indices_main[:m-1, :n].ravel(),
img_grid_indices_main[1:m, :n].ravel(),
img_grid_indices_main[1:m, 1:n+1].ravel(),
img_grid_indices_main[:m-1, 1:n+1].ravel()]).T
# then handle the top and bottom strips separately ...
img_grid_indices_top = np.vstack([img_grid_indices[0,n//2:][::-1],
img_grid_indices[0,:n//2]])
squares_top = np.vstack([img_grid_indices_top[0, :img_grid_indices_top.shape[1]-1].ravel(),
img_grid_indices_top[1, :img_grid_indices_top.shape[1]-1].ravel(),
img_grid_indices_top[1, 1:img_grid_indices_top.shape[1]].ravel(),
img_grid_indices_top[0, 1:img_grid_indices_top.shape[1]].ravel()]).T
img_grid_indices_bottom = np.vstack([img_grid_indices[-1,:n//2],
img_grid_indices[-1,n//2:][::-1]])
squares_bottom = np.vstack([img_grid_indices_bottom[0, :img_grid_indices_bottom.shape[1]-1].ravel(),
img_grid_indices_bottom[1, :img_grid_indices_bottom.shape[1]-1].ravel(),
img_grid_indices_bottom[1, 1:img_grid_indices_bottom.shape[1]].ravel(),
img_grid_indices_bottom[0, 1:img_grid_indices_bottom.shape[1]].ravel()]).T
all_squares = np.vstack([squares_main,
squares_top,
squares_bottom])
if bounds == 'none':
all_squares = np.vstack([img_grid_indices[:m-1, :n-1].ravel(),
img_grid_indices[1:m, :n-1].ravel(),
img_grid_indices[1:m, 1:n].ravel(),
img_grid_indices[:m-1, 1:n].ravel()]).T
all_squares = all_squares[:,::-1]
if return_triangles:
all_squares_to_triangles = trimesh.geometry.triangulate_quads(all_squares)
return all_squares, all_squares_to_triangles
else:
return all_squares
def parametric_mesh_constant_img_flow(mesh, external_img_gradient,
niters=1,
deltaL=5e-4,
step_size=1,
method='implicit',
robust_L=False,
mollify_factor=1e-5,
conformalize=True,
gamma=1,
alpha=0.2,
beta=0.1,
eps=1e-12):
r""" This function performs implicit Euler propagation of a 3D mesh with steps of constant ``step_size`` in the direction of an external image gradient specified by ``external_img_gradient``
Parameters
----------
mesh : trimesh.Trimesh
input mesh
external_img_gradient : (MxNxLx3) array
the 3D volumetric displacement field with x,y,z coordinates the last axis.
niters : int
the number of total steps
deltaL : scalar
a stiffness regularization constant for the conformalized mean curvature flow propagation
step_size : scalar
the multiplicative factor the image gradient is multipled with per iteration
method : str
one of 'implicit' for implicit Euler or 'explicit' for explicit Euler. 'implicit' is slower but much more stable and results in mesh updates that minimize foldover and instabilities. 'explicit' is unstable but fast.
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [1]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
conformalize : bool
if True, uses the simplified conformalized mean curvature variant mesh propagation derived in the paper [2]_. If False, uses the normal active contours update which uses ``gamma``, ``alpha`` and ``beta`` parameters.
gamma : scalar
stability regularization parameter in the active contour
alpha : scalar
stiffness regularization parameters in the active contour
beta : scalar
bending regularization parameters in the active contour
eps : scalar
small constant for numerical stability
Returns
-------
Usteps : (n_vertices,3,n_iters+1) array
the vertex positions of the mesh at every interation. The face connectivity of the mesh does not change.
References
----------
.. [1] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
.. [2] c.f. Unwrapping paper.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
from ..Image_Functions import image as image_fn
vol_shape = external_img_gradient.shape[:-1]
v = np.array(mesh.vertices.copy())
f = np.array(mesh.faces.copy())
if robust_L:
import robust_laplacian
L, M = robust_laplacian.mesh_laplacian(np.array(v), np.array(f), mollify_factor=mollify_factor)
L = -L # need to invert sign to be same convention as igl.
else:
L = igl.cotmatrix(v,f)
"""
initialise
"""
# initialise the save array.
Usteps = np.zeros(np.hstack([v.shape, niters+1]))
Usteps[...,0] = v.copy()
U = v.copy()
"""
propagation
"""
for ii in tqdm(range(niters)):
U_prev = U.copy(); # make a copy.
# get the next image gradient
U_grad = np.array([image_fn.map_intensity_interp3(U_prev,
grid_shape=vol_shape,
I_ref=external_img_gradient[...,ch]) for ch in np.arange(v.shape[-1])])
U_grad = U_grad.T
if method == 'explicit':
U_grad = U_grad / (np.linalg.norm(U_grad, axis=-1)[:,None]**2 + eps) # square this.
U = U_prev + U_grad * step_size #update.
Usteps[...,ii+1] = U.copy()
if method == 'implicit':
U_grad = U_grad / (np.linalg.norm(U_grad, axis=-1)[:,None] + eps)
if conformalize:
# if ii ==0:
if robust_L:
import robust_laplacian
_, M = robust_laplacian.mesh_laplacian(U_prev, f, mollify_factor=mollify_factor)
else:
M = igl.massmatrix(U_prev, f, igl.MASSMATRIX_TYPE_BARYCENTRIC) # -> this is the only matrix that doesn't degenerate.
# # implicit solve.
S = (M - deltaL*L) # what happens when we invert?
b = M.dot(U_prev + U_grad * step_size)
else:
# construct the active contour version.
S = gamma * spsparse.eye(len(v), len(v)) - alpha * L + beta * L.dot(L)
b = U_prev + U_grad * step_size
# get the next coordinate by solving
U = spsparse.linalg.spsolve(S,b)
Usteps[...,ii+1] = U.copy()
# return all the intermediate steps.
return Usteps
def parametric_uv_unwrap_mesh_constant_img_flow(uv_grid,
external_img_gradient,
niters=1,
deltaL=5e-4,
surf_pts_ref=None,
step_size=1,
pad_dist=5,
method='implicit',
robust_L=False,
mollify_factor=1e-5,
conformalize=True, gamma=1, alpha=0.2, beta=0.1, eps=1e-12):
r""" This convenience function performs implicit Euler propagation of an open uv-parametrized 3D mesh with steps of constant ``step_size`` in the direction of an external image gradient specified by ``external_img_gradient``
the uv-parametrization is closed before propagating in 3D (x,y,z) space
Parameters
----------
uv_grid : (M,N,3) image
input mesh as an image with xyz on the last dimension.
external_img_gradient : (MxNxLx3) array
the 3D volumetric displacement field with x,y,z coordinates the last axis.
niters : int
the number of total steps
deltaL : scalar
a stiffness regularization constant for the conformalized mean curvature flow propagation
surf_pts_ref : (N,3) array
if provided, this is a reference surface with which to automatically determine the niters when propagating the surface outwards to ensure the full reference shape is sampled in topography space.
step_size : scalar
the multiplicative factor the image gradient is multipled with per iteration
pad_dist : int
an additional fudge factor added to the automatically determined n_dist when surf_pts_ref is provided and n_dist is not user provided
method : str
one of 'implicit' for implicit Euler or 'explicit' for explicit Euler. 'implicit' is slower but much more stable and results in mesh updates that minimize foldover and instabilities. 'explicit' is unstable but fast.
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [1]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
conformalize : bool
if True, uses the simplified conformalized mean curvature variant mesh propagation derived in the paper [2]_. If False, uses the normal active contours update which uses ``gamma``, ``alpha`` and ``beta`` parameters.
gamma : scalar
stability regularization parameter in the active contour
alpha : scalar
stiffness regularization parameters in the active contour
beta : scalar
bending regularization parameters in the active contour
eps : scalar
small constant for numerical stability
Returns
-------
Usteps_out_rec : (niters+1,M,N,3) array
the vertex positions of the mesh for every interation for every pixel position
See Also
--------
:func:`unwrap3D.Mesh.meshtools.parametric_mesh_constant_img_flow` :
the propagation for a general 3D mesh
:func:`unwrap3D.Unzipping.unzip.prop_ref_surface` :
the equivalent for explicit Euler propagation using the uv-based image coordinates without closing the mesh
References
----------
.. [1] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
.. [2] c.f. Unwrapping paper.
"""
"""
convert the uv image into a trimesh object and prop this with some conformal regularization in one function.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
from ..Unzipping import unzip_new as uzip
import trimesh
vol_shape = external_img_gradient.shape[:-1]
"""
Build the UV mesh connectivity.
"""
uv_connectivity_verts, uv_connectivity_tri = get_uv_grid_tri_connectivity(uv_grid[...,0])
v = (uv_grid.reshape(-1,uv_grid.shape[-1]))[uv_connectivity_verts]
f = uv_connectivity_tri.copy()
mesh_tri = trimesh.Trimesh(vertices=v,
faces=f,
validate=False,
process=False)
trimesh.repair.fix_winding(mesh_tri) # fix any orientation issues.
"""
determine the propagation distance.
"""
# infer the number of dists to step for from the reference if not prespecified.
if niters is None :
unwrap_params_ref_flat = uv_grid.reshape(-1, uv_grid.shape[-1])
# infer the maximum step size so as to cover the initial otsu surface.
mean_pt = np.nanmean(unwrap_params_ref_flat, axis=0)
# # more robust to do an ellipse fit. ? => doesn't seem so... seems best to take the extremal point -> since we should have a self-similar shape.
# unwrap_params_fit_major_len = np.max(np.linalg.eigvalsh(np.cov((unwrap_params_ref_flat-mean_pt[None,:]).T))); unwrap_params_fit_major_len=np.sqrt(unwrap_params_fit_major_len)
# surf_ref_major_len = np.max(np.linalg.eigvalsh(np.cov((surf_pts_ref-mean_pt[None,:]).T))); surf_ref_major_len = np.sqrt(surf_ref_major_len)
mean_dist_unwrap_params_ref = np.linalg.norm(unwrap_params_ref_flat-mean_pt[None,:], axis=-1).max()
mean_surf_pts_ref = np.linalg.norm(surf_pts_ref-mean_pt[None,:], axis=-1).max() # strictly should do an ellipse fit...
niters = np.int(np.ceil(mean_surf_pts_ref-mean_dist_unwrap_params_ref))
niters = niters + pad_dist # this is in pixels
niters = np.int(np.ceil(niters / np.abs(float(step_size)))) # so if we take 1./2 step then we should step 2*
print('auto_infer_prop_distance', niters)
print('----')
"""
Do the propagation wholly with this watertight mesh.
"""
Usteps_out = parametric_mesh_constant_img_flow(mesh_tri,
external_img_gradient=external_img_gradient,
niters=niters,
deltaL=deltaL,
step_size=step_size,
method=method,
robust_L=robust_L,
conformalize=conformalize,
gamma=gamma,
alpha=alpha,
beta=beta,
eps=eps)
Usteps_out_rec = Usteps_out[:-2].reshape((uv_grid.shape[0]-2, uv_grid.shape[1]-1, Usteps_out.shape[1], Usteps_out.shape[2]))
Usteps_out_rec = np.vstack([Usteps_out_rec[-2][None,...],
Usteps_out_rec,
Usteps_out_rec[-1][None,...]])
Usteps_out_rec = np.hstack([Usteps_out_rec,
Usteps_out_rec[:,0][:,None,...]])
# return all the intermediate steps.
return Usteps_out_rec # return the propagated out mesh.
def area_distortion_flow_relax_sphere(mesh,
mesh_orig,
max_iter=50,
smooth_iters=0,
delta=0.1,
stepsize=.1,
conformalize=False,
flip_delaunay=False,
robust_L=False,
mollify_factor=1e-5,
eps = 1e-12,
debugviz=False):
r""" This function relaxes the area distortion of a spherical mesh by advecting vertex coordinates whilst maintaining the spherical geometry.
Parameters
----------
mesh : trimesh.Trimesh
the input unit spherical mesh to relax
mesh_orig : trimesh.Trimesh
the input original geometric mesh whose vertices correspond 1 to 1 with vertices of the spherical mesh. This is used to compute the area distortion per iteration
max_iter : int
the number of iterations relaxation will occur. The function may exit early if the mesh becomes unable to support further relaxation. A collapsed mesh will return vertices that are all np.nan
smooth_iters : int
if > 0, the number of Laplacian smoothing to smooth the per vertex area distortion
delta : scalar
a stiffness constant of the mesh. it used to ensure maintenance of relative topology during advection
stepsize : scalar
the stepsize in the direction of steepest descent of area distortion. smaller steps can improve stability and precision but with much slower convergence
conformalize : bool
if True, uses the initial Laplacian without recomputing the Laplacian. This is a very severe penalty and stops area relaxation flow without reducing ``delta``. In general set this as False since relaxing area is in opposition to minimizing conformal error.
flip_delaunay : bool
if True, flip triangles during advection. On the sphere we find this slows flow, affects barycentric interpolation and is generated not required. This option requires the ``meshplex`` library
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [1]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
eps : scalar
small constant for numerical stability
debugviz : bool
if True, a histogram of the area distortion is plotted per iteration to check if the flow is working properly. The area distortion is plotted as log(distortion) and so should move towards a peak of 0
Returns
-------
v_steps : list of (n_vertices, 3) array
the vertex position at every iteration
f_steps : list of (n_faces, 3) array
the face connectivity at every iteration. This will be the same for all timepoints unless flip_delaunay=True
area_distortion_iter : list
the area distortion factor per face computed as area_original/area_sphere for every timepoint.
References
----------
.. [1] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
# import meshplex
import pylab as plt
if robust_L:
import robust_laplacian
V = mesh.vertices.copy()
F = mesh.faces.copy()
v = mesh.vertices.copy()
f = mesh.faces.copy()
if robust_L:
L, M = robust_laplacian.mesh_laplacian(np.array(v), np.array(f), mollify_factor=mollify_factor)
L = -L # need to invert sign to be same convention as igl.
else:
L = igl.cotmatrix(v,f)
area_distortion_iter = []
v_steps = [v]
f_steps = [f]
for ii in tqdm(range(max_iter)):
try:
if conformalize == False:
if robust_L:
L, m = robust_laplacian.mesh_laplacian(np.array(v), np.array(f),mollify_factor=mollify_factor); L = -L; # this must be computed. # if not... then no growth -> flow must change triangle shape!.
else:
L = igl.cotmatrix(v,f)
m = igl.massmatrix(v,f, igl.MASSMATRIX_TYPE_BARYCENTRIC)
# # compute the area distortion of the face -> having normalized for surface area. -> this is because the sphere minimise the surface area. -> guaranteeing positive.
# which is correct?
# why we need to use the original connectivity?
# area_distortion_mesh = igl.doublearea(mesh_orig.vertices/np.sqrt(np.nansum(igl.doublearea(mesh_orig.vertices,mesh_orig.faces)*.5)), mesh_orig.faces) / igl.doublearea(v/np.sqrt(np.nansum(igl.doublearea(v,f)*.5)), f) # this is face measure!. and the connectivity is allowed to change! during evolution !.
area_distortion_mesh = igl.doublearea(mesh_orig.vertices/np.sqrt(np.nansum(igl.doublearea(mesh_orig.vertices,f)*.5)), f) / igl.doublearea(v/np.sqrt(np.nansum(igl.doublearea(v,f)*.5)), f) # this is face measure!. and the connectivity is allowed to change! during evolution !.
# area_distortion_mesh = area_distortion(mesh_orig.vertices,f, v)
# area_distortion_mesh = area_distortion(mesh_orig.vertices)
# area_distortion_iter.append(area_distortion_mesh) # append this.
# push to vertex.
area_distortion_mesh_vertex = igl.average_onto_vertices(v,
f,
np.vstack([area_distortion_mesh,area_distortion_mesh,area_distortion_mesh]).T)[:,0]
# smooth ...
if debugviz:
plt.figure()
plt.hist(np.log10(area_distortion_mesh_vertex)) # why no change?
plt.show()
if smooth_iters > 0:
smooth_area_distortion_mesh_vertex = np.vstack([area_distortion_mesh_vertex,area_distortion_mesh_vertex,area_distortion_mesh_vertex]).T # smooth this instead of the gradient.
for iter_ii in range(smooth_iters):
smooth_area_distortion_mesh_vertex = igl.per_vertex_attribute_smoothing(smooth_area_distortion_mesh_vertex, f) # seems to work.
area_distortion_mesh_vertex = smooth_area_distortion_mesh_vertex[:,0]
# compute the gradient.
g = igl.grad(v,
f)
# if method == 'Kazhdan2019':
# compute the vertex advection gradient.
gA = g.dot(-np.log(area_distortion_mesh_vertex)).reshape(f.shape, order="F")
# scale by the edge length.
gu_mag = np.linalg.norm(gA, axis=1)
max_size = igl.avg_edge_length(v, f) / np.nanmedian(gu_mag) # if divide by median less good.
vA = max_size*gA # this is vector.
normal = igl.per_vertex_normals(v,f)
# Vvertex = Vvertex - np.nansum(v*normal, axis=-1)[:,None]*normal # this projection actually makes it highly unstable?
vA_vertex = igl.average_onto_vertices(v,
f, vA)
vA_vertex = vA_vertex - np.nansum(vA_vertex*normal, axis=-1)[:,None]*normal # this seems necessary...
"""
advection step
"""
S = (m - delta*L)
# if adaptive_step:
# v = spsparse.linalg.spsolve(S, m.dot(v + scale_factor * stepsize * vA_vertex))
# else:
v = spsparse.linalg.spsolve(S, m.dot(v + stepsize * vA_vertex))
"""
rescale and reproject back to normal
"""
area = np.nansum(igl.doublearea(v,f)*.5) #total area.
c = np.nansum((0.5*igl.doublearea(v,f)/area)[...,None] * igl.barycenter(v,f), axis=0) # this is just weighted centroid
v = v - c[None,:]
# sphericalize
v = v/np.linalg.norm(v, axis=-1)[:,None] # forces sphere.... topology.... relaxation.
"""
flip delaunay ? or use optimesh refine? -> to improve triangle quality?
"""
if flip_delaunay:
import meshplex
# this clears out the overlapping. is this necessary
mesh_out = meshplex.MeshTri(v, f)
mesh_out.flip_until_delaunay()
# update v and f!
v = mesh_out.points.copy()
f = mesh_out.cells('points').copy()
# update.
v_steps.append(v)
f_steps.append(f)
area_distortion_iter.append(area_distortion_mesh) # append this.
except:
# if error then get out quickly.
return v_steps, f_steps, area_distortion_iter
return v_steps, f_steps, area_distortion_iter
def area_distortion_flow_relax_disk(mesh, mesh_orig,
max_iter=50,
# smooth_iters=5,
delta_h_bound=0.5,
stepsize=.1,
flip_delaunay=True, # do this in order to dramatically improve flow!.
robust_L=False, # use the robust laplacian instead of cotmatrix - slows flow.
mollify_factor=1e-5,
eps = 1e-8,
lam = 1e-4,
debugviz=False,
debugviz_tri=True):
r""" This function relaxes the area distortion of a mesh with disk topology i.e. a disk, square or rectangle mesh by advecting inner vertex coordinates to minimise area distortion.
The explicit Euler scheme of [1]_ is used. Due to the numerical instability of such a scheme, the density of mesh vertices and the stepsize constrains the full extent of relaxation.
Parameters
----------
mesh : trimesh.Trimesh
the input disk, square or rectangle mesh to relax. The first coordinate of all the vertices, i.e. mesh.vertices[:,0] should be uniformly set to a constant e.g. 0 to specify a 2D mesh
mesh_orig : trimesh.Trimesh
the input original geometric mesh whose vertices correspond 1 to 1 with vertices of the input mesh. This is used to compute the area distortion per iteration
delta_h_bound : scalar
the maximum value of the absolute area difference between original and the relaxing mesh. This constrains the maximum gradient difference, avoiding updating local areas too fast which will then destroy local topology.
stepsize : scalar
the stepsize in the direction of steepest descent of area distortion. smaller steps can improve stability and precision but with much slower convergence
flip_delaunay : bool
if True, flip triangles during advection. We find this is important with the explicit Euler scheme adopted here to ensure correct topology and ensure fast relaxation.
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [2]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
eps : scalar
small constant for numerical stability
debugviz : bool
if True, a histogram of the area distortion is plotted per iteration to check if the flow is working properly. The area distortion is plotted as log(distortion) and so should move towards a peak of 0
debugvis_tri : bool
if True, plots the triangle mesh per iteration.
Returns
-------
v_steps : list of (n_vertices, 3) array
the vertex position at every iteration. The first coordinate of the vertices is set to 0.
f_steps : list of (n_faces, 3) array
the face connectivity at every iteration. This will be the same for all timepoints unless flip_delaunay=True
area_distortion_iter : list
the area distortion factor per face computed as area_original/area_sphere for every timepoint.
References
----------
.. [1] Zou, Guangyu, et al. "Authalic parameterization of general surfaces using Lie advection." IEEE Transactions on Visualization and Computer Graphics 17.12 (2011): 2005-2014.
.. [2] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
# import meshplex
import pylab as plt
if robust_L:
import robust_laplacian
V = mesh.vertices.copy()
F = mesh.faces.copy()
v = mesh.vertices.copy()
f = mesh.faces.copy()
f = igl.intrinsic_delaunay_triangulation(igl.edge_lengths(v,f), f)[1]
if robust_L:
L, M = robust_laplacian.mesh_laplacian(np.array(v), np.array(f), mollify_factor=mollify_factor)
else:
L = -igl.cotmatrix(v,f)
area_distortion_iter = []
v_steps = [v]
f_steps = [f]
for ii in tqdm(range(max_iter)):
# try:
# if conformalize == False:
if robust_L:
L, m = robust_laplacian.mesh_laplacian(np.array(v), np.array(f),mollify_factor=mollify_factor); # this must be computed. # if not... then no growth -> flow must change triangle shape!.
else:
L = -igl.cotmatrix(v,f)
v_bound = igl.boundary_loop(f)
# # compute the area distortion of the face -> having normalized for surface area. -> this is because the sphere minimise the surface area. -> guaranteeing positive.
A2 = igl.doublearea(mesh_orig.vertices/np.sqrt(np.nansum(igl.doublearea(mesh_orig.vertices,f)*.5)), f)
A1 = igl.doublearea(v/np.sqrt(np.nansum(igl.doublearea(v,f)*.5)), f)
# B = np.log10(A1/(A2)) # - 1
B = (A1+eps)/(A2+eps) - 1 # adding regularizer to top and bottom is better!.
area_distortion_mesh = (A2/(A1+eps)) # this is face measure!. and the connectivity is allowed to change! during evolution !.
area_distortion_mesh_vertex = igl.average_onto_vertices(v,
f,
np.vstack([area_distortion_mesh,area_distortion_mesh,area_distortion_mesh]).T)[:,0]
# smooth ...
if debugviz:
plt.figure()
plt.hist(np.log10(area_distortion_mesh_vertex)) # why no change?
plt.show()
# if smooth_iters > 0:
# smooth_area_distortion_mesh_vertex = np.vstack([area_distortion_mesh_vertex,area_distortion_mesh_vertex,area_distortion_mesh_vertex]).T # smooth this instead of the gradient.
# for iter_ii in range(smooth_iters):
# smooth_area_distortion_mesh_vertex = igl.per_vertex_attribute_smoothing(smooth_area_distortion_mesh_vertex, f) # seems to work.
# area_distortion_mesh_vertex = smooth_area_distortion_mesh_vertex[:,0]
B = np.clip(B, -delta_h_bound, delta_h_bound) # bound above and below.
# B_vertex = igl.average_onto_vertices(v,
# f,
# np.vstack([B,B,B]).T)[:,0] # more accurate?
B_vertex = f2v(v,f).dot(B)
# from scipy.sparse.linalg import lsqr ---- this sometimes fails!...
I = spsparse.spdiags(lam*np.ones(len(v)), [0], len(v), len(v)) # tikholov regulariser.
g = spsparse.linalg.spsolve((L.T).dot(L) + I, (L.T).dot(B_vertex)) # solve for a smooth potential field. # this is the least means square.
# g = spsparse.linalg.lsqr(L.T.dot(L), L.dot(B_vertex), iter_lim=100)[0] # is there a better way to solve this quadratic?
face_vertex = v[f].copy()
face_normals = np.cross(face_vertex[:,1]-face_vertex[:,0],
face_vertex[:,2]-face_vertex[:,0], axis=-1)
face_normals = face_normals / (np.linalg.norm(face_normals, axis=-1)[:,None] + eps)
# face_normals = np.vstack([np.ones(len(face_vertex)),
# np.zeros(len(face_vertex)),
# np.zeros(len(face_vertex))]).T # should this be something else?
face_g = g[f].copy()
# vertex_normals = igl.per_vertex_normals(v,f)
# i,j,k = 1,2,3
face_vertex_lhs = np.concatenate([(face_vertex[:,1]-face_vertex[:,0])[:,None,:],
(face_vertex[:,2]-face_vertex[:,1])[:,None,:],
face_normals[:,None,:]], axis=1)
face_g_rhs = np.vstack([(face_g[:,1]-face_g[:,0]),
(face_g[:,2]-face_g[:,1]),
np.zeros(len(face_g))]).T
# solve a simultaneous set of 3x3 problems
dg_face = np.linalg.solve( face_vertex_lhs, face_g_rhs)
gu_mag = np.linalg.norm(dg_face, axis=1)
max_size = igl.avg_edge_length(v, f) / np.nanmax(gu_mag) # stable if divide by nanmax # must be nanmax!.
# dg_face = stepsize*max_size*dg_face # this is vector. and is scaled by step size
# dg_face = max_size*dg_face
# average onto the vertex.
dg_vertex = igl.average_onto_vertices(v,
f,
dg_face)
dg_vertex = dg_vertex * max_size
# dg_vertex = dg_vertex - np.nansum(dg_vertex*vertex_normals,axis=-1)[:,None]*vertex_normals
# correct the flow at the boundary!. # this is good? ---> this is good for an explicit euler.
normal_vect = L.dot(v)
normal_vect = normal_vect / (np.linalg.norm(normal_vect, axis=-1)[:,None] + 1e-8)
# dg_vertex[v_bound] = dg_vertex[v_bound] - np.nansum(dg_vertex[v_bound] * v[v_bound], axis=-1)[:,None]*v[v_bound]
"""
this is the gradient at the vertex.
"""
dg_vertex[v_bound] = dg_vertex[v_bound] - np.nansum(dg_vertex[v_bound] * normal_vect[v_bound], axis=-1)[:,None]*normal_vect[v_bound]
# disps.append(dg_vertex)
# print('no_adaptive')
scale_factor=stepsize
# print('scale_factor, ', scale_factor)
"""
advection step
"""
# v = V[:,1:] + np.array(disps).sum(axis=0)[:,1:] # how to make this step stable?
v = v_steps[-1][:,1:] + scale_factor*dg_vertex[:,1:] # last one.
v = np.hstack([np.zeros(len(v))[:,None], v])
if flip_delaunay: # we have to flip!.
# import meshplex
# # this clears out the overlapping. is this necessary
# mesh_out = meshplex.MeshTri(v, f)
# mesh_out.flip_until_delaunay()
# # update v and f!
# v = mesh_out.points.copy()
# f = mesh_out.cells('points').copy()
f = igl.intrinsic_delaunay_triangulation(igl.edge_lengths(v,f), f)[1]
if debugviz_tri:
plt.figure(figsize=(5,5))
plt.triplot(v[:,1],
v[:,2], f, 'g-', lw=.1)
plt.show()
v_steps.append(v)
f_steps.append(f)
area_distortion_iter.append(area_distortion_mesh) # append this.
# except:
# # if error then break
# return v_steps, f_steps, area_distortion_iter
return v_steps, f_steps, area_distortion_iter
def adjacency_edge_cost_matrix(V,E, n=None):
r""" Build the Laplacian matrix for a line given the vertices and the undirected edge-edge connections
Parameters
----------
V : (n_points,d) array
the vertices of the d-dimensional line
E : (n_edges,2) array
the edge connections as integer vertex indices specifying how the vertices are joined together
n : int
if specified, the size of the Laplacian matrix, if not the same as the number of points in V. the returned Laplacian matrix will be of dimension ((n,n))
Returns
-------
C : (n,n) sparse array
the n x n symmetric vertex laplacian matrix
"""
import numpy as np
import scipy.sparse as spsparse
# % compute edge norms
edge_norms = np.linalg.norm(V[E[:,0]]-V[E[:,1]], axis=-1)
# % number of vertices
if n is None:
n = len(V);
#% build sparse adjacency matrix with non-zero entries indicated edge costs
C = spsparse.csr_matrix((edge_norms, (E[:,0], E[:,1])), shape=(n, n))
C = C + C.transpose() # to make undirected.
return C
def adjacency_matrix(E, n=None):
r""" Build the Laplacian matrix for a line given the undirected edge-edge connections without taking into account distances between vertices
Parameters
----------
E : (n_edges,2) array
the edge connections as integer vertex indices specifying how the vertices are joined together
n : int
if specified, the size of the Laplacian matrix, if not the same as the number of points in V. the returned Laplacian matrix will be of dimension ((n,n))
Returns
-------
C : (n,n) sparse array
the n x n symmetric vertex laplacian matrix
"""
import numpy as np
import scipy.sparse as spsparse
# % number of vertices
if n is None:
n = len(E);
#% build sparse adjacency matrix with non-zero entries indicated edge costs
C = spsparse.csr_matrix((np.ones(len(E)), (E[:,0], E[:,1])), shape=(n, n))
C = C + C.transpose() # to make undirected.
return C
def mass_matrix2D(A):
r""" Build the Mass matrix for a given adjacency or Laplacian matrix. The mass matrix is a diagonal matrix of the row sums of the input matrix, A
Parameters
----------
A : (N,N) array or sparse array
the Adjacency or symmetric Laplacian matrix
Returns
-------
M : (N,N) sparse array
a diagonal matrix whose entries are the row sums of the symmetric input matrix
"""
import scipy.sparse as spsparse
import numpy as np
vals = np.squeeze(np.array(A.sum(axis=1)))
M = spsparse.diags(vals, 0)
# M = M / np.max(M.diagonal())
return M
def vertex_dihedral_angle_matrix(mesh, eps=1e-12):
r""" Build the Dihedral angle matrix for vertices given an input mesh. The dihedral angles, is the angle between the normals of pairs of vertices measures the local mesh convexity. the dihedral angle is captured as a cosime distance
Parameters
----------
mesh : trimesh.Trimesh
the input mesh
eps : scalar
a small constant scalar for numerical stability
Returns
-------
angles_edges_matrix : (n_vertices, n_vertices) sparse array
a matrix capturing the dihedral angle between vertex_i to vertex_j between vertex neighbors
"""
import numpy as np
import igl
import scipy.sparse as spsparse
# we use the dihdral angle formula...
vertex_edge_list = igl.edges(mesh.faces)
normals1 = mesh.vertex_normals[vertex_edge_list[:,0]].copy() ; normals1 = normals1/(np.linalg.norm(normals1, axis=-1)[:,None] + eps)
normals2 = mesh.vertex_normals[vertex_edge_list[:,1]].copy() ; normals2 = normals2/(np.linalg.norm(normals2, axis=-1)[:,None] + eps)
# dot product.
angles_edges = np.nansum(normals1 * normals2, axis=-1) # this is signed cosine..
# cosine distance matrix
angles_edges = (1.-angles_edges) / 2. # this makes it a proper distance!. # smaller should be closer...?
# make into adjacency matrix
n = len(mesh.vertices)
angles_edges_matrix = spsparse.csr_matrix((angles_edges, (vertex_edge_list[:,0], vertex_edge_list[:,1])),
shape=(n,n))
angles_edges_matrix = angles_edges_matrix + angles_edges_matrix.transpose() # symmetric
return angles_edges_matrix
def vertex_edge_lengths_matrix(mesh):
r""" Build the edge distance matrix between local vertex neighbors of the input mesh
Parameters
----------
mesh : trimesh.Trimesh
the input mesh
Returns
-------
D : (n_vertices, n_vertices) sparse array
a matrix capturing the euclidean edge distance between vertex_i to vertex_j of vertex neighbors
"""
import numpy as np
import igl
import scipy.sparse as spsparse
vertex_edge_list = igl.edges(mesh.faces) # this is unique edges hence not undirected. (upper triangular)
# get the distance matrix between the edges.
dist_edges = np.linalg.norm(mesh.vertices[vertex_edge_list[:,0]] - mesh.vertices[vertex_edge_list[:,1]],
axis=-1)
# make into adjacency matrix
n = len(mesh.vertices)
D = spsparse.csr_matrix((dist_edges, (vertex_edge_list[:,0], vertex_edge_list[:,1])),
shape=(n,n))
D = D + D.transpose() # make symmetric!
return D
def vertex_edge_affinity_matrix(mesh, gamma=None):
r""" Compute an affinity distance matrix of the edge distances. This is done by computing the pairwise edge length distances between vertex neighbors and applying a heat kernel.
.. math::
A_{dist} = \exp^{\left(\frac{-D_{dist}^2}{2\sigma^2}\right)}
where :math:`sigma` is set as the mean distance of :math:`D` or :math:`\gamma` if provided.
Parameters
----------
mesh : trimesh.Trimesh
the input mesh
gamma : scalar
a scalar normalisation of the distances in the distance matrix
Returns
-------
A : (n_vertices, n_vertices) sparse array
a matrix capturing the euclidean edge affinity between vertex_i to vertex_j of vertex neighbors. This is a normalised measure of distances with values mainly in the scale of [0,1]
"""
D = vertex_edge_lengths_matrix(mesh)
A = distance_to_heat_affinity_matrix(D, gamma=gamma)
return A
def vertex_dihedral_angle_affinity_matrix(mesh, gamma=None, eps=1e-12):
r""" Compute an affinity distance matrix of the vertex dihedral angles. This is done by computing the vertex dihedral angle distances and applying a heat kernel.
.. math::
A_{angle} = \exp^{\left(\frac{-D_{angle}^2}{2\sigma^2}\right)}
where :math:`sigma` is set as the mean distance of :math:`D` or :math:`\gamma` if provided.
Parameters
----------
mesh : trimesh.Trimesh
the input mesh
gamma : scalar
a scalar normalisation of the distances in the distance matrix
eps : scalar
a small constant for numerical stability
Returns
-------
A : (n_vertices, n_vertices) sparse array
a matrix capturing the euclidean dihedral angle cosine distance affinity between vertex_i to vertex_j of vertex neighbors. This is a normalised measure of distances with values mainly in the scale of [0,1]
"""
D = vertex_dihedral_angle_matrix(mesh, eps=eps)
A = distance_to_heat_affinity_matrix(D, gamma=gamma)
return A
def vertex_geometric_affinity_matrix(mesh, gamma=None, eps=1e-12, alpha=.5, normalize=True):
r""" Compute an affinity matrix balancing geodesic distances and convexity by taking a weighted average of the edge distance affinity matrix and the vertex dihedral angle affinity matrix.
.. math::
A = \alpha A_{dist} + (1-\alpha) A_{dihedral}
Parameters
----------
mesh : trimesh.Trimesh
the input mesh
gamma : scalar
a scalar normalisation of the distances in the distance matrix
eps : scalar
a small constant for numerical stability of the dihedral angle distance matrix
alpha : 0-1
the weight for averaging the two affinity matrices
normalize : bool
if True, apply left normalization to the averaged affinity matrix given by :math:`M^{-1}A` where :math:`M` is the mass matrix.
Returns
-------
W : (n_vertex, n_vertex) scipy sparse matrix
the combined average affinity matrix
See Also
--------
:func:`unwrap3D.Mesh.meshtools.vertex_edge_affinity_matrix` :
function used to compute the vertex edge distance affinity matrix
:func:`unwrap3D.Mesh.meshtools.vertex_dihedral_angle_affinity_matrix` :
function used to compute the vertex dihedral angle distance affinity matrix
"""
import scipy.sparse as spsparse
import numpy as np
Distance_matrix = vertex_edge_affinity_matrix(mesh, gamma=gamma)
Convexity_matrix = vertex_dihedral_angle_affinity_matrix(mesh, gamma=gamma, eps=eps)
W = alpha * Distance_matrix + (1.-alpha) * Convexity_matrix
if normalize:
DD = 1./W.sum(axis=-1)
DD = spsparse.spdiags(np.squeeze(DD), [0], DD.shape[0], DD.shape[0])
W = DD.dot(W) # this is perfect normalization.
return W
def distance_to_heat_affinity_matrix(Dmatrix, gamma=None):
r""" Convert any distance matrix to an affinity matrix by applying a heat kernel.
.. math::
A = \exp^{\left(\frac{-D^2}{2\sigma^2}\right)}
where :math:`sigma` is set as the mean distance of :math:`D` or :math:`\gamma` if provided.
Parameters
----------
Dmatrix : (N,N) sparse array
a scipy.sparse input distance matrix
gamma : scalar
the normalisation scale factor of distances
Returns
-------
A : (N,N) sparse array
a scipy.sparse output affinity distance matrix
"""
import numpy as np
import igl
import scipy.sparse as spsparse
l = Dmatrix.shape[0]
A = Dmatrix.copy()
if gamma is None:
sigma_D = np.mean(A.data)
else:
sigma_D = gamma
den_D = 2 * (sigma_D ** 2)
np.exp( -A.data**2/den_D, out=A.data )
A = A + spsparse.diags(np.ones(l), 0) # diagonal is 1 by definition.
return A
def conformalized_mean_line_flow( contour_pts, E=None, close_contour=True, fixed_boundary = False, lambda_flow=1000, niters=10, topography_edge_fix=False, conformalize=True):
r""" Conformalized mean curvature flow of a curve, also known as the isoperimetric flow.
This function is adapted from the Matlab GPToolbox
Parameters
----------
contour_pts : (n_points,d) array
the list of coordinates of the line
E : (n_edges,2) array
the edge connectivity of points on the line
close_contour : bool
if True and E is None, construct the edge connectivity assuming the order of the given contour_pts and connecting the last point to the 1st point. If False and E is None, the order of the given contour_pts is still assumed but the last point to the 1st point is not connected by an edge
fixed_boundary : bool
if True, the ends of the contour_pts is not involved but is pinned to its original position. Only the interior points are updated
lambda_flow : scalar
controls the stepsize of the evolution per iteration. Smaller values given less movement
niters : int
the number of iterations to run
topography_edge_fix : bool
this is only relevant for :func:`unwrap3D.Mesh.meshtools.conformalized_mean_curvature_flow_topography` or lines coming from topographic boundaries where we wish to remove all flow in other directions except that in the depth axis at the boundary.
conformalize : bool
if True, the Laplacian matrix is not recomputed at every iteration.
Returns
-------
contour_pts_flow : (n_points,d,niters+1)
the list of coordinates of the line at each iteration including the initial position. The edge connectivity is the same as input
"""
# Fix boundary will find all degree = 1 nodes and make their laplacian 0 ---> inducing no flow. and therefore returning the identity
import numpy as np
import scipy.sparse as spsparse
if E is None:
if close_contour:
E = [np.arange(len(contour_pts)),
np.hstack([np.arange(len(contour_pts))[1:], 0])]
else:
E = [np.arange(len(contour_pts))[:-1],
np.arange(len(contour_pts))[1:]]
E = np.vstack(E).T
A = adjacency_edge_cost_matrix(contour_pts, E)
L = A-spsparse.diags(np.squeeze(np.array(A.sum(axis=1)))); # why is this so slow?
if fixed_boundary:
boundary_nodes = np.arange(len(contour_pts))[A.sum(axis=1) == 1]
L[boundary_nodes,:] = 0 # slice this in.
# so we need no flux boundary conditions to prevent flow in x,y at the boundary!....----> one way is to do mirror...( with rectangular grid this is easy... but with triangle is harder...)
contour_pts_flow = [contour_pts]
for iter_ii in np.arange(niters):
A = adjacency_edge_cost_matrix(contour_pts_flow[-1], E)
if conformalize ==False:
L = A-spsparse.diags(np.squeeze(np.array(A.sum(axis=1))));
if fixed_boundary:
boundary_nodes = np.arange(len(contour_pts))[A.sum(axis=1) == 1]
L[boundary_nodes,:] = 0 # slice this in.
M = mass_matrix2D(A)
# # unfixed version of the problem
# vvv = spsparse.linalg.spsolve(M-lambda_flow*L, M.dot(boundary_mesh_pos[-1]))
if topography_edge_fix:
rhs_term = -lambda_flow*L.dot(contour_pts_flow[-1]) # this balances the flow. # the x-y plane has normal with z. # so we just the opposite.
rhs_term[:,0] = 0 # ok this is correct - this blocks all into plane flow. but what if we relax this.... -> permit just not orthogonal....
vvv = spsparse.linalg.spsolve(M-lambda_flow*L, M.dot(contour_pts_flow[-1]) + rhs_term)
else:
vvv = spsparse.linalg.spsolve(M-lambda_flow*L, M.dot(contour_pts_flow[-1]))
contour_pts_flow.append(vvv)
contour_pts_flow = np.array(contour_pts_flow)
contour_pts_flow = contour_pts_flow.transpose(1,2,0)
return contour_pts_flow
def conformalized_mean_curvature_flow(mesh, max_iter=50, delta=5e-4, rescale_output = True, min_diff = 1e-13, conformalize = True, robust_L =False, mollify_factor=1e-5):
r""" Conformalized mean curvature flow of a mesh of Kazhdan et al. [1]_
Parameters
----------
mesh : trimesh.Trimesh
the input 3D mesh
max_iter : int
the number of iterations
delta : scalar
controls the stepsize of the evolution per iteration. Smaller values gives less deformation
rescale_output : bool
if False will return a surface area normalised mesh instead. if True return the mean curvature flow surfaces at the same scale as the input mesh
min_diff :
not used for now
conformalize :
if True, the Laplacian matrix is not recomputed at every iteration.
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [2]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
Returns
-------
Usteps : (n_points,3,niters+1) array
an array of the vertex coordinates of the mesh at each iteration
F : (n_faces,3) array
the face connectivity of the mesh
flow_metrics_dict : dict
a dict of various statistical measures of the flow
'mean_curvature_iter' : array
mean of absolute values of mean curvature per face per iteration
'max_curvature_iter' : array
maximum of absolute values of mean curvature per face per iteration
'gauss_curvature_iter' : array
mean of absolute values of Gaussian curvature per face per iteration
'canonical_c_all' : array
array of the computed face area weighted centroid per iteration with respect to an area normalised mesh
'canonical_area_all' : array
array of the total surface area used for area normalising per iteration
'flow_d_all' : array
matrix norm difference between current and previous vertex coordinate positions
'V0_max' : scalar
the maximum scalar value over all coordinate values used to initially scale the mesh vertices
References
----------
.. [1] Kazhdan, Michael, Jake Solomon, and Mirela Ben‐Chen. "Can mean‐curvature flow be modified to be non‐singular?." Computer Graphics Forum. Vol. 31. No. 5. Oxford, UK: Blackwell Publishing Ltd, 2012.
.. [2] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
"""
"""
input is a trimesh mesh object with vertices, faces etc.
delta: the step size of diffusion.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
if robust_L:
import robust_laplacian
V = mesh.vertices
# V = V - np.mean(V, axis=0) # center this
F = mesh.faces
# or the robust version (tufted -> see Keenan Crane) # sign is inversed..... from IGL.
if robust_L:
L, M = robust_laplacian.mesh_laplacian(np.array(V), np.array(F), mollify_factor=mollify_factor);
L = -L
else:
# first build the laplacian.
L = igl.cotmatrix(V,F) # this is negative semi-definite
# make a copy of the initial vertex, face
SF = F.copy() # make a copy that is the initial faces connectivity.
V0 = V.copy();
# V0_max = float(np.abs(V).max())
V0_max = float(V.max())
# V0_max = 1
# initialise the save array.
Usteps = np.zeros(np.hstack([V.shape, max_iter+1]))
# first step.
U = V.copy();
# pre-normalize for stability.
U = U / V0_max # pre-divided by U.max().... here so we are in [0,1] # this is best for image-derived meshes.. not for scanned meshes?
Usteps[...,0] = U.copy() # initialise.
# save various curvature measures of intermediate.
curvature_steps = []
max_curvature_steps = []
gauss_curvature_steps = []
# these must be applied iteratively in order to reconstitute the actual size ?
c_all = []
area_all = []
d_all = []
c0 = np.hstack([0,0,0])
area0 = 1.
for ii in tqdm(range(max_iter)):
# iterate.
U_prev = U.copy(); # make a copy.
# % 'full' seems slight more stable than 'barycentric' which is more stable
# % than 'voronoi'
if not robust_L:
M = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_BARYCENTRIC) # -> this is the only matrix that doesn't degenerate.
else:
L_, M = robust_laplacian.mesh_laplacian(np.array(U), np.array(F), mollify_factor=mollify_factor); L_ = -L_
# M = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_FULL) # what about this ?
# % M = massmatrix(U,F,'full');
if conformalize==False:
if not robust_L:
# L = laplacian(V,F);
L = igl.cotmatrix(U,F) # should be recomputation.
else:
L = L_.copy()
# # implicit solve.
S = (M-delta*L) # what happens when we invert?
b = M.dot(U)
# b = U.copy()
# # Solve # compare with spsolve. # best way to solve? ---> S is symmetric therefore we can do splu then solve.---> which should be really fast!.
# u1,xx = spsparse.linalg.bicgstab(S, b[:,0]) # not that bad...
# u2,yy = spsparse.linalg.bicgstab(S, b[:,1])
# u3,zz = spsparse.linalg.bicgstab(S, b[:,2])
# u1,xx = spsparse.linalg.cg(S, b[:,0], maxiter=100) # not that bad...
# u2,yy = spsparse.linalg.cg(S, b[:,1], maxiter=100)
# u3,zz = spsparse.linalg.cg(S, b[:,2], maxiter=100)
# u1,xx = spsparse.linalg.bicg(S, b[:,0], maxiter=100) # not that bad...
# u2,yy = spsparse.linalg.bicg(S, b[:,1], maxiter=100)
# u3,zz = spsparse.linalg.bicg(S, b[:,2], maxiter=100)
# U = np.vstack([u1,u2,u3]).T
U = spsparse.linalg.spsolve(S,b)
if np.sum(np.isnan(U[:,0])) > 0:
# if we detect nan, no good.
break
else:
# canonical centering is a must to stabilize -> essentially affects a scaling + translation.
# rescale by the area? # is this a mobius transformation? ( can)
area = np.sum(igl.doublearea(U,SF)*.5) #total area.
c = np.sum((0.5*igl.doublearea(U,SF)/area)[...,None] * igl.barycenter(U,F), axis=0) # this is just weighted centroid
U = U - c[None,:]
U = U/(np.sqrt(area)) # avoid zero area
d = ((((U-U_prev).T).dot(M.dot(U-U_prev)))**2).diagonal().sum() # assessment of convergence.
d_all.append(d)
# append key parameters.
c_all.append(c)
area_all.append(area)
"""
Compute assessments of smoothness.
"""
# compute the mean curvature # use the principal curvature computation.
# ll = igl.cotmatrix(U, F)
# mm = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_VORONOI)
# minv = spsparse.diags(1 / mm.diagonal())
# hn = -minv.dot(ll.dot(U))
# h = np.linalg.norm(hn, axis=1)
# more robust:
_, _, k1, k2 = igl.principal_curvature(U, F)
h2 = 0.5 * (k1 + k2)
curvature_steps.append(np.nanmean(np.abs(h2)))
max_curvature_steps.append(np.nanmax(np.abs(h2)))
# this is the best.
kk = igl.gaussian_curvature(U, F)
gauss_curvature_steps.append(np.nanmean(np.abs(kk)))
if rescale_output:
# x area + c
c0 = c0 + c
area0 = area0*np.sqrt(area)
Usteps[...,ii+1] = ((U * area0) + c0[None,:]).copy() # since it is just iterative...
else:
Usteps[...,ii+1] = U.copy() # copy the current iteration into it.
c_all = np.vstack(c_all)
area_all = np.hstack(area_all)
Usteps = Usteps[..., :len(area_all)+1]
if rescale_output == False:
# area = np.sum(igl.doublearea(Usteps[...,0],SF)*0.5); # original area.
# c = np.sum((0.5*igl.doublearea(Usteps[...,0],SF)/area)[...,None] * igl.barycenter(Usteps[...,0],SF), axis=0);
# below is more easy to get back
area = area_all[0] # this is wrong? # -> this might be the problem ... we should have the same as number of iterations.
c = c_all[0]
# print(area, c)
# if nargout > 1
for iteration in range(Usteps.shape[-1]-1):
Usteps[:,:,iteration+1] = Usteps[:,:,iteration+1]*np.sqrt(area);
Usteps[:,:,iteration+1] = Usteps[:,:,iteration+1] + c[None,:]
# finally multiply all Usteps by umax
Usteps = Usteps * V0_max
# to save the key parameters that we will make use of ....
flow_metrics_dict = {'mean_curvature_iter': curvature_steps,
'max_curvature_iter': max_curvature_steps,
'gauss_curvature_iter': gauss_curvature_steps,
'canonical_c_all': c_all,
'canonical_area_all': area_all,
'flow_d_all': d_all,
'V0_max': V0_max}
return Usteps, F, flow_metrics_dict
def conformalized_mean_curvature_flow_topography(mesh,
max_iter=50,
delta=5e-4,
min_diff = 1e-13,
conformalize = True,
robust_L =False,
mollify_factor=1e-5):
r""" Adapted conformalized mean curvature flow of a mesh of Kazhdan et al. [1]_ to allow for topographic meshes such that iterative applications flattens the topography to the plane.
Parameters
----------
mesh : trimesh.Trimesh
the input topography mesh
max_iter : int
the number of iterations
delta : scalar
controls the stepsize of the evolution per iteration. Smaller values gives less deformation
min_diff :
not used for now
conformalize :
if True, the Laplacian matrix is not recomputed at every iteration.
robust_L : bool
if True, uses the robust Laplacian construction of Sharpe et al. [2]_. If False, the standard cotan Laplacian is used. The robust Laplacian enables proper handling of degenerate and nonmanifold vertices such as that if using the triangle mesh constructed from a uv image grid. The normal 3D mesh if remeshed does not necessarily need this
mollify_factor : scalar
the mollification factor used in the robust Laplacian. see https://github.com/nmwsharp/robust-laplacians-py
Returns
-------
Usteps : (n_points,3,niters+1) array
an array of the vertex coordinates of the mesh at each iteration
F : (n_faces,3) array
the face connectivity of the mesh
flow_metrics_dict : dict
a dict of various statistical measures of the flow
'mean_curvature_iter' : array
mean of absolute values of mean curvature per face per iteration
'max_curvature_iter' : array
maximum of absolute values of mean curvature per face per iteration
'gauss_curvature_iter' : array
mean of absolute values of Gaussian curvature per face per iteration
'canonical_c_all' : array
array of the computed face area weighted centroid per iteration with respect to an area normalised mesh
'canonical_area_all' : array
array of the total surface area used for area normalising per iteration
'flow_d_all' : array
matrix norm difference between current and previous vertex coordinate positions
'V0_max' : scalar
the maximum scalar value over all coordinate values used to initially scale the mesh vertices
References
----------
.. [1] Kazhdan, Michael, Jake Solomon, and Mirela Ben‐Chen. "Can mean‐curvature flow be modified to be non‐singular?." Computer Graphics Forum. Vol. 31. No. 5. Oxford, UK: Blackwell Publishing Ltd, 2012.
.. [2] Sharp, Nicholas, and Keenan Crane. "A laplacian for nonmanifold triangle meshes." Computer Graphics Forum. Vol. 39. No. 5. 2020.
"""
import igl
import numpy as np
import scipy.sparse as spsparse
from tqdm import tqdm
if robust_L:
import robust_laplacian
V = mesh.vertices
F = mesh.faces
# parsing the boundary loop -> we assume largely a simple surface with just the 1 major boundary
b = igl.boundary_loop(F) # boundary
v_b = np.unique(b) # this is the unique vertex indices.
# build edge connectivity matrix in original index.
E = [b,
np.hstack([b[1:], b[0]])]
E = np.vstack(E).T
## List of all vertex indices
v_all = np.arange(V.shape[0])
## List of interior indices
v_in = np.setdiff1d(v_all, v_b)
# build the laplacian for the boundary loop.
A_b = adjacency_edge_cost_matrix( V, E, n=len(v_all))
L_b = A_b-spsparse.diags(np.squeeze(np.array(A_b.sum(axis=1))));
# or the robust version (tufted -> see Keenan Crane) # sign is inversed..... from IGL.
if robust_L:
L, M = robust_laplacian.mesh_laplacian(np.array(V), np.array(F), mollify_factor=mollify_factor);
L = -L
else:
# first build the laplacian.
L = igl.cotmatrix(V,F) # this is negative semi-definite
L[v_b] = L_b[v_b] # slice in is allowed. wow.
# make a copy of the initial vertex, face
SF = F.copy() # make a copy that is the initial faces connectivity.
V0 = V.copy();
# better to do area norm straight up!.
# V0_max = float(np.sum(igl.doublearea(V0,SF)*.5)) # rescale - assume this is image based
# V0_max = float(V.max())
V0_max = float(1.)
# initialise the save array.
Usteps = np.zeros(np.hstack([V.shape, max_iter+1]))
# first step.
U = V.copy();
# pre-normalize for stability. # actually might not be the case but will help convergence.
# U = U / V0_max # pre-divided by U.max().... here so we are in [0,1] # this is best for image-derived meshes.. not for scanned meshes?
U[:,0] = U[:,0] - np.nanmean(V[:,0])
Usteps[...,0] = U.copy() # initialise.
# save various curvature measures of intermediate.
curvature_steps = []
max_curvature_steps = []
gauss_curvature_steps = []
# these must be applied iteratively in order to reconstitute the actual size ?
c_all = []
area_all = []
d_all = []
c0 = np.hstack([0,0,0])
area0 = 1.
for ii in tqdm(range(max_iter)):
# iterate.
U_prev = U.copy(); # make a copy.
# % 'full' seems slight more stable than 'barycentric' which is more stable
# % than 'voronoi'
if not robust_L:
M = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_BARYCENTRIC) # -> this is the only matrix that doesn't degenerate.
M = M.tocsr()
else:
L_, M = robust_laplacian.mesh_laplacian(np.array(U), np.array(F), mollify_factor=mollify_factor); L_ = -L_
M = M.tocsr()
A_b = adjacency_edge_cost_matrix(U, E, n=len(v_all))
M_b = mass_matrix2D(A_b); M_b = M_b.tocsr()
M[v_b,:] = M_b[v_b,:]
# M = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_FULL) # what about this ?
# % M = massmatrix(U,F,'full');
if conformalize==False:
if not robust_L:
# L = laplacian(V,F);
L = igl.cotmatrix(U,F) # should be recomputation.
else:
L = L_.copy()
L_b = A_b-spsparse.diags(np.squeeze(np.array(A_b.sum(axis=1))));
L[v_b] = L_b[v_b] # slice in is allowed. wow.
# # implicit solve.
S = (M-delta*L) # what happens when we invert?
b = M.dot(U)
"""
add additional boundary term on right
"""
b_bnd_all = -delta*L.dot(U)
b_bnd = np.zeros(b_bnd_all.shape)
b_bnd[v_b,1:] = b_bnd_all[v_b,1:] # this generically destroys all x-y plane deformation.
# # do prefactorisation?
# S = S.tocsc()
# # S_ = spsparse.linalg.splu(S)
U = spsparse.linalg.spsolve(S, b + b_bnd)
# U = S_.solve(b + b_bnd)
if np.sum(np.isnan(U[:,0])) > 0:
# if we detect nan, no good.
break
else:
# canonical centering is a must to stabilize -> essentially affects a scaling + translation.
# rescale by the area? # is this a mobius transformation? ( can)
area = np.sum(igl.doublearea(U,SF)*.5) #total area.
# c = np.sum((0.5*igl.doublearea(U,SF)/area)[...,None] * igl.barycenter(U,F), axis=0) # this is just weighted centroid
# U = U - c[None,:]
# U = U/(np.sqrt(area)) # avoid zero area
d = ((((U-U_prev).T).dot(M.dot(U-U_prev)))**2).diagonal().sum() # assessment of convergence.
# U = U*(np.sqrt(area))
d_all.append(d)
# append key parameters.
# c_all.append(c)
area_all.append(area)
"""
Compute assessments of smoothness.
"""
# # compute the mean curvature
# ll = igl.cotmatrix(U, F)
# mm = igl.massmatrix(U, F, igl.MASSMATRIX_TYPE_VORONOI)
# minv = spsparse.diags(1 / mm.diagonal())
# hn = -minv.dot(ll.dot(U))
# h = np.linalg.norm(hn, axis=1)
# curvature_steps.append(np.nanmean(np.abs(h)))
# max_curvature_steps.append(np.nanmax(np.abs(h)))
# more robust:
_, _, k1, k2 = igl.principal_curvature(U, F)
h2 = 0.5 * (k1 + k2)
curvature_steps.append(np.nanmean(np.abs(h2)))
max_curvature_steps.append(np.nanmax(np.abs(h2)))
# this is the best.
kk = igl.gaussian_curvature(U, F)
gauss_curvature_steps.append(np.nanmean(np.abs(kk)))
# if rescale_output:
# # # x area + c
# # c0 = c0 + c
# area0 = area0*np.sqrt(area)
# Usteps[...,ii+1] = U * area0 #+ c0[None,:]).copy() # since it is just iterative...
# else:
# Usteps[...,ii+1] = U.copy() # copy the current iteration into it.
Usteps[...,ii+1] = U.copy()
# c_all = np.vstack(c_all)
area_all = np.hstack(area_all)
Usteps = Usteps[..., :len(area_all)+1]
# if rescale_output == False:
# # area = np.sum(igl.doublearea(Usteps[...,0],SF)*0.5); # original area.
# # c = np.sum((0.5*igl.doublearea(Usteps[...,0],SF)/area)[...,None] * igl.barycenter(Usteps[...,0],SF), axis=0);
# # below is more easy to get back
# area = area_all[0] # this is wrong? # -> this might be the problem ... we should have the same as number of iterations.
# # c = c_all[0]
# # print(area, c)
# # if nargout > 1
# for iteration in range(Usteps.shape[-1]-1):
# Usteps[:,:,iteration+1] = Usteps[:,:,iteration+1]*np.sqrt(area);
# # Usteps[:,:,iteration+1] = Usteps[:,:,iteration+1] + c[None,:]
# # finally multiply all Usteps by umax
# Usteps = Usteps * V0_max
Usteps[:,0] = Usteps[:,0] + np.nanmean(V[:,0])
# to save the key parameters that we will make use of ....
flow_metrics_dict = {'mean_curvature_iter': curvature_steps,
'max_curvature_iter': max_curvature_steps,
'gauss_curvature_iter': gauss_curvature_steps,
'canonical_c_all': c_all,
'canonical_area_all': area_all,
'flow_d_all': d_all,
'V0_max': V0_max}
return Usteps, F, flow_metrics_dict
def recover_img_coordinate_conformal_mean_flow(Usteps, flow_dict):
r""" This function reverses the iterative, centroid computation, subtraction and area normalisation in the conformalized mean curvature flow of a general 3D mesh, :func:`unwrap3D.Mesh.meshtools.conformalized_mean_curvature_flow`
Parameters
----------
Usteps : (n_vertices,3,niters) array
the area normalised vertex positions of a 3D mesh for every iteration of the conformalized mean curvature flow. 1st output of :func:`unwrap3D.Mesh.meshtools.conformalized_mean_curvature_flow` computed with rescale_output=False
flow_dict :
the statistical measures of a mesh deformed under conformalized mean curvature flow. 3rd output of :func:`unwrap3D.Mesh.meshtools.conformalized_mean_curvature_flow`
'mean_curvature_iter' : array
mean of absolute values of mean curvature per face per iteration
'max_curvature_iter' : array
maximum of absolute values of mean curvature per face per iteration
'gauss_curvature_iter' : array
mean of absolute values of Gaussian curvature per face per iteration
'canonical_c_all' : array
array of the computed face area weighted centroid per iteration with respect to an area normalised mesh
'canonical_area_all' : array
array of the total surface area used for area normalising per iteration
'flow_d_all' : array
matrix norm difference between current and previous vertex coordinate positions
'V0_max' : scalar
the maximum scalar value over all coordinate values used to initially scale the mesh vertices
Returns
-------
Usteps_ : (n_vertices,3,niters) array
the reconstructed image vertex positions of a 3D mesh for every iteration of the conformalized mean curvature flow, identical to if :func:`unwrap3D.Mesh.meshtools.conformalized_mean_curvature_flow` had been run with rescale_output=True
"""
import numpy as np
import pylab as plt
# in the default case, all the secondary points have recovered
sqrt_area_all = np.sqrt(np.hstack(flow_dict['canonical_area_all'])) # this is not such an easy scaling factor.....
c_all = np.vstack(flow_dict['canonical_c_all'])
U_max = flow_dict['V0_max']
cum_area_all = np.cumprod(sqrt_area_all) # this should be cumulative.
cum_c_all = np.cumsum(c_all, axis=0).T
Usteps_ = Usteps / U_max # first divide this.
Usteps_[...,2:] = (Usteps_[...,2:] - cum_c_all[:,0][None,:,None]) / cum_area_all[0] # remove...
Usteps_[...,2:] = (Usteps_[...,2:] * (cum_area_all[1:][None,None,:])) + cum_c_all[None,:,1:] # multiply first.
Usteps_ = Usteps_*U_max
return Usteps_
def relax_mesh( mesh_in, relax_method='CVT (block-diagonal)', tol=1.0e-5, n_iters=20, omega=1.):
r""" wraps the optimesh library to perform mesh relaxation with Delaunay edge flipping. This is done mainly to improve triangle quality to improve the convergence of linear algebra solvers
Parameters
----------
mesh_in : trimesh.Trimesh
input mesh to relax
relax_method : str
any of those compatible with optimesh.optimize()
tol : scalar
sets the accepted tolerance for convergence
n_iters : int
the maximum number of iterations
omega : scalar
controls the stepping size, smaller values will have better accuracy but slower convergence.
Returns
-------
mesh : trimesh.Trimesh
output relaxed mesh with no change in the number of vertices but with changes to faces
opt_result : optimization results
returns tuple of number of iterations and difference
mean_mesh_quality : scalar
mean triangle quanlity, where trangle quality is 2*inradius/circumradius
"""
import optimesh
import trimesh
import meshplex
points = mesh_in.vertices.copy()
cells = mesh_in.faces.copy()
mesh = meshplex.MeshTri(points, cells)
opt_result = optimesh.optimize(mesh, relax_method, tol=tol, max_num_steps=n_iters, omega=omega)
mean_mesh_quality = mesh.q_radius_ratio.mean()
# give back the mesh.
mesh = trimesh.Trimesh(vertices=mesh.points, faces=mesh.cells('points'), validate=False, process=False) # suppress any other processing to keep the correct lookup.
return mesh, opt_result, mean_mesh_quality
def smooth_scalar_function_mesh(mesh, scalar_fn, exact=False, n_iters=10, weights=None, return_weights=True, alpha=0):
r""" wraps the optimesh library to perform mesh relaxation with Delaunay edge flipping. This is done mainly to improve triangle quality to improve the convergence of linear algebra solvers
Parameters
----------
mesh : trimesh.Trimesh
input mesh
scalar_fn : (n_vertices,d) array
the d-dimensional scalar values to spatially smooth over the mesh
exact : bool
if True, evaluates the normalised :math:`M^-1 L` where :math:`M` is the mass and :math:`L` is the cotan Laplacian matrices respectively and uses this as the weights for spatial smoothing. The inversion is very slow. Setting to False, use the cotan Laplacian to smooth.
n_iters : int
the maximum number of iterations
weights : (n_vertices,n_vertices) sparse array
user-specified vertex smoothing matrix. This overrides the options of ``exact``.
return_weights : bool
return additionally the weights matrix used as a second optional output
alpha : 0-1 scalar
not used at present
Returns
-------
scalar0 : (n_vertices,d) array
the spatially smoothed d-dimensional scalar values over the mesh
weights : (n_vertices,n_vertices) sparse array
if return_weights=True, the weights used is returned for convenience if the user wishes to reuse the weights e.g. to avoid recomputing.
"""
"""
If exact we use M-1^L else we use the cotangent laplacian which is super fast with no inversion required.
allow optional usage of weights.
"""
import igl
import time
import numpy as np
import scipy.sparse as spsparse
v = mesh.vertices.copy()
f = mesh.faces.copy()
scalar0 = scalar_fn.copy()
# # if ii ==0:
L = igl.cotmatrix(v,f)
M = igl.massmatrix(v,
f,
igl.MASSMATRIX_TYPE_BARYCENTRIC) # -> this is the only matrix that doesn't degenerate.
if exact:
if weights is None:
# t1 = time.time()
weights = spsparse.linalg.spsolve(M, L) # m_inv_l # this inversion is slow..... the results for me is very similar.... but much slower!.
# print('matrix inversion for weights in: ', time.time() - t1,'s') # 65s?
else:
if weights is None:
weights = L
for iteration in np.arange(n_iters):
scalar0_next = (np.squeeze((np.abs(weights)).dot(scalar0)) / (np.abs(weights).sum(axis=1)))
scalar0_next = np.array(scalar0_next).ravel()
scalar0_next = scalar0_next.reshape(scalar_fn.shape)
scalar0 = scalar0_next.copy()
# print(kappa0_next.shape)
scalar0 = np.array(scalar0)
# case to numpy array and return
if return_weights:
return scalar0, weights
else:
return scalar0
def connected_components_mesh(mesh, original_face_indices=None, engine=None, min_len=1):
r""" find the connected face components given a mesh or submesh
Parameters
----------
mesh : trimesh.Trimesh
input mesh,
original_face_indices : (N,) array
if provided these should be the original face indices that mesh.faces come from. The final connected components will be re-indexed with the provided original_face_indices.
engine : str
Which graph engine to use ('scipy', 'networkx')
min_len : int
the minimum number of faces in a connected component. Those with a number of faces that these will be dropped
Returns
-------
components : list of arrays
list of an array of face indices forming a connected component
"""
import trimesh
import numpy as np
f = mesh.faces.copy()
components = trimesh.graph.connected_components(
edges=mesh.face_adjacency,
nodes=np.arange(len(f)),
min_len=min_len, # this makes sure we don't exclude everything!. by setting this to 1!!!! c.f. trimesh definitions.
engine=engine)
# if the original_face_indices is provided, then the mesh was formed as a subset of the triangles and we want to get this back!.
if original_face_indices is not None:
components = [original_face_indices[cc] for cc in components] # remap to the original indexing
return components
def get_k_neighbor_ring(mesh, K=1, stateful=False):
r""" Find all vertex indices within a K-ring neighborhood of individual vertices of a mesh. For a vertex its K-Neighbors are all those of maximum length K edges away. The result is return as an adjacency list
Parameters
----------
mesh : trimesh.Trimesh
input mesh,
K : int
the maximum distance of a topological neighbor defined by the number of edge-hops away.
stateful : bool
if True, returns list of adjacency lists for all neighborhoods k=1..to..K. if False, only the asked for K neighborhood is returned.
Returns
-------
k_rings : (n_vertex long adjacency list) or (list of n_vertex long adjacency list)
if stateful=False, one adjacency list for the specified K of length n_vertex is returned else all list of adjacency lists for all neighborhoods k=1..to..K is provided
"""
# by default we only compute the 1_ring
# if return_sparse_matrix then map tp adjacency .....
# if stateful return list if k>1
import networkx as nx
import numpy as np
g = nx.from_edgelist(mesh.edges_unique) # build edges .
one_ring = [np.array(list(g[i].keys())) for i in range(len(mesh.vertices))] # one neighborhood....
if K > 1:
k_rings = [one_ring]
iters = K-1
for iter_ii in np.arange(iters):
k_ring = [np.unique(np.hstack([one_ring[rrr] for rrr in (k_rings[-1])[rr]])) for rr in np.arange(len(one_ring))]
k_ring = [np.unique(np.hstack([(k_rings[-1])[rr_ii], k_ring[rr_ii]])) for rr_ii in np.arange(len(k_ring))] # make sure the previous was covered.
k_rings.append(k_ring)
if stateful:
return k_rings
else:
k_rings = list(k_rings[-1])
return k_rings
else:
k_rings = list(one_ring)
return k_rings
# # edge_list to sparse matrix. ?
# def edge_list_to_matrix(edge_list):
# r""" Function to convert a given list or array of edge connections to an adjacency matrix where 1 denotes the presence of an edge between
# """
# import scipy.sparse as spsparse
# import numpy as np
# row_inds = np.hstack([[ii]*len(edge_list[ii]) for ii in len(edge_list)])
# col_inds = np.hstack(edge_list)
# # crucial third array in python, which can be left out in r
# ones = np.ones(len(row_inds), np.uint32)
# matrix = spsparse.csr_matrix((ones, (row_inds, col_inds)))
# return matrix # useful for clustering applications. and for saving ....
def find_central_ind(v, vertex_components_indices):
r""" Given a list of mesh patches in the form of vertex indices of the mesh, find the index on the mesh surface for each patch that is closest to the patch centroid. This assumes that each patch is local such that the patch centroid is covered by the convex hull.
Parameters
----------
v : (n_vertex,3)
vertices of the full 3D mesh
vertex_components_indices : list of arrays
list of patches, where each patch is given as vertex indices into ``v``
Returns
-------
central_inds : (n_components,)
an array the same number as the given vertex patches/components given the index into ``v`` closest to the geometrical centroid of the vertex component
"""
import numpy as np
central_inds = []
for component_inds in vertex_components_indices:
verts = v[component_inds].copy()
mean_verts = np.nanmean(verts, axis=0)
central_inds.append(component_inds[np.argmin(np.linalg.norm(verts - mean_verts[None,:]))])
central_inds = np.hstack(central_inds)
return central_inds
def compute_geodesic_sources_distance_on_mesh(mesh, source_vertex_indices, t_diffuse=.5, return_solver=True, method='heat'):
r""" Compute the geodesic distance of all vertex points on a mesh to given sources using the fast approximate vector heat method of Crane et al. [1]_, [2]_ or using exact Djikstras shortest path algorithm
Parameters
----------
mesh : trimesh.Trimesh
input mesh
source_vertex_indices : list of arrays
List of individual 'sources' specifying multiple sources to compute distance from. Sources are vertex points where the geodesic distance are 0. The vector heat method, method='heat' allows arrays to describe individual sources as non-point like. if method='exact', multipoint sources are reduced to a central single-point source
t_diffuse : scalar
set the time used for short-time heat flow in method='heat'. Larger values may make the solution more stable at the cost of over-smoothing
return_solver : bool
if True, return the solver used in the vector heat method, see https://github.com/nmwsharp/potpourri3d
method : str
specifies the geodesic distance computation method. either of 'heat' for vector heat or 'exact' for Djikstra
Returns
-------
if method == 'heat' :
geodesic_distances_components : (n_sources, n_vertex) array
the geodesic distance of each vertex point of the mesh to each of the sources specified in ``source_vertex_indices``
solver : potpourri3d MeshHeatMethodDistanceSolver instance
if return_solver=True, return the vector heat solver used for geodesic distance computation
if method == 'exact' :
distances : (n_vertex,) array
an array of the shortest geodesic distance to any source for each vertex
best_source : (n_vertex,) array
the id of the closest source for each vertex
References
----------
.. [1] Crane, Keenan, Clarisse Weischedel, and Max Wardetzky. "The heat method for distance computation." Communications of the ACM 60.11 (2017): 90-99.
.. [2] Sharp, Nicholas, Yousuf Soliman, and Keenan Crane. "The vector heat method." ACM Transactions on Graphics (TOG) 38.3 (2019): 1-19.
"""
import igl # igl version is incredibly slow!. use nick sharps potpourri3D!
# import potpourri3d as pp3d
import numpy as np
v = mesh.vertices.copy()
f = mesh.faces.copy()
# geodesic_distances_components = [igl.heat_geodesic(v=v,
# f=f,
# t=t_diffuse,
# gamma=np.array(cc)) for cc in source_vertex_indices]
if method == 'heat':
import potpourri3d as pp3d
solver = pp3d.MeshHeatMethodDistanceSolver(v,f,t_coef=t_diffuse)
geodesic_distances_components = [solver.compute_distance_multisource(np.array(cc)) for cc in source_vertex_indices]
geodesic_distances_components = np.array(geodesic_distances_components)
if return_solver:
return geodesic_distances_components, solver
else:
return geodesic_distances_components
if method == 'exact':
# use the very fast method in pygeodesic.
import pygeodesic.geodesic as geodesic
geoalg = geodesic.PyGeodesicAlgorithmExact(v, f)
source_centre_vertex_indices = find_central_ind(v,source_vertex_indices)
source_indices = np.array(source_centre_vertex_indices) # just one ind per component.
target_indices = np.array(np.arange(len(v)))
distances, best_source = geoalg.geodesicDistances(source_indices, target_indices)
return distances, best_source
# using the above we can do watershed with seed regions and optional masks....
def mesh_watershed_segmentation_faces(mesh, face_components, t_diffuse=.5, mesh_face_mask=None, return_solver=True, method='heat'):
r""" Do marker seeded watershed segmentation on the mesh by assigning individual faces to the user provided 'seeds' or sources by geodesic distance. Output is an integer label for each mesh face with -1 denoting a user masked out face.
Parameters
----------
mesh : trimesh.Trimesh
input mesh
face_components : list of arrays
the seeds or 'sources' given as a list of face index components
t_diffuse : scalar
set the time used for short-time heat flow in method='heat'. Larger values may make the solution more stable at the cost of over-smoothing
mesh_face_mask : (n_faces,) array
a binary array 0 or 1 specifying which faces should not be included in the final labels. Masked out faces are assigned a label of -1, whereas all valid labels are integer 0 or above.
return_solver : bool
if True, return the solver used in the vector heat method, see https://github.com/nmwsharp/potpourri3d
method : str
specifies the geodesic distance computation method. either of 'heat' for vector heat or 'exact' for Djikstra
Returns
-------
geodesic_distances_components : (n_faces,) array
for each face, the geodesic distance to the assigned source
geodesic_distances_label : (n_faces,) array
for each faces, the id of the source assigned
"""
# also see. https://pypi.org/project/pygeodesic/
import numpy as np
import igl
v = mesh.vertices.copy()
f = mesh.faces.copy()
# convert the face to vertex components for processing
vertex_components = [np.unique(f[ff_c].ravel()) for ff_c in face_components]
if method=='heat':
# give the face components directly in terms of the original mesh indices.
if return_solver:
geodesic_distances_components, heat_solver = compute_geodesic_sources_distance_on_mesh(mesh, vertex_components, t_diffuse=t_diffuse)
else:
geodesic_distances_components = compute_geodesic_sources_distance_on_mesh(mesh, vertex_components, t_diffuse=t_diffuse)
# average onto the faces.
# use the average onto faces to get n_components x n_faces.
geodesic_distances_components = igl.average_onto_faces(f, geodesic_distances_components.T).T
# assign to nearest neighbor.
geodesic_distances_label = np.argmin(geodesic_distances_components, axis=0)
# apply mask if exists.
if mesh_face_mask is not None:
geodesic_distances_label[mesh_face_mask>0] = -1 # assign this negative.
# return the original distance computations as well as the nearest neighbor.
if return_solver:
return geodesic_distances_components, geodesic_distances_label, heat_solver
else:
return geodesic_distances_components, geodesic_distances_label
if method =='exact':
import scipy.stats as spstats
geodesic_distances_components, geodesic_distances_label = compute_geodesic_sources_distance_on_mesh(mesh, vertex_components, t_diffuse=t_diffuse, method=method)
# project onto faces.
geodesic_distances_components = igl.average_onto_faces(f, geodesic_distances_components[:,None]).T
geodesic_distances_label = spstats.mode( geodesic_distances_label[f], axis=1, nan_policy='omit' )[0]
geodesic_distances_label = np.squeeze(geodesic_distances_label)
# apply mask if exists.
if mesh_face_mask is not None:
geodesic_distances_label[mesh_face_mask>0] = -1 # assign this negative.
return geodesic_distances_components, geodesic_distances_label
def find_curvature_cutoff_index(values, thresh=None, absval=True):
r""" For a given array of values, find the first index where the difference or absolute difference between two values falls below a threshold value. This function can be used to find the stopping iteration number for conformalized mean curvature smoothing based on the dcrease in absolute Gaussian curvature. If no such index can be found then np.nan is returned
Parameters
----------
values : (N,) array
1d array of values
thresh : scalar
the cutoff value threshold where we return the index where values <= thresh. If None, the median of np.diff(values) is used.
absval : bool
determine whether the cut-off is on the absolute differences in value or differences in value
Returns
-------
ind : int
if an index is found return an int otherwise return np.nan
"""
import numpy as np
diff_values = np.diff(values)
if absval:
diff_values = np.abs(diff_values)
if thresh is None:
thresh = np.median(diff_values)
ind = np.arange(len(diff_values))[diff_values<=thresh]
# print(ind, thresh)
if len(ind) > 0:
ind = ind[0]
else:
ind = np.nan # couldn't find one -> means more runs of flow is required.
return ind
def average_onto_barycenter(v,f,vals, return_barycenter=True):
r""" Convert vertex values to face values by barycentric averaging of multi-dimensional vertex-associated values. This function does not work for segmentation labels.
Parameters
----------
v : array
the vertices of the 3D mesh
f : array
the faces of the 3D mesh specified by vertex indices
vals : (n_vertex, d) array
the multi-dimensional values associated with each vertex to convert to face values
return_barycenter : bool
if True, return the barycenter coordinates
Returns
-------
barycenter_vals_f : (n_faces,d) array
the face-associated resampling of the input vertex-associated ``vals``
barycenter : (n_faces,3) array
the barycenter coordinates of the mesh
"""
import igl
if len(vals.shape) == 1:
vals_ = vals[:,None].copy()
else:
vals_ = vals.copy()
barycenter = igl.barycenter(v,f)
vals_f = vals_[f].copy()
barycenter_vals_f = 1./3*vals_f[:,0] + 1./3*vals_f[:,1] + 1./3*vals_f[:,2]
return barycenter_vals_f, barycenter
def find_principal_axes_surface_heterogeneity(pts, pts_weights=None, map_to_sphere=False, sort='ascending'):
r""" Find the principal axes of a point cloud given individual weights for each point. If weights are not given, every point is weighted equally
Parameters
----------
pts : array
the coordinates of a point cloud
pts_weights : array
the positive weights specifying the importance of each point in the principal axes computation
map_to_sphere : bool
if True, the unit sphere coordinate by projecting each point by distance normalization to compute principal axes. This enables geometry-independent computation useful for e.g. getting directional alignment based only on surface intensity
sort : 'ascending' or 'descending'
the sorting order of the eigenvectors in terms of the absolute value of the respective eigenvalues
Returns
-------
w : (d,) array
the sorted eigenvalues of the principal eigenvectors of the d-dimensional point cloud
v : (d,d) array
the sorted eigenvectors of the corresponding eigenvalues
See Also
--------
:func:`unwrap3D.Unzipping.unzip.find_principal_axes_uv_surface` :
Equivalent for finding the principal eigenvectors when give a uv parametrized surface of xyz coordinates.
:func:`unwrap3D.Mesh.meshtools.find_principal_axes_surface_heterogeneity_mesh` :
Equivalent for finding the principal eigenvectors when give a 3D triangle mesh.
"""
"""
weights should be positive. map_to_sphere so as not to be affected by geometry / reduce this.
"""
import numpy as np
if pts_weights is None:
pts_weights = np.ones(len(pts))
pts_mean = np.mean(pts, axis=0) # this shouldn't have weighting
# # compute the weighted centroid.
# pts_mean = np.nansum(pts * pts_weights[:,None]/ float(np.sum(pts_weights)), axis=0)
pts_demean = pts - pts_mean[None,:]
if map_to_sphere:
# r = np.linalg.norm(pts_demean, axis=-1)
# theta = np.arctan2(pts_demean[:,1], pts_demean[:,0])
# phi = np.arccos(pts_demean[:,2] / r)
# construct a new version with 0 magnitude?
pts_demean = pts_demean / (np.linalg.norm(pts_demean, axis=-1)[:,None] + 1e-8)
# apply the weighting
pts_demean = pts_demean * pts_weights[:,None] / float(np.sum(pts_weights))
pts_cov = np.cov(pts_demean.T) # 3x3 matrix #-> expect symmetric.
w, v = np.linalg.eigh(pts_cov)
# sort large to small.
if sort=='descending':
w_sort = np.argsort(np.abs(w))[::-1]
if sort=='ascending':
w_sort = np.argsort(np.abs(w))
w = w[w_sort]
v = v[:,w_sort]
return w, v
def find_principal_axes_surface_heterogeneity_mesh(v, f, v_weights=None, map_to_sphere=False, sort='ascending'):
r""" Find the principal axes of a mesh given individual weights for each vertex. If weights are not given, every vertex is weighted equally
Parameters
----------
v : array
the vertex cordinates of the 3D mesh
f : array
the faces of the 3D mesh specified by vertex indices
v_weights : array
the positive weights specifying the importance of each vertex in the principal axes computation
map_to_sphere : bool
if True, the unit sphere coordinate by projecting each vertex by distance normalization to compute principal axes. This enables geometry-independent computation useful for e.g. getting directional alignment based only on surface intensity
sort : 'ascending' or 'descending'
the sorting order of the eigenvectors in terms of the absolute value of the respective eigenvalues
Returns
-------
w : (d,) array
the sorted eigenvalues of the principal eigenvectors of the d-dimensional point cloud
v : (d,d) array
the sorted eigenvectors of the corresponding eigenvalues
See Also
--------
:func:`unwrap3D.Unzipping.unzip.find_principal_axes_uv_surface` :
Equivalent for finding the principal eigenvectors when give a uv parametrized surface of xyz coordinates.
:func:`unwrap3D.Mesh.meshtools.find_principal_axes_surface_heterogeneity_mesh` :
Equivalent for finding the principal eigenvectors when give a 3D triangle mesh.
"""
"""
weights should be positive. map_to_sphere so as not to be affected by geometry / reduce this.
"""
import numpy as np
import igl
# pts = v.copy()
pts = igl.barycenter(v,f)
# pts_mean = np.mean(pts, axis=0) # use the barycenter?
pts_area_weights = igl.doublearea(v,f)
pts_area_weights = pts_area_weights / float(np.nansum(pts_area_weights))
pts_mean = np.mean(pts*pts_area_weights[:,None], axis=0)
pts_demean = pts - pts_mean[None,:]
if map_to_sphere:
# r = np.linalg.norm(pts_demean, axis=-1)
# theta = np.arctan2(pts_demean[:,1], pts_demean[:,0])
# phi = np.arccos(pts_demean[:,2] / r)
# construct a new version with 0 magnitude?
pts_demean = pts_demean / (np.linalg.norm(pts_demean, axis=-1)[:,None] + 1e-8)
# unweighted version.
v_weights_barycenter = igl.average_onto_faces(f, v_weights[:,None])
v_weights_ = v_weights_barycenter*pts_area_weights
pts_demean = pts_demean * v_weights_[:,None] / float(np.sum(v_weights_))
pts_cov = np.cov(pts_demean.T) # 3x3 matrix #-> expect symmetric.
w, v = np.linalg.eigh(pts_cov)
# sort large to small.
if sort=='descending':
w_sort = np.argsort(np.abs(w))[::-1]
if sort=='ascending':
w_sort = np.argsort(np.abs(w))
w = w[w_sort]
v = v[:,w_sort]
return w, v
def rescale_mesh_points_to_grid_size(rect_mesh, grid=None, grid_shape=None):
r""" Give a rectangular-like mesh where the last 2 coordinate axes is the 2D xy coordinates such as that from a rectangular conformal map, resize points coordinates along x- and y- axes onto a given image grid so that we can for example interpolate mesh values onto an image
Parameters
----------
rect_mesh : trimesh.Trimesh
input 2D mesh where the first 2 coordinate axes is the 2D xy coordinates
grid : (M,N) or (M,N,d) single- or multi- channel image
input image to get the (M,N) shape
grid_shape : (M,N) tuple
the shape of the grid, only used if grid is not specified. Only one of grid or grid_shape needs to be passed
Returns
-------
mesh_ref : trimesh.Trimesh
output 2D mesh with resized vertex coordinates where like input the last 2 coordinate axes is the 2D xy coordinates
grid_shape : (M,N) tuple
the shape of the image grid, the output mesh indexes into
"""
import trimesh
import pylab as plt
import numpy as np
# either give a predefined image grid coordinates or grid_shape.
if grid is not None:
grid_shape = grid.shape[:2]
else:
grid = np.indices(grid_shape)
grid = np.dstack(grid) # m x n x 2
# grid_pts = grid.reshape(-1,grid.shape[-1]) # make flat.
v = rect_mesh.vertices.copy(); v = v[:,1:].copy() # take just the last two axes.
f = rect_mesh.faces.copy()
scale_v_0 = (grid.shape[0]-1.) / (v[:,0].max() - v[:,0].min())
scale_v_1 = (grid.shape[1]-1.) / (v[:,1].max() - v[:,1].min())
v[:,0] = v[:,0] * scale_v_0
v[:,1] = v[:,1] * scale_v_1
v = np.hstack([np.ones(len(v))[:,None], v])
mesh_ref = trimesh.Trimesh(v, f, validate=False, process=False)
return mesh_ref, grid_shape
def match_and_interpolate_img_surface_to_rect_mesh(rect_mesh, grid=None, grid_shape=None, rescale_mesh_pts=True, match_method='cross'):
r""" Match the grid of an image to the faces of a reference rectangular-like triangle mesh where the last 2 coordinate axes is the 2D xy coordinates to allow mapping of mesh measurements to an image
Parameters
----------
rect_mesh : trimesh.Trimesh
input 2D mesh where the first 2 coordinate axes is the 2D xy coordinates
grid : (M,N) or (M,N,d) single- or multi- channel image
input image to get the (M,N) shape
grid_shape : (M,N) tuple
the shape of the grid, only used if grid is not specified. Only one of grid or grid_shape needs to be passed
rescale_mesh_pts : bool
if True, the rect_mesh vertices are first rescaled in order to maximally cover the size of the intended image
match_method : str
one of 'cross' implementing https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf or 'cramer' implementing http://blackpawn.com/texts/pointinpoly for computing the barycentric coordinate after matching each image pixel to the rect_mesh
Returns
-------
tri_id : (MxN,)
1d array giving the face index each image pixel maps to in the rect_mesh
mesh_ref_closest_pt_barycentric : (MxN,3)
the barycentric weights giving the position inside the matched triangle face, each image pixel maps to
grid_shape : (M,N) tuple
the shape of the image grid
"""
import trimesh
# import pylab as plt
import numpy as np
# either give a predefined image grid coordinates or grid_shape.
if grid is not None:
grid_shape = grid.shape[:2]
else:
grid = np.indices(grid_shape)
grid = np.dstack(grid) # m x n x 2
# grid_pts = grid.reshape(-1,grid.shape[-1]) # make flat.
v = rect_mesh.vertices.copy(); v = v[:,1:].copy() # take just the last two axes.
f = rect_mesh.faces.copy()
# print(v.shape)
if rescale_mesh_pts:
scale_v_0 = (grid.shape[0]-1.) / (v[:,0].max() - v[:,0].min())
scale_v_1 = (grid.shape[1]-1.) / (v[:,1].max() - v[:,1].min())
v[:,0] = v[:,0] * scale_v_0
v[:,1] = v[:,1] * scale_v_1
# fig, ax = plt.subplots()
# ax.triplot(v[:,1], v[:,0], f, lw=.1)
# ax.set_aspect(1)
# plt.show()
# we have to force this to make it 3D to leverage the functions.
v = np.hstack([np.ones(len(v))[:,None], v])
mesh_ref = trimesh.Trimesh(v, f, validate=False, process=False)
# create nearest lookup object
prox_mesh_ref = trimesh.proximity.ProximityQuery(mesh_ref) # this is the lookup object.
# get the closest point on the mesh to the unwrap_params surface
grid_query = grid.reshape(-1,grid.shape[-1])
grid_query = np.hstack([np.ones(len(grid_query))[:,None], grid_query])
closest_pt, dist_pt, tri_id = prox_mesh_ref.on_surface(grid_query)
"""
get the barycentric for interpolation.
"""
# given then triangle id, we can retrieve the corresponding vertex point and the corresponding vertex values to interpolate.
# fetch the barycentric.
mesh_ref_tri_id_vertices = mesh_ref.vertices[mesh_ref.faces[tri_id]] # get the vertex points (N,3)
# convert to barycentric for each triangle which gives the interpolating weights.
mesh_ref_closest_pt_barycentric = trimesh.triangles.points_to_barycentric(mesh_ref_tri_id_vertices,
closest_pt,
method=match_method)
return tri_id, mesh_ref_closest_pt_barycentric, grid_shape
def match_and_interpolate_uv_surface_to_mesh(unwrap_params, mesh_ref, match_method='cross'):
r""" Match the grid of an image given by the shape of the uv unwrapped surface to a reference 3D triangle mesh based on nearest distance for reinterpolation of mesh measurements to unwrapped surface
Parameters
----------
unwrap_params : (UxVx3) array
the input 2D image specifying the uv unwrapped (x,y,z) surface
mesh_ref : trimesh.Trimesh
input 3D mesh we wish to match the coordinates of unwrap_params to, to allow barycentric interpolation
match_method : str
one of 'cross' implementing https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf or 'cramer' implementing http://blackpawn.com/texts/pointinpoly for computing the barycentric coordinate after matching each image pixel to the rect_mesh
Returns
-------
tri_id : (UxV,)
1d array giving the face index each (u,v) image pixel maps to in ``mesh_ref``
mesh_ref_closest_pt_barycentric : (UxV,3)
the barycentric weights giving the position inside the matched triangle face, each (u,v) image pixel maps to
"""
"""
we use the mesh as a reference
"""
import trimesh
# create nearest lookup object
prox_mesh_ref = trimesh.proximity.ProximityQuery(mesh_ref) # this is the lookup object.
# get the closest point on the mesh to the unwrap_params surface
closest_pt, dist_pt, tri_id = prox_mesh_ref.on_surface(unwrap_params.reshape(-1,unwrap_params.shape[-1]))
# given then triangle id, we can retrieve the corresponding vertex point and the corresponding vertex values to interpolate.
# fetch the barycentric.
mesh_ref_tri_id_vertices = mesh_ref.vertices[mesh_ref.faces[tri_id]] # get the vertex points (N,3)
# convert to barycentric for each triangle which gives the interpolating weights.
mesh_ref_closest_pt_barycentric = trimesh.triangles.points_to_barycentric(mesh_ref_tri_id_vertices,
closest_pt,
method=match_method)
return tri_id, mesh_ref_closest_pt_barycentric
def mesh_vertex_interpolate_scalar(mesh_ref, mesh_tri_id, mesh_tri_barycentric, scalar_vals):
r""" Interpolate vertex associated values associated with the vertices of a reference mesh onto a different geometry specified implicitly by the face id and barycentric coordinates the new geometry maps to in the reference mesh
Parameters
----------
mesh_ref : trimesh.Trimesh
input 3D mesh we wish to match the coordinates of unwrap_params to, to allow barycentric interpolation
mesh_tri_id : (N,)
1d array of the triangle face index in ``mesh_ref`` we want to interpolate ``scalar_vals`` on
mesh_tri_barycentric : (N,3)
the barycentric weights specifying the linear weighting of the vertex scalar_vals associated with the vertices of ``mesh_ref`` to compute the new scalar values
scalar_vals : (n_vertices,d)
the vertex associated measurements on the mesh_ref which is used to compute the new scalar values at the coordinate locations on the mesh specified by ``mesh_tri_id`` and ``mesh_tri_barycentric``
Returns
-------
scalar_vals_interp : (N,d)
the reinterpolated ``scalar_vals`` at the coordinate locations on the mesh specified by ``mesh_tri_id`` and ``mesh_tri_barycentric``
"""
import numpy as np
scalar_vals_tri = scalar_vals[mesh_ref.faces[mesh_tri_id]].copy() # N_faces x 3 x d
# print(scalar_vals_tri.shape)
scalar_vals_interp = np.sum(np.array([mesh_tri_barycentric[:,ch][:,None]*scalar_vals_tri[:,ch] for ch in np.arange(mesh_ref.vertices.shape[-1])]), axis=0)
return scalar_vals_interp
def uv_surface_pulldown_mesh_surface_coords( unwrap_params, mesh_ref, Varray, match_method='cross', return_interp=False):
r""" Main function to unwrap a list of 3D triangle meshes given by their vertices onto a 2D image grid based on matching the uv-unwrap of a joint 3D triangle mesh typically this is the uv-rectangle and the unit sphere.
Parameters
----------
unwrap_params : (M,N,3)
(u,v) parameterization of the 3D triangle mesh given by `mesh_ref`
mesh_ref : trimesh.Trimesh
the 3D triangle mesh equivalent of the geometry specified ``unwrap_params`` e.g. the unit sphere when ``unwrap_params`` is the UV-map
Varray : list of (n_vertices,3)
a list of 3D meshes given only by their vertices whom are bijective to ``mesh_ref`` such that they share the same number of vertices and the same face connectivity
match_method : str
one of 'cross' implementing https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf or 'cramer' implementing http://blackpawn.com/texts/pointinpoly for computing the barycentric coordinate after matching each image pixel to the rect_mesh
return_interp : bool
if True, also return the matching parameters between ``unwrap_params`` and ``mesh_ref`` for reuse
Returns
-------
pulldown_Varray_coords : (len(Varray),M,N,3) array
The UV-unwrapping of all 3D surface meshes bijective to ``mesh_ref``
(mesh_tri_id, mesh_ref_closest_pt_barycentric) : ( (M*N,), (M*N,3) ) tuple of arrays
These are the matching parameters that establish correspondence between ``unwrap_params`` and ``mesh_ref`` in order to map all other 3D meshes given by ``Varray`` bijective to ``mesh_ref`` into the 2D grid specified by ``unwrap_params``
"""
import numpy as np
unwrap_params_shape = unwrap_params.shape
F = mesh_ref.faces.copy()
mesh_tri_id, mesh_ref_closest_pt_barycentric = match_and_interpolate_uv_surface_to_mesh(unwrap_params, mesh_ref, match_method=match_method)
# interpolate ...
pulldown_Varray_coords = []
for iii in np.arange(len(Varray)):
Varray_tri_id_vertices_iii = Varray[iii][F[mesh_tri_id]].copy()
# interpolate using the barycentric coordinates. to build the depth lookup array.
# Varray_interp_coords = closest_pt_barycentric[:,0][:,None] * tri_id_vertices_orig[:,0] + closest_pt_barycentric[:,1][:,None] * tri_id_vertices_orig[:,1] + closest_pt_barycentric[:,2][:,None] * tri_id_vertices_orig[:,2]
Varray_interp_coords = np.sum(np.array([mesh_ref_closest_pt_barycentric[:,ch][:,None]*Varray_tri_id_vertices_iii[:,ch] for ch in np.arange(unwrap_params.shape[-1])]), axis=0)
Varray_interp_coords = Varray_interp_coords.reshape(unwrap_params_shape)
pulldown_Varray_coords.append(Varray_interp_coords)
pulldown_Varray_coords = np.array(pulldown_Varray_coords)
if return_interp:
return pulldown_Varray_coords, (mesh_tri_id, mesh_ref_closest_pt_barycentric)
else:
return pulldown_Varray_coords
def xyz_surface_pulldown_mesh_surface_coords( unwrap_params, mesh_ref, Varray, mesh_tri_id=None, mesh_ref_closest_pt_barycentric=None, match_method='cross', return_interp=False):
r""" Main function to unwrap a list of 3D triangle meshes given by their vertices bijective to a common 3D mesh onto another 3D surface through proximity-based matching
Parameters
----------
unwrap_params : (N,3)
3D triangle mesh to transfer coordinates to
mesh_ref : trimesh.Trimesh
the 3D triangle mesh equivalent or similar to the geometry of ``unwrap_params`` bijective to geometrices given by `Varray`
Varray : list of (n_vertices,3)
a list of 3D meshes given only by their vertices whom are bijective to ``mesh_ref`` such that they share the same number of vertices and the same face connectivity
match_method : str
one of 'cross' implementing https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf or 'cramer' implementing http://blackpawn.com/texts/pointinpoly for computing the barycentric coordinate after matching each image pixel to the rect_mesh
return_interp : bool
if True, also return the matching parameters between ``unwrap_params`` and ``mesh_ref`` for reuse
Returns
-------
pulldown_Varray_coords : (len(Varray),N,3) array
The remapped coordinates of 3D surface meshes bijective to ``mesh_ref`` as vertex measurements on ``unwrap_params``
(mesh_tri_id, mesh_ref_closest_pt_barycentric) : ( (M*N,), (M*N,3) ) tuple of arrays
Returned if return_interp=True. These are the matching parameters that establish correspondence between ``unwrap_params`` and ``mesh_ref`` in order to map all other 3D meshes given by ``Varray`` bijective to ``mesh_ref`` into the 2D grid specified by ``unwrap_params``
"""
import numpy as np
# unwrap_params_shape = unwrap_params.shape
F = mesh_ref.faces.copy()
if mesh_tri_id is None or mesh_ref_closest_pt_barycentric is None:
mesh_tri_id, mesh_ref_closest_pt_barycentric = match_and_interpolate_uv_surface_to_mesh(unwrap_params, mesh_ref, match_method=match_method)
# interpolate ...
pulldown_Varray_coords = []
for iii in np.arange(len(Varray)):
Varray_tri_id_vertices_iii = Varray[iii][F[mesh_tri_id]].copy()
# interpolate using the barycentric coordinates. to build the depth lookup array.
# Varray_interp_coords = closest_pt_barycentric[:,0][:,None] * tri_id_vertices_orig[:,0] + closest_pt_barycentric[:,1][:,None] * tri_id_vertices_orig[:,1] + closest_pt_barycentric[:,2][:,None] * tri_id_vertices_orig[:,2]
Varray_interp_coords = np.sum(np.array([mesh_ref_closest_pt_barycentric[:,ch][:,None]*Varray_tri_id_vertices_iii[:,ch] for ch in np.arange(unwrap_params.shape[-1])]), axis=0)
# Varray_interp_coords = Varray_interp_coords.reshape(unwrap_params_shape)
pulldown_Varray_coords.append(Varray_interp_coords)
pulldown_Varray_coords = np.array(pulldown_Varray_coords)
if return_interp:
return pulldown_Varray_coords, (mesh_tri_id, mesh_ref_closest_pt_barycentric)
else:
return pulldown_Varray_coords
def grid2D_surface_pulldown_mesh_surface_coords( rect_mesh, Varray, grid=None, grid_shape=None, rescale_mesh_pts=True, match_method='cross', return_interp=False, interp_method='linear'):
r""" Main function to map a 2D rectangular mesh and list of 3D triangle meshes given by their vertices bijective to the 3D surface it describes to an image of a given grid_shape through proximity-based matching
Parameters
----------
rect_mesh : trimesh.Trimesh
A 2D triangle mesh specified as a 3D triangle mesh where the last 2 coordinate axes are taken to be the x-,y- coordinates of the output image.
Varray : list of (n_vertices,3)
a list of 3D meshes given only by their vertices whom are bijective to ``rect_mesh`` such that they share the same number of vertices and the same face connectivity. We assume the order of the vertices in ``rect_mesh`` and the meshes in ``Varray`` are aligned.
grid : (M,N) or (M,N,d) single- or multi- channel image
input image to get the (M,N) shape
grid_shape : (M,N) tuple
the shape of the grid, only used if grid is not specified. Only one of grid or grid_shape needs to be passed
rescale_mesh_pts : bool
if True, the rect_mesh vertices are first rescaled in order to maximally cover the size of the intended image
match_method : str
one of 'cross' implementing https://www.cs.ubc.ca/~heidrich/Papers/JGT.05.pdf or 'cramer' implementing http://blackpawn.com/texts/pointinpoly for computing the barycentric coordinate after matching each image pixel to the rect_mesh
return_interp : bool
if True, also return the matching parameters between the final image coordinates and ``rect_mesh`` for reuse
interp_method : str
One of 'linear' for ``matplotlib.tri.LinearTriInterpolator`` interpolation,
'cubic_geom' for ``matplotlib.tri.CubicTriInterpolator`` with kind='geom' and 'cubic_min_E' for mtri.CubicTriInterpolator with kind='min_E'
Returns
-------
pulldown_Varray_coords : (len(Varray),N,3) array
The remapped coordinates of 3D surface meshes bijective to ``mesh_ref`` as vertex measurements on ``unwrap_params``
triang : matplotlib.tri.Triangulation instance
Optional return if ``return_interp=True``. The Matlplotlib triangulation of the rescaled ``rect_mesh`` used for interpolation with ``matplotlib.tri.LinearTriInterpolator`` internally
"""
# since 2D we can directly exploit matplotlib.
import numpy as np
import matplotlib.tri as mtri
if rescale_mesh_pts:
rect_mesh_rescale, grid_shape = rescale_mesh_points_to_grid_size(rect_mesh, grid=grid, grid_shape=grid_shape)
else:
rect_mesh_rescale = rect_mesh.copy()
if grid_shape is None:
grid_shape = grid.shape[:2]
# print(rect_mesh_rescale.shape)
triang = mtri.Triangulation(rect_mesh_rescale.vertices[:,1],
rect_mesh_rescale.vertices[:,2],
triangles=rect_mesh.faces)
# specify the grid points
xi, yi = np.indices(grid_shape)
# interpolate ...
pulldown_Varray_coords = []
for iii in np.arange(len(Varray)):
Varray_iii = Varray[iii].copy()
if interp_method == 'linear':
# define the interpolation object for the Varray.
interp_objs = [mtri.LinearTriInterpolator(triang, Varray_iii[:,ch]) for ch in np.arange(Varray_iii.shape[-1])]
if interp_method == 'cubic_geom':
interp_objs = [mtri.CubicTriInterpolator(triang, Varray_iii[:,ch], kind='geom') for ch in np.arange(Varray_iii.shape[-1])]
if interp_method == 'cubic_min_E':
interp_objs = [mtri.CubicTriInterpolator(triang, Varray_iii[:,ch], kind='min_E') for ch in np.arange(Varray_iii.shape[-1])]
interp_objs_scalars = np.dstack([interp_objs[ch](xi,yi) for ch in np.arange(Varray_iii.shape[-1])])
pulldown_Varray_coords.append(interp_objs_scalars)
pulldown_Varray_coords = np.array(pulldown_Varray_coords)
if return_interp:
return pulldown_Varray_coords, triang
else:
return pulldown_Varray_coords
# """
# include rectangular conformal map functions
# """
def angle_distortion(v,f, param):
r""" Calculate the angle difference of triangles between two meshes of the same face connectivity
Parameters
----------
v : (n_vertices, 3) array
vertex coordinates of triangle mesh 1
f : (n_faces, 3) array
triangulations of both meshes given in terms of the vertex indices
param : (n_vertices, 3) array
vertex coordinates of triangle mesh 2
Returns
-------
distortion : (n_faces, 3) array
array of angle differences in degrees at each triangle face
"""
import numpy as np
nv = len(v)
nv2 = len(param)
if nv!=nv2:
print('Error: The two meshes are of different size.')
return []
else:
# if input is not 3d coords... then make it 3D.
if v.shape[-1] == 1:
# if 1d not 3d.
v = np.vstack([np.real(v), np.imag(v), np.zeros(len(v))]).T;
if v.shape[-1] == 2:
v = np.hstack([v, np.zeros((len(v),1))]);
if param.shape[-1] == 1:
param = np.vstack([np.real(param), np.imag(param), np.zeros(len(param))]).T;
if param.shape[-1] == 2:
param = np.hstack([param, np.zeros((len(param), 1))])
f1 = f[:,0].copy(); f2 = f[:,1].copy(); f3 = f[:,2].copy();
# % calculate angles on v
a3 = np.vstack([v[f1,0]-v[f3,0], v[f1,1]-v[f3,1], v[f1,2]-v[f3,2]]).T
b3 = np.vstack([v[f2,0]-v[f3,0], v[f2,1]-v[f3,1], v[f2,2]-v[f3,2]]).T
a1 = np.vstack([v[f2,0]-v[f1,0], v[f2,1]-v[f1,1], v[f2,2]-v[f1,2]]).T
b1 = np.vstack([v[f3,0]-v[f1,0], v[f3,1]-v[f1,1], v[f3,2]-v[f1,2]]).T
a2 = np.vstack([v[f3,0]-v[f2,0], v[f3,1]-v[f2,1], v[f3,2]-v[f2,2]]).T
b2 = np.vstack([v[f1,0]-v[f2,0], v[f1,1]-v[f2,1], v[f1,2]-v[f2,2]]).T
vcos1 = (a1[:,0]*b1[:,0] + a1[:,1]*b1[:,1] + a1[:,2]*b1[:,2]) / (np.sqrt(a1[:,0]**2+a1[:,1]**2+a1[:,2]**2) * np.sqrt(b1[:,0]**2+b1[:,1]**2+b1[:,2]**2))
vcos2 = (a2[:,0]*b2[:,0] + a2[:,1]*b2[:,1] + a2[:,2]*b2[:,2]) / (np.sqrt(a2[:,0]**2+a2[:,1]**2+a2[:,2]**2) * np.sqrt(b2[:,0]**2+b2[:,1]**2+b2[:,2]**2))
vcos3 = (a3[:,0]*b3[:,0] + a3[:,1]*b3[:,1] + a3[:,2]*b3[:,2]) / (np.sqrt(a3[:,0]**2+a3[:,1]**2+a3[:,2]**2) * np.sqrt(b3[:,0]**2+b3[:,1]**2+b3[:,2]**2))
# % calculate angles on param
c3 = np.vstack([param[f1,0]-param[f3,0], param[f1,1]-param[f3,1], param[f1,2]-param[f3,2]]).T
d3 = np.vstack([param[f2,0]-param[f3,0], param[f2,1]-param[f3,1], param[f2,2]-param[f3,2]]).T
c1 = np.vstack([param[f2,0]-param[f1,0], param[f2,1]-param[f1,1], param[f2,2]-param[f1,2]]).T
d1 = np.vstack([param[f3,0]-param[f1,0], param[f3,1]-param[f1,1], param[f3,2]-param[f1,2]]).T
c2 = np.vstack([param[f3,0]-param[f2,0], param[f3,1]-param[f2,1], param[f3,2]-param[f2,2]]).T
d2 = np.vstack([param[f1,0]-param[f2,0], param[f1,1]-param[f2,1], param[f1,2]-param[f2,2]]).T
paramcos1 = (c1[:,0]*d1[:,0] + c1[:,1]*d1[:,1] + c1[:,2]*d1[:,2]) / (np.sqrt(c1[:,0]**2+c1[:,1]**2+c1[:,2]**2) * np.sqrt(d1[:,0]**2+d1[:,1]**2+d1[:,2]**2))
paramcos2 = (c2[:,0]*d2[:,0] + c2[:,1]*d2[:,1] + c2[:,2]*d2[:,2]) / (np.sqrt(c2[:,0]**2+c2[:,1]**2+c2[:,2]**2) * np.sqrt(d2[:,0]**2+d2[:,1]**2+d2[:,2]**2))
paramcos3 = (c3[:,0]*d3[:,0] + c3[:,1]*d3[:,1] + c3[:,2]*d3[:,2]) / (np.sqrt(c3[:,0]**2+c3[:,1]**2+c3[:,2]**2) * np.sqrt(d3[:,0]**2+d3[:,1]**2+d3[:,2]**2))
# % calculate the angle difference
# distortion = (np.arccos(np.hstack([paramcos1, paramcos2, paramcos3])) - np.arccos(np.hstack([vcos1,vcos2,vcos3])))*180/np.pi;
distortion = (np.arccos(np.vstack([paramcos1, paramcos2, paramcos3])) - np.arccos(np.vstack([vcos1,vcos2,vcos3])))*180/np.pi;
distortion = distortion.T
return distortion # in terms of angles. ( the angles is the same number as triangles. )
# % histogram
# figure;
# hist(distortion,-180:1:180);
# xlim([-180 180])
# title('Angle Distortion');
# xlabel('Angle difference (degree)')
# ylabel('Number of angles')
# set(gca,'FontSize',12);
def _cotangent_laplacian(v,f):
# % Compute the cotagent Laplacian of a mesh used in the rectangular conformal unwrapping
#
# See:
# % [1] T. W. Meng, G. P.-T. Choi and L. M. Lui,
# % "TEMPO: Feature-Endowed Teichmüller Extremal Mappings of Point Clouds."
# % SIAM Journal on Imaging Sciences, 9(4), pp. 1922-1962, 2016.
import numpy as np
import scipy.sparse as sparse
nv = len(v);
f1 = f[:,0];
f2 = f[:,1];
f3 = f[:,2];
l1 = np.sqrt(np.sum((v[f2] - v[f3])**2,1));
l2 = np.sqrt(np.sum((v[f3] - v[f1])**2,1));
l3 = np.sqrt(np.sum((v[f1] - v[f2])**2,1));
s = (l1 + l2 + l3)*0.5;
area = np.sqrt( s*(s-l1)*(s-l2)*(s-l3));
cot12 = (l1**2 + l2**2 - l3**2)/(area)/2.;
cot23 = (l2**2 + l3**2 - l1**2)/(area)/2.;
cot31 = (l1**2 + l3**2 - l2**2)/(area)/2.;
diag1 = -cot12-cot31;
diag2 = -cot12-cot23;
diag3 = -cot31-cot23;
# II = [f1; f2; f2; f3; f3; f1; f1; f2; f3];
# JJ = [f2; f1; f3; f2; f1; f3; f1; f2; f3];
# V = [cot12; cot12; cot23; cot23; cot31; cot31; diag1; diag2; diag3];
II = np.hstack([f1,f2,f2,f3,f3,f1,f1,f2,f3])
JJ = np.hstack([f2,f1,f3,f2,f1,f3,f1,f2,f3])
V = np.hstack([cot12, cot12, cot23, cot23, cot31, cot31, diag1, diag2, diag3])
L = sparse.csc_matrix((V, (II,JJ)), shape=(nv,nv));
return L
def beltrami_coefficient(v, f, map_):
r""" Compute the Beltrami coefficient of a mapping between two triangle meshes. The lower the Beltrami coefficient the lower the metric distortion between the meshes
Parameters
----------
v : (n_vertices, 3) array
vertex coordinates of triangle mesh 1
f : (n_faces, 3) array
triangulations of both meshes given in terms of the vertex indices
map_ : (n_vertices, 3) array
vertex coordinates of triangle mesh 2
Returns
-------
mu : (n_faces, ) complex array
array of the beltrami coefficient for each triangle face
References
----------
.. [1] T. W. Meng, G. P.-T. Choi and L. M. Lui, "TEMPO: Feature-Endowed Teichmüller Extremal Mappings of Point Clouds." SIAM Journal on Imaging Sciences, 9(4), pp. 1922-1962, 2016.
"""
import numpy as np
import scipy.sparse as sparse
nf = len(f);
Mi = np.reshape(np.vstack([np.arange(nf),
np.arange(nf),
np.arange(nf)]), ((1,3*nf)), order='F').copy();
Mj = np.reshape(f.T, ((1,3*nf)), order='F').copy();
e1 = v[f[:,2],:2] - v[f[:,1],:2];
e2 = v[f[:,0],:2] - v[f[:,2],:2];
e3 = v[f[:,1],:2] - v[f[:,0],:2];
area = (-e2[:,0]*e1[:,1] + e1[:,0]*e2[:,1])/2.;
area = np.vstack([area,area,area])
# should this be F or C?
# Mx = np.reshape(np.vstack([e1[:,1],e2[:,1],e3[:,1]])/area /2. , ((1, 3*nf)), order='C');
# My = -np.reshape(np.vstack([e1[:,0],e2[:,0],e3[:,0]])/area /2. , ((1, 3*nf)), order='C');
Mx = np.reshape(np.vstack([e1[:,1],e2[:,1],e3[:,1]])/area /2. , ((1, 3*nf)), order='F');
My = -np.reshape(np.vstack([e1[:,0],e2[:,0],e3[:,0]])/area /2. , ((1, 3*nf)), order='F');
Mi = Mi.ravel()
Mj = Mj.ravel()
Mx = Mx.ravel()
My = My.ravel()
# Dx = sparse(Mi,Mj,Mx);
# Dy = sparse(Mi,Mj,My);
# S = sparse(i,j,s) where m = max(i) and n = max(j).
Dx = sparse.csr_matrix((Mx, (Mi,Mj)), shape=((np.max(Mi)+1, np.max(Mj)+1)))
Dy = sparse.csr_matrix((My, (Mi,Mj)), shape=((np.max(Mi)+1, np.max(Mj)+1)))
dXdu = Dx*map_[:,0];
dXdv = Dy*map_[:,0];
dYdu = Dx*map_[:,1];
dYdv = Dy*map_[:,1];
dZdu = Dx*map_[:,2];
dZdv = Dy*map_[:,2];
E = dXdu**2 + dYdu**2 + dZdu**2;
G = dXdv**2 + dYdv**2 + dZdv**2;
F = dXdu*dXdv + dYdu*dYdv + dZdu*dZdv;
# this line?
mu = (E - G + 2 * 1j * F) / ((E + G + 2.*np.sqrt(E*G - F**2))+1e-12);
return mu
def linear_beltrami_solver(v,f,mu,landmark,target):
r""" Linear Beltrami solver to find the minimal quasiconformal distortion mapping for unwrapping an open 3D mesh to a 2D rectangular map
Parameters
----------
v : (n_vertices, 3) array
vertex coordinates of triangle mesh 1
f : (n_faces, 3) array
triangulations of both meshes given in terms of the vertex indices
mu : (n_faces,) complex array
the beltrami coefficient at each triangular face
landmark : (n,) array
the vertex indices in the triangle mesh to enforce mapping to ``target``
target : (n,) complex array
the coordinates of ``landmark`` vertices in the 2D unwrapping
Returns
-------
param : (n_vertices, 2) array
the 2D coordinates of the now 2D parametrized vertex coordinates of the input mesh
References
----------
.. [1] P. T. Choi, K. C. Lam, and L. M. Lui, "FLASH: Fast Landmark Aligned Spherical Harmonic Parameterization for Genus-0 Closed Brain Surfaces." SIAM Journal on Imaging Sciences, vol. 8, no. 1, pp. 67-94, 2015.
"""
import numpy as np
import scipy.sparse as spsparse
af = (1-2.*np.real(mu)+np.abs(mu)**2)/(1.0-np.abs(mu)**2);
bf = -2*np.imag(mu)/(1.0-np.abs(mu)**2);
gf = (1+2*np.real(mu)+np.abs(mu)**2)/(1.0-np.abs(mu)**2);
f0 = f[:,0].copy(); f1 = f[:,1].copy(); f2 = f[:,2].copy();
uxv0 = v[f1,1] - v[f2,1];
uyv0 = v[f2,0] - v[f1,0];
uxv1 = v[f2,1] - v[f0,1];
uyv1 = v[f0,0] - v[f2,0];
uxv2 = v[f0,1] - v[f1,1];
uyv2 = v[f1,0] - v[f0,0];
l = np.vstack([np.sqrt(uxv0**2 + uyv0**2), np.sqrt(uxv1**2 + uyv1**2), np.sqrt(uxv2**2 + uyv2**2)]).T;
# l = np.vstack([np.sqrt(np.sum(uxv0**2 + uyv0**2, axis=-1)), np.sqrt(np.sum(uxv1**2 + uyv1**2,axis=-1)), np.sqrt(np.sum(uxv2**2 + uyv2**2,axis=-1))]).T; # this is just the lengths.
s = np.sum(l,axis=-1)*0.5;
area = np.sqrt(s*(s-l[:,0])*(s-l[:,1])*(s-l[:,2])) + 1e-12; # heron's formula.
v00 = (af*uxv0*uxv0 + 2*bf*uxv0*uyv0 + gf*uyv0*uyv0)/area;
v11 = (af*uxv1*uxv1 + 2*bf*uxv1*uyv1 + gf*uyv1*uyv1)/area;
v22 = (af*uxv2*uxv2 + 2*bf*uxv2*uyv2 + gf*uyv2*uyv2)/area;
v01 = (af*uxv1*uxv0 + bf*uxv1*uyv0 + bf*uxv0*uyv1 + gf*uyv1*uyv0)/area;
v12 = (af*uxv2*uxv1 + bf*uxv2*uyv1 + bf*uxv1*uyv2 + gf*uyv2*uyv1)/area;
v20 = (af*uxv0*uxv2 + bf*uxv0*uyv2 + bf*uxv2*uyv0 + gf*uyv0*uyv2)/area;
I = np.hstack([f0,f1,f2,f0,f1,f1,f2,f2,f0]);
J = np.hstack([f0,f1,f2,f1,f0,f2,f1,f0,f2]);
V = np.hstack([v00,v11,v22,v01,v01,v12,v12,v20,v20])/2.;
# # A = sparse(I,J,-V);
A = spsparse.csr_matrix((-V, (I,J)), (len(v),len(v)), dtype=np.cfloat); A = spsparse.lil_matrix(A, dtype=np.cfloat)
targetc = target[:,0] + 1j*target[:,1];
b = -A[:,landmark].dot(targetc);
b[landmark] = targetc;
A[landmark,:] = 0; A[:,landmark] = 0;
A = A + spsparse.csr_matrix((np.ones(len(landmark)), (landmark,landmark)), (A.shape[0], A.shape[1])); # size(A,1), size(A,2));
param = spsparse.linalg.spsolve(A,b)
param = np.vstack([np.real(param), np.imag(param)]).T
# map = A\b;
# map = [real(map),imag(map)];
return param
def direct_spherical_conformal_map(v,f):
r""" A linear method for computing spherical conformal map of a genus-0 closed surface using quasiconformal mapping
Parameters
----------
v : (n_vertices, 3) array
vertex coordinates of a genus-0 triangle mesh
f : (n_faces, 3) array
triangulations of a genus-0 triangle mesh
Returns
-------
param : (n_vertices, 3) array
vertex coordinates of the spherical conformal parameterization which maps the input mesh to the unit sphere.
References
----------
.. [1] P. T. Choi, K. C. Lam, and L. M. Lui, "FLASH: Fast Landmark Aligned Spherical Harmonic Parameterization for Genus-0 Closed Brain Surfaces." SIAM Journal on Imaging Sciences, vol. 8, no. 1, pp. 67-94, 2015.
"""
import numpy as np
import scipy.sparse as spsparse
import scipy.sparse.linalg as spalg
# # # %% Check whether the input mesh is genus-0
# # if len(v)-3*len(f)/2+len(f) != 2:
# # print('The mesh is not a genus-0 closed surface.\n');
# # return []
# # else:
# print('spherical param')
# %% Find the most regular triangle as the "big triangle"
temp = v[f.ravel()].copy()
e1 = np.sqrt(np.sum((temp[1::3] - temp[2::3])**2, axis=-1))
e2 = np.sqrt(np.sum((temp[0::3] - temp[2::3])**2, axis=-1))
e3 = np.sqrt(np.sum((temp[0::3] - temp[1::3])**2, axis=-1))
regularity = np.abs(e1/(e1+e2+e3)-1./3) + np.abs(e2/(e1+e2+e3)-1./3) + np.abs(e3/(e1+e2+e3)-1./3) # this being the most equilateral.
bigtri = np.argmin(regularity)
# % In case the spherical parameterization result is not evenly distributed,
# % try to change bigtri to the id of some other triangles with good quality
# %% North pole step: Compute spherical map by solving laplace equation on a big triangle
nv = len(v);
M = _cotangent_laplacian(v,f);
# this becomes the fixed triangle.
p1 = f[bigtri,0]#.copy();
p2 = f[bigtri,1]#.copy();
p3 = f[bigtri,2]#.copy();
fixed = np.hstack([p1,p2,p3]);
# [mrow,mcol,mval] = find(M(fixed,:));
(mrow, mcol, mval) = spsparse.find(M[fixed])
# print(mrow,mcol,mval)
M = M - spsparse.csr_matrix((mval, (fixed[mrow],mcol)),(nv,nv)) + spsparse.csr_matrix((np.ones(3), (fixed,fixed)),(nv,nv));
# % set the boundary condition for big triangle
x1 = 0; y1 = 0; x2 = 1; y2 = 0; #% arbitrarily set the two points
a = v[p2] - v[p1];
b = v[p3] - v[p1];
sin1 = (np.linalg.norm(np.cross(a,b), ord=2))/(np.linalg.norm(a,ord=2)*np.linalg.norm(b,ord=2));
ori_h = np.linalg.norm(b,ord=2)*sin1;
ratio = np.linalg.norm([x1-x2,y1-y2],ord=2)/np.linalg.norm(a,ord=2);
y3 = ori_h*ratio; #% compute the coordinates of the third vertex
x3 = np.sqrt(np.linalg.norm(b,ord=2)**2*ratio**2-y3**2);
# print(x3,y3)
# % Solve the Laplace equation to obtain a harmonic map
c = np.zeros(nv); c[p1] = x1; c[p2] = x2; c[p3] = x3;
d = np.zeros(nv); d[p1] = y1; d[p2] = y2; d[p3] = y3;
z = spalg.spsolve(M , c+1j*d);
z = z-np.mean(z); # o this.
# print(np.mean(z))
# print('z', z.shape)
# % inverse stereographic projection
S = np.vstack([2.*np.real(z)/(1+np.abs(z)**2), 2*np.imag(z)/(1.+np.abs(z)**2), (-1+np.abs(z)**2)/(1+np.abs(z)**2)]).T
# %% Find optimal big triangle size
w = S[:,0]/(1.+S[:,2]) + 1j*S[:,1]/(1.+S[:,2])
# % find the index of the southernmost triangle
index = np.argsort(np.abs(z[f[:,0]]) + np.abs(z[f[:,1]]) + np.abs(z[f[:,2]]), kind='stable') # this is absolutely KEY!
inner = index[0];
if inner == bigtri:
inner = index[1]; # select the next one. # this is meant to be the northernmost....
# print('bigtri', bigtri)
# print('inner', index[:20])
# % Compute the size of the northern most and the southern most triangles
NorthTriSide = (np.abs(z[f[bigtri,0]]-z[f[bigtri,1]]) + np.abs(z[f[bigtri,1]]-z[f[bigtri,2]]) + np.abs(z[f[bigtri,2]]-z[f[bigtri,0]]))/3.; # this is a number.
SouthTriSide = (np.abs(w[f[inner,0]]-w[f[inner,1]]) + np.abs(w[f[inner,1]]-w[f[inner,2]]) + np.abs(w[f[inner,2]]-w[f[inner,0]]))/3.;
# % rescale to get the best distribution
z = z*(np.sqrt(NorthTriSide*SouthTriSide))/(NorthTriSide);
# % inverse stereographic projection
S = np.vstack([2.*np.real(z)/(1+np.abs(z)**2), 2*np.imag(z)/(1.+np.abs(z)**2), (-1+np.abs(z)**2)/(1+np.abs(z)**2)]).T
if np.sum(np.isnan(S)) > 0:
# if harmonic map fails due to very bad triangulations, use tutte map
print('implement tutte map')
return []
# %% South pole step
I = np.argsort(S[:,2], kind='stable')
# % number of points near the south pole to be fixed
# % simply set it to be 1/10 of the total number of vertices (can be changed)
# % In case the spherical parameterization is not good, change 10 to
# % something smaller (e.g. 2)
fixnum = np.maximum(int(np.round(len(v)/10)), 3)
fixed = I[:np.minimum(len(v), fixnum)]
# % south pole stereographic projection
P = np.vstack([S[:,0]/(1.+S[:,2]), S[:,1]/(1.+S[:,2])]).T
# % compute the Beltrami coefficient
mu = beltrami_coefficient(P, f, v);
# problem is here.
# % compose the map with another quasi-conformal map to cancel the distortion
param = linear_beltrami_solver(P,f,mu,fixed,P[fixed]); # fixed is index.
# print('num_nan: ', np.sum(np.isnan(param)))
if np.sum(np.isnan(param)) > 0: # this is failing at the moment
print('recomputing fixed elements')
# % if the result has NaN entries, then most probably the number of
# % boundary constraints is not large enough
# % increase the number of boundary constrains and run again
fixnum = fixnum*5; #% again, this number can be changed
fixed = I[:np.minimum(len(v),fixnum)];
param = linear_beltrami_solver(P,f,mu,fixed,P[fixed]);
if np.sum(np.isnan(param)) > 0:
param = P.copy(); #% use the old result
z = param[:,0] + 1j*param[:,1]
# z = complex(map(:,1),map(:,2));
# % inverse south pole stereographic projection
param = np.vstack([2*np.real(z)/(1.+np.abs(z)**2), 2*np.imag(z)/(1+np.abs(z)**2), -(np.abs(z)**2-1)/(1.+np.abs(z)**2)]).T
# map = [2*real(z)./(1+abs(z).^2), 2*imag(z)./(1+abs(z).^2), -(abs(z).^2-1)./(1+abs(z).^2)];
return param
# implementation of extension functions to improve conformal mapping.
def _face_area(v,f):
""" Compute the area of every face of a triangle mesh.
References
----------
[1] P. T. Choi, K. C. Lam, and L. M. Lui, "FLASH: Fast Landmark Aligned Spherical Harmonic Parameterization for Genus-0 Closed Brain Surfaces." SIAM Journal on Imaging Sciences, vol. 8, no. 1, pp. 67-94, 2015.
"""
# % Compute the area of every face of a triangle mesh.
# %
# % If you use this code in your own work, please cite the following paper:
# % [1] P. T. Choi, K. C. Lam, and L. M. Lui,
# % "FLASH: Fast Landmark Aligned Spherical Harmonic Parameterization for Genus-0 Closed Brain Surfaces."
# % SIAM Journal on Imaging Sciences, vol. 8, no. 1, pp. 67-94, 2015.
# %
# % Copyright (c) 2013-2018, Gary Pui-Tung Choi
# % https://scholar.harvard.edu/choi
import numpy as np
v12 = v[f[:,1]] - v[f[:,0]]
v23 = v[f[:,2]] - v[f[:,1]]
v31 = v[f[:,0]] - v[f[:,2]]
a = np.sqrt(np.nansum( v12 * v12, axis=-1))
b = np.sqrt(np.nansum( v23 * v23, axis=-1))
c = np.sqrt(np.nansum( v31 * v31, axis=-1))
s = (a+b+c)/2.;
fa = np.sqrt(s*(s-a)*(s-b)*(s-c)); # heron's formula
return fa
# def area_distortion(v,f,param):
# # % Calculate and visualize the area distortion log(area_map/area_v)
# # %
# # % Input:
# # % v: nv x 3 vertex coordinates of a genus-0 triangle mesh
# # % f: nf x 3 triangulations of a genus-0 triangle mesh
# # % param: nv x 2 or 3 vertex coordinates of the mapping result
# # %
# # % Output:
# # % distortion: 3*nf x 1 area differences
# # %
# # % If you use this code in your own work, please cite the following paper:
# # % [1] G. P. T. Choi, Y. Leung-Liu, X. Gu, and L. M. Lui,
# # % "Parallelizable global conformal parameterization of simply-connected surfaces via partial welding."
# # % SIAM Journal on Imaging Sciences, 2020.
# # %
# # % Copyright (c) 2018-2020, Gary Pui-Tung Choi
# # % https://scholar.harvard.edu/choi
# import numpy as np
# nv = len(v);
# nv2 = len(param);
# if nv != nv2:
# print('Error: The two meshes are of different size.');
# return []
# if v.shape[-1] == 1:
# v = np.vstack([np.real(v), np.imag(v), np.zeros(len(v))]).T
# if v.shape[-1] == 2:
# v = np.hstack([v, np.zeros((len(v),1))])
# if param.shape[-1] == 1:
# param = np.vstack([np.real(param), np.imag(param), np.zeros(len(param))]).T
# if param.shape[-1] == 2:
# param = np.hstack([np.real(param), np.zeros((len(param),1))])
# # % calculate area of v
# area_v = _face_area(v,f);
# # % calculate area of map
# area_map = _face_area(param,f);
# # % normalize the total area # have to normalize this....
# v = v*np.sqrt(np.nansum(area_map)/np.nansum(area_v));
# area_v = _face_area(v,f);
# # % calculate the area ratio
# # distortion = np.log(area_map/area_v);
# distortion = np.log(area_map) - np.log(area_v) # might be more stable.
# return distortion
# # % histogram
# # figure;
# # histogram(distortion,30);
# # xlim([-5 5])
# # title('Area Distortion');
# # xlabel('log(final area/initial area)')
# # ylabel('Number of faces')
# # set(gca,'FontSize',12);
def area_distortion_measure(v1,v2, f):
r""" Compute the normalised area scaling factor as measure of area distortion between two triangle meshes
.. math::
\lambda = \frac{A_1}{A_2}
where :math:`A_1, A_2` are the areas of the mesh after rescaling the meshes by the square root of the respective total surface areas, :math:`S_1,S_2` respectively.
Parameters
----------
v1 : (n_vertices, 3) array
vertex coordinates of a triangle mesh 1
v2 : (n_vertices, 3) array
vertex coordinates of a triangle mesh 2
f : (n_faces, 3) array
the triangulation of both the first and second mesh, given in terms of the vertex indices
Returns
-------
ratio : (n_faces, 3) array
the area distortion factor per face between meshes ``v1`` and ``v2``
"""
import numpy as np
import igl
v1_ = v1/np.sqrt(np.nansum(igl.doublearea(v1,f)/2.))
v2_ = v2/np.sqrt(np.nansum(igl.doublearea(v2,f)/2.))
ratio = igl.doublearea(v1_,f)/igl.doublearea(v2_,f)
return ratio
# # % calculate area of v
# area_v = face_area(v,f);
# # % calculate area of map
# area_map = face_area(param,f);
# # % normalize the total area # have to normalize this....
# v = v*np.sqrt(np.nansum(area_map)/np.nansum(area_v));
# area_v = face_area(v,f);
# # % calculate the area ratio
# # distortion = np.log(area_map/area_v);
# distortion = np.log(area_map) - np.log(area_v) # might be more stable.
# return distortion
def _finitemean(A):
""" for avoiding the Inf values caused by division by a very small area
"""
import numpy as np
# % for avoiding the Inf values caused by division by a very small area
m = np.mean(A[~np.isnan(A)], axis=0) # return mean of columns.
return m
def _stereographic(u):
# % STEREOGRAPHIC Stereographic projection.
# % v = STEREOGRAPHIC(u), for N-by-2 matrix, projects points in plane to sphere
# % ; for N-by-3 matrix, projects points on sphere to plane
import numpy as np
if u.shape[-1] == 1:
u = np.vstack([np.real(u), np.imag(u)])
x = u[:,0].copy()
y = u[:,1].copy()
if u.shape[-1] < 3:
z = 1 + x**2 + y**2;
v = np.vstack([2*x / z, 2*y / z, (-1 + x**2 + y**2) / z]).T;
else:
z = u[:,2].copy()
v = np.vstack([x/(1.-z), y/(1.-z)]).T
return v
def mobius_area_correction_spherical(v,f,param):
r""" Find an optimal Mobius transformation for reducing the area distortion of a spherical conformal parameterization using the method in [1]_.
Parameters
----------
v : (n_vertices,3) array
vertex coordinates of a genus-0 closed triangle mesh
f : (n_faces,3) array
triangulations of the genus-0 closed triangle mesh
param : (n_vertices,3) array
vertex coordinates of the spherical conformal parameterization of the mesh given by ``v`` and ``f``
Returns
-------
map_mobius : (n_vertices,3) array
vertex coordinates of the updated spherical conformal parameterization
References
----------
.. [1] G. P. T. Choi, Y. Leung-Liu, X. Gu, and L. M. Lui, "Parallelizable global conformal parameterization of simply-connected surfaces via partial welding." SIAM Journal on Imaging Sciences, 2020.
"""
# % Find an optimal Mobius transformation for reducing the area distortion of a spherical conformal parameterization using the method in [1].
# %
# % Input:
# % v: nv x 3 vertex coordinates of a genus-0 closed triangle mesh
# % f: nf x 3 triangulations of a genus-0 closed triangle mesh
# % map: nv x 3 vertex coordinates of the spherical conformal parameterization
# %
# % Output:
# % map_mobius: nv x 3 vertex coordinates of the updated spherical conformal parameterization
# % x: the optimal parameters for the Mobius transformation, where
# % f(z) = \frac{az+b}{cz+d}
# % = ((x(1)+x(2)*1i)*z+(x(3)+x(4)*1i))./((x(5)+x(6)*1i)*z+(x(7)+x(8)*1i))
# %
# % If you use this code in your own work, please cite the following paper:
# % [1] G. P. T. Choi, Y. Leung-Liu, X. Gu, and L. M. Lui,
# % "Parallelizable global conformal parameterization of simply-connected surfaces via partial welding."
# % SIAM Journal on Imaging Sciences, 2020.
# %
# % Copyright (c) 2019-2020, Gary Pui-Tung Choi
# % https://scholar.harvard.edu/choi
import numpy as np
import scipy.optimize as spotimize
# %%
# % Compute the area with normalization
area_v = _face_area(v,f); area_v = area_v/np.nansum(area_v);
# % Project the sphere onto the plane
p = _stereographic(param);
z = p[:,0] + 1j*p[:,1] # make into complex.
# % Function for calculating the area after the Mobius transformation
def area_map(x):
mobius = ((x[0]+x[1]*1j)*z +(x[2]+x[3]*1j))/((x[4]+x[5]*1j)*z + (x[6]+x[7]*1j)) # this is the mobius transform
area_mobius = _face_area(_stereographic(np.vstack([np.real(mobius), np.imag(mobius)]).T), f)
return area_mobius / np.nansum(area_mobius) # normalised area.
def d_area(x):
return _finitemean(np.abs(np.log(area_map(x)/area_v)))
# % Optimization setup
x0 = np.hstack([1,0,0,0,0,0,1,0]); #% initial guess
lb = np.hstack([-1,-1,-1,-1,-1,-1,-1,-1])*100; #% lower bound for the parameters
ub = np.hstack([1,1,1,1,1,1,1,1])*100; #% upper bound for the parameters
bounds = tuple((lb[ii],ub[ii]) for ii in np.arange(len(lb)))
# options = optimoptions('fmincon','Display','iter');
# % Optimization (may further supply gradients for better result, not yet implemented)
# x = fmincon(d_area,x0,[],[],[],[],lb,ub,[],options);
opt_res = spotimize.minimize(d_area, x0, bounds=bounds)
x = opt_res.x
# % obtain the conformal parameterization with area distortion corrected
fz = ((x[0]+x[1]*1j)*z + (x[2]+x[3]*1j)) / ((x[4]+x[5]*1j)*z+(x[6]+x[7]*1j))
map_mobius = _stereographic(np.vstack([np.real(fz), np.imag(fz)]).T);
return map_mobius
def mobius_area_correction_disk(v,f,param):
r""" Find an optimal Mobius transformation for reducing the area distortion of a disk conformal parameterization using the method in [1]_.
Parameters
----------
v : (n_vertices,3) array
vertex coordinates of a simply-connected open triangle mesh
f : (n_faces,3) array
triangulations of a simply-connected open triangle mesh
param : (n_vertices,2) array
vertex coordinates of the disk conformal parameterization of the mesh given by ``v`` and ``f``
Returns
-------
map_mobius_disk : (n_vertices,2) array
vertex coordinates of the updated disk conformal parameterization
References
----------
.. [1] G. P. T. Choi, Y. Leung-Liu, X. Gu, and L. M. Lui, "Parallelizable global conformal parameterization of simply-connected surfaces via partial welding." SIAM Journal on Imaging Sciences, 2020.
"""
# % Find an optimal Mobius transformation for reducing the area distortion of a disk conformal parameterization using the method in [1].
# %
# % Input:
# % v: nv x 3 vertex coordinates of a simply-connected open triangle mesh
# % f: nf x 3 triangulations of a simply-connected open triangle mesh
# % map: nv x 2 vertex coordinates of the disk conformal parameterization
# %
# % Output:
# % map_mobius_disk: nv x 2 vertex coordinates of the updated disk conformal parameterization
# % x: the optimal parameters for the Mobius transformation, where
# % f(z) = \frac{z-a}{1-\bar{a} z}
# % x(1): |a| (0 ~ 1) magnitude of a
# % x(2): arg(a) (0 ~ 2pi) argument of a
# %
# % If you use this code in your own work, please cite the following paper:
# % [1] G. P. T. Choi, Y. Leung-Liu, X. Gu, and L. M. Lui,
# % "Parallelizable global conformal parameterization of simply-connected surfaces via partial welding."
# % SIAM Journal on Imaging Sciences, 2020.
# %
# % Copyright (c) 2019-2020, Gary Pui-Tung Choi
# % https://scholar.harvard.edu/choi
import numpy as np
import scipy.optimize as spotimize
# % Compute the area with normalization
area_v = _face_area(v,f); area_v = area_v/float(np.nansum(area_v));
z = param[:,0] + 1j*param[:,1]
# % Function for calculating the area after the Mobius transformation
def area_map(x):
v_mobius = np.vstack([np.real((z-x[0]*np.exp(1j*x[1]))/(1.-np.conj(x[0]*np.exp(1j*x[1]))*z)), np.imag((z-x[0]*np.exp(1j*x[1]))/(1.-np.conj(x[0]*np.exp(1j*x[1]))*z))]).T
area_mobius = _face_area( v_mobius, f )
return area_mobius / np.nansum(area_mobius) # normalised area.
# % objective function: mean(abs(log(area_map./area_v)))
def d_area(x):
return _finitemean(np.abs(np.log(area_map(x)/area_v)))
# % Optimization setup
x0 = np.hstack([0,0]); #% initial guess, try something diferent if the result is not good
lb = np.hstack([0,0]); #% lower bound for the parameters
ub = np.hstack([1,2*np.pi]); #% upper bound for the parameters
bounds = tuple((lb[ii],ub[ii]) for ii in np.arange(len(lb)))
opt_res = spotimize.minimize(d_area, x0, bounds=bounds)
x = opt_res.x
# % obtain the conformal parameterization with area distortion corrected
fz = (z-x[1]*np.exp(1j*x[1]))/(1.-np.conj(x[0]*np.exp(1j*x[1]))*z);
map_mobius_disk = np.vstack([np.real(fz), np.imag(fz)]).T;
return map_mobius_disk
def _generalized_laplacian(v,f,mu):
# function A = generalized_laplacian(v,f,mu)
# % Compute the generalized Laplacian.
# %
# % If you use this code in your own work, please cite the following paper:
# % [1] T. W. Meng, G. P.-T. Choi and L. M. Lui,
# % "TEMPO: Feature-Endowed Teichmüller Extremal Mappings of Point Clouds."
# % SIAM Journal on Imaging Sciences, 9(4), pp. 1922-1962, 2016.
# %
# % Copyright (c) 2015-2018, Gary Pui-Tung Choi
# % https://scholar.harvard.edu/choi
import numpy as np
import scipy.sparse as sparse
af = (1.-2*mu.real+np.abs(mu)**2)/(1.0-np.abs(mu)**2);
bf = -2.*mu.imag/(1.0-np.abs(mu)**2);
gf = (1.+2*mu.real+np.abs(mu)**2)/(1.0-np.abs(mu)**2);
f0 = f[:,0].copy();
f1 = f[:,1].copy();
f2 = f[:,2].copy();
uxv0 = v[f1,1] - v[f2,1];
uyv0 = v[f2,0] - v[f1,0];
uxv1 = v[f2,1] - v[f0,1];
uyv1 = v[f0,0] - v[f2,0];
uxv2 = v[f0,1] - v[f1,1];
uyv2 = v[f1,0] - v[f0,0];
l = np.vstack([np.sqrt(uxv0**2 + uyv0**2),
np.sqrt(uxv1**2 + uyv1**2),
np.sqrt(uxv2**2 + uyv2**2)]).T;
s = np.sum(l,1)*0.5;
area = np.sqrt(s*(s-l[:,0])*(s-l[:,1])*(s-l[:,2]) + 1e-12) #+ 1e-12;
v00 = (af*uxv0*uxv0 + 2*bf*uxv0*uyv0 + gf*uyv0*uyv0)/area;
v11 = (af*uxv1*uxv1 + 2*bf*uxv1*uyv1 + gf*uyv1*uyv1)/area;
v22 = (af*uxv2*uxv2 + 2*bf*uxv2*uyv2 + gf*uyv2*uyv2)/area;
v01 = (af*uxv1*uxv0 + bf*uxv1*uyv0 + bf*uxv0*uyv1 + gf*uyv1*uyv0)/area;
v12 = (af*uxv2*uxv1 + bf*uxv2*uyv1 + bf*uxv1*uyv2 + gf*uyv2*uyv1)/area;
v20 = (af*uxv0*uxv2 + bf*uxv0*uyv2 + bf*uxv2*uyv0 + gf*uyv0*uyv2)/area;
I = np.hstack([f0,f1,f2,f0,f1,f1,f2,f2,f0])
J = np.hstack([f0,f1,f2,f1,f0,f2,f1,f0,f2])
V = np.hstack([v00,v11,v22,v01,v01,v12,v12,v20,v20])/2.
A = sparse.csr_matrix((-V, (I,J)), shape=((np.max(I)+1, np.max(J)+1)))
return A
def rectangular_conformal_map(v,f,corner=None, map2square=False, random_state=0, return_bdy_index=False):
r""" Compute the rectangular conformal mapping using the fast method in [1]_. This first maps the open mesh to a disk then from a disk to the rectangle.
Parameters
----------
v : (n_vertices, 3) array
vertex coordinates of a simply-connected open triangle mesh
f : (n_faces, 3) array
triangulations of a simply-connected open triangle mesh
corner : (4,) array
optional input for specifying the exact 4 vertex indices for the four corners of the final rectangle, with anti-clockwise orientation
map2square : bool
if True, do the rectangular conformal map, else if False, return the intermediate Harmonic disk parametrization which is much faster.
random_state : int
if corner is None, this is a random seed that randomly picks the 4 corners of the final rectangle from the input vertices.
return_bdy_index : bool
if True, returns additionally the indices of the vertex that form the boundary of the input triangle mesh
Returns
-------
map_ : (n_vertices,2) array
vertex coordinates of the rectangular conformal parameterization if map2square=True of the harmonic disk conformal parametrization if map2square=False.
h_opt : scalar
if map2square=True, return the optimal y-coordinate scaling factor to have the lowest Beltrami coefficient in the rectangular conformal map
bdy_index :
if return_bdy_index=True, return as the last output the vertex indices that form the boundary of the input triangle mesh
References
----------
.. [1] T. W. Meng, G. P.-T. Choi and L. M. Lui, "TEMPO: Feature-Endowed Teichmüller Extremal Mappings of Point Clouds." SIAM Journal on Imaging Sciences, 9(4), pp. 1922-1962, 2016.
Notes
-----
1. Please make sure that the input mesh does not contain any unreferenced vertices/non-manifold vertices/non-manifold edges.
2. Please remove all valence 1 boundary vertices (i.e. vertices with only 1 face attached to them) before running the program.
3. Please make sure that the input triangulations f are with anti-clockwise orientation.
4. The output rectangular domain will always have width = 1, while the height depends on the choice of the corners and may not be 1. (The Riemann mapping theorem guarantees that there exists a conformal map from any simple-connected open surface to the unit square, but if four vertices on the surface boundary are specified to be the four corners of the planar domain, the theorem is no longer applicable.)
"""
# corner is given as an index of the original boundary.
import trimesh
import igl
import numpy as np
import scipy.sparse as sparse
from scipy.optimize import fminbound
# import time
nv = len(v);
bdy_index = igl.boundary_loop(f)
if corner is None:
# just pick 4 regularly sampled indices on the boundary
if random_state is not None:
np.random.seed(random_state)
corner = bdy_index[(np.linspace(0, len(bdy_index)-1, 5)[:4]).astype(np.int)]
# % rearrange the boundary indices to be correct anticlockwise.
id1 = np.arange(len(bdy_index))[bdy_index==corner[0]]
if len(id1)>0:
id1 = id1[0]
# re-index.
bdy_index = np.hstack([bdy_index[id1:], bdy_index[:id1]]);
# relabel
id1 = 0;
id2 = np.arange(len(bdy_index))[bdy_index==corner[1]]
id3 = np.arange(len(bdy_index))[bdy_index==corner[2]]
id4 = np.arange(len(bdy_index))[bdy_index==corner[3]]
id2 = id2[0]
id3 = id3[0]
id4 = id4[0]
# print(id1,id2,id3,id4)
# print('=====')
# %% Step 1: Mapping the input mesh onto the unit disk
bdy_length = np.sqrt((v[bdy_index,0] - v[np.hstack([bdy_index[1:], bdy_index[0]]),0])**2 +
(v[bdy_index,1] - v[np.hstack([bdy_index[1:], bdy_index[0]]),1])**2 +
(v[bdy_index,2] - v[np.hstack([bdy_index[1:], bdy_index[0]]),2])**2);
# partial_edge_sum = np.zeros(len(bdy_length));
partial_edge_sum = np.cumsum(bdy_length)
# # % arc-length parameterization boundary constraint
# theta = 2*np.pi*partial_edge_sum/np.sum(bdy_length); # theta.
# bdy = np.exp(theta*1j); # r
## Map the boundary to a circle, preserving edge proportions
bnd_uv = igl.map_vertices_to_circle(v, bdy_index)
# % 1. disk harmonic map
disk = igl.harmonic_weights(v.astype(np.float),
f,
bdy_index,
bnd_uv,
1); # if 2 then biharmonic
if map2square:
# then do conformal mapping to square
# return disk, [id1,id2,id3,id4], bdy_index
# if sum(sum(isnan(disk))) ~= 0
# % use tutte embedding instead
# disk = tutte_map(v,f,bdy_index,bdy);
# end
# the below is super slow -> try to find a faster way.
# %% Step 2: Mapping the unit disk to the unit square [ super slow ... construction...]
# % compute the generalized Laplacian
mu = beltrami_coefficient(disk, f, v)
# mu = beltrami_coefficient(disk,f,v);
Ax = _generalized_laplacian(disk,f,mu); # ok....-> this does look like just the degree matrix?
Ay = Ax.copy();
# % set the boundary constraints
bottom = bdy_index[id1:id2+1];
right = bdy_index[id2:id3+1];
top = bdy_index[id3:id4+1];
left = np.hstack([bdy_index[id4:], bdy_index[0]])
# print(bottom, right, top, left)
Ax = sparse.lil_matrix(Ax); # convert to this first...
Ay = sparse.lil_matrix(Ay);
bx = np.zeros(nv); by = bx.copy();
Ax[np.hstack([left,right]),:] = 0;
Ax[np.hstack([left,right]), np.hstack([left,right])[:,None]] = np.diag(np.ones(len(np.hstack([left,right]))));
# this diag sounds like just putting ones...
# Ax[np.hstack([left,right]), np.hstack([left,right])] = 1
bx[right] = 1;
Ay[np.hstack([top,bottom]),:] = 0;
Ay[np.hstack([top,bottom]), np.hstack([top,bottom])[:,None]] = np.diag(np.ones(len(np.hstack([top,bottom]))));
# Ay[np.hstack([top,bottom]), np.hstack([top,bottom])] = 1
by[top] = 1;
Ax = sparse.csr_matrix(Ax);
Ay = sparse.csr_matrix(Ay);
# % solve the generalized Laplace equation
square_x = sparse.linalg.spsolve(Ax, bx);
square_y = sparse.linalg.spsolve(Ay, by);
# square_x = sparse.linalg.cg(Ax, bx)[0]; # no solve?
# square_y = sparse.linalg.cg(Ay, by)[0];
# print(square_x.max())
# print(square_y.max())
# %% Step 3: Optimize the height of the square to achieve a conformal map
def func(h):
# here.
return np.sum(np.abs(beltrami_coefficient(np.hstack([square_x[:,None],h*square_y[:,None]]),f,v))**2)
h_opt = fminbound(func, 0,5);
map_ = np.vstack([square_x, h_opt*square_y]).T;
# map_ = np.vstack([square_x, square_y]).T;
if return_bdy_index:
return map_, h_opt, bdy_index
else:
return map_, h_opt
else:
map_ = disk.copy()
if return_bdy_index:
return map_, bdy_index
else:
# just return disk
return map_
def f2v(v,f):
r""" Compute the face to vertex interpolation matrix taking into account unequal lengths.
Parameters
----------
v : (n_vertices,3) array
vertex coordinates of a triangle mesh
f : (n_faces, 3) array
triangulations of a triangle mesh
Returns
-------
S : (n_vertices, n_faces) sparse array
the face to vertex matrix such that S.dot(face_values), gives the interpolated vertex values equivalent
"""
"""
Compute the face to vertex interpolation matrix. of
% [1] P. T. Choi and L. M. Lui,
% "Fast Disk Conformal Parameterization of Simply-Connected Open Surfaces."
% Journal of Scientific Computing, 65(3), pp. 1065-1090, 2015.
"""
import trimesh
import scipy.sparse as spsparse
import numpy as np
mesh = trimesh.Trimesh(vertices=v,
faces=f,
process=False,
validate=False)
S = mesh.faces_sparse.copy() #.dot(rgba.astype(np.float64))
degree = mesh.vertex_degree
nonzero = degree > 0
normalizer = np.zeros(degree.shape)
normalizer[nonzero] = 1./degree[nonzero]
D = spsparse.spdiags(np.squeeze(normalizer), [0], len(normalizer), len(normalizer))
S = D.dot(S)
return S
def disk_conformal_map(v,f,corner=None, random_state=0, north=5, south=100, threshold=0.00001, max_iter=5):
r""" Compute the disk conformal mapping using the method in [1].
Parameters
----------
v : (n_vertices,3) array
vertex coordinates of a simply-connected open triangle mesh
f : (n_faces,3) array
triangulations of a simply-connected open triangle mesh
corner : (4,) array
optional input for specifying the exact 4 vertex indices for rearranging the boundary index, with anti-clockwise orientation
random_state : int
if corner is None, this is a random seed that randomly picks the 4 corners for rearranging the boundary index.
north : int
scalar for fixing the north pole iterations
south :
scalar for fixing the south pole iterations
threshold : scalar
convergence threshold between the old and new energy cost per iteration in the Beltrami coefficient optimization.
max_iter : int
the maximum number of Beltrami coefficient optimization
Returns
-------
disk_new : (n_vertices,2) array
vertex coordinates of the updated disk conformal parameterization starting from an initial harmonic disk parametrization
References
----------
.. [1] P. T. Choi and L. M. Lui, "Fast Disk Conformal Parameterization of Simply-Connected Open Surfaces." Journal of Scientific Computing, 65(3), pp. 1065-1090, 2015.
Notes
-----
1. Please make sure that the input mesh does not contain any unreferenced vertices/non-manifold vertices/non-manifold edges.
2. Please remove all valence 1 boundary vertices (i.e. vertices with only 1 face attached to them) before running the program.
"""
# % Compute the disk conformal mapping using the method in [1].
# %
# % Input:
# % v: nv x 3 vertex coordinates of a simply-connected open triangle mesh
# % f: nf x 3 triangulations of a simply-connected open triangle mesh
# %
# % Output:
# % map: nv x 2 vertex coordinates of the disk conformal parameterization
# %
# % Remark:
# % 1. Please make sure that the input mesh does not contain any
# % unreferenced vertices/non-manifold vertices/non-manifold edges.
# % 2. Please remove all valence 1 boundary vertices (i.e. vertices with
# % only 1 face attached to them) before running the program.
# %
# % If you use this code in your own work, please cite the following paper:
# % [1] P. T. Choi and L. M. Lui,
# % "Fast Disk Conformal Parameterization of Simply-Connected Open Surfaces."
# % Journal of Scientific Computing, 65(3), pp. 1065-1090, 2015.
# %
# % Copyright (c) 2014-2018, Gary Pui-Tung Choi
# % https://scholar.harvard.edu/choi
# corner is given as an index of the original boundary.
import trimesh
import igl
import numpy as np
import scipy.sparse as spsparse
from scipy.optimize import fminbound
import pylab as plt
# import time
"""
Stage 1: obtain a harmonic map initialization.
"""
nv = len(v);
bdy_index = igl.boundary_loop(f)
if corner is None:
# just pick 4 regularly sampled indices on the boundary
if random_state is not None:
np.random.seed(random_state)
corner = bdy_index[(np.linspace(0, len(bdy_index)-1, 5)[:4]).astype(np.int)]
# % rearrange the boundary indices to be correct anticlockwise.
id1 = np.arange(len(bdy_index))[bdy_index==corner[0]]
if len(id1)>0:
id1 = id1[0]
# re-index.
bdy_index = np.hstack([bdy_index[id1:], bdy_index[:id1]]);
# relabel
id1 = 0;
id2 = np.arange(len(bdy_index))[bdy_index==corner[1]]
id3 = np.arange(len(bdy_index))[bdy_index==corner[2]]
id4 = np.arange(len(bdy_index))[bdy_index==corner[3]]
id2 = id2[0]
id3 = id3[0]
id4 = id4[0]
# print(id1,id2,id3,id4)
# print('=====')
# %% Step 1: Mapping the input mesh onto the unit disk
bdy_length = np.sqrt((v[bdy_index,0] - v[np.hstack([bdy_index[1:], bdy_index[0]]),0])**2 +
(v[bdy_index,1] - v[np.hstack([bdy_index[1:], bdy_index[0]]),1])**2 +
(v[bdy_index,2] - v[np.hstack([bdy_index[1:], bdy_index[0]]),2])**2);
# partial_edge_sum = np.zeros(len(bdy_length));
partial_edge_sum = np.cumsum(bdy_length)
# # % arc-length parameterization boundary constraint
# theta = 2*np.pi*partial_edge_sum/np.sum(bdy_length); # theta.
# bdy = np.exp(theta*1j); # r
## Map the boundary to a circle, preserving edge proportions
bnd_uv = igl.map_vertices_to_circle(v, bdy_index)
# % 1. disk harmonic map
disk = igl.harmonic_weights(v.astype(np.float),
f,
bdy_index,
bnd_uv,
1); # if 2 then biharmonic
z = disk[:,0]+disk[:,1]*1j
### the remainder is optimization.
# %% North Pole iteration
# % Use the Cayley transform to map the disk to the upper half plane
# % All boundary points will be mapped to the real line
mu = beltrami_coefficient(disk, f, v);
mu_v = f2v(v,f).dot(mu); # map this from face to vertex.
bdy_index_temp = np.hstack([bdy_index[1:], bdy_index[0]]);
least = np.argmin(np.abs(mu_v[bdy_index])+np.abs(mu_v[bdy_index_temp]))
z = z*np.exp(-1j*(np.angle(z[bdy_index[least]])+np.angle(z[bdy_index[np.mod(least,len(bdy_index))]])/2.)); # this is not giving the same as matlab?
g = 1j*(1. + z)/(1. - z);
#fix the points near the puncture, i.e. near z = 1
ind = np.argsort(-np.real(z));
fixed = np.setdiff1d(ind[:np.max([int(np.round(float(len(v))/north)),np.min([100,len(z)-1])])], bdy_index);
# fixed = [fixed; find(real(g) == max(real(g))); find(real(g) == min(real(g)))];
fixed = np.hstack([fixed, np.argmax(np.real(g)), np.argmin(np.real(g))])
P = np.vstack([np.real(g),
np.imag(g),
np.ones(len(g))]).T
mu = beltrami_coefficient(P, f, v);
#compute the updated x coordinates
target = P[fixed,0];
A = _generalized_laplacian(P,f,mu); # is this more efficient by changing to a column structure.
A = spsparse.lil_matrix(A)
Ax = A.copy(); Ay = A.copy();
b = -Ax[:,fixed].dot(target);
b[fixed] = target;
Ax[fixed,:] = 0; Ax[:,fixed] = 0;
Ax = Ax.tocsr()
Ax = Ax + spsparse.csr_matrix((np.ones(len(fixed)), (fixed,fixed)), shape=(A.shape[0], A.shape[1]));
x = spsparse.linalg.spsolve(Ax,b)
#compute the updated y coordinates
target = P[fixed,1];
fixed = np.hstack([fixed, bdy_index])
target = np.hstack([target, np.zeros(len(bdy_index))]);
b = -Ay[:,fixed].dot(target);
b[fixed] = target;
Ay[fixed,:] = 0; Ay[:,fixed] = 0;
Ay = Ay.tocsr()
Ay = Ay + spsparse.csr_matrix((np.ones(len(fixed)), (fixed,fixed)), shape=(A.shape[0], A.shape[1]));
y = spsparse.linalg.spsolve(Ay,b)
g_new = x+y*1j
z_new = (g_new - 1j)/(g_new + 1j);
disk_new = np.vstack([np.real(z_new), np.imag(z_new)]).T;
if np.sum(np.isnan(disk_new)) != 0:
#% use the old result in case of getting NaN entries
disk_new = disk.copy();
z_new = disk_new[:,0] + 1j*disk_new[:,2];
print('North pole step completed.\n')
"""
reflection in the unit disk to a triangle.
"""
f_temp = f + len(v);
a = np.sort(bdy_index + len(v)); # this is an actual sort!!!
for i in np.arange(len(a)-1, -1, -1):
f_temp[f_temp == a[i]] = a[i] - len(v);
f_temp = f_temp - (f_temp > a[i]);
f_filled = np.vstack([f, np.fliplr(f_temp)]);
z_filled = np.hstack([z_new, 1./np.conj(z_new)]);
select = np.setdiff1d(np.arange(len(z_filled)), bdy_index + len(v))
z_filled = z_filled[select] # = [];
energy_old = 0;
energy = np.mean(np.abs(beltrami_coefficient(np.vstack([np.real(z_new), np.imag(z_new), np.zeros(len(z_new))]).T, f, v)));
iteration_count = 1;
map_opt = disk_new.copy();
print('Reflection completed.\n')
while np.abs(energy_old-energy) > threshold:
energy_old = energy;
mu = beltrami_coefficient(np.vstack([np.real(z_new), np.imag(z_new), np.zeros(len(z_new))]).T, f, v); # vector.
mu_filled = np.hstack([mu,
1./3*((z_new[f[:,0]]/(np.conj(z_new[f[:,0]])))**2 +
(z_new[f[:,1]]/(np.conj(z_new[f[:,1]])))**2 +
(z_new[f[:,2]]/(np.conj(z_new[f[:,2]])))**2)*np.conj(mu)/ np.abs(((z_new[f[:,0]]/(np.conj(z_new[f[:,0]])))**2 +
(z_new[f[:,1]]/(np.conj(z_new[f[:,1]])))**2 +
(z_new[f[:,2]]/(np.conj(z_new[f[:,2]])))**2))]); # doubles in length.
# % fix the points near infinity
ind = np.argsort(-np.abs(z_filled))
fixed2 = ind[:np.max([int(np.round(float(len(v))/south)), np.min([100,len(z)-1])])];
map_filled = linear_beltrami_solver(np.vstack([np.real(z_filled), np.imag(z_filled), np.zeros(len(z_filled))]).T,
f_filled, mu_filled,
fixed2, np.vstack([np.real(z_filled[fixed2]), np.imag(z_filled[fixed2])]).T);
z_big = map_filled[:,0] + 1j*map_filled[:,1]
z_final = z_big[:len(v)].copy();
# % normalization
z_final = z_final - np.mean(z_final); #% move centroid to zero
if np.max(np.abs(z_final))>1:
z_final = z_final/(np.max(np.abs(z_final))); #% map it into unit circle
mu_temp = beltrami_coefficient(np.vstack([np.real(z_final), np.imag(z_final), np.zeros(len(z_final))]).T , f,v);
map_temp = linear_beltrami_solver(np.vstack([np.real(z_final), np.imag(z_final), np.zeros(len(z_final))]).T,
f,
mu_temp,
bdy_index,
np.vstack([np.real(z_final[bdy_index]/np.abs(z_final[bdy_index])),
np.imag(z_final[bdy_index]/np.abs(z_final[bdy_index]))]).T);
z_new = map_temp[:,0] + 1j*map_temp[:,1];
z_filled = np.hstack([z_new, 1./np.conj(z_new)]);
select = np.setdiff1d(np.arange(len(z_filled)), bdy_index + len(v))
z_filled = z_filled[select] # = [];
disk_iter = np.vstack([np.real(z_new), np.imag(z_new)]).T;
# # return disk_new
# # return disk_new
# plt.figure(figsize=(10,10))
# plt.title('iter disk')
# plt.plot(disk[:,0], disk[:,1], 'r.', ms=.1)
# plt.plot(disk_new[:,0], disk_new[:,1], 'g.', ms=.1)
# plt.show()
if np.sum(np.isnan(disk_iter)) != 0:
# % use the previous result in case of getting NaN entries
disk_iter = map_opt.copy();
# disk_iter[:,0] = -disk_iter[:,0].copy(); # don't get this
energy = np.mean(np.abs(beltrami_coefficient(disk_iter, f, v)));
map_opt = disk_iter.copy();
print('Iteration %d: mean(|mu|) = %.4f\n' %(iteration_count, energy));
iteration_count = iteration_count+1;
if iteration_count > max_iter:
# % it usually converges within 5 iterations so we set 5 here
break;
disk_new = map_opt.copy()
# disk_new[:,0] = -disk_new[:,0].copy()
# # return disk_new
# plt.figure(figsize=(10,10))
# plt.title('final disk')
# plt.plot(disk[:,0], disk[:,1], 'r.', ms=.1)
# plt.plot(disk_new[:,0], disk_new[:,1], 'g.', ms=.1)
# plt.show()
return disk_new
def _squicircle(uv, _epsilon = 0.0000000001):
import numpy as np
#_fgs_disc_to_square
u = uv[:,0].copy()
v = uv[:,1].copy()
x = u.copy()
y = v.copy()
u2 = u * u
v2 = v * v
r2 = u2 + v2
uv = u * v
fouru2v2 = 4.0 * uv * uv
rad = r2 * (r2 - fouru2v2)
sgnuv = np.sign(uv)
sgnuv[uv==0.0] = 0.0
sqrto = np.sqrt(0.5 * (r2 - np.sqrt(rad)))
y[np.abs(u) > _epsilon] = (sgnuv / u * sqrto)[np.abs(u) > _epsilon]
x[np.abs(v) > _epsilon] = (sgnuv / v * sqrto)[np.abs(v) > _epsilon]
return np.vstack([x,y]).T
def _elliptical_nowell(uv):
#https://squircular.blogspot.com/2015/09/mapping-circle-to-square.html
import numpy as np
u = uv[:,0].copy()
v = uv[:,1].copy()
x = .5*np.sqrt(2.+2.*u*np.sqrt(2) + u**2 - v**2) - .5*np.sqrt(2.-2.*u*np.sqrt(2) + u**2 - v**2)
y = .5*np.sqrt(2.+2.*v*np.sqrt(2) - u**2 + v**2) - .5*np.sqrt(2.-2.*v*np.sqrt(2) - u**2 + v**2)
# there is one nan.
nan_select = np.isnan(x)
# check the nan in the original
x[nan_select] = np.sign(u[nan_select]) # map to 1 or -1
y[nan_select] = np.sign(v[nan_select])
return np.vstack([x,y]).T
def find_and_loc_corner_rect_open_surface(mesh, vol_shape, ref_depth=0, order='cc', curvature_flow=True, delta_flow=1e3, flow_iters=50):
r""" Find and locate the 4 corners of a rectangular topography mesh. Curvature flow of the boundary is used to identify the corners fast and accurately
Parameters
----------
mesh : trimesh.Trimesh
a simply-connected open triangle topography mesh
vol_shape : (D,U,V) tuple
the shape of the topography volume space the topography mesh comes from
ref_depth : int
if curvature_flow=False, this is the depth coordinate of the topography mesh used to locate corners (implicitly assuming all corners are of equal depth)
order : 'cc' or 'acc'
specifies whether the input mesh has faces oriented 'cc'-clockwise or 'acc'-anticlockwise
curvature_flow : bool
if True, uses curvature flow of the boundary to help locate the corners of the topography mesh. This is most accurate. If False, the corners will attempt to be found by idealistic matching to 4 corners constructed by ref_depth and the 4 corners of the image grid spanned by vertices of the input mesh
delta_flow : scalar
specifies the speed of flow if curvature_flow=True. Higher flow gives faster convergence.
flow_iters : int
specifies the number of iterations of curvature flow. Higher will give more flow
Returns
-------
bnd : (n,) array
the vertex indices of the boundary of the topography mesh
corner_bnd_ind : (4,) array
the indices of ``bnd`` specifying the 4 corners in anti-clockwise order
corner_v_ind : (4,) array
the vertex indices of the input mesh specifying the 4 corners in anti-clockwise order
"""
import numpy as np
import igl
# make copy of the input mesh.
v = mesh.vertices.copy()
f = mesh.faces.copy()
# =============================================================================
# 3) Fix the boundary of the surface unwrapping
# =============================================================================
d, m, n = vol_shape[:3]
if order=='cc':
# the 4 corners of the image.
corner1yx = np.hstack([0,0])
corner2yx = np.hstack([m-1,0])
corner3yx = np.hstack([m-1,n-1])
corner4yx = np.hstack([0,n-1])
if order =='acc':
# the 4 corners of the image.
corner1yx = np.hstack([0,0])
corner2yx = np.hstack([0,n-1])
corner3yx = np.hstack([m-1,n-1])
corner4yx = np.hstack([m-1,0])
## convert the coordinates to the indices of the open boundary
bnd = igl.boundary_loop(f) # vertex index.
bnd_vertex = v[bnd].copy()
bnd_index = np.arange(len(bnd))
# initial algorithm which fails to properly constrain the x-y plane
# the problem here is because of the curvature of the curve... -> to be fully accurate we should do curvature flow of the bounary edge line!.
if curvature_flow:
bnd_vertex_evolve = conformalized_mean_line_flow( bnd_vertex,
E=None,
close_contour=True,
fixed_boundary = False,
lambda_flow=delta_flow,
niters=flow_iters,
topography_edge_fix=True,
conformalize=True)
# we then solve for the index on the evolved boundary!.
min1_ind = np.argmin(np.linalg.norm(bnd_vertex_evolve[...,-1] - np.hstack([ref_depth, corner1yx])[None,:], axis=-1))
min2_ind = np.argmin(np.linalg.norm(bnd_vertex_evolve[...,-1] - np.hstack([ref_depth, corner2yx])[None,:], axis=-1))
min3_ind = np.argmin(np.linalg.norm(bnd_vertex_evolve[...,-1] - np.hstack([ref_depth, corner3yx])[None,:], axis=-1))
min4_ind = np.argmin(np.linalg.norm(bnd_vertex_evolve[...,-1] - np.hstack([ref_depth, corner4yx])[None,:], axis=-1))
else:
min1_ind = np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner1yx])[None,:], axis=-1))
min2_ind = np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner2yx])[None,:], axis=-1))
min3_ind = np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner3yx])[None,:], axis=-1))
min4_ind = np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner4yx])[None,:], axis=-1))
pts1_ind_bnd = bnd_index[min1_ind]
pts2_ind_bnd = bnd_index[min2_ind]
pts3_ind_bnd = bnd_index[min3_ind]
pts4_ind_bnd = bnd_index[min4_ind]
pts1_ind_v = bnd[min1_ind]
pts2_ind_v = bnd[min2_ind]
pts3_ind_v = bnd[min3_ind]
pts4_ind_v = bnd[min4_ind]
# =============================================================================
# 3) rectangular conformal map -> first maps to the disk
# =============================================================================
# stack the corners.
corner_bnd_ind = np.hstack([pts1_ind_bnd, pts2_ind_bnd, pts3_ind_bnd, pts4_ind_bnd])
corner_v_ind = np.hstack([pts1_ind_v, pts2_ind_v, pts3_ind_v, pts4_ind_v])
return bnd, corner_bnd_ind, corner_v_ind
def reconstruct_border_inds(all_border_inds, corner_inds):
r""" Given an ordered list of corner indices within an array of boundary indices specifying a closed loop, construct the continuous line segments linking the corner points
Parameters
----------
all_border_inds : (N,) array
array of vertex indices specifying the boundary of a mesh
corner_inds : (n_corners,) array
array specifying which indices of ``all_border_inds`` are 'corners'. This should be ordered such that corner_inds[0]:corner_inds[1] constitute a continuous segment.
Returns
-------
segs : list of n_corners+1 arrays
a list of all the continuous boundary segments between consecutive corners
"""
import numpy as np
corner_inds_ = np.hstack([corner_inds, corner_inds[0]])
# print(corner_inds_)
N = len(corner_inds_)
segs = []
for ii in np.arange(N-1):
start = corner_inds_[ii]
end = corner_inds_[ii+1]
# print(start,end)
if end > start:
inds = np.arange(start,end,1)
else:
inds = np.hstack([np.arange(start, len(all_border_inds),1),
np.arange(0, end)])
segs.append(inds)
return segs
def flat_open_surface(mesh, vol_shape, map2square=False, square_method='elliptical',
ref_depth=0,
order='cc',
curvature_flow=True,
delta_flow=1e3,
flow_iters=50,
optimize=True):
r""" Main wrapping function to unwrap an open 3D mesh, primarily a topography into 2D disk, or 2D rectangle (continuing from the 2D disk)
Parameters
----------
mesh : trimesh.Trimesh
a simply-connected open triangle topography mesh
vol_shape : (M,N,L) tuple
the shape of the volume space the topography mesh comes from
map2square : bool
If True, continue to map the disk to the square or conformal rectangle with options specified by ``square_method``. If False or if square_method=None, the intermediate disk parameterization is returned
square_method : str
One of 'Teichmuller' for conformal rectangular mapping, 'squicircle' for squicircle squaring of disk to square, 'elliptical' for elliptical mapping of Nowell of disk to square. 'Teichmuller' is slow but conformal minimizing.
ref_depth : int
if curvature_flow=False, this is the depth coordinate of the topography mesh used to locate corners (implicitly assuming all corners are of equal depth)
order : 'cc' or 'acc'
specifies whether the input mesh has faces oriented 'cc'-clockwise or 'acc'-anticlockwise
optimize : bool
if True, applies Beltrami coefficient optimization to compute the rectangular aspect ratio to minimize distortion given the square_method='squicircle' and square_method='elliptical' options. Teichmuller by default will have this option enabled.
Returns
-------
square : (n_vertices, 2)
the disk or square parametrization of the input mesh
"""
import numpy as np
import igl
from scipy.optimize import fminbound
# make copy of the input mesh.
v = mesh.vertices.copy()
f = mesh.faces.copy()
# =============================================================================
# 3) Fix the boundary of the surface unwrapping
# =============================================================================
# d, m, n = vol_shape[:3]
# if order=='cc':
# # the 4 corners of the image.
# corner1yx = np.hstack([0,0])
# corner2yx = np.hstack([m-1,0])
# corner3yx = np.hstack([m-1,n-1])
# corner4yx = np.hstack([0,n-1])
# if order =='acc':
# # the 4 corners of the image.
# corner1yx = np.hstack([0,0])
# corner2yx = np.hstack([0,n-1])
# corner3yx = np.hstack([m-1,n-1])
# corner4yx = np.hstack([m-1,0])
# ## convert the coordinates to the indices of the open boundary
# bnd = igl.boundary_loop(f) # vertex index.
# bnd_vertex = v[bnd].copy()
# """
# to do: replace this with the actual boundary....
# """
# # match by distance rather than exact match.
# pts1_ind = bnd[np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner1yx])[None,:], axis=-1))]
# pts2_ind = bnd[np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner2yx])[None,:], axis=-1))]
# pts3_ind = bnd[np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner3yx])[None,:], axis=-1))]
# pts4_ind = bnd[np.argmin(np.linalg.norm(bnd_vertex - np.hstack([ref_depth, corner4yx])[None,:], axis=-1))]
bnd, corner_bnd_ind, _ = find_and_loc_corner_rect_open_surface(mesh,
vol_shape,
ref_depth=ref_depth,
order=order,
curvature_flow=curvature_flow,
delta_flow=delta_flow,
flow_iters=flow_iters)
bnd_vertex = v[bnd].copy()
pts1_ind, pts2_ind, pts3_ind, pts4_ind = corner_bnd_ind
# # this needs proper sorting...
# print(pts1_ind, pts2_ind, pts3_ind, pts4_ind)
# import pylab as plt
# plt.figure()
# plt.plot([corner1yx[0], corner2yx[0], corner3yx[0], corner4yx[0]],
# [corner1yx[1], corner2yx[1], corner3yx[1], corner4yx[1]], 'r.-')
# plt.show()
# =============================================================================
# 3) rectangular conformal map -> first maps to the disk
# =============================================================================
# stack the corners.
corner = np.hstack([pts1_ind, pts2_ind, pts3_ind, pts4_ind])
if map2square == True:
if square_method is not None:
if square_method == 'Teichmuller':
square, h_opt = rectangular_conformal_map(v, f, corner, map2square=map2square)
# return square
else:
# then the disk = the remesh.
disk = rectangular_conformal_map(v, f, corner, map2square=map2square)
if square_method == 'squicircle':
print('squicircle')
square = _squicircle(disk)
if square_method == 'elliptical':
print('elliptical')
square = _elliptical_nowell(disk)
# then we try to optimize aspect ratio to get conformality.
def func(h):
return np.sum(np.abs(beltrami_coefficient(np.hstack([square[:,0][:,None],h*square[:,1][:,None]]), f, v))**2)
if optimize:
h_opt = fminbound(func, 0, 5);
square = np.vstack([square[:,0], h_opt*square[:,1]]).T;
# return square
else:
disk = rectangular_conformal_map(v, f, corner, map2square=map2square)
# print('direct return')
square = disk.copy()
# return square
else:
# print('Teichmuller')
# then the disk = the remesh.
# default to disk!.
disk = rectangular_conformal_map(v, f, corner, map2square=False)
square = disk.copy()
return square
"""
mesh quality metrics.
"""
# not used.
# def conformal_distortion_factor_trimesh(pts2D, pts3D, triangles, eps=1e-20):
# """
# """
# # this metric is implemented from http://hhoppe.com/tmpm.pdf and which seems to be mainly used by all the graphical community.
# # 1 = conformal, this is also just the stretch factor.
# # measuring the quasi-conformal error, computed as the area-weighted average of the ratios of the largest to smallest singular values of the map’s Jacobian
# import igl
# import numpy as np
# tri2D = pts2D[triangles].copy() # N x 3 x 2
# tri3D = pts3D[triangles].copy() # N x 3 x 3
# q1 = tri3D[:,0].copy()
# q2 = tri3D[:,1].copy()
# q3 = tri3D[:,2].copy()
# # 2D coordinates.
# s1 = tri2D[:,0,0].copy()
# s2 = tri2D[:,1,0].copy()
# s3 = tri2D[:,2,0].copy()
# t1 = tri2D[:,0,1].copy()
# t2 = tri2D[:,1,1].copy()
# t3 = tri2D[:,2,1].copy()
# # A = ((tri2D[:,1,0] - tri2D[:,0,0]) * (tri2D[:,2,1] - tri2D[:,0,1]) - (tri2D[:,2,0] - tri2D[:,0,0]) * (tri2D[:,1,1] - tri2D[:,0,1])) / 2. # area 2D triangles
# A = ((s2 - s1)*(t3-t1) - (s3 - s1)*(t2-t1)) / 2.
# Ss = (q1*(t2-t3)[:,None] + q2*(t3-t1)[:,None] + q3*(t1-t2)[:,None]) / (2*A[:,None] + eps) # dS / ds
# St = (q1*(s3-s2)[:,None] + q2*(s1-s3)[:,None] + q3*(s2-s1)[:,None]) / (2*A[:,None] + eps) # dS / dt
# # get the largest and smaller single values of the Jacobian for each element...
# a = Ss.dot(Ss)
# b = Ss.dot(St)
# c = St.dot(St)
# Gamma = np.sqrt((a+c + np.sqrt((a-c)**2 + 4*b**2))/2.)
# gamma = np.sqrt((a+c - np.sqrt((a-c)**2 + 4*b**2))/2.)
# stretch_ratios = Gamma/gamma
# area = igl.doublearea(pts3D,triangles) #total area.
# mean_stretch_ratio = np.nansum(area * stretch_ratios) / (np.nansum(area))
# return mean_stretch_ratio, stretch_ratios
# # compute the 3D to 3D deformation analysis.
# # def statistical_strain_rate_mesh(grid_squares_time, unwrap_params_3D):
# def statistical_strain_mesh3D(pts1, pts2, triangles):
# # we do this in (x,y,z) coordinates. for polygonal mesh.
# # see, http://graner.net/francois/publis/graner_tools.pdf for an introduction of the mathematics.
# # both pts1 and pts2 are 3D !
# import numpy as np
# # compute the differential change in links.
# triangles1 = pts1[triangles].copy() # N_tri x 3 x 3
# triangles2 = pts2[triangles].copy()
# # form the displacements -> i.e the edge vectors !.
# links_3D = triangles1 - triangles2 # displacements (x,y,z)
# # build the covariance matrices.
# M_matrix_00 = np.mean( links_3D[...,0] ** 2, axis=1)
# M_matrix_01 = np.mean( links_3D[...,0] * links_3D[...,1], axis=1)
# M_matrix_02 = np.mean( links_3D[...,0] * links_3D[...,2], axis=1)
# M_matrix_10 = np.mean( links_3D[...,1] * links_3D[...,0], axis=1)
# M_matrix_11 = np.mean( links_3D[...,1] **2, axis=1)
# M_matrix_12 = np.mean( links_3D[...,1] * links_3D[...,2], axis=1)
# M_matrix_20 = np.mean( links_3D[...,2] * links_3D[...,0], axis=1)
# M_matrix_21 = np.mean( links_3D[...,2] * links_3D[...,1], axis=1)
# M_matrix_22 = np.mean( links_3D[...,2] **2, axis=-1)
# # compute the inverse 3 x 3 matrix using fomulae.
# M_matrix = np.array([[M_matrix_00, M_matrix_01, M_matrix_02],
# [M_matrix_10, M_matrix_11, M_matrix_12],
# [M_matrix_20, M_matrix_21, M_matrix_22]])
# M_matrix = M_matrix.transpose(2,0,1)
# # from this we should be able to go ahead and extract the principal strains.
# return M_matrix
### need to check the following.
# def mesh_strain_polygon(pts1, pts2, triangles):
# r""" Compute the temporal polygonal mesh strain 3D deformation as described in reference [1]_
# Parameters
# ----------
# pts1 : (n_time, n_vertices, 3) array
# vertices of mesh 1 for all timepoints
# pts2 : (n_time, n_vertices, 3) array
# vertices of mesh 2 for all timepoints
# triangles : (n_time, n_faces, 3) array
# triangulations of the mesh at all timepoints
# Returns
# -------
# V :
# strain matrix (symmetric component)
# Omega :
# rotational strain matrix (antisymmetric component)
# References
# ----------
# .. [1] Graner, François, et al. "Discrete rearranging disordered patterns, part I: Robust statistical tools in two or three dimensions." The European Physical Journal E 25.4 (2008): 349-369.
# """
# # we can do this in (x,y,z) coordinates.
# # see, http://graner.net/francois/publis/graner_tools.pdf
# import numpy as np
# # get the triangles and combine.
# triangles12 = np.array([pts1[triangles],
# pts2[triangles]]) # combine to 2 x N_tri x 3 x 3
# triangles12 = np.concatenate([triangles12,
# triangles12[:,:,0,:][:,:,None,:]], axis=2)
# links_squares_time_3D = triangles12[:,:,1:] - triangles12[:,:,:-1] # compute the edge vectors.
# # links_squares_time_3D = unwrap_params_3D[grid_squares_time[:,:,1:,1].astype(np.int),
# # grid_squares_time[:,:,1:,0].astype(np.int)] - unwrap_params_3D[grid_squares_time[:,:,:-1,1].astype(np.int),
# # grid_squares_time[:,:,:-1,0].astype(np.int)]
# # time differential. => here this is the evolution.
# d_links_squares_time_3D = links_squares_time_3D[1:] - links_squares_time_3D[:-1] # this is the stretch ...
# # links_squares_time_3D = links_squares_time_3D[1:] - links_squares_time_3D[:-1] # this is the stretch ...
# M_matrix_00 = np.mean( links_squares_time_3D[...,0] ** 2, axis=-1) # take the 2nd last to get the average of the polygons.
# M_matrix_01 = np.mean( links_squares_time_3D[...,0] * links_squares_time_3D[...,1], axis=-1)
# M_matrix_02 = np.mean( links_squares_time_3D[...,0] * links_squares_time_3D[...,2], axis=-1)
# M_matrix_10 = np.mean( links_squares_time_3D[...,1] * links_squares_time_3D[...,0], axis=-1)
# M_matrix_11 = np.mean( links_squares_time_3D[...,1] **2, axis=-1)
# M_matrix_12 = np.mean( links_squares_time_3D[...,1] * links_squares_time_3D[...,2], axis=-1)
# M_matrix_20 = np.mean( links_squares_time_3D[...,2] * links_squares_time_3D[...,0], axis=-1)
# M_matrix_21 = np.mean( links_squares_time_3D[...,2] * links_squares_time_3D[...,1], axis=-1)
# M_matrix_22 = np.mean( links_squares_time_3D[...,2] **2, axis=-1)
# # compute the inverse 3 x 3 matrix using fomulae.
# M_matrix = np.array([[M_matrix_00, M_matrix_01, M_matrix_02],
# [M_matrix_10, M_matrix_11, M_matrix_12],
# [M_matrix_20, M_matrix_21, M_matrix_22]])
# M_matrix = M_matrix.transpose(2,3,0,1)
# M_inv = np.linalg.pinv(M_matrix.reshape(-1,3,3)).reshape(M_matrix.shape)
# # print(np.allclose(M_matrix[0,0], np.dot(M_matrix[0,0], np.dot(M_inv[0,0], M_matrix[0,0]))))
# # # print(M_inv[0,0])
# # # print(np.linalg.inv(M_matrix[0,0]))
# # # print(np.dot(M_matrix[0,0], np.linalg.inv(M_matrix[0,0])))
# C_matrix_00 = np.mean( links_squares_time_3D[:-1,...,0] * d_links_squares_time_3D[...,0], axis=-1) # this one is inner product....
# C_matrix_01 = np.mean( links_squares_time_3D[:-1,...,0] * d_links_squares_time_3D[...,1], axis=-1)
# C_matrix_02 = np.mean( links_squares_time_3D[:-1,...,0] * d_links_squares_time_3D[...,2], axis=-1)
# C_matrix_10 = np.mean( links_squares_time_3D[:-1,...,1] * d_links_squares_time_3D[...,0], axis=-1)
# C_matrix_11 = np.mean( links_squares_time_3D[:-1,...,1] * d_links_squares_time_3D[...,1], axis=-1)
# C_matrix_12 = np.mean( links_squares_time_3D[:-1,...,1] * d_links_squares_time_3D[...,2], axis=-1)
# C_matrix_20 = np.mean( links_squares_time_3D[:-1,...,2] * d_links_squares_time_3D[...,0], axis=-1)
# C_matrix_21 = np.mean( links_squares_time_3D[:-1,...,2] * d_links_squares_time_3D[...,1], axis=-1)
# C_matrix_22 = np.mean( links_squares_time_3D[:-1,...,2] * d_links_squares_time_3D[...,2], axis=-1)
# C_matrix = np.array([[C_matrix_00, C_matrix_01, C_matrix_02],
# [C_matrix_10, C_matrix_11, C_matrix_12],
# [C_matrix_20, C_matrix_21, C_matrix_22]])
# C_matrix = C_matrix.transpose(2,3,0,1)
# C_matrix_T = C_matrix.transpose(0,1,3,2) # obtain the matrix transpose.
# # V = 1./2 *( np.matmul(M_inv.reshape(-1,3,3), C_matrix.reshape()) + np.matmul(C_matrix_T, M_inv))
# # MM = M_inv.reshape(-1,3,3)
# # CC = C_matrix.reshape(-1,3,3)
# # CC_T = C_matrix_T.reshape(-1,3,3)
# V = 1./2 *( np.matmul(M_inv[:-1], C_matrix) +
# np.matmul(C_matrix_T, M_inv[:-1]))
# Omega = 1./2 * ( np.matmul(M_inv[:-1], C_matrix) -
# np.matmul(C_matrix_T, M_inv[:-1]))
# return V, Omega
# # return M_matrix
def map_3D_to_2D_triangles(pts3D, triangles):
r""" Isometric projection of 3D triangles to 2D coordinates This function implements the solution of [1]_. This function is similar to igl.project_isometrically_to_plane
Given the vertices :math:`v_1, v_2, v_3` of a triangle in 3D, a 2D isometric projection can be constructed that preserves length and area with new vertex coordinate defined by
.. math::
v^{2D}_1 &= (0, 0) \\
v^{2D}_2 &= (|A|, 0) \\
v^{2D}_3 &= (A.B/ |A|, |A \times B|/|A|)
where :math:`A=v_2-v_1`, :math:`B=v_3-v_1`.
Parameters
----------
pts3D : (n_vertices,3) array
the 3D vertices of the mesh
triangles : (n_faces,3) array
the triangulation of pts3D given by vertex indices
Returns
-------
pts_2D : (n_faces,2) array
the vertices of the triangle in 2D
References
----------
.. [1] https://stackoverflow.com/questions/8051220/flattening-a-3d-triangle
.. [2] https://scicomp.stackexchange.com/questions/25327/finding-shape-functions-for-a-triangle-in-3d-coordinate-space
"""
import numpy as np
pts_tri = pts3D[triangles].copy()
A = pts_tri[:,1] - pts_tri[:,0]
B = pts_tri[:,2] - pts_tri[:,0]
# set the first point to (0,0)
pts_2D_0 = np.zeros((len(pts_tri), 2))
pts_2D_1 = np.hstack([np.linalg.norm(A, axis=-1)[:,None], np.zeros(len(pts_tri))[:,None]])
pts_2D_2 = np.hstack([(np.sum(A*B, axis=-1))[:,None], (np.linalg.norm(np.cross(A,B), axis=-1))[:,None]]) / (np.linalg.norm(A, axis=-1))[:,None]
pts_2D = np.concatenate([pts_2D_0[:,None,:],
pts_2D_1[:,None,:],
pts_2D_2[:,None,:]], axis=1)
return pts_2D
def quasi_conformal_error(pts1_3D, pts2_3D, triangles):
r""" Computes the quasi-conformal error between two 3D triangle meshes as defined in [1]_
Parameters
----------
pts1_3D : (n_vertices,3) array
vertices of mesh 1
pts2_3D : (n_vertices,3) array
vertices of mesh 2
triangles : (n_faces,3) array
the triangulation of pts1_3D and pts2_3D in terms of the vertex indices
Returns
-------
Jac_eigvals : (n_faces,)
eigenvalues of the transformation matrix mapping the 2D isometric projections of pts1_3D to pts_2_3D
stretch_factor : (n_faces,)
the ratio of the square root of maximum singular value over square root of of the minimum singular value of the square form of the transformation matrix mapping the 2D isometric projections of pts1_3D to pts_2_3D
mean_stretch_factor : scalar
the area weighted mean stretch factor or quasi-conformal error
(areas3D, areas3D_2) : ((n_faces,), (n_faces,)) list of arrays
the triangle areas of the first and second mesh respectively
References
----------
.. [1] Hormann, K. & Greiner, G. MIPS: An efficient global parametrization method. (Erlangen-Nuernberg Univ (Germany) Computer Graphics Group, 2000)
"""
"""
maps R^3 to R^2 triangle. Describes the transformation by linear means -> equivalent to the jacobian matrix.
# we also take the opportunity to compute the area.
"""
import igl
import numpy as np
# map the 3D triangle to 2D triangle coordinates.
pts1_2D = map_3D_to_2D_triangles(pts1_3D, triangles)
pts2_2D = map_3D_to_2D_triangles(pts2_3D, triangles)
# convert 2D coordinates to homogeneous coordinates in order to solve uniquely.
# having converted we can now get the jacobian by specifying Y = AX (homogeneous coordinates.)
pts1_2D_hom = np.concatenate([pts1_2D,
np.ones((pts1_2D.shape[0], pts1_2D.shape[1]))[...,None]], axis=-1)
pts2_2D_hom = np.concatenate([pts2_2D,
np.ones((pts2_2D.shape[0], pts2_2D.shape[1]))[...,None]], axis=-1)
pts1_2D_hom = pts1_2D_hom.transpose(0,2,1).copy()
pts2_2D_hom = pts2_2D_hom.transpose(0,2,1).copy()
# solve exactly.
try:
Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom)) # this really is just solving registration problem ?
except:
Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom + np.finfo(float).eps)) # if fails we need a small eps to stabilise.
JacMatrix = Tmatrix[:,:2,:2].copy() # take the non jacobian component?
# The error is given as the ratio of the largest to smallest eigenvalue. -> since SVD, hence the singular values are squared.
u, s, v = np.linalg.svd(JacMatrix)
# see http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/13_Parameterization2.pdf to better understand.
Jac_eigvals = s.copy()
# stretch_factor is gotten from eigenvalues of J^T J
JacMatrix2 = np.matmul(JacMatrix.transpose(0,2,1), JacMatrix)
stretch_eigenvalues, stretch_eigenvectors = np.linalg.eigh(JacMatrix2) # this should be square root.!
# stretch_eigenvalues = np.sqrt(stretch_eigenvalues) # we should do this !!!! since we squared the matrix form!.
# stretch_factor = np.sqrt(np.max(np.abs(s), axis=1) / np.min(np.abs(s), axis=1)) # since this was SVD decomposition.
stretch_factor = np.sqrt(np.max(np.abs(stretch_eigenvalues), axis=1) / np.min(np.abs(stretch_eigenvalues), axis=1)) # since this was SVD decomposition.
areas3D = igl.doublearea(pts1_3D, triangles) / 2.
mean_stretch_factor = np.nansum(areas3D*stretch_factor / (float(np.sum(areas3D)))) # area weighted average.
# we also compute the final areas to derive an area change factor.
areas3D_2 = igl.doublearea(pts2_3D, triangles) / 2.
return Jac_eigvals, stretch_factor, mean_stretch_factor, (areas3D, areas3D_2)
def MIPS_cost(pts1_3D, pts2_3D, triangles, area_mips_theta=1, norm_pts=True):
r""" Compute the Most isometric parametrization (MIPs) and the Area-preserving MIPs cost defined in [1]_ and [2]_ respectively
Parameters
----------
pts1_3D : (n_vertices,3) array
vertices of mesh 1
pts2_3D : (n_vertices,3) array
vertices of mesh 2
triangles : (n_faces,3) array
the triangulation of pts1_3D and pts2_3D in terms of the vertex indices
area_mips_theta : scalar
the exponent of the area-preserving MIPs cost in [2]_. If area_mips_theta=1, the area-preserving MIPs measures the area uniformity of stretch distortion of the surface
norm_pts : True
normalize vertex points by the respective surface areas of the mesh before computing the cost
Returns
-------
(MIPS, area_MIPS, MIPS_plus) : ((n_faces,), (n_faces,), (n_faces,)) list of array
the MIPs, area preserving MIPs and the direct sum of stretch + area distortion
(mean_MIPS, mean_area_MIPS, mean_MIPS_plus) : (3,) tuple
tuple of the mean MIPs, area preserving MIPs and the sum of stretch + area distortion
(sigma1,sigma2) : ((n_faces,), (n_faces,)) tuple
the square root of the maximum singular and square root of the minimum singular value of the square form of the transformation matrix mapping the 2D isometric projections of pts1_3D to pts_2_3D
(stretch_eigenvalues, stretch_eigenvectors) : ((n_faces,), (n_faces,)) tuple
the singular value eigenvalue matrix and corresponding eigenvector matrix of the square form of the transformation matrix mapping the 2D isometric projections of pts1_3D to pts_2_3D
References
----------
.. [1] Hormann, K. & Greiner, G. MIPS: An efficient global parametrization method. (Erlangen-Nuernberg Univ (Germany) Computer Graphics Group, 2000)
.. [2] Degener, P., Meseth, J. & Klein, R. An Adaptable Surface Parameterization Method. IMR 3, 201-213 (2003).
"""
"""
maps R^3 to R^2 triangle. Describes the transformation by linear means -> equivalent to the jacobian matrix.
# we also take the opportunity to compute the area.
"""
"""
use the Most isometric parametrization cost.
https://arxiv.org/pdf/1810.09031.pdf
"""
import igl
import numpy as np
if norm_pts:
pts1_3D_ = pts1_3D / np.nansum((igl.doublearea(pts1_3D, triangles) / 2.))
pts2_3D_ = pts2_3D / np.nansum(igl.doublearea(pts2_3D, triangles) / 2.)
pts1_2D = map_3D_to_2D_triangles(pts1_3D_, triangles)
pts2_2D = map_3D_to_2D_triangles(pts2_3D_, triangles)
else:
# map the 3D triangle to 2D triangle coordinates.
pts1_2D = map_3D_to_2D_triangles(pts1_3D, triangles)
pts2_2D = map_3D_to_2D_triangles(pts2_3D, triangles)
# convert 2D coordinates to homogeneous coordinates in order to solve uniquely.
# having converted we can now get the jacobian by specifying Y = AX (homogeneous coordinates.)
pts1_2D_hom = np.concatenate([pts1_2D,
np.ones((pts1_2D.shape[0], pts1_2D.shape[1]))[...,None]], axis=-1)
pts2_2D_hom = np.concatenate([pts2_2D,
np.ones((pts2_2D.shape[0], pts2_2D.shape[1]))[...,None]], axis=-1)
pts1_2D_hom = pts1_2D_hom.transpose(0,2,1).copy()
pts2_2D_hom = pts2_2D_hom.transpose(0,2,1).copy()
# solve exactly.
try:
Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom)) # this really is just solving registration problem ?
except:
Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom + np.finfo(float).eps)) # if fails we need a small eps to stabilise.
# Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom)) # this really is just solving registration problem ?
JacMatrix = Tmatrix[:,:2,:2].copy() # take the non jacobian component?
# The error is given as the ratio of the largest to smallest eigenvalue. -> since SVD, hence the singular values are squared.
u, s, v = np.linalg.svd(JacMatrix)
# see http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/13_Parameterization2.pdf to better understand.
# Jac_eigvals = s.copy()
# stretch_factor is gotten from eigenvalues of J^T J
JacMatrix2 = np.matmul(JacMatrix.transpose(0,2,1), JacMatrix)
stretch_eigenvalues, stretch_eigenvectors = np.linalg.eigh(JacMatrix2)
sigma1 = np.sqrt(np.max(stretch_eigenvalues, axis=1)) # this is the ones.
sigma2 = np.sqrt(np.min(stretch_eigenvalues, axis=1))
# sigma1 = np.max(np.abs(s), axis=1)
# sigma2 = np.min(np.abs(s), axis=1)
MIPS = sigma1/sigma2 + sigma2/sigma1
area_MIPS = (sigma1/sigma2 + sigma2/sigma1)*(sigma1*sigma2+1./(sigma1*sigma2))**area_mips_theta
MIPS_plus = sigma1/sigma2 + sigma1*sigma2
areas3D = igl.doublearea(pts1_3D, triangles) / 2.
mean_MIPS = np.nansum(areas3D*MIPS / (float(np.sum(areas3D)))) # area weighted average.
mean_area_MIPS = np.nansum(areas3D*area_MIPS / (float(np.sum(areas3D))))
mean_MIPS_plus = np.nansum(areas3D*MIPS_plus / (float(np.sum(areas3D))))
return (MIPS, area_MIPS, MIPS_plus), (mean_MIPS, mean_area_MIPS, mean_MIPS_plus), (sigma1,sigma2), (stretch_eigenvalues, stretch_eigenvectors)
# def MIPS_cost(pts1_3D, pts2_3D, triangles):
# """
# use the Most isometric parametrization cost.
# https://arxiv.org/pdf/1810.09031.pdf
# """
# import igl
# import numpy as np
# # normalize the pts
# pts1_3D_ = pts1_3D / np.sqrt( np.sum(igl.doublearea(pts1_3D, triangles)/2.) )
# pts2_3D_ = pts2_3D / np.sqrt( np.sum(igl.doublearea(pts2_3D, triangles)/2.) )
# # pts1_3D_ = pts1_3D.copy()
# # pts2_3D_ = pts2_3D.copy()
# # map the 3D triangle to 2D triangle coordinates.
# [U1,UF1,I1] = igl.project_isometrically_to_plane(pts1_3D_, triangles) # V to U.
# [U2,UF2,I2] = igl.project_isometrically_to_plane(pts2_3D_, triangles)
# pts1_2D = U1[UF1]
# pts2_2D = U2[UF2]
# # convert 2D coordinates to homogeneous coordinates in order to solve uniquely.
# # having converted we can now get the jacobian by specifying Y = AX (homogeneous coordinates.)
# pts1_2D_hom = np.concatenate([pts1_2D,
# np.ones((pts1_2D.shape[0], pts1_2D.shape[1]))[...,None]], axis=-1)
# pts2_2D_hom = np.concatenate([pts2_2D,
# np.ones((pts2_2D.shape[0], pts2_2D.shape[1]))[...,None]], axis=-1)
# pts1_2D_hom = pts1_2D_hom.transpose(0,2,1).copy()
# pts2_2D_hom = pts2_2D_hom.transpose(0,2,1).copy()
# # solve exactly.
# Tmatrix = np.matmul(pts2_2D_hom, np.linalg.inv(pts1_2D_hom)) # this really is just solving registration problem ?
# JacMatrix = Tmatrix[:,:2,:2].copy() # take the non jacobian component?
# # The error is given as the ratio of the largest to smallest eigenvalue. -> since SVD, hence the singular values are squared.
# u, s, v = np.linalg.svd(JacMatrix)
# Jac_eigvals = s.copy()
# # stretch_factor is gotten from eigenvalues of J^T J
# JacMatrix2 = np.matmul(JacMatrix.transpose(0,2,1), JacMatrix)
# stretch_eigenvalues, stretch_eigenvectors = np.linalg.eigh(JacMatrix2)
# print(stretch_eigenvalues.shape)
# # sigma1 = np.sqrt(np.max(stretch_eigenvalues, axis=1))
# # sigma2 = np.sqrt(np.min(stretch_eigenvalues, axis=1))
# sigma1 = np.max(np.abs(s), axis=1)
# sigma2 = np.min(np.abs(s), axis=1)
# # stretch_factor = np.sqrt(np.max(np.abs(s), axis=1) / np.min(np.abs(s), axis=1)) # since this was SVD decomposition.
# stretch_factor = np.sqrt(np.max(np.abs(stretch_eigenvalues), axis=1) / np.min(np.abs(stretch_eigenvalues), axis=1)) # since this was SVD decomposition.
# return sigma1/sigma2 + sigma2/sigma1, stretch_factor # this is the MIPS cost... as a balanced cost.
# # return sigma1/sigma2 + sigma2*sigma1, stretch_factor
# # return sigma1*sigma2 + 1./(sigma2*sigma1), stretch_factor
# #### functions for mesh-based morphological operations.
def remove_small_mesh_components_binary(v,f,labels, vertex_labels_bool=True, physical_size=True, minsize=100): # assume by default vertex labels.
r""" Remove small connected components of a binary labelled mesh. Connected components is run and regions with number of vertices/faces or covering an area less than the specified threshold is removed by returning a new binary label array where they have been set to 0
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
labels : (n_vertices,) or (n_faces,) array
the binary labels either specified for the vertex or face. Which is which is set by the parameter ``vertex_labels_bool``.
vertex_labels_bool : bool
if True, process the ``labels`` as associated with vertices or if False, process the ``labels`` as associated with faces.
physical_size : bool
if True, interpret ``minsize`` as the minimum surface area of each connected component. If False, interpret ``minsize`` as the minimum number of vertex/face elements within the connected component
minsize : scalar
if physical_size=True, the minimum surface area of a connected component or if physical_size=False, the minimum number of vertex/face elements within the connected component
Returns
-------
labels_clean : (n_vertices,) or (n_faces,) array
The updated vertex (if vertex_labels_bool=True) or face (if vertex_labels_bool=False) binary label array
"""
import numpy as np
import scipy.stats as spstats
import trimesh
import igl
if vertex_labels_bool:
face_labels = spstats.mode(labels[f], axis=1)[0]
face_labels = np.squeeze(face_labels)
else:
face_labels = labels.copy()
mesh_cc_label = connected_components_mesh(trimesh.Trimesh(vertices=v,
faces=f[face_labels>0],
process=False,
validate=False),
original_face_indices=np.arange(len(f))[face_labels>0])
if physical_size:
mesh_cc_area = [np.nansum(igl.doublearea(v, f[cc])/2.) for cc in mesh_cc_label] # we need to double check this
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_area)) if mesh_cc_area[cc] > minsize]
else:
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_label)) if len(mesh_cc_label[cc]) > minsize] # just by number of faces.!
# rebuild the output vertex/face labels
labels_clean = np.zeros(labels.shape, dtype=np.int32)
if vertex_labels_bool:
for cc in mesh_cc_label:
faces_cc = f[cc]
unique_verts_cc = np.unique(faces_cc.ravel())
labels_clean[unique_verts_cc] = 1
else:
for cc in mesh_cc_label:
labels_clean[cc] = 1
return labels_clean
def remove_small_mesh_components_labels(v,f,labels,
bg_label=0,
vertex_labels_bool=True,
physical_size=True,
minsize=100,
keep_largest_only=True): # assume by default vertex labels.
r""" Remove small connected components of a multi-labelled integer mesh. Connected components is run on each labelled region and disconnected regions with number of vertices/faces or covering an area less than the specified threshold is removed by returning a new multi label array where they have been set to the specified background label
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
labels : (n_vertices,) or (n_faces,) array
the integer labels specified for the vertex or face as determined by the boolean parameter ``vertex_labels_bool``.
bg_label : int
the integer label of background regions
vertex_labels_bool : bool
if True, process the ``labels`` as associated with vertices or if False, process the ``labels`` as associated with faces.
physical_size : bool
if True, interpret ``minsize`` as the minimum surface area of each connected component. If False, interpret ``minsize`` as the minimum number of vertex/face elements within the connected component
minsize : scalar
if physical_size=True, the minimum surface area of a connected component or if physical_size=False, the minimum number of vertex/face elements within the connected component
keep_largest_only : bool
if True, keep only the largest connected region per label of size > minsize. if False, all connected regions per label of size > minsize is kept
Returns
-------
labels_clean : (n_vertices,) or (n_faces,) array
The updated vertex (if vertex_labels_bool=True) or face (if vertex_labels_bool=False) multi label array
"""
import numpy as np
import scipy.stats as spstats
import trimesh
import igl
if vertex_labels_bool:
face_labels = spstats.mode(labels[f], axis=1)[0]
face_labels = np.squeeze(face_labels)
else:
face_labels = labels.copy()
# create a vector to stick output to.
labels_clean = (np.ones(face_labels.shape, dtype=np.int32) * bg_label).astype(np.int32)
uniq_labels = np.setdiff1d(np.unique(labels), bg_label)
for lab in uniq_labels:
# return a binary selector to place the labels.
mesh_cc_label = connected_components_mesh(trimesh.Trimesh(vertices=v,
faces=f[face_labels==lab],
process=False,
validate=False),
original_face_indices=np.arange(len(f))[face_labels==lab])
if physical_size:
mesh_cc_area = [np.nansum(igl.doublearea(v, f[cc])/2.) for cc in mesh_cc_label] # we need to double check this
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_area)) if mesh_cc_area[cc] > minsize]
mesh_cc_area = [mesh_cc_area[cc] for cc in np.arange(len(mesh_cc_area)) if mesh_cc_area[cc] > minsize] # also update this.
else:
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_label)) if len(mesh_cc_label[cc]) > minsize] # just by number of faces.!
mesh_cc_area = [len(cc) for cc in mesh_cc_area]
if keep_largest_only:
if len(mesh_cc_label) > 0:
# print('Region label ', lab, len(mesh_cc_label), len(mesh_cc_area))
labels_clean[mesh_cc_label[np.argmax(mesh_cc_area)]] = lab
else:
for cc in mesh_cc_label: # set all of them!.
labels_clean[cc] = lab
if vertex_labels_bool:
# case to vertex labels
mesh = trimesh.Trimesh(vertices=v,
faces=f,
process=False,
validate=False)
vertex_triangle_adj = trimesh.geometry.vertex_face_indices(len(v),
f,
mesh.faces_sparse)
vertex_triangle_labels = labels_clean[vertex_triangle_adj].astype(np.float16) # cast to a float
vertex_triangle_labels[vertex_triangle_adj==-1] = np.nan # cast to nan.
vertex_triangle_labels = np.squeeze(spstats.mode(vertex_triangle_labels, axis=1, nan_policy='omit')[0].astype(np.int32)) # recast to int.
labels_clean = vertex_triangle_labels.copy()
return labels_clean
def remove_small_mesh_label_holes_binary(v, f, labels, vertex_labels_bool=True, physical_size=True, minsize=100):
r""" Remove small binary holes i.e. small islands of zeros within a region of 1s in a binary-labelled mesh. Connected components is run on 0's and regions with number of vertices/faces or covering an area less than the specified threshold is removed by returning a new binary label array where they have been set to 1
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
labels : (n_vertices,) or (n_faces,) array
the binary labels specified for the vertex or face as determined by the boolean parameter ``vertex_labels_bool``.
vertex_labels_bool : bool
if True, process the ``labels`` as associated with vertices or if False, process the ``labels`` as associated with faces.
physical_size : bool
if True, interpret ``minsize`` as the minimum surface area of each connected component. If False, interpret ``minsize`` as the minimum number of vertex/face elements within the connected component
minsize : scalar
if physical_size=True, the minimum surface area of a connected component or if physical_size=False, the minimum number of vertex/face elements within the connected component
Returns
-------
labels_clean : (n_vertices,) or (n_faces,) array
The updated vertex (if vertex_labels_bool=True) or face (if vertex_labels_bool=False) binary array
"""
import numpy as np
import scipy.stats as spstats
import trimesh
import igl
if vertex_labels_bool:
face_labels = spstats.mode(labels[f], axis=1)[0]
face_labels = np.squeeze(face_labels)
else:
face_labels = labels.copy()
mesh_cc_label = connected_components_mesh(trimesh.Trimesh(vertices=v,
faces=f[face_labels==0], # note the inverse!
process=False,
validate=False),
original_face_indices=np.arange(len(f))[face_labels==0])
if physical_size:
mesh_cc_area = [np.nansum(igl.doublearea(v, f[cc])) for cc in mesh_cc_label]
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_area)) if mesh_cc_area[cc] < minsize and mesh_cc_area[cc]>0]
else:
mesh_cc_label = [mesh_cc_label[cc] for cc in np.arange(len(mesh_cc_label)) if len(mesh_cc_label[cc]) < minsize and len(mesh_cc_label[cc])>1] # just by number of faces.!
# rebuild the output vertex/face labels
labels_clean = labels.copy()
labels_clean = labels_clean.astype(np.int32) #copy the previous labels.
if vertex_labels_bool:
for cc in mesh_cc_label:
faces_cc = f[cc]
unique_verts_cc = np.unique(faces_cc.ravel())
labels_clean[unique_verts_cc] = 1 # flip 0 -> 1
else:
for cc in mesh_cc_label:
labels_clean[cc] = 1
return labels_clean
#### functions for label spreading
def labelspreading_mesh_binary(v,f,y,W=None, niters=10, return_proba=True, thresh=1):
r""" Applies Laplacian 'local weighted' smoothing with a default or specified affinity matrix to diffuse vertex-based binary labels on a 3D triangular mesh
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
y : (n_vertices,) array
the initial binary labels to diffuse
W : (n_vertex, n_vertex) sparse array
if specified, the Laplacian-like affinity matrix used to diffuse binary labels. Defaults to the cotan Laplacian matrix
niters : int
the number of iterations
return_proba : (n_vertices,)
if True, return the diffused probability matrix
thresh : 0-1 scalar
if less than 1, the probability matrix per iteration is binarised by thresholding > thresh. This allows faster diffusion of positive labels, equivalent of an inflation factor
Returns
-------
labels_clean : (n_vertices,) array
The updated vertex binary label array
"""
import scipy.sparse as spsparse
import igl
import numpy as np
if W is None:
W_ = igl.cotmatrix(v, f)
else:
W_ = W.copy()
# normalize.
# DD = 1./W_.sum(axis=-1)
sumW_ = np.array(np.absolute(W_).sum(axis=1))
sumW_ = np.squeeze(sumW_)
DD = np.zeros(len(sumW_))
DD[sumW_>0] = 1./np.sqrt(sumW_[sumW_>0])
DD = np.nan_to_num(DD) # avoid infs.
DD = spsparse.spdiags(np.squeeze(DD), [0], DD.shape[0], DD.shape[0])
W_ = DD.dot(W_) # this is perfect normalization.
init_matrix = y.copy()
for ii in np.arange(niters):
init_matrix = W_.dot(init_matrix)
if thresh<1:
prob_matrix = init_matrix.copy()
init_matrix = init_matrix > thresh
else:
prob_matrix = init_matrix.copy()
if return_proba:
return init_matrix, prob_matrix
else:
return init_matrix
def labelspreading_mesh(v,f, x, y, W=None, niters=10, alpha_prop=.1, return_proba=False, renorm=False, convergence_iter=5):
r""" Applies Label propagation of [1]_ with a default or specified affinity matrix, W to competitively diffuse vertex-based multi-labels on a 3D triangular mesh. Background labels are assumed to be 0
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
x : (N,) array
the vertex indices that have been assigned integer labels > 0
y : (N,) array
the matching assumed sequential integer labels from 1 to n_labels of the specified vertex indices in ``x``
W : (n_vertex, n_vertex) sparse array
if specified, the Laplacian-like affinity matrix used to diffuse binary labels. Defaults to the cotan Laplacian matrix
niters : int
the number of iterations
alpha_prop : 0-1 scalar
clamping factor. A value in (0, 1) that specifies the relative amount that a vertex should adopt the information from its neighbors as opposed to its initial label. alpha=0 means keeping the initial label information; alpha=1 means replacing all initial information.
return_proba : (n_vertices,)
if True, return the diffused probability matrix
renorm : bool
if True, at each iteration assign each vertex to the most probable label with probability = 1.
convergence_iter : int
the number of iterations for which the diffused labels do not change for. After this number of iterations the function will early stop before ``n_iters``, otherwise the propagation occurs for at least ``n_iters``.
Returns
-------
z_label : (n_vertices,) array
The updated vertex multi label array
z : (n_vertices, n_labels+1)
The probabilistic vertex multi label assignment where rowsums = 1
References
----------
.. [1] Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston, Bernhard Schoelkopf. Learning with local and global consistency (2004)
"""
# we do it on vertex.
import igl
import numpy as np
import scipy.sparse as spsparse
n_samples = len(v)
n_classes = int(np.nanmax(y)+1)
init_matrix = np.zeros((n_samples,n_classes)) # one hot encode.
# print(init_matrix.shape)
# this is the prior - labelled.
base_matrix = np.zeros((n_samples, n_classes));
base_matrix[x.astype(np.int), y.astype(np.int)] = 1;
base_matrix = (1.-alpha_prop)*base_matrix # this is the moving average.
if W is None:
W_ = igl.cotmatrix(v, f)
else:
W_ = W.copy()
sumW_ = np.array(np.absolute(W_).sum(axis=1))
sumW_ = np.squeeze(sumW_)
D = np.zeros(len(sumW_))
D[sumW_>0] = 1./np.sqrt(sumW_[sumW_>0])
D = np.nan_to_num(D) # avoid infs.
D = spsparse.spdiags(np.squeeze(D), [0], n_samples, n_samples)
W_ = D.dot(W_.dot(D)) # apply the normalization!.
# print(W_[0].data)
# print(W_[0].data)
W_ = alpha_prop * W_
# init_matrix = base_matrix.copy()
convergence_count = 0
n_comps = np.sum(base_matrix)
# propagate this version is better diffusion with laplacian matrix.
for iter_ii in np.arange(niters): # no convergence...
# base_matrix should act as a clamp!. why is this getting smaller and smaller?
init_matrix = W_.dot(init_matrix) + base_matrix # this is just moving average # why is this not changing? # we should renormalize... # this is weird.
# init_matrix = spsparse.linalg.spsolve(spsparse.identity(base_matrix.shape[0])-W_, init_matrix)
# init_matrix = init_matrix/init_matrix.max() # renormalize.
# init_matrix = (init_matrix-init_matrix.min())/ (init_matrix.max()-init_matrix.min())
# convert to proba
z = np.nansum(init_matrix, axis=1)
z[z==0] += 1 # Avoid division by 0
z = ((init_matrix.T)/z).T
z_label = np.argmax(z, axis=1)
n_comps2 = np.sum(z_label)
# print(n_comps2)
if np.abs(n_comps2 - n_comps) == 0:
convergence_count+=1
if convergence_count == convergence_iter:
break
else:
n_comps = n_comps2
if renorm:
init_matrix = z.copy() # need to renormalize
# # print(init_matrix.min(), init_matrix.max())
init_matrix = np.zeros(init_matrix.shape)
init_matrix[np.arange(len(init_matrix)), z_label] = 1
else:
init_matrix = z.copy()
if return_proba:
return z_label, z
else:
return z_label # this is the new.
# assumes vertex labels
def labelspreading_fill_mesh(v,f, vertex_labels, niters=10, alpha_prop=0., minsize=0, bg_label=0):
r""" Applies Constrained Label propagation of [1]_ with the uniform Laplacian matrix to diffuse vertex-based multi-labels on a 3D triangular mesh to infill small non-labelled background areas within the boundary of individual labelled regions
Parameters
----------
v : (n_vertices,) array
vertices of the triangle mesh
f : (n_faces,) array
faces of the triangle mesh
vertex_labels : (n_vertices,) array
the integer vertex-based multi labels
niters : int
the number of iterations of infilling
alpha_prop : 0-1 scalar
clamping factor. A value in (0, 1) that specifies the relative amount that a vertex should adopt the information from its neighbors as opposed to its initial label. alpha=0 means keeping the initial label information; alpha=1 means replacing all initial information.
minsize : int
the minimum size of a labelled region to infill. Small labelled regions are not infilled as they themselves are assumed to be unstable
bg_label : int
the integer label denoting the background regions
Returns
-------
vertex_labels_final : (n_vertices,) array
The updated vertex multi label array
References
----------
.. [1] Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston, Bernhard Schoelkopf. Learning with local and global consistency (2004)
"""
"""restricts diffusion to the external boundary by disconnecting the boundary loop. from the rest of the mesh with optional designation of size.
"""
import igl
import scipy.stats as spstats
import numpy as np
import trimesh
import scipy.sparse as spsparse
unique_labels = np.setdiff1d(np.unique(vertex_labels), bg_label)
# precompute the adjacency lists.
adj_mesh = igl.adjacency_list(f) # get the master list.
adj_matrix = igl.adjacency_matrix(f).tocsr()
l = adj_matrix.shape[0]
# transfer vertex to face labels.
face_labels = spstats.mode(vertex_labels[f], axis=1)[0] # this could be more efficient using one hot encoding. to do.
face_labels = np.squeeze(face_labels)
# compute separately for each unique label
vertex_labels_final = np.ones_like(vertex_labels) * bg_label # initialise all to background label!.
for unique_lab in unique_labels:
mesh_cc_label = connected_components_mesh(trimesh.Trimesh(vertices=v,
faces=f[face_labels==unique_lab], # connecting only the current lab
process=False, validate=False),
original_face_indices=np.arange(len(face_labels))[face_labels==unique_lab])
# only process a component of minsize
mesh_cc_label = [cc for cc in mesh_cc_label if len(cc) >= minsize]
adj_matrix_label = igl.adjacency_matrix(f).tocsr()
# now we diffuse the labels inside here... ( we need to form the laplacian matrix. )
for cc in mesh_cc_label[:]:
# get the unique verts
unique_verts = np.unique(f[np.squeeze(cc)])
boundary_verts = igl.boundary_loop(f[np.squeeze(cc)])
#### for the unique_verts # maybe we can't diffuse in parallel?
for vv in boundary_verts: # iterate over the boundary only! and disconnect.
adj_v = adj_mesh[vv].copy()
for adj_vv in adj_v:
if adj_vv not in unique_verts:
adj_matrix_label[vv,adj_vv] = 0. # set to 0
adj_matrix_label[adj_vv,vv] = 0.
adj_matrix_label.eliminate_zeros()
# produce the propagation matrix.
Laplacian_adj_matrix = adj_matrix - spsparse.spdiags(np.squeeze(adj_matrix_label.sum(axis=1)), [0], l,l)
Laplacian_adj_matrix = Laplacian_adj_matrix.tocsr()
# print(Laplacian_adj_matrix[0].data)
# # create the label_indices and labels of unique_lab
labels_ind = np.arange(len(vertex_labels))[vertex_labels==unique_lab]
labels_labels = (np.ones(len(labels_ind)) * unique_lab).astype(np.int32)
# diffusion has to occur now diffuse...
prop_label = labelspreading_mesh(v,
f,
x=labels_ind,
y=labels_labels,
W=Laplacian_adj_matrix,
niters=niters,
alpha_prop=alpha_prop,
return_proba=False)
vertex_labels_final[prop_label==unique_lab] = unique_lab
return vertex_labels_final
# implementing some measures of discrepancy between two meshes.
def chamfer_distance_point_cloud(pts1, pts2):
r""" Compute the standard L2 chamfer distance (CD) between two points clouds. For each point in each cloud, CD finds the nearest point in the other point set, and finds the mean L2 distance.
Given two point clouds, :math:`S_1, S_2`, the chamfer distance is defined as
.. math::
\text{CD}(S_1,S_2)=\frac{1}{|S_1|}\sum_{x\in S_1} {\min_{y\in S_2} ||x-y||_2} + \frac{1}{|S_2|}\sum_{x\in S_2} {\min_{y\in S_1} ||x-y||_2}
Parameters
----------
pts1 : (n_vertices_1,3) array
the vertices of point cloud 1. The number of vertices can be different to that of ``pts2``
pts2 : (n_vertices_2,3) array
the vertices of point cloud 2. The number of vertices can be different to that of ``pts1``
Returns
-------
chamfer_dist : scalar
the chamfer distance between the two point clouds
"""
import point_cloud_utils as pcu
import numpy as np
pts1_ = np.array(pts1, order='C')
pts2_ = np.array(pts2, order='C')
chamfer_dist = pcu.chamfer_distance(pts1_.astype(np.float32), pts2_.astype(np.float32))
return chamfer_dist
def hausdorff_distance_point_cloud(pts1, pts2, mode='two-sided', return_index=False):
r""" Compute the Hausdorff distance (H) between two points clouds. The Hausdorff distance is the it is the greatest of all the distances from a point in one point cloud to the closest point in the other point cloud.
The 'two-sided' Hausdorff distance takes the maximum of comparing the 1st point cloud to the 2nd point cloud and the 2nd point cloud to the 1st point cloud
Parameters
----------
pts1 : (n_vertices_1, 3) array
the vertices of point cloud 1. The number of vertices can be different to that of ``pts2``
pts2 : (n_vertices_2, 3) array
the vertices of point cloud 2. The number of vertices can be different to that of ``pts1``
mode : 'one-sided' or 'two-sided'
compute either the one sided with the specified order of pts1 to pts2 or the 'two-sided' which compares both orders and returns the maximum
return_index : bool
if True, return two additional optional outputs that specify the index of a point cloud and the index of its closest neighbor in the other point cloud
Returns
-------
hausdorff_dist : scalar
the chamfer distance between the two point clouds
id_a : (N,) array
the vertex id of the points in pts1 matched with maximum shortest distance to vertex ids ``id_b`` in pts2
id_b : (N,)
the vertex id of the points in pts2 matched with maximum shortest distance to vertex ids ``id_b`` in pts1
"""
import point_cloud_utils as pcu
import numpy as np
if mode == 'one-sided':
# Compute one-sided squared Hausdorff distances
if return_index:
hausdorff_dist, id_a, id_b = pcu.one_sided_hausdorff_distance(np.array(pts1,order='C'), np.array(pts2, order='C'), return_index=True)
else:
hausdorff_dist = pcu.one_sided_hausdorff_distance(np.array(pts1,order='C'), np.array(pts2, order='C'))
# hausdorff_b_to_a = pcu.one_sided_hausdorff_distance(b, a)
if mode == 'two-sided':
# Take a max of the one sided squared distances to get the two sided Hausdorff distance
if return_index:
hausdorff_dist, id_a, id_b = pcu.hausdorff_distance(np.array(pts1,order='C'), np.array(pts2, order='C'), return_index=True)
else:
hausdorff_dist = pcu.hausdorff_distance(np.array(pts1,order='C'), np.array(pts2, order='C'))
if return_index:
return hausdorff_dist, id_a, id_b
else:
return hausdorff_dist
def wasserstein_distance_trimesh_trimesh(trimesh1,trimesh2,n_samples_1=1000,n_samples_2=1000):
r""" Compute the Wasserstein distance between two triangle meshes using the Sinkhorn approximation and point cloud subsampling
The triangle meshes are converted into a weighted point cloud or measure using the normalised triangle area
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
trimesh2 : trimesh.Trimesh
a 3D triangle mesh
n_samples_1 : int
the number of uniformly sampled random vertices from trimesh1
n_samples_2 : int
the number of uniformly sampled random vertices from trimesh2
Returns
-------
sinkhorn_dist : scalar
the approximated wasserstein distance between the two meshes
Notes
-----
https://github.com/fwilliams/point-cloud-utils for sinkhorn computation
"""
# use sampling to bring this down. random sampling.
# https://www.kernel-operations.io/geomloss/_auto_examples/optimal_transport/plot_interpolation_3D.html#sphx-glr-auto-examples-optimal-transport-plot-interpolation-3d-py
# we need to turn the mesh into a measure. i.e. load it with dirac atoms.
import igl
import numpy as np
import trimesh
import point_cloud_utils as pcu
area1 = igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.
area1 = area1/np.nansum(area1)
pts1 = igl.barycenter(trimesh1.vertices,trimesh1.faces)
area2 = igl.doublearea(trimesh2.vertices, trimesh2.faces) / 2.
area2 = area2/np.nansum(area2) # so it sums up to 1.
pts2 = igl.barycenter(trimesh2.vertices,trimesh2.faces)
# subsample.
if n_samples_1 is not None:
select1 = np.random.choice(len(area1), n_samples_1)
area1 = area1[select1].copy() # this is also the weights.
# area1 = area1 / float(np.nansum(area1)) # renormalize. to be a measure.
pts1 = pts1[select1].copy()
if n_samples_2 is not None:
select2 = np.random.choice(len(area2), n_samples_2)
area2 = area2[select2].copy() # this is also the weights.
# area2 = area2 / float(np.nansum(area2)) # renormalize. to be a measure.
pts2 = pts2[select2].copy()
M = pcu.pairwise_distances(pts1,pts2)
P = pcu.sinkhorn(area1.astype(np.float32),
area2.astype(np.float32),
M.astype(np.float32), eps=1e-3,
max_iters=500)
# to get distance we compute the frobenius inner product <M, P>
sinkhorn_dist = np.nansum(M*P)
return sinkhorn_dist
def wasserstein_distance_trimesh_uv(trimesh1,uv2, eps=1e-12, pad=True, uv_to_trimesh=False, n_samples_1=1000, n_samples_2=1000):
r""" Compute the Wasserstein distance between a triangle 3D mesh and a (u,v) image parameterized 3D mesh using the Sinkhorn approximation and point cloud subsampling
The meshes are converted into a weighted point cloud or measure using the normalised areas
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
uv2 : (U,V,3) array
a (u,v) image parameterized 3D surface
eps : scalar
a small constant for numerical stability
pad : bool
if True, uses edge padding to compute the finite differences for evaluating the differential areas of ``uv2``
uv_to_trimesh : bool
if True, convert the (u,v) image parameterized 3D triangle mesh into a 3D triangle mesh before evaluating the difference.
n_samples_1 : int
the number of uniformly sampled random vertices from trimesh1
n_samples_2 : int
the number of uniformly sampled random vertices from trimesh2
Returns
-------
sinkhorn_dist : scalar
the approximated wasserstein distance between the two meshes
Notes
-----
https://github.com/fwilliams/point-cloud-utils for sinkhorn computation
"""
# https://www.kernel-operations.io/geomloss/_auto_examples/optimal_transport/plot_interpolation_3D.html#sphx-glr-auto-examples-optimal-transport-plot-interpolation-3d-py
# we need to turn the mesh into a measure. i.e. load it with dirac atoms.
import igl
import numpy as np
import trimesh
import point_cloud_utils as pcu
if uv_to_trimesh:
uv_vertex_indices_all, uv_triangles = get_uv_grid_tri_connectivity(np.zeros(uv2.shape[:2]))
uv_pos_3D_v = uv2.reshape(-1,3)[uv_vertex_indices_all]
trimesh2 = trimesh.Trimesh(vertices=uv_pos_3D_v, faces=uv_triangles,
process=False, validate=False)
# reduces to the triangle case.
sinkhorn_dist = wasserstein_distance_trimesh_trimesh(trimesh1, trimesh2,
n_samples_1=n_samples_1,
n_samples_2=n_samples_2)
else:
area1 = igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.
area1 = area1/np.nansum(area1)
pts1 = igl.barycenter(trimesh1.vertices,trimesh1.faces)
dS_du, dS_dv = uzip.gradient_uv(uv2, eps=eps, pad=pad) # might be more accurate to convert ...
# area of the original surface.
area2 = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
area2 = area2/np.nansum(area2)
area2 = area2.ravel()
pts2 = uv2.reshape(-1,uv2.shape[-1]).copy() # just make this a point cloud.
# print(pts1.shape, area1.shape)
# print(pts2.shape, area2.shape)
# # subsample.
if n_samples_1 is not None:
select1 = np.random.choice(len(area1), n_samples_1)
area1 = area1[select1].copy() # this is also the weights.
# area1 = area1 / float(np.nansum(area1)) # renormalize. to be a measure.
pts1 = pts1[select1].copy()
if n_samples_2 is not None:
select2 = np.random.choice(len(area2), n_samples_2)
area2 = area2[select2].copy() # this is also the weights.
# area2 = area2 / float(np.nansum(area2)) # renormalize. to be a measure.
pts2 = pts2[select2].copy()
M = pcu.pairwise_distances(pts1,pts2)
P = pcu.sinkhorn(area1.astype(np.float32),
area2.astype(np.float32),
M.astype(np.float32), eps=1e-3)
# to get distance we compute the frobenius inner product <M, P>
sinkhorn_dist = np.nansum(M*P)
# print(area1.sum(), area2.sum())
return sinkhorn_dist
def sliced_wasserstein_distance_trimesh_trimesh(trimesh1,trimesh2,
n_seeds=10,
n_projections=50,
p=1,
mode='max',
seed=None):
r""" Compute the sliced Wasserstein distance approximation between two triangle meshes which gives a proxy of the Wasserstein distance using summed 1D random projections.
This method is advantageous in terms of speed and computational resources for very large meshes.
The triangle meshes are converted into a weighted point cloud or measure using the normalised triangle area
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
trimesh2 : trimesh.Trimesh
a 3D triangle mesh
n_seeds : int
the number of trials to average the distance over. Larger numbers give greater stability
n_projections : int
the number of 1D sliced random projections to sum over
p : int
the order of the Wasserstein distance. 1 is equivalent to the Earth Mover's distance
mode : 'max' or any other string
if mode='max' compute the maximum sliced wasserstein distance see ``ot.max_sliced_wasserstein_distance`` in the Python Optimal Transport library
seed : int
if specified, fix the random seed for reproducibility runs
Returns
-------
sliced_W_dist : scalar
the mean sliced wasserstein distance between the two meshes over `n_seeds` iterations
Notes
-----
https://pythonot.github.io/ for sliced wassersten distance computation
"""
import igl
import numpy as np
import trimesh
import ot
area1 = igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.
area1 = area1/np.nansum(area1)
pts1 = igl.barycenter(trimesh1.vertices,trimesh1.faces)
area2 = igl.doublearea(trimesh2.vertices, trimesh2.faces) / 2.
area2 = area2/np.nansum(area2) # so it sums up to 1.
pts2 = igl.barycenter(trimesh2.vertices,trimesh2.faces)
# subsample.
sliced_W_dist_iters = []
for iter_ii in np.arange(n_seeds):
if mode=='max':
sliced_W_dist = ot.max_sliced_wasserstein_distance(pts1,
pts2,
a=area1,
b=area2,
p=p,
n_projections=n_projections,
seed=seed) # hm...
else:
sliced_W_dist = ot.sliced_wasserstein_distance(pts1,
pts2,
a=area1,
b=area2,
p=p,
n_projections=n_projections,
seed=seed) # hm...
sliced_W_dist_iters.append(sliced_W_dist)
sliced_W_dist = np.nanmean(sliced_W_dist_iters)
return sliced_W_dist
def sliced_wasserstein_distance_trimesh_uv(trimesh1,
uv2,
eps=1e-12,
pad=True,
uv_to_trimesh=False,
n_seeds=10,
n_projections=50,
p=1,
mode='max',
seed=None):
r""" Compute the sliced Wasserstein distance approximation between a triangle mesh and a (u,v) image parameterized 3D mesh which gives a proxy of the Wasserstein distance using summed 1D random projections.
This method is advantageous in terms of speed and computational resources for very large meshes.
The triangle meshes are converted into a weighted point cloud or measure using the normalised triangle area
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
uv2 : (U,V,3) array
a (u,v) image parameterized 3D surface
eps : scalar
a small constant for numerical stability
pad : bool
if True, uses edge padding to compute the finite differences for evaluating the differential areas of ``uv2``
uv_to_trimesh : bool
if True, convert the (u,v) image parameterized 3D triangle mesh into a 3D triangle mesh before evaluating the difference.
n_seeds : int
the number of trials to average the distance over. Larger numbers give greater stability
n_projections : int
the number of 1D sliced random projections to sum over
p : int
the order of the Wasserstein distance. 1 is equivalent to the Earth Mover's distance
mode : 'max' or any other string
if mode='max' compute the maximum sliced wasserstein distance see ``ot.max_sliced_wasserstein_distance`` in the Python Optimal Transport library
seed : int
if specified, fix the random seed for reproducibility runs
Returns
-------
sliced_W_dist : scalar
the mean sliced wasserstein distance between the two meshes over `n_seeds` iterations
Notes
-----
https://pythonot.github.io/ for sliced wassersten distance computation
"""
import igl
import numpy as np
import trimesh
import ot # uses the Python POT library for optimal transport.
if uv_to_trimesh:
uv_vertex_indices_all, uv_triangles = get_uv_grid_tri_connectivity(np.zeros(uv2.shape[:2]))
uv_pos_3D_v = uv2.reshape(-1,3)[uv_vertex_indices_all]
trimesh2 = trimesh.Trimesh(vertices=uv_pos_3D_v, faces=uv_triangles,
process=False, validate=False)
sliced_W_dist = sliced_wasserstein_distance_trimesh_trimesh(trimesh1,trimesh2,
n_seeds=n_seeds,
n_projections=n_projections,
p=p,
seed=seed)
else:
area1 = igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.
area1 = area1/np.nansum(area1)
pts1 = igl.barycenter(trimesh1.vertices,trimesh1.faces)
dS_du, dS_dv = uzip.gradient_uv(uv2, eps=eps, pad=pad) # might be more accurate to convert ...
# area of the original surface.
area2 = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
area2 = area2/np.nansum(area2)
pts2 = uv2.reshape(-1,uv2.shape[-1]).copy() # just make this a point cloud.
area2 = area2.ravel().copy()
# print(pts1.shape, pts2.shape)
# print(area1.shape, area2.shape)
sliced_W_dist_iters = []
for iter_ii in np.arange(n_seeds):
if mode=='max':
sliced_W_dist = ot.max_sliced_wasserstein_distance(pts1,
pts2,
a=area1,
b=area2,
p=p,
n_projections=n_projections,
seed=seed) # hm...
else:
sliced_W_dist = ot.sliced_wasserstein_distance(pts1,
pts2,
a=area1,
b=area2,
p=p,
n_projections=n_projections,
seed=seed) # hm...
sliced_W_dist_iters.append(sliced_W_dist)
sliced_W_dist = np.nanmean(sliced_W_dist_iters)
return sliced_W_dist
def diff_area_trimesh_trimesh(trimesh1, trimesh2):
r""" Difference in total surface area between two triangle meshes
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
trimesh2 : trimesh.Trimesh
a 3D triangle mesh
Returns
-------
diff_area : scalar
the signed difference in the total surface area between mesh 1 and mesh 2
"""
import igl
import numpy as np
area1 = np.nansum(igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.)
area2 = np.nansum(igl.doublearea(trimesh2.vertices, trimesh2.faces) / 2.)
diff_area = area1-area2
return diff_area
def diff_area_trimesh_uv(trimesh1, uv2, eps=1e-12, pad=False, uv_to_trimesh=False):
r""" Difference in total surface area between a triangle mesh and a (u,v) image parameterized 3D mesh
Parameters
----------
trimesh1 : trimesh.Trimesh
a 3D triangle mesh
uv2 : (U,V,3) array
a (u,v) image parameterized 3D surface
eps : scalar
a small constant for numerical stability
pad : bool
if True, uses edge padding to compute the finite differences for evaluating the differential areas of ``uv2``
uv_to_trimesh : bool
if True, convert the (u,v) image parameterized 3D triangle mesh into a 3D triangle mesh before evaluating the difference.
Returns
-------
diff_area : scalar
the signed difference in the total surface area between the triangle mesh and the (u,v) parameterized mesh
"""
import igl
import numpy as np
import trimesh
area1 = np.nansum(igl.doublearea(trimesh1.vertices, trimesh1.faces) / 2.)
if uv_to_trimesh:
uv_vertex_indices_all, uv_triangles = get_uv_grid_tri_connectivity(np.zeros(uv2.shape[:2])) # oh... this is only valid uv unwrap not topography!. -> double check the ushape3D error analyses!.
uv_pos_3D_v = uv2.reshape(-1,3)[uv_vertex_indices_all]
trimesh2 = trimesh.Trimesh(vertices=uv_pos_3D_v, faces=uv_triangles,
process=False, validate=False)
area2 = np.nansum(igl.doublearea(trimesh2.vertices, trimesh2.faces) / 2.)
else:
dS_du, dS_dv = uzip.gradient_uv(uv2, eps=eps, pad=pad) # might be more accurate to convert ...
# area of the original surface.
area2 = np.linalg.norm(np.cross(dS_du,
dS_dv), axis=-1)# # use the cross product
area2 = np.nansum(area2)
# difference in area.
diff_area = np.abs(area1-area2)
return diff_area
| 294,805 | 43.378443 | 411 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Mesh/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Features/features.py
|
from ..Utility_Functions import file_io as fio
import numpy as np
from scipy import signal
class DsiftExtractor:
r"""
The class that does dense sift feature extractor. See https://github.com/Yangqing/dsift-python
Sample Usage:
extractor = DsiftExtractor(gridSpacing,patchSize,[optional params])
feaArr,positions = extractor.process_image(Image)
Reference :
Y. Jia and T. Darrell. "Heavy-tailed Distances for Gradient Based Image Descriptors". NIPS 2011.
Lowe, David G. "Object recognition from local scale-invariant features." Proceedings of the seventh IEEE international conference on computer vision. Vol. 2. Ieee, 1999.
"""
def __init__(self, gridSpacing, patchSize,
nrml_thres = 1.0,\
sigma_edge = 0.8,\
sift_thres = 0.2,
Nangles = 8,
Nbins = 4,
alpha = 9.0):
'''
gridSpacing:
the spacing for sampling dense descriptors
patchSize: int
the size of each sift patch
nrml_thres: scalar
low contrast normalization threshold
sigma_edge: scalar
the standard deviation for the gaussian smoothing before computing the gradient
sift_thres: scalar
sift thresholding (0.2 works well based on Lowe's SIFT paper)
'''
self.Nangles = Nangles
self.Nbins = Nbins
self.alpha = alpha
self.Nsamples = Nbins**2
self.angles = np.array(range(Nangles))*2.0*np.pi/Nangles # the thresholds of the angle histogram [0,2pi]
self.gS = gridSpacing
self.pS = patchSize
self.nrml_thres = nrml_thres
self.sigma = sigma_edge
self.sift_thres = sift_thres
# compute the weight contribution map
sample_res = self.pS / np.double(Nbins) # spatial resolution.
sample_p = np.array(range(self.pS))
sample_ph, sample_pw = np.meshgrid(sample_p,sample_p) # this is 32 x 32 (image squared?)
sample_ph.resize(sample_ph.size)
sample_pw.resize(sample_pw.size)
bincenter = np.array(range(1,Nbins*2,2)) / 2.0 / Nbins * self.pS - 0.5
# print(bincenter)
bincenter_h, bincenter_w = np.meshgrid(bincenter,bincenter)
# print(bincenter_h)
# print(bincenter_w)
bincenter_h.resize((bincenter_h.size,1))
bincenter_w.resize((bincenter_w.size,1))
dist_ph = abs(sample_ph - bincenter_h)
dist_pw = abs(sample_pw - bincenter_w)
weights_h = dist_ph / sample_res
weights_w = dist_pw / sample_res
weights_h = (1-weights_h) * (weights_h <= 1)
weights_w = (1-weights_w) * (weights_w <= 1)
# weights is the contribution of each pixel to the corresponding bin center
self.weights = weights_h * weights_w
def gen_dgauss(self,sigma):
r'''
generates a derivative of Gaussian filter with the same specified :math:`\sigma` in both the X and Y
directions.
'''
fwid = np.int(2*np.ceil(sigma))
G = np.array(range(-fwid,fwid+1))**2
G = G.reshape((G.size,1)) + G
G = np.exp(- G / 2.0 / sigma / sigma)
G /= np.sum(G)
GH,GW = np.gradient(G)
GH *= 2.0/np.sum(np.abs(GH))
GW *= 2.0/np.sum(np.abs(GW))
return GH,GW
def process_image(self, image, positionNormalize = True,\
verbose = True):
'''
processes a single image, return the locations
and the values of detected SIFT features.
image: a M*N image which is a numpy 2D array. If you pass a color image, it will automatically be convertedto a grayscale image.
positionNormalize: whether to normalize the positions to [0,1]. If False, the pixel-based positions of the top-right position of the patches is returned.
Return values:
feaArr: the feature array, each row is a feature
positions: the positions of the features
'''
image = image.astype(np.double)
if image.ndim == 3:
# we do not deal with color images.
image = np.mean(image,axis=2)
# compute the grids
H,W = image.shape
gS = self.gS
pS = self.pS
remH = np.mod(H-pS, gS)
remW = np.mod(W-pS, gS)
offsetH = remH//2
offsetW = remW//2
gridH,gridW = np.meshgrid(range(offsetH,H-pS+1,gS), range(offsetW,W-pS+1,gS))
gridH = gridH.flatten()
gridW = gridW.flatten()
if verbose:
print ('Image: w {}, h {}, gs {}, ps {}, nFea {}'.\
format(W,H,gS,pS,gridH.size))
feaArr = self.calculate_sift_grid(image,gridH,gridW) # this is the heavy lifting.
feaArr = self.normalize_sift(feaArr)
if positionNormalize:
positions = np.vstack((gridH / np.double(H), gridW / np.double(W)))
else:
positions = np.vstack((gridH, gridW))
return feaArr, positions
def calculate_sift_grid(self,image,gridH,gridW):
'''
This function calculates the unnormalized sift features at equidistantly spaced control points in the image as specified by the number in height (gridH) and in width (gridW)
It is called by process_image().
'''
from scipy import signal
H,W = image.shape
Npatches = gridH.size
feaArr = np.zeros((Npatches, self.Nsamples*self.Nangles)) # Nsamples is the number of grid positions of the image being taken. # number of angles
# calculate gradient
GH,GW = self.gen_dgauss(self.sigma) # this is the gradient filter for the image.
IH = signal.convolve2d(image,GH,mode='same')
IW = signal.convolve2d(image,GW,mode='same')
Imag = np.sqrt(IH**2+IW**2)
Itheta = np.arctan2(IH,IW)
Iorient = np.zeros((self.Nangles,H,W))
for i in range(self.Nangles):
Iorient[i] = Imag * np.maximum(np.cos(Itheta - self.angles[i])**self.alpha,0) # either increment the count or not.
#pyplot.imshow(Iorient[i])
#pyplot.show()
for i in range(Npatches):
currFeature = np.zeros((self.Nangles,self.Nsamples))
for j in range(self.Nangles):
# this is the gaussian spatial weights in each cell.
currFeature[j] = np.dot(self.weights,\
Iorient[j,gridH[i]:gridH[i]+self.pS, gridW[i]:gridW[i]+self.pS].flatten())
feaArr[i] = currFeature.flatten()
return feaArr
def normalize_sift(self,feaArr):
'''
This function does sift feature normalization
following David Lowe's definition (normalize length ->
thresholding at 0.2 -> renormalize length)
'''
siftlen = np.sqrt(np.sum(feaArr**2,axis=1)) # this is the L2
hcontrast = (siftlen >= self.nrml_thres)
siftlen[siftlen < self.nrml_thres] = self.nrml_thres
# normalize with contrast thresholding
feaArr /= siftlen.reshape((siftlen.size,1))
# suppress large gradients
feaArr[feaArr>self.sift_thres] = self.sift_thres
# renormalize high-contrast ones
feaArr[hcontrast] /= np.sqrt(np.sum(feaArr[hcontrast]**2,axis=1)).\
reshape((feaArr[hcontrast].shape[0],1))
return feaArr
class SingleSiftExtractor(DsiftExtractor):
'''
The simple wrapper class that does feature extraction, treating
the whole image as a local image patch.
'''
def __init__(self, patchSize,
nrml_thres = 1.0,\
sigma_edge = 0.8,\
sift_thres = 0.2,
Nangles = 8,
Nbins = 4,
alpha = 9.0):
# simply call the super class __init__ with a large gridSpace
DsiftExtractor.__init__(self, patchSize, patchSize, nrml_thres, sigma_edge, sift_thres)
def process_image(self, image):
return DsiftExtractor.process_image(self, image, False, False)[0]
| 6,965 | 34.907216 | 175 |
py
|
u-unwrap3D
|
u-unwrap3D-master/unwrap3D/Features/__init__.py
| 0 | 0 | 0 |
py
|
|
u-unwrap3D
|
u-unwrap3D-master/docs/source/scipyoptdoc.py
|
"""
===========
scipyoptdoc
===========
Proper docstrings for scipy.optimize.minimize et al.
Usage::
.. scipy-optimize:function:: scipy.optimize.minimize
:impl: scipy.optimize._optimize._minimize_nelder_mead
:method: Nelder-Mead
Produces output similar to autodoc, except
- The docstring is obtained from the 'impl' function
- The call signature is mangled so that the default values for method keyword
and options dict are substituted
- 'Parameters' section is replaced by 'Options' section
- See Also link to the actual function documentation is inserted
"""
import os, sys, re, pydoc
import sphinx
import inspect
import collections
import textwrap
import warnings
if sphinx.__version__ < '1.0.1':
raise RuntimeError("Sphinx 1.0.1 or newer is required")
from numpydoc.numpydoc import mangle_docstrings
from docutils.parsers.rst import Directive
from docutils.statemachine import ViewList
from sphinx.domains.python import PythonDomain
from scipy._lib._util import getfullargspec_no_self
def setup(app):
app.add_domain(ScipyOptimizeInterfaceDomain)
return {'parallel_read_safe': True}
def _option_required_str(x):
if not x:
raise ValueError("value is required")
return str(x)
def _import_object(name):
parts = name.split('.')
module_name = '.'.join(parts[:-1])
__import__(module_name)
obj = getattr(sys.modules[module_name], parts[-1])
return obj
class ScipyOptimizeInterfaceDomain(PythonDomain):
name = 'scipy-optimize'
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
self.directives = dict(self.directives)
self.directives['function'] = wrap_mangling_directive(self.directives['function'])
BLURB = """
.. seealso:: For documentation for the rest of the parameters, see `%s`
"""
def wrap_mangling_directive(base_directive):
class directive(base_directive):
def run(self):
env = self.state.document.settings.env
# Interface function
name = self.arguments[0].strip()
obj = _import_object(name)
args, varargs, keywords, defaults = getfullargspec_no_self(obj)[:4]
# Implementation function
impl_name = self.options['impl']
impl_obj = _import_object(impl_name)
impl_args, impl_varargs, impl_keywords, impl_defaults = getfullargspec_no_self(impl_obj)[:4]
# Format signature taking implementation into account
args = list(args)
defaults = list(defaults)
def set_default(arg, value):
j = args.index(arg)
defaults[len(defaults) - (len(args) - j)] = value
def remove_arg(arg):
if arg not in args:
return
j = args.index(arg)
if j < len(args) - len(defaults):
del args[j]
else:
del defaults[len(defaults) - (len(args) - j)]
del args[j]
options = []
for j, opt_name in enumerate(impl_args):
if opt_name in args:
continue
if j >= len(impl_args) - len(impl_defaults):
options.append((opt_name, impl_defaults[len(impl_defaults) - (len(impl_args) - j)]))
else:
options.append((opt_name, None))
set_default('options', dict(options))
if 'method' in self.options and 'method' in args:
set_default('method', self.options['method'].strip())
elif 'solver' in self.options and 'solver' in args:
set_default('solver', self.options['solver'].strip())
special_args = {'fun', 'x0', 'args', 'tol', 'callback', 'method',
'options', 'solver'}
for arg in list(args):
if arg not in impl_args and arg not in special_args:
remove_arg(arg)
# XXX deprecation that we should fix someday using Signature (?)
with warnings.catch_warnings(record=True):
warnings.simplefilter('ignore')
signature = inspect.formatargspec(
args, varargs, keywords, defaults)
# Produce output
self.options['noindex'] = True
self.arguments[0] = name + signature
lines = textwrap.dedent(pydoc.getdoc(impl_obj)).splitlines()
# Change "Options" to "Other Parameters", run numpydoc, reset
new_lines = []
for line in lines:
# Remap Options to the "Other Parameters" numpydoc section
# along with correct heading length
if line.strip() == 'Options':
line = "Other Parameters"
new_lines.extend([line, "-"*len(line)])
continue
new_lines.append(line)
# use impl_name instead of name here to avoid duplicate refs
mangle_docstrings(env.app, 'function', impl_name,
None, None, new_lines)
lines = new_lines
new_lines = []
for line in lines:
if line.strip() == ':Other Parameters:':
new_lines.extend((BLURB % (name,)).splitlines())
new_lines.append('\n')
new_lines.append(':Options:')
else:
new_lines.append(line)
self.content = ViewList(new_lines, self.content.parent)
return base_directive.run(self)
option_spec = dict(base_directive.option_spec)
option_spec['impl'] = _option_required_str
option_spec['method'] = _option_required_str
return directive
| 5,801 | 34.163636 | 104 |
py
|
u-unwrap3D
|
u-unwrap3D-master/docs/source/conf.py
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'u-Unwrap3D'
copyright = '2023, Felix Y. Zhou'
author = 'Felix Y. Zhou'
# The full version, including alpha/beta/rc tags
release = '0.1.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
'sphinx.ext.mathjax',
'numpydoc'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -----------------------------------------------------------------------------
# Coverage checker
# -----------------------------------------------------------------------------
coverage_ignore_functions = r"""
test($|_) (some|all)true bitwise_not cumproduct pkgload
generic\.
""".split()
coverage_c_path = []
coverage_c_regexes = {}
coverage_ignore_c_items = {}
| 2,702 | 31.178571 | 79 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/fc.py
|
"""
This code is from Jin-Hwa Kim, Jaehyun Jun, Byoung-Tak Zhang's repository.
https://github.com/jnhwkim/ban-vqa
"""
from __future__ import print_function
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
class FCNet(nn.Module):
"""Simple class for non-linear fully connect network
"""
def __init__(self, dims, act='ReLU', dropout=0):
super(FCNet, self).__init__()
layers = []
for i in range(len(dims)-2):
in_dim = dims[i]
out_dim = dims[i+1]
if 0 < dropout:
layers.append(nn.Dropout(dropout))
layers.append(weight_norm(nn.Linear(in_dim, out_dim), dim=None))
if ''!=act:
layers.append(getattr(nn, act)())
if 0 < dropout:
layers.append(nn.Dropout(dropout))
layers.append(weight_norm(nn.Linear(dims[-2], dims[-1]), dim=None))
if ''!=act:
layers.append(getattr(nn, act)())
self.main = nn.Sequential(*layers)
def forward(self, x):
return self.main(x)
if __name__ == '__main__':
fc1 = FCNet([10, 20, 10])
print(fc1)
print('============')
fc2 = FCNet([10, 20])
print(fc2)
| 1,212 | 27.880952 | 76 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/main.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa)
"""
import os
import argparse
import torch
from torch.utils.data import DataLoader, ConcatDataset
import dataset_VQA
import base_model
from train import train
import utils
try:
import _pickle as pickle
except:
import pickle
def parse_args():
parser = argparse.ArgumentParser()
# MODIFIABLE MEVF HYPER-PARAMETERS--------------------------------------------------------------------------------
# Model loading/saving
parser.add_argument('--input', type=str, default=None,
help='input file directory for continue training from stop one')
parser.add_argument('--output', type=str, default='saved_models/san_mevf',
help='save file directory')
# Utilities
parser.add_argument('--seed', type=int, default=1204,
help='random seed')
parser.add_argument('--epochs', type=int, default=40,
help='the number of epoches')
parser.add_argument('--lr', default=0.005, type=float, metavar='lr',
help='initial learning rate')
# Gradient accumulation
parser.add_argument('--batch_size', type=int, default=32,
help='batch size')
parser.add_argument('--update_freq', default='1', metavar='N',
help='update parameters every n batches in an epoch')
# Choices of attention models
parser.add_argument('--model', type=str, default='SAN', choices=['BAN', 'SAN'],
help='the model we use')
# Choices of RNN models
parser.add_argument('--rnn', type=str, default='LSTM', choices=['LSTM', 'GRU'],
help='the RNN we use')
# BAN - Bilinear Attention Networks
parser.add_argument('--gamma', type=int, default=2,
help='glimpse in Bilinear Attention Networks')
parser.add_argument('--use_counter', action='store_true', default=False,
help='use counter module')
# SAN - Stacked Attention Networks
parser.add_argument('--num_stacks', default=2, type=int,
help='num of stacks in Stack Attention Networks')
# Utilities - support testing, gpu training or sampling
parser.add_argument('--print_interval', default=20, type=int, metavar='N',
help='print per certain number of steps')
parser.add_argument('--gpu', type=int, default=0,
help='specify index of GPU using for training, to use CPU: -1')
parser.add_argument('--clip_norm', default=.25, type=float, metavar='NORM',
help='clip threshold of gradients')
# Question embedding
parser.add_argument('--question_len', default=12, type=int, metavar='N',
help='maximum length of input question')
parser.add_argument('--tfidf', type=bool, default=True,
help='tfidf word embedding?')
parser.add_argument('--op', type=str, default='c',
help='concatenated 600-D word embedding')
# Joint representation C dimension
parser.add_argument('--num_hid', type=int, default=1024,
help='dim of joint semantic features')
# Activation function + dropout for classification module
parser.add_argument('--activation', type=str, default='relu', choices=['relu'],
help='the activation to use for final classifier')
parser.add_argument('--dropout', default=0.5, type=float, metavar='dropout',
help='dropout of rate of final classifier')
# Train with VQA dataset
parser.add_argument('--use_VQA', action='store_true', default=False,
help='Using TDIUC dataset to train')
parser.add_argument('--VQA_dir', type=str,
help='RAD dir')
# Optimization hyper-parameters
parser.add_argument('--eps_cnn', default=1e-5, type=float, metavar='eps_cnn',
help='eps - batch norm for cnn')
parser.add_argument('--momentum_cnn', default=0.05, type=float, metavar='momentum_cnn',
help='momentum - batch norm for cnn')
# input visual feature dimension
parser.add_argument('--feat_dim', default=32, type=int,
help='visual feature dim')
parser.add_argument('--img_size', default=84, type=int,
help='image size')
# Auto-encoder component hyper-parameters
parser.add_argument('--autoencoder', action='store_true', default=False,
help='End to end model?')
parser.add_argument('--ae_model_path', type=str, default='pretrained_ae.pth',
help='the maml_model_path we use')
parser.add_argument('--ae_alpha', default=0.001, type=float, metavar='ae_alpha',
help='ae_alpha')
# MAML component hyper-parameters
parser.add_argument('--maml', action='store_true', default=False,
help='End to end model?')
parser.add_argument('--maml_model_path', type=str, default='pretrained_maml_pytorch_other_optimization_5shot_newmethod.pth',
help='the maml_model_path we use')
parser.add_argument('--maml_nums', type=str, default='0,1,2,3,4,5',
help='the numbers of maml models')
# Return args
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
args.maml_nums = args.maml_nums.split(',')
# create output directory and log file
utils.create_dir(args.output)
logger = utils.Logger(os.path.join(args.output, 'log.txt'))
logger.write(args.__repr__())
# Set GPU device
device = torch.device("cuda:" + str(args.gpu) if args.gpu >= 0 else "cpu")
args.device = device
# Fixed ramdom seed
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
# Load dictionary and RAD training dataset
if args.use_VQA:
dictionary = dataset_VQA.Dictionary.load_from_file(os.path.join(args.VQA_dir, 'dictionary.pkl'))
train_dset = dataset_VQA.VQAFeatureDataset('train', args, dictionary, question_len=args.question_len)
# load validation set (RAD doesnt have validation set)
if 'RAD' not in args.VQA_dir:
val_dset = dataset_VQA.VQAFeatureDataset('val', args, dictionary, question_len=args.question_len)
batch_size = args.batch_size
# Create VQA model
constructor = 'build_%s' % args.model
model = getattr(base_model, constructor)(train_dset, args)
optim = None
epoch = 0
# load snapshot
if args.input is not None:
print('loading %s' % args.input)
model_data = torch.load(args.input)
model.load_state_dict(model_data.get('model_state', model_data))
model.to(device)
optim = torch.optim.Adamax(filter(lambda p: p.requires_grad, model.parameters()))
optim.load_state_dict(model_data.get('optimizer_state', model_data))
epoch = model_data['epoch'] + 1
# create training dataloader
train_loader = DataLoader(train_dset, batch_size, shuffle=True, num_workers=0, collate_fn=utils.trim_collate, pin_memory=True)
if 'RAD' not in args.VQA_dir:
eval_loader = DataLoader(val_dset, batch_size, shuffle=False, num_workers=0, collate_fn=utils.trim_collate, pin_memory=True)
else:
eval_loader = None
# training phase
train(args, model, train_loader, eval_loader, args.epochs, args.output, optim, epoch)
| 7,710 | 45.173653 | 132 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/base_model.py
|
"""
This code is developed based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
import torch
import torch.nn as nn
from attention import BiAttention, StackedAttention
from language_model import WordEmbedding, QuestionEmbedding
from classifier import SimpleClassifier
from fc import FCNet
from bc import BCNet
from counting import Counter
from utils import tfidf_loading
from simple_cnn import SimpleCNN, SimpleCNN32
from learner import MAML
from auto_encoder import Auto_Encoder_Model
# Create BAN model
class BAN_Model(nn.Module):
def __init__(self, dataset, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, args, maml_v_emb, ae_v_emb):
super(BAN_Model, self).__init__()
self.args = args
self.dataset = dataset
self.op = args.op
self.glimpse = args.gamma
self.w_emb = w_emb
self.q_emb = q_emb
self.v_att = v_att
self.b_net = nn.ModuleList(b_net)
self.q_prj = nn.ModuleList(q_prj)
if counter is not None: # if do not use counter
self.c_prj = nn.ModuleList(c_prj)
self.classifier = classifier
self.counter = counter
self.drop = nn.Dropout(.5)
self.tanh = nn.Tanh()
if args.maml:
# init multiple maml models
if len(self.args.maml_nums) > 1:
self.maml_v_emb = nn.ModuleList(model for model in maml_v_emb)
else:
self.maml_v_emb = maml_v_emb
if args.autoencoder:
self.ae_v_emb = ae_v_emb
self.convert = nn.Linear(16384, args.feat_dim)
def forward(self, v, q):
"""Forward
v: [batch, num_objs, obj_dim]
b: [batch, num_objs, b_dim]
q: [batch_size, seq_length]
return: logits, not probs
"""
# get visual feature
if self.args.maml: # get maml feature
# compute multiple maml embeddings and concatenate them
if len(self.args.maml_nums) > 1:
maml_v_emb = self.maml_v_emb[0](v[0]).unsqueeze(1)
for j in range(1, len(self.maml_v_emb)):
maml_v_emb_temp = self.maml_v_emb[j](v[0]).unsqueeze(1)
maml_v_emb = torch.cat((maml_v_emb, maml_v_emb_temp), 2)
else:
maml_v_emb = self.maml_v_emb(v[0]).unsqueeze(1)
v_emb = maml_v_emb
if self.args.autoencoder: # get dae feature
encoder = self.ae_v_emb.forward_pass(v[1])
decoder = self.ae_v_emb.reconstruct_pass(encoder)
ae_v_emb = encoder.view(encoder.shape[0], -1)
ae_v_emb = self.convert(ae_v_emb).unsqueeze(1)
v_emb = ae_v_emb
if self.args.maml and self.args.autoencoder: # concatenate maml feature with dae feature
v_emb = torch.cat((maml_v_emb, ae_v_emb), 2)
# get lextual feature
w_emb = self.w_emb(q)
q_emb = self.q_emb.forward_all(w_emb) # [batch, q_len, q_dim]
# Attention
b_emb = [0] * self.glimpse
att, logits = self.v_att.forward_all(v_emb, q_emb) # b x g x v x q
for g in range(self.glimpse):
b_emb[g] = self.b_net[g].forward_with_weights(v_emb, q_emb, att[:,g,:,:]) # b x l x h
atten, _ = logits[:,g,:,:].max(2)
q_emb = self.q_prj[g](b_emb[g].unsqueeze(1)) + q_emb
if self.args.autoencoder:
return q_emb.sum(1), decoder
return q_emb.sum(1)
def classify(self, input_feats):
return self.classifier(input_feats)
# Create SAN model
class SAN_Model(nn.Module):
def __init__(self, w_emb, q_emb, v_att, classifier, args, maml_v_emb, ae_v_emb):
super(SAN_Model, self).__init__()
self.args = args
self.w_emb = w_emb
self.q_emb = q_emb
self.v_att = v_att
self.classifier = classifier
if args.maml:
# init multiple maml models
if len(self.args.maml_nums) > 1:
self.maml_v_emb = nn.ModuleList(model for model in maml_v_emb)
else:
self.maml_v_emb = maml_v_emb
if args.autoencoder:
self.ae_v_emb = ae_v_emb
self.convert = nn.Linear(16384, args.feat_dim)
def forward(self, v, q):
"""Forward
v: [batch, num_objs, obj_dim]
b: [batch, num_objs, b_dim]
q: [batch_size, seq_length]
return: logits, not probs
"""
# get visual feature
if self.args.maml: # get maml feature
# compute multiple maml embeddings and concatenate them
if len(self.args.maml_nums) > 1:
maml_v_emb = self.maml_v_emb[0](v[0]).unsqueeze(1)
for j in range(1, len(self.maml_v_emb)):
maml_v_emb_temp = self.maml_v_emb[j](v[0]).unsqueeze(1)
maml_v_emb = torch.cat((maml_v_emb, maml_v_emb_temp), 2)
else:
maml_v_emb = self.maml_v_emb(v[0]).unsqueeze(1)
v_emb = maml_v_emb
if self.args.autoencoder: # get dae feature
encoder = self.ae_v_emb.forward_pass(v[1])
decoder = self.ae_v_emb.reconstruct_pass(encoder)
ae_v_emb = encoder.view(encoder.shape[0], -1)
ae_v_emb = self.convert(ae_v_emb).unsqueeze(1)
v_emb = ae_v_emb
if self.args.maml and self.args.autoencoder: # concatenate maml feature with dae feature
v_emb = torch.cat((maml_v_emb, ae_v_emb), 2)
# get textual feature
w_emb = self.w_emb(q)
q_emb = self.q_emb(w_emb) # [batch, q_dim], return final hidden state
# Attention
att = self.v_att(v_emb, q_emb)
if self.args.autoencoder:
return att, decoder
return att
def classify(self, input_feats):
return self.classifier(input_feats)
# Build BAN model
def build_BAN(dataset, args, priotize_using_counter=False):
# init word embedding module, question embedding module, and Attention network
w_emb = WordEmbedding(dataset.dictionary.ntoken, 300, .0, args.op)
q_emb = QuestionEmbedding(300 if 'c' not in args.op else 600, args.num_hid, 1, False, .0, args.rnn)
v_att = BiAttention(dataset.v_dim, args.num_hid, args.num_hid, args.gamma)
# build and load pre-trained MAML model(s)
if args.maml:
# load multiple pre-trained maml models(s)
if len(args.maml_nums) > 1:
maml_v_emb = []
for model_t in args.maml_nums:
weight_path = args.VQA_dir + '/maml/' + 't%s_'%(model_t) + args.maml_model_path
print('load initial weights MAML from: %s' % (weight_path))
# maml_v_emb = SimpleCNN32(weight_path, args.eps_cnn, args.momentum_cnn)
maml_v_emb_temp = MAML(args.VQA_dir)
maml_v_emb_temp.load_state_dict(torch.load(weight_path))
maml_v_emb.append(maml_v_emb_temp)
else:
weight_path = args.VQA_dir + '/maml/' + 't%s_' % (args.maml_nums[0]) + args.maml_model_path
print('load initial weights MAML from: %s' % (weight_path))
# maml_v_emb = SimpleCNN32(weight_path, args.eps_cnn, args.momentum_cnn)
maml_v_emb = MAML(args.VQA_dir)
maml_v_emb.load_state_dict(torch.load(weight_path))
# build and load pre-trained Auto-encoder model
if args.autoencoder:
ae_v_emb = Auto_Encoder_Model()
weight_path = args.VQA_dir + '/' + args.ae_model_path
print('load initial weights DAE from: %s'%(weight_path))
ae_v_emb.load_state_dict(torch.load(weight_path))
# Loading tfidf weighted embedding
if hasattr(args, 'tfidf'):
w_emb = tfidf_loading(args.tfidf, w_emb, args)
# Optional module: counter for BAN
use_counter = args.use_counter if priotize_using_counter is None else priotize_using_counter
if use_counter or priotize_using_counter:
objects = 10 # minimum number of boxes
if use_counter or priotize_using_counter:
counter = Counter(objects)
else:
counter = None
# init BAN residual network
b_net = []
q_prj = []
c_prj = []
for i in range(args.gamma):
b_net.append(BCNet(dataset.v_dim, args.num_hid, args.num_hid, None, k=1))
q_prj.append(FCNet([args.num_hid, args.num_hid], '', .2))
if use_counter or priotize_using_counter:
c_prj.append(FCNet([objects + 1, args.num_hid], 'ReLU', .0))
# init classifier
classifier = SimpleClassifier(
args.num_hid, args.num_hid * 2, dataset.num_ans_candidates, args)
# contruct VQA model and return
if args.maml and args.autoencoder:
return BAN_Model(dataset, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, args, maml_v_emb,
ae_v_emb)
elif args.maml:
return BAN_Model(dataset, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, args, maml_v_emb,
None)
elif args.autoencoder:
return BAN_Model(dataset, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, args, None,
ae_v_emb)
return BAN_Model(dataset, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, args, None, None)
# Build SAN model
def build_SAN(dataset, args):
# init word embedding module, question embedding module, and Attention network
w_emb = WordEmbedding(dataset.dictionary.ntoken, 300, 0.0, args.op)
q_emb = QuestionEmbedding(300 if 'c' not in args.op else 600, args.num_hid, 1, False, 0.0, args.rnn)
v_att = StackedAttention(args.num_stacks, dataset.v_dim, args.num_hid, args.num_hid, dataset.num_ans_candidates,
args.dropout)
# build and load pre-trained MAML model(s)
if args.maml:
# load multiple pre-trained maml models(s)
if len(args.maml_nums) > 1:
maml_v_emb = []
for model_t in args.maml_nums:
weight_path = args.VQA_dir + '/maml/' + 't%s_'%(model_t) + args.maml_model_path
print('load initial weights MAML from: %s' % (weight_path))
# maml_v_emb = SimpleCNN32(weight_path, args.eps_cnn, args.momentum_cnn)
maml_v_emb_temp = MAML(args.VQA_dir)
maml_v_emb_temp.load_state_dict(torch.load(weight_path))
maml_v_emb.append(maml_v_emb_temp)
else:
weight_path = args.VQA_dir + '/maml/' + 't%s_' % (args.maml_nums[0]) + args.maml_model_path
print('load initial weights MAML from: %s' % (weight_path))
maml_v_emb = MAML(args.VQA_dir)
maml_v_emb.load_state_dict(torch.load(weight_path))
# build and load pre-trained Auto-encoder model
if args.autoencoder:
ae_v_emb = Auto_Encoder_Model()
weight_path = args.VQA_dir + '/' + args.ae_model_path
print('load initial weights DAE from: %s'%(weight_path))
ae_v_emb.load_state_dict(torch.load(weight_path))
# Loading tfidf weighted embedding
if hasattr(args, 'tfidf'):
w_emb = tfidf_loading(args.tfidf, w_emb, args)
# init classifier
classifier = SimpleClassifier(
args.num_hid, 2 * args.num_hid, dataset.num_ans_candidates, args)
# contruct VQA model and return
if args.maml and args.autoencoder:
return SAN_Model(w_emb, q_emb, v_att, classifier, args, maml_v_emb, ae_v_emb)
elif args.maml:
return SAN_Model(w_emb, q_emb, v_att, classifier, args, maml_v_emb, None)
elif args.autoencoder:
return SAN_Model(w_emb, q_emb, v_att, classifier, args, None, ae_v_emb)
return SAN_Model(w_emb, q_emb, v_att, classifier, args, None, None)
| 11,762 | 44.949219 | 141 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/test.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
import argparse
import torch
from torch.utils.data import DataLoader
import dataset_VQA
import base_model
import utils
import pandas as pd
import os
import json
answer_types = ['CLOSED', 'OPEN', 'ALL']
quesntion_types = ['COUNT', 'COLOR', 'ORGAN', 'PRES', 'PLANE', 'MODALITY', 'POS', 'ABN', 'SIZE', 'OTHER', 'ATTRIB']
def compute_score_with_logits(logits, labels):
logits = torch.max(logits, 1)[1].data # argmax
one_hots = torch.zeros(*labels.size()).to(logits.device)
one_hots.scatter_(1, logits.view(-1, 1), 1)
scores = (one_hots * labels)
return scores
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--ensemble', type=bool, default=False,
help='ensemble flag. If True, generate a logit file which is used in the ensemble part')
# MODIFIABLE MEVF HYPER-PARAMETERS--------------------------------------------------------------------------------
# Model loading/saving
parser.add_argument('--split', type=str, default='test')
parser.add_argument('--input', type=str, default='saved_models/SAN_MEVF',
help='input file directory for loading a model')
parser.add_argument('--output', type=str, default='results',
help='output file directory for saving VQA answer prediction file')
# Utilities
parser.add_argument('--epoch', type=str, default=19,
help='the best epoch')
# Gradient accumulation
parser.add_argument('--batch_size', type=int, default=1,
help='batch size')
# Choices of Attention models
parser.add_argument('--model', type=str, default='SAN', choices=['BAN', 'SAN'],
help='the model we use')
# Choices of RNN models
parser.add_argument('--rnn', type=str, default='LSTM', choices=['LSTM', 'GRU'],
help='the RNN we use')
# BAN - Bilinear Attention Networks
parser.add_argument('--gamma', type=int, default=2,
help='glimpse in Bilinear Attention Networks')
parser.add_argument('--use_counter', action='store_true', default=False,
help='use counter module')
# SAN - Stacked Attention Networks
parser.add_argument('--num_stacks', default=2, type=int,
help='num of stacks in Stack Attention Networks')
# Utilities - gpu
parser.add_argument('--gpu', type=int, default=0,
help='specify index of GPU using for training, to use CPU: -1')
# Question embedding
parser.add_argument('--op', type=str, default='c',
help='concatenated 600-D word embedding')
# Joint representation C dimension
parser.add_argument('--num_hid', type=int, default=1024,
help='dim of joint semantic features')
# Activation function + dropout for classification module
parser.add_argument('--activation', type=str, default='relu', choices=['relu'],
help='the activation to use for final classifier')
parser.add_argument('--dropout', default=0.5, type=float, metavar='dropout',
help='dropout of rate of final classifier')
# Train with RAD
parser.add_argument('--use_VQA', action='store_true', default=False,
help='Using TDIUC dataset to train')
parser.add_argument('--VQA_dir', type=str,
help='RAD dir')
# Optimization hyper-parameters
parser.add_argument('--eps_cnn', default=1e-5, type=float, metavar='eps_cnn',
help='eps - batch norm for cnn')
parser.add_argument('--momentum_cnn', default=0.05, type=float, metavar='momentum_cnn',
help='momentum - batch norm for cnn')
# input visual feature dimension
parser.add_argument('--feat_dim', default=32, type=int,
help='visual feature dim')
parser.add_argument('--img_size', default=256, type=int,
help='image size')
# Auto-encoder component hyper-parameters
parser.add_argument('--autoencoder', action='store_true', default=False,
help='End to end model?')
parser.add_argument('--ae_model_path', type=str, default='pretrained_ae.pth',
help='the maml_model_path we use')
# MAML component hyper-parameters
parser.add_argument('--maml', action='store_true', default=False,
help='End to end model?')
parser.add_argument('--maml_model_path', type=str, default='pretrained_maml_pytorch_other_optimization_5shot_newmethod.pth',
help='the maml_model_path we use')
parser.add_argument('--maml_nums', type=str, default='0,1,2,3,4,5',
help='the numbers of maml models')
# Return args
args = parser.parse_args()
return args
# Load questions
def get_question(q, dataloader):
q = q.squeeze(0)
str = []
dictionary = dataloader.dataset.dictionary
for i in range(q.size(0)):
str.append(dictionary.idx2word[q[i]] if q[i] < len(dictionary.idx2word) else '_')
return ' '.join(str)
# Load answers
def get_answer(p, dataloader):
_m, idx = p.max(1)
return dataloader.dataset.label2ans[idx.item()]
# Logit computation (for train, test or evaluate)
def get_result_pathVQA(model, dataloader, device, args):
ans_types = ['other', 'yes/no', 'all']
keys = ['correct', 'total', 'score']
result = dict((i, dict((j, 0.0) for j in keys)) for i in ans_types)
answers_list = []
with torch.no_grad():
import time
t = time.time()
total_time = 0.0
for v, q, a, ans_type, q_type, _ in iter(dataloader):
if args.maml:
v[0] = v[0].reshape(v[0].shape[0], 3, args.img_size, args.img_size)
if args.autoencoder:
v[1] = v[1].reshape(v[1].shape[0], 128, 128).unsqueeze(1)
v[0] = v[0].to(device)
v[1] = v[1].to(device)
q = q.to(device)
a = a.to(device)
# inference and get logit
if args.autoencoder:
features, _ = model(v, q)
else:
features = model(v, q)
preds = model.classifier(features)
final_preds = preds
batch_score = compute_score_with_logits(final_preds, a.data).sum()
answer = {}
answer['answer_type'] = ans_type[0]
answer['predict'] = get_answer(final_preds, dataloader)
answer['ref'] = get_answer(a, dataloader)
answers_list.append(answer)
# Compute accuracy for each type answer
if ans_type[0] == "yes/no":
result[ans_type[0]]['correct'] += float(batch_score)
result[ans_type[0]]['total'] += 1
else:
result['other']['correct'] += float(batch_score)
result['other']['total'] += 1
result['all']['correct'] += float(batch_score)
result['all']['total'] += 1
total_time += time.time() - t
t = time.time()
print('time <s/sample>: ', total_time/result['all']['total'])
result['yes/no']['score'] = result['yes/no']['correct'] / result['yes/no']['total']
result['other']['score'] = result['other']['correct'] / result['other']['total']
result['all']['score'] = result['all']['correct'] / result['all']['total']
return result, answers_list
def get_result_RAD(model, dataloader, device, args):
keys = ['count', 'real', 'true', 'real_percent', 'score', 'score_percent']
question_types_result = dict((i, dict((j, dict((k, 0.0) for k in keys)) for j in quesntion_types)) for i in answer_types)
result = dict((i, dict((j, 0.0) for j in keys)) for i in answer_types)
with torch.no_grad():
for v, q, a, ans_type, q_types, p_type in iter(dataloader):
if p_type[0] != "freeform":
continue
if args.maml:
v[0] = v[0].reshape(v[0].shape[0], 84, 84).unsqueeze(1)
# v[0] = v[0].transpose(1, 3)
if args.autoencoder:
v[1] = v[1].reshape(v[1].shape[0], 128, 128).unsqueeze(1)
v[0] = v[0].to(device)
v[1] = v[1].to(device)
q = q.to(device)
a = a.to(device)
# inference and get logit
if args.autoencoder:
features, _ = model(v, q)
else:
features = model(v, q)
preds = model.classifier(features)
final_preds = preds
batch_score = compute_score_with_logits(final_preds, a.data).sum()
# Compute accuracy for each type answer
result[ans_type[0]]['count'] += 1.0
result[ans_type[0]]['true'] += float(batch_score)
result[ans_type[0]]['real'] += float(a.sum())
result['ALL']['count'] += 1.0
result['ALL']['true'] += float(batch_score)
result['ALL']['real'] += float(a.sum())
q_types = q_types[0].split(", ")
for i in q_types:
question_types_result[ans_type[0]][i]['count'] += 1.0
question_types_result[ans_type[0]][i]['true'] += float(batch_score)
question_types_result[ans_type[0]][i]['real'] += float(a.sum())
question_types_result['ALL'][i]['count'] += 1.0
question_types_result['ALL'][i]['true'] += float(batch_score)
question_types_result['ALL'][i]['real'] += float(a.sum())
for i in answer_types:
result[i]['score'] = result[i]['true']/result[i]['count']
result[i]['score_percent'] = round(result[i]['score']*100,1)
for j in quesntion_types:
if question_types_result[i][j]['count'] != 0.0:
question_types_result[i][j]['score'] = question_types_result[i][j]['true'] / question_types_result[i][j]['count']
question_types_result[i][j]['score_percent'] = round(question_types_result[i][j]['score']*100, 1)
if question_types_result[i][j]['real'] != 0.0:
question_types_result[i][j]['real_percent'] = round(question_types_result[i][j]['real']/question_types_result[i][j]['count']*100.0, 1)
return result, question_types_result
# Test phase
if __name__ == '__main__':
args = parse_args()
args.maml_nums = args.maml_nums.split(',')
print(args)
torch.backends.cudnn.benchmark = True
args.device = torch.device("cuda:" + str(args.gpu) if args.gpu >= 0 else "cpu")
# Check if evaluating on TDIUC dataset or VQA dataset
if args.use_VQA:
dictionary = dataset_VQA.Dictionary.load_from_file(os.path.join(args.VQA_dir, 'dictionary.pkl'))
eval_dset = dataset_VQA.VQAFeatureDataset(args.split, args, dictionary)
batch_size = args.batch_size
constructor = 'build_%s' % args.model
model = getattr(base_model, constructor)(eval_dset, args)
print(model)
eval_loader = DataLoader(eval_dset, batch_size, shuffle=False, num_workers=0, pin_memory=True, collate_fn=utils.trim_collate)
def save_questiontype_results(outfile_path, quesntion_types_result):
for i in quesntion_types_result:
pd.DataFrame(quesntion_types_result[i]).transpose().to_csv(outfile_path + '/question_type_' + i + '.csv')
# Testing process
def process(args, model, eval_loader):
model_path = args.input + '/model_epoch%s.pth' % args.epoch
print('loading %s' % model_path)
model_data = torch.load(model_path)
# Comment because do not use multi gpu
# model = nn.DataParallel(model)
model = model.to(args.device)
model.load_state_dict(model_data.get('model_state', model_data))
model.train(False)
if not os.path.exists(args.output):
os.makedirs(args.output)
if args.use_VQA:
if 'RAD' in args.VQA_dir:
result, answers_list = get_result_RAD(model, eval_loader, args.device, args)
else:
result, answers_list = get_result_pathVQA(model, eval_loader, args.device, args)
outfile_path = args.output + '/' + args.input.split('/')[1]
outfile = outfile_path + '/results_epoch%s.json' % args.epoch
if not os.path.exists(os.path.dirname(outfile)):
os.makedirs(os.path.dirname(outfile))
print(result)
json.dump(result, open(outfile, 'w'), indent=4)
json.dump(answers_list, open(outfile_path + '/answer_list.json', 'w'), indent=4)
return
process(args, model, eval_loader)
| 12,886 | 45.189964 | 154 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/evaluation_script.py
|
from utils import *
import math
import json
def bleu(candidate, references, n, weights):
pn = []
bp = brevity_penalty(candidate, references)
for i in range(n):
pn.append(modified_precision(candidate, references, i + 1))
if len(weights) > len(pn):
tmp_weights = []
for i in range(len(pn)):
tmp_weights.append(weights[i])
bleu_result = calculate_bleu(tmp_weights, pn, n, bp)
print("(warning: the length of weights is bigger than n)")
return bleu_result
elif len(weights) < len(pn):
tmp_weights = []
for i in range(len(pn)):
tmp_weights.append(0)
for i in range(len(weights)):
tmp_weights[i] = weights[i]
bleu_result = calculate_bleu(tmp_weights, pn, n, bp)
print("(warning: the length of weights is smaller than n)")
return bleu_result
else:
bleu_result = calculate_bleu(weights, pn, n, bp)
return bleu_result
# BLEU
def calculate_bleu(weights, pn, n, bp):
sum_wlogp = 0
for i in range(n):
if pn[i] != 0:
sum_wlogp += float(weights[i]) * math.log(pn[i])
bleu_result = bp * math.exp(sum_wlogp)
return bleu_result
# Exact match
def calculate_exactmatch(candidate, reference):
candidate_words = split_sentence(candidate, 1)
reference_words = split_sentence(reference, 1)
count = 0
total = 0
for word in reference_words:
if word in candidate_words:
count += 1
for word in candidate_words:
total += candidate_words[word]
if total == 0:
return "0 (warning: length of candidate's words is 0)"
else:
return count / total
# F1
def calculate_f1score(candidate, reference):
candidate_words = split_sentence(candidate, 1)
reference_words = split_sentence(reference, 1)
word_set = set()
for word in candidate_words:
word_set.add(word)
for word in reference_words:
word_set.add(word)
tp = 0
fp = 0
fn = 0
for word in word_set:
if word in candidate_words and word in reference_words:
tp += candidate_words[word]
elif word in candidate_words and word not in reference_words:
fp += candidate_words[word]
elif word not in candidate_words and word in reference_words:
fn += reference_words[word]
if len(candidate_words) == 0:
return "0 (warning: length of candidate's words is 0)"
elif len(reference_words) == 0:
return 0
else:
precision = tp / (tp + fp)
recall = tp / (tp + fn)
if tp == 0:
return 0
else:
return 2 * precision * recall / (precision + recall)
if __name__ == "__main__":
n = 4
weights = [0.25, 0.25, 0.25, 0.25]
answer_file = "results/BAN_maml_256/answer_list.json"
answer_list = json.load(open(answer_file, 'r'))
BLEU = [0.0, 0.0, 0.0]
f1_score = 0.0
count = 0
for i in answer_list:
if i['answer_type'] != "yes/no":
count+=1
BLEU[0]+=bleu(i['predict'], [i['ref']], 1, weights)
BLEU[1]+=bleu(i['predict'], [i['ref']], 2, weights)
BLEU[2] += bleu(i['predict'], [i['ref']], 3, weights)
f1_score += calculate_f1score(i['predict'], i['ref'])
BLEU = BLEU / count
print(BLEU)
f1_score = f1_score / count
print(f1_score)
| 3,415 | 29.774775 | 69 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/dataset_VQA.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
from __future__ import print_function
import os
import json
import _pickle as cPickle
import numpy as np
import utils
import torch
from language_model import WordEmbedding
from torch.utils.data import Dataset
import itertools
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=FutureWarning)
COUNTING_ONLY = False
# Following Trott et al. (ICLR 2018)
# Interpretable Counting for Visual Question Answering
def is_howmany(q, a, label2ans):
if 'how many' in q.lower() or \
('number of' in q.lower() and 'number of the' not in q.lower()) or \
'amount of' in q.lower() or \
'count of' in q.lower():
if a is None or answer_filter(a, label2ans):
return True
else:
return False
else:
return False
def answer_filter(answers, label2ans, max_num=10):
for ans in answers['labels']:
if label2ans[ans].isdigit() and max_num >= int(label2ans[ans]):
return True
return False
class Dictionary(object):
def __init__(self, word2idx=None, idx2word=None):
if word2idx is None:
word2idx = {}
if idx2word is None:
idx2word = []
self.word2idx = word2idx
self.idx2word = idx2word
@property
def ntoken(self):
return len(self.word2idx)
@property
def padding_idx(self):
return len(self.word2idx)
def tokenize(self, sentence, add_word):
sentence = sentence.lower()
if "? -yes/no" in sentence:
sentence = sentence.replace("? -yes/no", "")
if "? -open" in sentence:
sentence = sentence.replace("? -open", "")
if "? - open" in sentence:
sentence = sentence.replace("? - open", "")
sentence = sentence.replace(',', '').replace('?', '').replace('\'s', ' \'s').replace('...', '').replace('x ray', 'x-ray').replace('.', '')
words = sentence.split()
tokens = []
if add_word:
for w in words:
tokens.append(self.add_word(w))
else:
for w in words:
# if a word is not in dictionary, it will be replaced with the last word of dictionary.
tokens.append(self.word2idx.get(w, self.padding_idx-1))
return tokens
def dump_to_file(self, path):
cPickle.dump([self.word2idx, self.idx2word], open(path, 'wb'))
print('dictionary dumped to %s' % path)
@classmethod
def load_from_file(cls, path):
print('loading dictionary from %s' % path)
word2idx, idx2word = cPickle.load(open(path, 'rb'))
d = cls(word2idx, idx2word)
return d
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
return self.word2idx[word]
def __len__(self):
return len(self.idx2word)
def _create_entry(img, data, answer):
if None!=answer:
answer.pop('image_name')
answer.pop('qid')
entry = {
'qid' : data['qid'],
'image_name' : data['image_name'],
'image' : img,
'question' : data['question'],
'answer' : answer,
'answer_type' : data['answer_type'],
'question_type': data['question_type'],
'phrase_type' : data['phrase_type'] if 'phrase_type' in data.keys() else -1
}
return entry
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError:
return False
return True
def _load_dataset(dataroot, name, img_id2val, label2ans):
"""Load entries
img_id2val: dict {img_id -> val} val can be used to retrieve image or features
dataroot: root path of dataset
name: 'train', 'val', 'test'
"""
data_path = os.path.join(dataroot, name + 'set.json')
samples = json.load(open(data_path))
samples = sorted(samples, key=lambda x: x['qid'])
answer_path = os.path.join(dataroot, 'cache', '%s_target.pkl' % name)
answers = cPickle.load(open(answer_path, 'rb'))
answers = sorted(answers, key=lambda x: x['qid'])
utils.assert_eq(len(samples), len(answers))
entries = []
for sample, answer in zip(samples, answers):
utils.assert_eq(sample['qid'], answer['qid'])
utils.assert_eq(sample['image_name'], answer['image_name'])
img_id = sample['image_name']
if not COUNTING_ONLY or is_howmany(sample['question'], answer, label2ans):
entries.append(_create_entry(img_id2val[img_id], sample, answer))
return entries
class VQAFeatureDataset(Dataset):
def __init__(self, name, args, dictionary, dataroot='data', question_len=12):
super(VQAFeatureDataset, self).__init__()
self.args = args
assert name in ['train', 'val', 'test']
dataroot = args.VQA_dir
ans2label_path = os.path.join(dataroot, 'cache', 'trainval_ans2label.pkl')
label2ans_path = os.path.join(dataroot, 'cache', 'trainval_label2ans.pkl')
self.ans2label = cPickle.load(open(ans2label_path, 'rb'))
self.label2ans = cPickle.load(open(label2ans_path, 'rb'))
self.num_ans_candidates = len(self.ans2label)
# End get the number of answer type class
self.dictionary = dictionary
# TODO: load img_id2idx
self.img_id2idx = json.load(open(os.path.join(dataroot, 'imgid2idx.json')))
self.entries = _load_dataset(dataroot, name, self.img_id2idx, self.label2ans)
# load image data for MAML module
if args.maml:
# TODO: load images
images_path = os.path.join(dataroot, 'pytorch_images'+ str(args.img_size) + '.pkl')
print('loading MAML image data from file: '+ images_path)
self.maml_images_data = cPickle.load(open(images_path, 'rb'))
# load image data for Auto-encoder module
if args.autoencoder:
# TODO: load images
if 'RAD' in self.args.VQA_dir:
images_path = os.path.join(dataroot, 'images128x128.pkl')
else:
images_path = os.path.join(dataroot, 'pytorch_images128_ae.pkl')
print('loading DAE image data from file: '+ images_path)
self.ae_images_data = cPickle.load(open(images_path, 'rb'))
# tokenization
self.tokenize(question_len)
self.tensorize()
if args.autoencoder and args.maml:
self.v_dim = args.feat_dim * len(args.maml_nums) + args.feat_dim
elif args.autoencoder:
self.v_dim = args.feat_dim
elif args.maml:
self.v_dim = args.feat_dim * len(args.maml_nums)
def tokenize(self, max_length=12):
"""Tokenizes the questions.
This will add q_token in each entry of the dataset.
-1 represent nil, and should be treated as padding_idx in embedding
"""
for entry in self.entries:
tokens = self.dictionary.tokenize(entry['question'], False)
tokens = tokens[:max_length]
if len(tokens) < max_length:
# Note here we pad in front of the sentence
padding = [self.dictionary.padding_idx] * (max_length - len(tokens))
tokens = tokens + padding
utils.assert_eq(len(tokens), max_length)
entry['q_token'] = tokens
def tensorize(self):
if self.args.maml:
# self.maml_images_data = torch.from_numpy(self.maml_images_data)
self.maml_images_data = torch.stack(self.maml_images_data)
self.maml_images_data = self.maml_images_data.type('torch.FloatTensor')
if self.args.autoencoder:
if 'RAD' in self.args.VQA_dir:
self.ae_images_data = torch.from_numpy(self.ae_images_data)
else:
self.ae_images_data = torch.stack(self.ae_images_data)
self.ae_images_data = self.ae_images_data.type('torch.FloatTensor')
for entry in self.entries:
question = torch.from_numpy(np.array(entry['q_token']))
entry['q_token'] = question
answer = entry['answer']
if None!=answer:
labels = np.array(answer['labels'])
scores = np.array(answer['scores'], dtype=np.float32)
if len(labels):
labels = torch.from_numpy(labels)
scores = torch.from_numpy(scores)
entry['answer']['labels'] = labels
entry['answer']['scores'] = scores
else:
entry['answer']['labels'] = None
entry['answer']['scores'] = None
def __getitem__(self, index):
entry = self.entries[index]
question = entry['q_token']
answer = entry['answer']
answer_type = entry['answer_type']
question_type = entry['question_type']
image_data = [0, 0]
if self.args.maml:
if 'RAD' in self.args.VQA_dir:
maml_images_data = self.maml_images_data[entry['image']].reshape(self.args.img_size * self.args.img_size)
else:
maml_images_data = self.maml_images_data[entry['image']].reshape(3 * self.args.img_size * self.args.img_size)
image_data[0] = maml_images_data
if self.args.autoencoder:
ae_images_data = self.ae_images_data[entry['image']].reshape(128*128)
image_data[1] = ae_images_data
if None!=answer:
labels = answer['labels']
scores = answer['scores']
target = torch.zeros(self.num_ans_candidates)
if labels is not None:
target.scatter_(0, labels, scores)
return image_data, question, target, answer_type, question_type, entry['phrase_type']
# return image_data, question, target, answer_type, question_type, [0]
else:
return image_data, question, answer_type, question_type
def __len__(self):
return len(self.entries)
def tfidf_from_questions(names, args, dictionary, dataroot='data', target=['rad']):
inds = [[], []] # rows, cols for uncoalesce sparse matrix
df = dict()
N = len(dictionary)
if args.use_VQA:
dataroot = args.VQA_dir
def populate(inds, df, text):
tokens = dictionary.tokenize(text, True)
for t in tokens:
df[t] = df.get(t, 0) + 1
combin = list(itertools.combinations(tokens, 2))
for c in combin:
if c[0] < N:
inds[0].append(c[0]); inds[1].append(c[1])
if c[1] < N:
inds[0].append(c[1]); inds[1].append(c[0])
if 'rad' in target:
for name in names:
assert name in ['train', 'val', 'test']
question_path = os.path.join(dataroot, name + 'set.json')
questions = json.load(open(question_path))
for question in questions:
populate(inds, df, question['question'])
# TF-IDF
vals = [1] * len(inds[1])
for idx, col in enumerate(inds[1]):
assert df[col] >= 1, 'document frequency should be greater than zero!'
vals[col] /= df[col]
# Make stochastic matrix
def normalize(inds, vals):
z = dict()
for row, val in zip(inds[0], vals):
z[row] = z.get(row, 0) + val
for idx, row in enumerate(inds[0]):
vals[idx] /= z[row]
return vals
vals = normalize(inds, vals)
tfidf = torch.sparse.FloatTensor(torch.LongTensor(inds), torch.FloatTensor(vals))
tfidf = tfidf.coalesce()
# Latent word embeddings
emb_dim = 300
glove_file = os.path.join(dataroot, 'glove', 'glove.6B.%dd.txt' % emb_dim)
weights, word2emb = utils.create_glove_embedding_init(dictionary.idx2word[N:], glove_file)
print('tf-idf stochastic matrix (%d x %d) is generated.' % (tfidf.size(0), tfidf.size(1)))
return tfidf, weights
if __name__=='__main__':
# dictionary = Dictionary.load_from_file('data_RAD/dictionary.pkl')
# tfidf, weights = tfidf_from_questions(['train'], None, dictionary)
# w_emb = WordEmbedding(dictionary.ntoken, 300, .0, 'c')
# w_emb.init_embedding(os.path.join('data_RAD', 'glove6b_init_300d.npy'), tfidf, weights)
# with open('data_RAD/embed_tfidf_weights.pkl', 'wb') as f:
# torch.save(w_emb, f)
# print("Saving embedding with tfidf and weights successfully")
dictionary = Dictionary.load_from_file('data_RAD/dictionary.pkl')
w_emb = WordEmbedding(dictionary.ntoken, 300, .0, 'c')
with open('data_RAD/embed_tfidf_weights.pkl', 'rb') as f:
w_emb = torch.load(f)
print("Load embedding with tfidf and weights successfully")
| 12,877 | 38.024242 | 146 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/learner.py
|
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
class MAML(nn.Module):
"""
Meta Learner
"""
def __init__(self, dataset_dir):
"""
:param args:
"""
super(MAML, self).__init__()
if 'RAD' in dataset_dir:
config = [
('conv2d', [64, 1, 3, 3, 2, 0]),
('relu', [True]),
('bn', [64]),
('conv2d', [64, 64, 3, 3, 2, 0]),
('relu', [True]),
('bn', [64]),
('conv2d', [64, 64, 3, 3, 2, 0]),
('relu', [True]),
('bn', [64]),
('conv2d', [64, 64, 2, 2, 1, 0]),
('relu', [True]),
('bn', [64]),
('flatten', []),
('linear', [3 + 1, 64*8*8])
]
else:
config = [
('conv2d', [32, 3, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 1, 0]),
('flatten', []),
('linear', [5 + 1, 32 * 5 * 5])
]
self.net = Learner(config)
self.frezze_final_layer()
def frezze_final_layer(self):
self.net.vars[16].requires_grad = False
self.net.vars[17].requires_grad = False
def forward(self, x):
return self.net.forward(x)
class Learner(nn.Module):
"""
"""
def __init__(self, config):
"""
:param config: network config file, type:list of (string, list)
"""
super(Learner, self).__init__()
self.config = config
# this dict contains all tensors needed to be optimized
self.vars = nn.ParameterList()
# running_mean and running_var
self.vars_bn = nn.ParameterList()
for i, (name, param) in enumerate(self.config):
if name is 'conv2d':
# [ch_out, ch_in, kernelsz, kernelsz]
w = nn.Parameter(torch.ones(*param[:4]))
# gain=1 according to cbfin's implementation
torch.nn.init.kaiming_normal_(w)
self.vars.append(w)
# [ch_out]
self.vars.append(nn.Parameter(torch.zeros(param[0])))
elif name is 'convt2d':
# [ch_in, ch_out, kernelsz, kernelsz, stride, padding]
w = nn.Parameter(torch.ones(*param[:4]))
# gain=1 according to cbfin's implementation
torch.nn.init.kaiming_normal_(w)
self.vars.append(w)
# [ch_in, ch_out]
self.vars.append(nn.Parameter(torch.zeros(param[1])))
elif name is 'linear':
# [ch_out, ch_in]
w = nn.Parameter(torch.ones(*param))
# gain=1 according to cbfinn's implementation
torch.nn.init.kaiming_normal_(w)
self.vars.append(w)
# [ch_out]
self.vars.append(nn.Parameter(torch.zeros(param[0])))
elif name is 'bn':
# [ch_out]
w = nn.Parameter(torch.ones(param[0]))
self.vars.append(w)
# [ch_out]
self.vars.append(nn.Parameter(torch.zeros(param[0])))
# must set requires_grad=False
running_mean = nn.Parameter(torch.zeros(param[0]), requires_grad=False)
running_var = nn.Parameter(torch.ones(param[0]), requires_grad=False)
self.vars_bn.extend([running_mean, running_var])
elif name in ['tanh', 'relu', 'upsample', 'avg_pool2d', 'max_pool2d',
'flatten', 'reshape', 'leakyrelu', 'sigmoid']:
continue
else:
raise NotImplementedError
def extra_repr(self):
info = ''
for name, param in self.config:
if name is 'conv2d':
tmp = 'conv2d:(ch_in:%d, ch_out:%d, k:%dx%d, stride:%d, padding:%d)'\
%(param[1], param[0], param[2], param[3], param[4], param[5],)
info += tmp + '\n'
elif name is 'convt2d':
tmp = 'convTranspose2d:(ch_in:%d, ch_out:%d, k:%dx%d, stride:%d, padding:%d)'\
%(param[0], param[1], param[2], param[3], param[4], param[5],)
info += tmp + '\n'
elif name is 'linear':
tmp = 'linear:(in:%d, out:%d)'%(param[1], param[0])
info += tmp + '\n'
elif name is 'leakyrelu':
tmp = 'leakyrelu:(slope:%f)'%(param[0])
info += tmp + '\n'
elif name is 'avg_pool2d':
tmp = 'avg_pool2d:(k:%d, stride:%d, padding:%d)'%(param[0], param[1], param[2])
info += tmp + '\n'
elif name is 'max_pool2d':
tmp = 'max_pool2d:(k:%d, stride:%d, padding:%d)'%(param[0], param[1], param[2])
info += tmp + '\n'
elif name in ['flatten', 'tanh', 'relu', 'upsample', 'reshape', 'sigmoid', 'use_logits', 'bn']:
tmp = name + ':' + str(tuple(param))
info += tmp + '\n'
else:
raise NotImplementedError
return info
def forward(self, x, vars=None, bn_training=True):
"""
This function can be called by finetunning, however, in finetunning, we dont wish to update
running_mean/running_var. Thought weights/bias of bn is updated, it has been separated by fast_weights.
Indeed, to not update running_mean/running_var, we need set update_bn_statistics=False
but weight/bias will be updated and not dirty initial theta parameters via fast_weiths.
:param x: [b, 1, 28, 28]
:param vars:
:param bn_training: set False to not update
:return: x, loss, likelihood, kld
"""
if vars is None:
vars = self.vars
idx = 0
bn_idx = 0
for name, param in self.config[:-1]:
if name is 'conv2d':
w, b = vars[idx], vars[idx + 1]
# remember to keep synchrozied of forward_encoder and forward_decoder!
x = F.conv2d(x, w, b, stride=param[4], padding=param[5])
idx += 2
# print(name, param, '\tout:', x.shape)
elif name is 'convt2d':
w, b = vars[idx], vars[idx + 1]
# remember to keep synchrozied of forward_encoder and forward_decoder!
x = F.conv_transpose2d(x, w, b, stride=param[4], padding=param[5])
idx += 2
# print(name, param, '\tout:', x.shape)
elif name is 'linear':
w, b = vars[idx], vars[idx + 1]
x = F.linear(x, w, b)
idx += 2
# print('forward:', idx, x.norm().item())
elif name is 'bn':
w, b = vars[idx], vars[idx + 1]
running_mean, running_var = self.vars_bn[bn_idx], self.vars_bn[bn_idx+1]
x = F.batch_norm(x, running_mean, running_var, weight=w, bias=b, training=bn_training)
idx += 2
bn_idx += 2
elif name is 'flatten':
# print(x.shape)
x = x.view(x.size(0), self.config[0][1][0], -1)
elif name is 'reshape':
# [b, 8] => [b, 2, 2, 2]
x = x.view(x.size(0), *param)
elif name is 'relu':
x = F.relu(x, inplace=param[0])
elif name is 'leakyrelu':
x = F.leaky_relu(x, negative_slope=param[0], inplace=param[1])
elif name is 'tanh':
x = F.tanh(x)
elif name is 'sigmoid':
x = torch.sigmoid(x)
elif name is 'upsample':
x = F.upsample_nearest(x, scale_factor=param[0])
elif name is 'max_pool2d':
x = F.max_pool2d(x, param[0], param[1], param[2])
elif name is 'avg_pool2d':
x = F.avg_pool2d(x, param[0], param[1], param[2])
else:
raise NotImplementedError
# make sure variable is used properly
# assert idx == len(vars)
assert bn_idx == len(self.vars_bn)
return torch.mean(x, 2)
def zero_grad(self, vars=None):
"""
:param vars:
:return:
"""
with torch.no_grad():
if vars is None:
for p in self.vars:
if p.grad is not None:
p.grad.zero_()
else:
for p in vars:
if p.grad is not None:
p.grad.zero_()
def parameters(self):
"""
override this function since initial parameters will return with a generator.
:return:
"""
return self.vars
| 9,463 | 34.051852 | 111 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/counting.py
|
"""
Learning to Count Objects in Natural Images for Visual Question Answering
Yan Zhang, Jonathon Hare, Adam Prügel-Bennett
ICLR 2018
This code is from Yan Zhang's repository.
https://github.com/Cyanogenoid/vqa-counting/blob/master/vqa-v2/counting.py
MIT License
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
class Counter(nn.Module):
""" Counting module as proposed in [1].
Count the number of objects from a set of bounding boxes and a set of scores for each bounding box.
This produces (self.objects + 1) number of count features.
[1]: Yan Zhang, Jonathon Hare, Adam Prügel-Bennett: Learning to Count Objects in Natural Images for Visual Question Answering.
https://openreview.net/forum?id=B12Js_yRb
"""
def __init__(self, objects, already_sigmoided=False):
super().__init__()
self.objects = objects
self.already_sigmoided = already_sigmoided
self.f = nn.ModuleList([PiecewiseLin(16) for _ in range(8)])
self.count_activation = None
def forward(self, boxes, attention):
""" Forward propagation of attention weights and bounding boxes to produce count features.
`boxes` has to be a tensor of shape (n, 4, m) with the 4 channels containing the x and y coordinates of the top left corner and the x and y coordinates of the bottom right corner in this order.
`attention` has to be a tensor of shape (n, m). Each value should be in [0, 1] if already_sigmoided is set to True, but there are no restrictions if already_sigmoided is set to False. This value should be close to 1 if the corresponding boundign box is relevant and close to 0 if it is not.
n is the batch size, m is the number of bounding boxes per image.
"""
# only care about the highest scoring object proposals
# the ones with low score will have a low impact on the count anyway
boxes, attention = self.filter_most_important(self.objects, boxes, attention)
# normalise the attention weights to be in [0, 1]
if not self.already_sigmoided:
attention = torch.sigmoid(attention)
relevancy = self.outer_product(attention)
distance = 1 - self.iou(boxes, boxes)
# intra-object dedup
score = self.f[0](relevancy) * self.f[1](distance)
# inter-object dedup
dedup_score = self.f[3](relevancy) * self.f[4](distance)
dedup_per_entry, dedup_per_row = self.deduplicate(dedup_score, attention)
score = score / dedup_per_entry
# aggregate the score
# can skip putting this on the diagonal since we're just summing over it anyway
correction = self.f[0](attention * attention) / dedup_per_row
score = score.sum(dim=2).sum(dim=1, keepdim=True) + correction.sum(dim=1, keepdim=True)
score = (score + 1e-20).sqrt()
one_hot = self.to_one_hot(score)
att_conf = (self.f[5](attention) - 0.5).abs()
dist_conf = (self.f[6](distance) - 0.5).abs()
conf = self.f[7](att_conf.mean(dim=1, keepdim=True) + dist_conf.mean(dim=2).mean(dim=1, keepdim=True))
return one_hot * conf
def deduplicate(self, dedup_score, att):
# using outer-diffs
att_diff = self.outer_diff(att)
score_diff = self.outer_diff(dedup_score)
sim = self.f[2](1 - score_diff).prod(dim=1) * self.f[2](1 - att_diff)
# similarity for each row
row_sims = sim.sum(dim=2)
# similarity for each entry
all_sims = self.outer_product(row_sims)
return all_sims, row_sims
def to_one_hot(self, scores):
""" Turn a bunch of non-negative scalar values into a one-hot encoding.
E.g. with self.objects = 3, 0 -> [1 0 0 0], 2.75 -> [0 0 0.25 0.75].
"""
# sanity check, I don't think this ever does anything (it certainly shouldn't)
scores = scores.clamp(min=0, max=self.objects)
# compute only on the support
i = scores.long().data
f = scores.frac()
# target_l is the one-hot if the score is rounded down
# target_r is the one-hot if the score is rounded up
target_l = scores.data.new(i.size(0), self.objects + 1).fill_(0)
target_r = scores.data.new(i.size(0), self.objects + 1).fill_(0)
target_l.scatter_(dim=1, index=i.clamp(max=self.objects), value=1)
target_r.scatter_(dim=1, index=(i + 1).clamp(max=self.objects), value=1)
# interpolate between these with the fractional part of the score
return (1 - f) * Variable(target_l) + f * Variable(target_r)
def filter_most_important(self, n, boxes, attention):
""" Only keep top-n object proposals, scored by attention weight """
attention, idx = attention.topk(n, dim=1, sorted=False)
idx = idx.unsqueeze(dim=1).expand(boxes.size(0), boxes.size(1), idx.size(1))
boxes = boxes.gather(2, idx)
return boxes, attention
def outer(self, x):
size = tuple(x.size()) + (x.size()[-1],)
a = x.unsqueeze(dim=-1).expand(*size)
b = x.unsqueeze(dim=-2).expand(*size)
return a, b
def outer_product(self, x):
# Y_ij = x_i * x_j
a, b = self.outer(x)
return a * b
def outer_diff(self, x):
# like outer products, except taking the absolute difference instead
# Y_ij = | x_i - x_j |
a, b = self.outer(x)
return (a - b).abs()
def iou(self, a, b):
# this is just the usual way to IoU from bounding boxes
inter = self.intersection(a, b)
area_a = self.area(a).unsqueeze(2).expand_as(inter)
area_b = self.area(b).unsqueeze(1).expand_as(inter)
return inter / (area_a + area_b - inter + 1e-12)
def area(self, box):
x = (box[:, 2, :] - box[:, 0, :]).clamp(min=0)
y = (box[:, 3, :] - box[:, 1, :]).clamp(min=0)
return x * y
def intersection(self, a, b):
size = (a.size(0), 2, a.size(2), b.size(2))
min_point = torch.max(
a[:, :2, :].unsqueeze(dim=3).expand(*size),
b[:, :2, :].unsqueeze(dim=2).expand(*size),
)
max_point = torch.min(
a[:, 2:, :].unsqueeze(dim=3).expand(*size),
b[:, 2:, :].unsqueeze(dim=2).expand(*size),
)
inter = (max_point - min_point).clamp(min=0)
area = inter[:, 0, :, :] * inter[:, 1, :, :]
return area
class PiecewiseLin(nn.Module):
def __init__(self, n):
super().__init__()
self.n = n
self.weight = nn.Parameter(torch.ones(n + 1))
# the first weight here is always 0 with a 0 gradient
self.weight.data[0] = 0
def forward(self, x):
# all weights are positive -> function is monotonically increasing
w = self.weight.abs()
# make weights sum to one -> f(1) = 1
w = w / w.sum()
w = w.view([self.n + 1] + [1] * x.dim())
# keep cumulative sum for O(1) time complexity
csum = w.cumsum(dim=0)
csum = csum.expand((self.n + 1,) + tuple(x.size()))
w = w.expand_as(csum)
# figure out which part of the function the input lies on
y = self.n * x.unsqueeze(0)
idx = Variable(y.long().data)
f = y.frac()
# contribution of the linear parts left of the input
x = csum.gather(0, idx.clamp(max=self.n))
# contribution within the linear segment the input falls into
x = x + f * w.gather(0, (idx + 1).clamp(max=self.n))
return x.squeeze(0)
| 7,535 | 42.310345 | 298 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/utils.py
|
"""
This code is extended from Hengyuan Hu's repository.
https://github.com/hengyuan-hu/bottom-up-attention-vqa
"""
from __future__ import print_function
import errno
import os
import re
import collections
import numpy as np
import operator
import functools
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch._six import string_classes
from torch.utils.data.dataloader import default_collate
import math
import time
import dataset_VQA
EPS = 1e-7
numpy_type_map = {
'float64': torch.DoubleTensor,
'float32': torch.FloatTensor,
'float16': torch.HalfTensor,
'int64': torch.LongTensor,
'int32': torch.IntTensor,
'int16': torch.ShortTensor,
'int8': torch.CharTensor,
'uint8': torch.ByteTensor,
}
def assert_eq(real, expected):
assert real == expected, '%s (true) vs %s (expected)' % (real, expected)
def assert_array_eq(real, expected):
assert (np.abs(real-expected) < EPS).all(), \
'%s (true) vs %s (expected)' % (real, expected)
def load_folder(folder, suffix):
imgs = []
for f in sorted(os.listdir(folder)):
if f.endswith(suffix):
imgs.append(os.path.join(folder, f))
return imgs
def load_imageid(folder):
images = load_folder(folder, 'jpg')
img_ids = set()
for img in images:
img_id = int(img.split('/')[-1].split('.')[0].split('_')[-1])
img_ids.add(img_id)
return img_ids
def pil_loader(path):
with open(path, 'rb') as f:
with Image.open(f) as img:
return img.convert('RGB')
def weights_init(m):
"""custom weights initialization."""
cname = m.__class__
if cname == nn.Linear or cname == nn.Conv2d or cname == nn.ConvTranspose2d:
m.weight.data.normal_(0.0, 0.02)
elif cname == nn.BatchNorm2d:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
else:
print('%s is not initialized.' % cname)
def init_net(net, net_file):
if net_file:
net.load_state_dict(torch.load(net_file))
else:
net.apply(weights_init)
def create_dir(path):
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
def print_model(model, logger):
print(model)
nParams = 0
for w in model.parameters():
nParams += functools.reduce(operator.mul, w.size(), 1)
if logger:
logger.write('nParams=\t'+str(nParams))
def save_model(path, model, epoch, optimizer=None):
model_dict = {
'epoch': epoch,
'model_state': model.state_dict()
}
if optimizer is not None:
model_dict['optimizer_state'] = optimizer.state_dict()
torch.save(model_dict, path)
# Select the indices given by `lengths` in the second dimension
# As a result, # of dimensions is shrinked by one
# @param pad(Tensor)
# @param len(list[int])
def rho_select(pad, lengths):
# Index of the last output for each sequence.
idx_ = (lengths-1).view(-1,1).expand(pad.size(0), pad.size(2)).unsqueeze(1)
extracted = pad.gather(1, idx_).squeeze(1)
return extracted
def trim_collate(batch):
"Puts each data field into a tensor with outer dimension batch size"
_use_shared_memory = True
error_msg = "batch must contain tensors, numbers, dicts or lists; found {}"
elem_type = type(batch[0])
if torch.is_tensor(batch[0]):
out = None
if 1 < batch[0].dim(): # image features
max_num_boxes = max([x.size(0) for x in batch])
if _use_shared_memory:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = len(batch) * max_num_boxes * batch[0].size(-1)
storage = batch[0].storage()._new_shared(numel)
out = batch[0].new(storage)
# warning: F.pad returns Variable!
return torch.stack([F.pad(x, (0,0,0,max_num_boxes-x.size(0))).data for x in batch], 0, out=out)
else:
if _use_shared_memory:
# If we're in a background process, concatenate directly into a
# shared memory tensor to avoid an extra copy
numel = sum([x.numel() for x in batch])
storage = batch[0].storage()._new_shared(numel)
out = batch[0].new(storage)
return torch.stack(batch, 0, out=out)
elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \
and elem_type.__name__ != 'string_':
elem = batch[0]
if elem_type.__name__ == 'ndarray':
# array of string classes and object
if re.search('[SaUO]', elem.dtype.str) is not None:
raise TypeError(error_msg.format(elem.dtype))
return torch.stack([torch.from_numpy(b) for b in batch], 0)
if elem.shape == (): # scalars
py_type = float if elem.dtype.name.startswith('float') else int
return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))
elif isinstance(batch[0], int):
return torch.LongTensor(batch)
elif isinstance(batch[0], float):
return torch.DoubleTensor(batch)
elif isinstance(batch[0], string_classes):
return batch
elif isinstance(batch[0], collections.Mapping):
return {key: default_collate([d[key] for d in batch]) for key in batch[0]}
elif isinstance(batch[0], collections.Sequence):
transposed = zip(*batch)
return [trim_collate(samples) for samples in transposed]
raise TypeError((error_msg.format(type(batch[0]))))
class Logger(object):
def __init__(self, output_name):
dirname = os.path.dirname(output_name)
if not os.path.exists(dirname):
os.mkdir(dirname)
self.log_file = open(output_name, 'w')
self.infos = {}
def append(self, key, val):
vals = self.infos.setdefault(key, [])
vals.append(val)
def log(self, extra_msg=''):
msgs = [extra_msg]
for key, vals in self.infos.iteritems():
msgs.append('%s %.6f' % (key, np.mean(vals)))
msg = '\n'.join(msgs)
self.log_file.write(msg + '\n')
self.log_file.flush()
self.infos = {}
return msg
def write(self, msg):
self.log_file.write(msg + '\n')
self.log_file.flush()
print(msg)
def create_glove_embedding_init(idx2word, glove_file):
word2emb = {}
# glove_file = glove_file if args.use_TDIUC else os.path.join(args.TDIUC_dir, 'glove', glove_file.split('/')[-1])
with open(glove_file, 'r', encoding='utf-8') as f:
entries = f.readlines()
emb_dim = len(entries[0].split(' ')) - 1
print('embedding dim is %d' % emb_dim)
weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32)
for entry in entries:
vals = entry.split(' ')
word = vals[0]
vals = list(map(float, vals[1:]))
word2emb[word] = np.array(vals)
for idx, word in enumerate(idx2word):
if word not in word2emb:
continue
weights[idx] = word2emb[word]
return weights, word2emb
# --------------------FAIRSEQ functions---------------------------
def move_to_cuda(sample):
if len(sample) == 0:
return {}
def _move_to_cuda(maybe_tensor):
if torch.is_tensor(maybe_tensor):
return maybe_tensor.cuda()
elif isinstance(maybe_tensor, dict):
return {
key: _move_to_cuda(value)
for key, value in maybe_tensor.items()
}
elif isinstance(maybe_tensor, list):
return [_move_to_cuda(x) for x in maybe_tensor]
else:
return maybe_tensor
return _move_to_cuda(sample)
def item(tensor):
if hasattr(tensor, 'item'):
return tensor.item()
if hasattr(tensor, '__getitem__'):
return tensor[0]
return tensor
def clip_grad_norm_(tensor, max_norm):
grad_norm = item(torch.norm(tensor))
if grad_norm > max_norm > 0:
clip_coef = max_norm / (grad_norm + 1e-6)
tensor.mul_(clip_coef)
return grad_norm
def to_sparse(x):
""" converts dense tensor x to sparse format """
x_typename = torch.typename(x).split('.')[-1]
sparse_tensortype = getattr(torch.sparse, x_typename)
indices = torch.nonzero(x)
if len(indices.shape) == 0: # if all elements are zeros
return sparse_tensortype(*x.shape)
indices = indices.t()
values = x[tuple(indices[i] for i in range(indices.shape[0]))]
return sparse_tensortype(indices, values, x.size())
def get_size_of_largest_vqa_batch(dataloader):
largest_v = None
largest_b = None
largest_q = None
largest_a = None
v, b, q, a = iter(dataloader).next()
# ignore 1st dimension (batch size)
largest_v = v.size()[1]
largest_b = b.size()[1]
largest_q = q.size()[1]
largest_a = a.size()[1]
for i, (v, b, q, a) in enumerate(dataloader):
if largest_v > v.size()[1]:
pass
def get_dummy_batch(args):
pass
def as_minutes(seconds):
minutes = math.floor(seconds / 60)
seconds -= minutes * 60
return '%dm %ds' % (minutes, seconds)
def time_since(since, percent):
now = time.time()
seconds = now - since
elapsed_seconds = seconds / (percent)
rest_seconds = elapsed_seconds - seconds
return '%s (- %s)' % (as_minutes(seconds), as_minutes(rest_seconds))
def tfidf_loading(use_tfidf, w_emb, args):
if use_tfidf:
if args.use_VQA:
dict = dataset_VQA.Dictionary.load_from_file(os.path.join(args.VQA_dir, 'dictionary.pkl'))
# load extracted tfidf and weights from file for saving loading time
if args.use_VQA:
if os.path.isfile(os.path.join(args.VQA_dir, 'embed_tfidf_weights.pkl')) == True:
print("Loading embedding tfidf and weights from file")
with open(os.path.join(args.VQA_dir ,'embed_tfidf_weights.pkl'), 'rb') as f:
w_emb = torch.load(f)
print("Load embedding tfidf and weights from file successfully")
else:
print("Embedding tfidf and weights haven't been saving before")
tfidf, weights = dataset_VQA.tfidf_from_questions(['train', 'val'], args, dict)
w_emb.init_embedding(os.path.join(args.VQA_dir, 'glove6b_init_300d.npy'), tfidf, weights)
with open(os.path.join(args.VQA_dir ,'embed_tfidf_weights.pkl'), 'wb') as f:
torch.save(w_emb, f)
print("Saving embedding with tfidf and weights successfully")
return w_emb
def brevity_penalty(candidate, references):
c = len(candidate)
ref_lens = (len(reference) for reference in references)
r = min(ref_lens, key=lambda ref_len: (abs(ref_len - c), ref_len))
if c > r:
return 1
else:
return math.exp(1 - r / c)
def modified_precision(candidate, references, n):
max_frequency = collections.defaultdict(int)
min_frequency = collections.defaultdict(int)
candidate_words = split_sentence(candidate, n)
for reference in references:
reference_words = split_sentence(reference, n)
for word in candidate_words:
max_frequency[word] = max(max_frequency[word], reference_words[word])
for word in candidate_words:
min_frequency[word] = min(max_frequency[word], candidate_words[word])
P = sum(min_frequency.values()) / sum(candidate_words.values())
return P
def split_sentence(sentence, n):
words = collections.defaultdict(int)
tmp_sentence = re.sub("[^a-zA-Z0-9]", "", sentence) #add 0-9
tmp_sentence = tmp_sentence.lower()
tmp_sentence = tmp_sentence.strip().split()
length = len(tmp_sentence)
for i in range(length - n + 1):
tmp_words = " ".join(tmp_sentence[i: i + n])
if tmp_words:
words[tmp_words] += 1
return words
| 12,029 | 33.371429 | 117 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/classifier.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
class SimpleClassifier(nn.Module):
def __init__(self, in_dim, hid_dim, out_dim, args):
super(SimpleClassifier, self).__init__()
activation_dict = {'relu': nn.ReLU()}
try:
activation_func = activation_dict[args.activation]
except:
raise AssertionError(args.activation + " is not supported yet!")
layers = [
weight_norm(nn.Linear(in_dim, hid_dim), dim=None),
activation_func,
nn.Dropout(args.dropout, inplace=True),
weight_norm(nn.Linear(hid_dim, out_dim), dim=None)
]
self.main = nn.Sequential(*layers)
def forward(self, x):
logits = self.main(x)
return logits
| 936 | 35.038462 | 140 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/simple_cnn.py
|
"""
MAML module for MEVF model
This code is written by Binh X. Nguyen and Binh D. Nguyen
<link paper>
"""
import torch
import torch.nn as nn
import numpy as np
import pickle
import torch.nn.functional as F
class SimpleCNN(nn.Module):
def __init__(self, weight_path='simple_cnn.weights', eps_cnn=1e-5, momentum_cnn=0.05):
super(SimpleCNN, self).__init__()
# init and load pre-trained model
weights = self.load_weight(weight_path)
self.conv1 = self.init_conv(1, 64, weights['conv1'], weights['b1'])
self.conv1_bn = nn.BatchNorm2d(num_features=64, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv2 = self.init_conv(64, 64, weights['conv2'], weights['b2'])
self.conv2_bn = nn.BatchNorm2d(num_features=64, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv3 = self.init_conv(64, 64, weights['conv3'], weights['b3'])
self.conv3_bn = nn.BatchNorm2d(num_features=64, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv4 = self.init_conv(64, 64, weights['conv4'], weights['b4'])
self.conv4_bn = nn.BatchNorm2d(num_features=64, eps=eps_cnn, affine=True, momentum=momentum_cnn)
def load_weight(self, path):
return pickle.load(open(path, 'rb'))
def forward(self, X):
out = F.relu(self.conv1(X))
out = self.conv1_bn(out)
out = F.relu(self.conv2(out))
out = self.conv2_bn(out)
out = F.relu(self.conv3(out))
out = self.conv3_bn(out)
out = F.relu(self.conv4(out))
out = self.conv4_bn(out)
out = out.view(-1, 64, 36)
return torch.mean(out, 2)
def convert_to_torch_weight(self, weight):
return np.transpose(weight, [3, 2, 0, 1])
def init_conv(self, inp, out, weight, bias, convert=True):
conv = nn.Conv2d(inp, out, 3, 2, 1, bias=True)
if convert:
weight = self.convert_to_torch_weight(weight)
conv.weight.data = torch.Tensor(weight).float()
conv.bias.data = torch.Tensor(bias).float()
return conv
class SimpleCNN32(nn.Module):
def __init__(self, weight_path='simple_cnn.weights', eps_cnn=1e-5, momentum_cnn=0.05):
super(SimpleCNN32, self).__init__()
# init and load pre-trained model
weights = self.load_weight(weight_path)
self.conv1 = self.init_conv(3, 32, weights['conv1'], weights['b1'])
self.conv1_bn = nn.BatchNorm2d(num_features=32, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv2 = self.init_conv(32, 32, weights['conv2'], weights['b2'])
self.conv2_bn = nn.BatchNorm2d(num_features=32, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv3 = self.init_conv(32, 32, weights['conv3'], weights['b3'])
self.conv3_bn = nn.BatchNorm2d(num_features=32, eps=eps_cnn, affine=True, momentum=momentum_cnn)
self.conv4 = self.init_conv(32, 32, weights['conv4'], weights['b4'])
self.conv4_bn = nn.BatchNorm2d(num_features=32, eps=eps_cnn, affine=True, momentum=momentum_cnn)
def load_weight(self, path):
return pickle.load(open(path, 'rb'))
def forward(self, X):
out = F.relu(self.conv1(X))
out = self.conv1_bn(out)
out = F.relu(self.conv2(out))
out = self.conv2_bn(out)
out = F.relu(self.conv3(out))
out = self.conv3_bn(out)
out = F.relu(self.conv4(out))
out = self.conv4_bn(out)
out = out.view(-1, 32, 256)
return torch.mean(out, 2)
def convert_to_torch_weight(self, weight):
return np.transpose(weight, [3, 2, 0, 1])
def init_conv(self, inp, out, weight, bias, convert=True):
conv = nn.Conv2d(inp, out, 3, 2, 1, bias=True)
if convert:
weight = self.convert_to_torch_weight(weight)
conv.weight.data = torch.Tensor(weight).float()
conv.bias.data = torch.Tensor(bias).float()
return conv
if __name__ == '__main__':
simple_cnn = SimpleCNN(weight_path='simple_cnn.weights', eps_cnn=1e-5, momentum_cnn=0.05)
npo = np.random.random((3, 1, 84, 84))
x = torch.tensor(npo, dtype=torch.float32).float()
simple_cnn(x)
| 4,169 | 41.121212 | 104 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/bc.py
|
"""
This code is from Jin-Hwa Kim, Jaehyun Jun, Byoung-Tak Zhang's repository.
https://github.com/jnhwkim/ban-vqa
"""
from __future__ import print_function
import torch
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
from fc import FCNet
class BCNet(nn.Module):
"""Simple class for non-linear bilinear connect network
"""
def __init__(self, v_dim, q_dim, h_dim, h_out, act='ReLU', dropout=[.2,.5], k=3):
super(BCNet, self).__init__()
self.c = 32
self.k = k
self.v_dim = v_dim; self.q_dim = q_dim
self.h_dim = h_dim; self.h_out = h_out
self.v_net = FCNet([v_dim, h_dim * self.k], act=act, dropout=dropout[0])
self.q_net = FCNet([q_dim, h_dim * self.k], act=act, dropout=dropout[0])
self.dropout = nn.Dropout(dropout[1]) # attention
if 1 < k:
self.p_net = nn.AvgPool1d(self.k, stride=self.k)
if None == h_out:
pass
elif h_out <= self.c:
self.h_mat = nn.Parameter(torch.Tensor(1, h_out, 1, h_dim * self.k).normal_())
self.h_bias = nn.Parameter(torch.Tensor(1, h_out, 1, 1).normal_())
else:
self.h_net = weight_norm(nn.Linear(h_dim*self.k, h_out), dim=None)
def forward(self, v, q):
if None == self.h_out:
v_ = self.v_net(v).transpose(1,2).unsqueeze(3)
q_ = self.q_net(q).transpose(1,2).unsqueeze(2)
d_ = torch.matmul(v_, q_) # b x h_dim x v x q
logits = d_.transpose(1,2).transpose(2,3) # b x v x q x h_dim
return logits
# broadcast Hadamard product, matrix-matrix production
# fast computation but memory inefficient
# epoch 1, time: 157.84
elif self.h_out <= self.c:
v_ = self.dropout(self.v_net(v)).unsqueeze(1)
q_ = self.q_net(q)
h_ = v_ * self.h_mat # broadcast, b x h_out x v x h_dim
logits = torch.matmul(h_, q_.unsqueeze(1).transpose(2,3)) # b x h_out x v x q
logits = logits + self.h_bias
return logits # b x h_out x v x q
# batch outer product, linear projection
# memory efficient but slow computation
# epoch 1, time: 304.87
else:
v_ = self.dropout(self.v_net(v)).transpose(1,2).unsqueeze(3)
q_ = self.q_net(q).transpose(1,2).unsqueeze(2)
d_ = torch.matmul(v_, q_) # b x h_dim x v x q
logits = self.h_net(d_.transpose(1,2).transpose(2,3)) # b x v x q x h_out
return logits.transpose(2,3).transpose(1,2) # b x h_out x v x q
def forward_with_weights(self, v, q, w):
v_ = self.v_net(v).transpose(1,2).unsqueeze(2) # b x d x 1 x v
q_ = self.q_net(q).transpose(1,2).unsqueeze(3) # b x d x q x 1
logits = torch.matmul(torch.matmul(v_.float(), w.unsqueeze(1).float()), q_.float()).type_as(v_) # b x d x 1 x 1
# logits = torch.matmul(torch.matmul(v_, w.unsqueeze(1)), q_)# b x d x 1 x 1
logits = logits.squeeze(3).squeeze(2)
if 1 < self.k:
logits = logits.unsqueeze(1) # b x 1 x d
logits = self.p_net(logits).squeeze(1) * self.k # sum-pooling
return logits
if __name__=='__main__':
net = BCNet(1024,1024,1024,1024).cuda()
x = torch.Tensor(512,36,1024).cuda()
y = torch.Tensor(512,14,1024).cuda()
out = net.forward(x,y)
| 3,408 | 40.573171 | 119 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/attention.py
|
"""
This code is extended from Jin-Hwa Kim, Jaehyun Jun, Byoung-Tak Zhang's repository.
https://github.com/jnhwkim/ban-vqa
This code is modified from ZCYang's repository.
https://github.com/zcyang/imageqa-san
"""
import torch
import torch.nn as nn
from torch.nn.utils.weight_norm import weight_norm
from bc import BCNet
# Bilinear Attention
class BiAttention(nn.Module):
def __init__(self, x_dim, y_dim, z_dim, glimpse, dropout=[.2,.5]):
super(BiAttention, self).__init__()
self.glimpse = glimpse
self.logits = weight_norm(BCNet(x_dim, y_dim, z_dim, glimpse, dropout=dropout, k=3), \
name='h_mat', dim=None)
def forward(self, v, q, v_mask=True):
"""
v: [batch, k, vdim]
q: [batch, qdim]
"""
p, logits = self.forward_all(v, q, v_mask)
return p, logits
def forward_all(self, v, q, v_mask=True):
v_num = v.size(1)
q_num = q.size(1)
logits = self.logits(v, q) # b x g x v x q
if v_mask:
mask = (0 == v.abs().sum(2)).unsqueeze(1).unsqueeze(3).expand(logits.size())
logits.data.masked_fill_(mask.data, -float('inf'))
p = nn.functional.softmax(logits.view(-1, self.glimpse, v_num * q_num), 2)
return p.view(-1, self.glimpse, v_num, q_num), logits
# Stacked Attention
class StackedAttention(nn.Module):
def __init__(self, num_stacks, img_feat_size, ques_feat_size, att_size, output_size, drop_ratio):
super(StackedAttention, self).__init__()
self.img_feat_size = img_feat_size
self.ques_feat_size = ques_feat_size
self.att_size = att_size
self.output_size = output_size
self.drop_ratio = drop_ratio
self.num_stacks = num_stacks
self.layers = nn.ModuleList()
self.dropout = nn.Dropout(drop_ratio)
self.tanh = nn.Tanh()
self.softmax = nn.Softmax(dim=1)
self.fc11 = nn.Linear(ques_feat_size, att_size, bias=True)
self.fc12 = nn.Linear(img_feat_size, att_size, bias=False)
self.fc13 = nn.Linear(att_size, 1, bias=True)
for stack in range(num_stacks - 1):
self.layers.append(nn.Linear(att_size, att_size, bias=True))
self.layers.append(nn.Linear(img_feat_size, att_size, bias=False))
self.layers.append(nn.Linear(att_size, 1, bias=True))
def forward(self, img_feat, ques_feat, v_mask=True):
# Batch size
B = ques_feat.size(0)
# Stack 1
ques_emb_1 = self.fc11(ques_feat)
img_emb_1 = self.fc12(img_feat)
# Compute attention distribution
h1 = self.tanh(ques_emb_1.view(B, 1, self.att_size) + img_emb_1)
h1_emb = self.fc13(self.dropout(h1))
# Mask actual bounding box sizes before calculating softmax
if v_mask:
mask = (0 == img_emb_1.abs().sum(2)).unsqueeze(2).expand(h1_emb.size())
h1_emb.data.masked_fill_(mask.data, -float('inf'))
p1 = self.softmax(h1_emb)
# Compute weighted sum
img_att_1 = img_emb_1*p1
weight_sum_1 = torch.sum(img_att_1, dim=1)
# Combine with question vector
u1 = ques_emb_1 + weight_sum_1
# Other stacks
us = []
ques_embs = []
img_embs = []
hs = []
h_embs =[]
ps = []
img_atts = []
weight_sums = []
us.append(u1)
for stack in range(self.num_stacks - 1):
ques_embs.append(self.layers[3 * stack + 0](us[-1]))
img_embs.append(self.layers[3 * stack + 1](img_feat))
# Compute attention distribution
hs.append(self.tanh(ques_embs[-1].view(B, -1, self.att_size) + img_embs[-1]))
h_embs.append(self.layers[3*stack + 2](self.dropout(hs[-1])))
# Mask actual bounding box sizes before calculating softmax
if v_mask:
mask = (0 == img_embs[-1].abs().sum(2)).unsqueeze(2).expand(h_embs[-1].size())
h_embs[-1].data.masked_fill_(mask.data, -float('inf'))
ps.append(self.softmax(h_embs[-1]))
# Compute weighted sum
img_atts.append(img_embs[-1] * ps[-1])
weight_sums.append(torch.sum(img_atts[-1], dim=1))
# Combine with previous stack
ux = us[-1] + weight_sums[-1]
# Combine with previous stack by multiple
us.append(ux)
return us[-1]
| 4,448 | 33.488372 | 101 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/train.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
import os
import time
import torch
import utils
import torch.nn as nn
from trainer import Trainer
warmup_updates = 4000
# Kaiming normalization initialization
def init_weights(m):
if type(m) == nn.Linear:
with torch.no_grad():
torch.nn.init.kaiming_normal_(m.weight)
# VQA score computation
def compute_score_with_logits(logits, labels):
logits = torch.max(logits, 1)[1].data # argmax
one_hots = torch.zeros(*labels.size()).to(logits.device)
one_hots.scatter_(1, logits.view(-1, 1), 1)
scores = (one_hots * labels)
return scores
# Train phase
def train(args, model, train_loader, eval_loader, num_epochs, output, opt=None, s_epoch=0):
device = args.device
# Scheduler learning rate
lr_default = args.lr
lr_decay_step = 2
lr_decay_rate = .75
lr_decay_epochs = range(10,20,lr_decay_step) if eval_loader is not None else range(10,20,lr_decay_step)
gradual_warmup_steps = [0.5 * lr_default, 1.0 * lr_default, 1.5 * lr_default, 2.0 * lr_default]
saving_epoch = 0 # Start point for model saving
grad_clip = args.clip_norm
utils.create_dir(output)
# Adamax optimizer
optim = torch.optim.Adamax(filter(lambda p: p.requires_grad, model.parameters()), lr=lr_default) \
if opt is None else opt
# Loss function
criterion = torch.nn.BCEWithLogitsLoss(reduction='sum')
ae_criterion = torch.nn.MSELoss()
# write hyper-parameter to log file
logger = utils.Logger(os.path.join(output, 'log.txt'))
logger.write(args.__repr__())
utils.print_model(model, logger)
logger.write('optim: adamax lr=%.4f, decay_step=%d, decay_rate=%.2f, grad_clip=%.2f' % \
(lr_default, lr_decay_step, lr_decay_rate, grad_clip))
# create trainer
trainer = Trainer(args, model, criterion, optim, ae_criterion)
update_freq = int(args.update_freq)
wall_time_start = time.time()
best_eval_score = 0
# Epoch passing in training phase
for epoch in range(s_epoch, num_epochs):
total_loss = 0
train_score = 0
total_norm = 0
count_norm = 0
num_updates = 0
t = time.time()
N = len(train_loader.dataset)
num_batches = int(N/args.batch_size + 1)
if epoch < len(gradual_warmup_steps):
trainer.optimizer.param_groups[0]['lr'] = gradual_warmup_steps[epoch]
logger.write('gradual warm up lr: %.4f' % trainer.optimizer.param_groups[0]['lr'])
elif epoch in lr_decay_epochs:
trainer.optimizer.param_groups[0]['lr'] *= lr_decay_rate
logger.write('decreased lr: %.4f' % trainer.optimizer.param_groups[0]['lr'])
else:
logger.write('lr: %.4f' % trainer.optimizer.param_groups[0]['lr'])
# Predicting and computing score
for i, (v, q, a, _, _, _) in enumerate(train_loader):
if args.maml:
if 'RAD' in args.VQA_dir:
v[0] = v[0].reshape(v[0].shape[0], args.img_size, args.img_size).unsqueeze(1)
else:
v[0] = v[0].reshape(v[0].shape[0], 3, args.img_size, args.img_size)
# v[0] = v[0].transpose(1, 3)
if args.autoencoder:
v[1] = v[1].reshape(v[1].shape[0], 128, 128).unsqueeze(1)
v[0] = v[0].to(device)
v[1] = v[1].to(device)
q = q.to(device)
a = a.to(device)
sample = [v, q, a]
if i < num_batches - 1 and (i + 1) % update_freq > 0:
trainer.train_step(sample, update_params=False)
else:
loss, grad_norm, batch_score = trainer.train_step(sample, update_params=True)
total_norm += grad_norm
count_norm += 1
total_loss += loss.item()
train_score += batch_score
num_updates += 1
if num_updates % int(args.print_interval / update_freq) == 0:
print("Iter: {}, Loss {:.4f}, Norm: {:.4f}, Total norm: {:.4f}, Num updates: {}, Wall time: {:.2f}, ETA: {}".format(i + 1, total_loss / ((num_updates + 1)), grad_norm, total_norm, num_updates, time.time() - wall_time_start, utils.time_since(t, i / num_batches)))
total_loss /= num_updates
train_score = 100 * train_score / (num_updates * args.batch_size)
# Evaluation
if eval_loader is not None:
print("Evaluating...")
trainer.model.train(False)
eval_score, bound = evaluate(model, eval_loader, args)
trainer.model.train(True)
logger.write('epoch %d, time: %.2f' % (epoch, time.time()-t))
logger.write('\ttrain_loss: %.2f, norm: %.4f, score: %.2f' % (total_loss, total_norm/count_norm, train_score))
if eval_loader is not None:
logger.write('\teval score: %.2f (%.2f)' % (100 * eval_score, 100 * bound))
# Save per epoch
if epoch >= saving_epoch:
model_path = os.path.join(output, 'model_epoch%d.pth' % epoch)
utils.save_model(model_path, model, epoch, trainer.optimizer)
# Save best epoch
if eval_loader is not None and eval_score > best_eval_score:
model_path = os.path.join(output, 'model_epoch_best.pth')
utils.save_model(model_path, model, epoch, trainer.optimizer)
best_eval_score = eval_score
# Evaluation
def evaluate(model, dataloader, args):
device = args.device
score = 0
upper_bound = 0
num_data = 0
with torch.no_grad():
for v, q, a, _, _, _ in iter(dataloader):
if args.maml:
if 'RAD' in args.VQA_dir:
v[0] = v[0].reshape(v[0].shape[0], args.img_size, args.img_size).unsqueeze(1)
else:
v[0] = v[0].reshape(v[0].shape[0], 3, args.img_size, args.img_size)
# v[0] = v[0].transpose(1, 3)
if args.autoencoder:
v[1] = v[1].reshape(v[1].shape[0], 128, 128).unsqueeze(1)
v[0] = v[0].to(device)
v[1] = v[1].to(device)
q = q.to(device)
a = a.to(device)
if args.autoencoder:
features, _ = model(v, q)
else:
features = model(v, q)
preds = model.classifier(features)
final_preds = preds
batch_score = compute_score_with_logits(final_preds, a.data).sum()
score += batch_score
upper_bound += (a.max(1)[0]).sum()
num_data += final_preds.size(0)
score = score / len(dataloader.dataset)
upper_bound = upper_bound / len(dataloader.dataset)
return score, upper_bound
| 6,862 | 39.609467 | 282 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/auto_encoder.py
|
"""
Auto-encoder module for MEVF model
This code is written by Binh X. Nguyen and Binh D. Nguyen
<link paper>
"""
import torch.nn as nn
from torch.distributions.normal import Normal
import functools
import operator
import torch.nn.functional as F
import torch
def add_noise(images, mean=0, std=0.1):
normal_dst = Normal(mean, std)
noise = normal_dst.sample(images.shape)
noisy_image = noise + images
return noisy_image
def print_model(model):
print(model)
nParams = 0
for w in model.parameters():
nParams += functools.reduce(operator.mul, w.size(), 1)
print(nParams)
class Auto_Encoder_Model(nn.Module):
def __init__(self):
super(Auto_Encoder_Model, self).__init__()
# Encoder
self.conv1 = nn.Conv2d(1, 64, padding=1, kernel_size=3)
self.max_pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(64, 32, padding=1, kernel_size=3)
self.max_pool2 = nn.MaxPool2d(2)
self.conv3 = nn.Conv2d(32, 16, padding=1, kernel_size=3)
# Decoder
self.tran_conv1 = nn.ConvTranspose2d(16, 32, kernel_size=3, stride=2, padding=1, output_padding=1)
self.conv4 = nn.Conv2d(32, 32, kernel_size=3, padding=1)
self.tran_conv2 = nn.ConvTranspose2d(32, 64, kernel_size=3, stride=2, padding=1, output_padding=1)
self.conv5 = nn.Conv2d(64, 1, kernel_size=3, padding=1)
def forward_pass(self, x):
output = F.relu(self.conv1(x))
output = self.max_pool1(output)
output = F.relu(self.conv2(output))
output = self.max_pool2(output)
output = F.relu(self.conv3(output))
return output
def reconstruct_pass(self, x):
output = F.relu(self.tran_conv1(x))
output = F.relu(self.conv4(output))
output = F.relu(self.tran_conv2(output))
output = torch.sigmoid(self.conv5(output))
return output
def forward(self, x):
output = self.forward_pass(x)
output = self.reconstruct_pass(output)
return output
| 2,019 | 32.114754 | 106 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/trainer.py
|
"""
This code is modified based on Jin-Hwa Kim's repository (Bilinear Attention Networks - https://github.com/jnhwkim/ban-vqa) by Xuan B. Nguyen
"""
import torch
import utils
import contextlib
from collections import defaultdict, OrderedDict
from meters import AverageMeter, TimeMeter
class Trainer(object):
"""
Main class for training.
"""
def __init__(self, args, model, criterion, optimizer=None, ae_criterion = None):
self.args = args
# copy model and criterion on current device
self.model = model.to(self.args.device)
self.criterion = criterion.to(self.args.device)
self.ae_criterion = ae_criterion.to(self.args.device)
# initialize meters
self.meters = OrderedDict()
self.meters['train_loss'] = AverageMeter()
self.meters['train_nll_loss'] = AverageMeter()
self.meters['valid_loss'] = AverageMeter()
self.meters['valid_nll_loss'] = AverageMeter()
self.meters['wps'] = TimeMeter() # words per second
self.meters['ups'] = TimeMeter() # updates per second
self.meters['wpb'] = AverageMeter() # words per batch
self.meters['bsz'] = AverageMeter() # sentences per batch
self.meters['gnorm'] = AverageMeter() # gradient norm
self.meters['clip'] = AverageMeter() # % of updates clipped
self.meters['oom'] = AverageMeter() # out of memory
self.meters['wall'] = TimeMeter() # wall time in seconds
self._buffered_stats = defaultdict(lambda: [])
self._flat_grads = None
self._num_updates = 0
self._optim_history = None
self._optimizer = None
if optimizer is not None:
self._optimizer = optimizer
self.total_loss = 0.0
self.train_score = 0.0
self.total_norm = 0.0
self.count_norm = 0.0
@property
def optimizer(self):
if self._optimizer is None:
self._build_optimizer()
return self._optimizer
def _build_optimizer(self):
# self._optimizer = optim.build_optimizer(self.args, self.model.parameters())
# self._optimizer =
# self.lr_scheduler = lr_scheduler.build_lr_scheduler(self.args, self._optimizer)
pass
def train_step(self, sample, update_params=True):
"""Do forward, backward and parameter update."""
# Set seed based on args.seed and the update number so that we get
# reproducible results when resuming from checkpoints
# seed = self.args.seed + self.get_num_updates()
# torch.manual_seed(seed)
# torch.cuda.manual_seed(seed)
# forward and backward pass
sample = self._prepare_sample(sample)
loss, sample_size, oom_fwd, batch_score = self._forward(sample)
oom_bwd = self._backward(loss)
# buffer stats and logging outputs
# self._buffered_stats['sample_sizes'].append(sample_size)
self._buffered_stats['sample_sizes'].append(1)
self._buffered_stats['ooms_fwd'].append(oom_fwd)
self._buffered_stats['ooms_bwd'].append(oom_bwd)
# update parameters
if update_params:
# gather logging outputs from all replicas
sample_sizes = self._buffered_stats['sample_sizes']
ooms_fwd = self._buffered_stats['ooms_fwd']
ooms_bwd = self._buffered_stats['ooms_bwd']
ooms_fwd = sum(ooms_fwd)
ooms_bwd = sum(ooms_bwd)
# aggregate stats and logging outputs
grad_denom = sum(sample_sizes)
grad_norm = 0
try:
# all-reduce and rescale gradients, then take an optimization step
grad_norm = self._all_reduce_and_rescale(grad_denom)
self._opt()
# update meters
if grad_norm is not None:
self.meters['gnorm'].update(grad_norm)
self.meters['clip'].update(1. if grad_norm > self.args.clip_norm else 0.)
self.meters['oom'].update(ooms_fwd + ooms_bwd)
except OverflowError as e:
self.zero_grad()
print('| WARNING: overflow detected, ' + str(e))
self.clear_buffered_stats()
return loss, grad_norm, batch_score
else:
return None # buffering updates
def _forward(self, sample, eval=False):
# prepare model and optimizer
if eval:
self.model.eval()
else:
self.model.train()
loss = None
oom = 0
batch_score = 0
if sample is not None:
try:
with torch.no_grad() if eval else contextlib.ExitStack():
answers = sample[2]
img_data = sample[0][1]
# MEVF loss computation
if self.args.autoencoder:
features, decoder = self.model(sample[0], sample[1])
else:
features = self.model(sample[0], sample[1])
preds = self.model.classifier(features)
loss = self.criterion(preds.float(), answers)
if self.args.autoencoder: # compute reconstruction loss
loss_ae = self.ae_criterion(img_data, decoder)
# multi-task loss
loss = loss + (loss_ae*self.args.ae_alpha)
loss /= answers.size()[0]
final_preds = preds
batch_score = compute_score_with_logits(final_preds, sample[2].data).sum()
except RuntimeError as e:
if not eval and 'out of memory' in str(e):
print('| WARNING: ran out of memory, skipping batch')
oom = 1
loss = None
else:
raise e
return loss, len(sample[0]), oom, batch_score # TODO: Not sure about sample size, need to recheck
def _backward(self, loss):
oom = 0
if loss is not None:
try:
# backward pass
loss.backward()
except RuntimeError as e:
if 'out of memory' in str(e):
print('| WARNING: ran out of memory, skipping batch')
oom = 1
self.zero_grad()
else:
raise e
return oom
def _all_reduce_and_rescale(self, grad_denom):
# flatten grads into a single buffer and all-reduce
flat_grads = self._flat_grads = self._get_flat_grads(self._flat_grads)
# rescale and clip gradients
flat_grads.div_(grad_denom)
grad_norm = utils.clip_grad_norm_(flat_grads, self.args.clip_norm)
# copy grads back into model parameters
self._set_flat_grads(flat_grads)
return grad_norm
def _get_grads(self):
grads = []
for name, p in self.model.named_parameters():
if not p.requires_grad:
continue
if p.grad is None:
raise RuntimeError('Model parameter did not receive gradient: ' + name + '. '
'Use the param in the forward pass or set requires_grad=False')
grads.append(p.grad.data)
return grads
def _get_flat_grads(self, out=None):
grads = self._get_grads()
if out is None:
grads_size = sum(g.numel() for g in grads)
out = grads[0].new(grads_size).zero_()
offset = 0
for g in grads:
numel = g.numel()
out[offset:offset+numel].copy_(g.view(-1))
offset += numel
return out[:offset]
def _set_flat_grads(self, new_grads):
grads = self._get_grads()
offset = 0
for g in grads:
numel = g.numel()
g.copy_(new_grads[offset:offset+numel].view_as(g))
offset += numel
def _opt(self):
# take an optimization step
self.optimizer.step()
self.zero_grad()
self._num_updates += 1
# update learning rate
# self.lr_scheduler.step_update(self._num_updates)
def zero_grad(self):
self.optimizer.zero_grad()
def clear_buffered_stats(self):
self._buffered_stats.clear()
def get_num_updates(self):
"""Get the number of parameters updates."""
return self._num_updates
def _prepare_sample(self, sample):
if sample is None or len(sample) == 0:
return None
return utils.move_to_cuda(sample)
def dummy_train_step(self, dummy_batch):
"""Dummy training step for warming caching allocator."""
self.train_step(dummy_batch, update_params=False)
self.zero_grad()
self.clear_buffered_stats()
def compute_score_with_logits(logits, labels):
logits = torch.max(logits, 1)[1].data # argmax
one_hots = torch.zeros(*labels.size()).to(logits.device)
one_hots.scatter_(1, logits.view(-1, 1), 1)
scores = (one_hots * labels)
return scores
| 9,194 | 36.226721 | 152 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/language_model.py
|
"""
This code is from Jin-Hwa Kim, Jaehyun Jun, Byoung-Tak Zhang's repository.
https://github.com/jnhwkim/ban-vqa
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
class WordEmbedding(nn.Module):
"""Word Embedding
The ntoken-th dim is used for padding_idx, which agrees *implicitly*
with the definition in Dictionary.
"""
def __init__(self, ntoken, emb_dim, dropout, op=''):
super(WordEmbedding, self).__init__()
self.op = op
self.emb = nn.Embedding(ntoken+1, emb_dim, padding_idx=ntoken)
if 'c' in op:
self.emb_ = nn.Embedding(ntoken+1, emb_dim, padding_idx=ntoken)
self.emb_.weight.requires_grad = False # fixed
self.dropout = nn.Dropout(dropout)
self.ntoken = ntoken
self.emb_dim = emb_dim
def init_embedding(self, np_file, tfidf=None, tfidf_weights=None):
weight_init = torch.from_numpy(np.load(np_file))
assert weight_init.shape == (self.ntoken, self.emb_dim)
self.emb.weight.data[:self.ntoken] = weight_init
if tfidf is not None:
if 0 < tfidf_weights.size:
weight_init = torch.cat([weight_init, torch.from_numpy(tfidf_weights)], 0)
weight_init = tfidf.matmul(weight_init) # (N x N') x (N', F)
self.emb_.weight.requires_grad = True
if 'c' in self.op:
self.emb_.weight.data[:self.ntoken] = weight_init.clone()
def forward(self, x):
emb = self.emb(x)
if 'c' in self.op:
emb = torch.cat((emb, self.emb_(x)), 2)
emb = self.dropout(emb)
return emb
class QuestionEmbedding(nn.Module):
def __init__(self, in_dim, num_hid, nlayers, bidirect, dropout, rnn_type='GRU'):
"""Module for question embedding
"""
super(QuestionEmbedding, self).__init__()
assert rnn_type == 'LSTM' or rnn_type == 'GRU'
rnn_cls = nn.LSTM if rnn_type == 'LSTM' else nn.GRU if rnn_type == 'GRU' else None
self.rnn = rnn_cls(
in_dim, num_hid, nlayers,
bidirectional=bidirect,
dropout=dropout,
batch_first=True)
self.in_dim = in_dim
self.num_hid = num_hid
self.nlayers = nlayers
self.rnn_type = rnn_type
self.ndirections = 1 + int(bidirect)
def init_hidden(self, batch):
# just to get the type of tensor
weight = next(self.parameters()).data
hid_shape = (self.nlayers * self.ndirections, batch, self.num_hid // self.ndirections)
if self.rnn_type == 'LSTM':
return (Variable(weight.new(*hid_shape).zero_()),
Variable(weight.new(*hid_shape).zero_()))
else:
return Variable(weight.new(*hid_shape).zero_())
def forward(self, x):
# x: [batch, sequence, in_dim]
batch = x.size(0)
hidden = self.init_hidden(batch)
output, hidden = self.rnn(x, hidden)
if self.ndirections == 1:
return output[:, -1]
forward_ = output[:, -1, :self.num_hid]
backward = output[:, 0, self.num_hid:]
return torch.cat((forward_, backward), dim=1)
def forward_all(self, x):
# x: [batch, sequence, in_dim]
batch = x.size(0)
hidden = self.init_hidden(batch)
output, hidden = self.rnn(x, hidden)
return output
| 3,405 | 35.234043 | 94 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/meters.py
|
"""
This code is from https://github.com/pytorch/fairseq
"""
import time
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
class TimeMeter(object):
"""Computes the average occurrence of some event per second"""
def __init__(self, init=0):
self.reset(init)
def reset(self, init=0):
self.init = init
self.start = time.time()
self.n = 0
def update(self, val=1):
self.n += val
@property
def avg(self):
return self.n / self.elapsed_time
@property
def elapsed_time(self):
return self.init + (time.time() - self.start)
class StopwatchMeter(object):
"""Computes the sum/avg duration of some event in seconds"""
def __init__(self):
self.reset()
def start(self):
self.start_time = time.time()
def stop(self, n=1):
if self.start_time is not None:
delta = time.time() - self.start_time
self.sum += delta
self.n += n
self.start_time = None
def reset(self):
self.sum = 0
self.n = 0
self.start_time = None
@property
def avg(self):
return self.sum / self.n
| 1,513 | 21.264706 | 66 |
py
|
MICCAI21_MMQ
|
MICCAI21_MMQ-main/tools/create_embedding.py
|
"""
This code is from Hengyuan Hu's repository.
https://github.com/hengyuan-hu/bottom-up-attention-vqa
"""
from __future__ import print_function
import os
import sys
import json
import functools
import operator
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import _pickle as cPickle
def create_glove_embedding_init(idx2word, glove_file):
word2emb = {}
with open(glove_file, 'r') as f:
entries = f.readlines()
emb_dim = len(entries[0].split(' ')) - 1
print('embedding dim is %d' % emb_dim)
weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32)
for entry in entries:
vals = entry.split(' ')
word = vals[0]
vals = list(map(float, vals[1:]))
word2emb[word] = np.array(vals)
count = 0
for idx, word in enumerate(idx2word):
if word not in word2emb:
updates = 0
for w in word.split(' '):
if w not in word2emb:
continue
weights[idx] += word2emb[w]
updates += 1
if updates == 0:
count+= 1
continue
weights[idx] = word2emb[word]
return weights, word2emb
if __name__ == '__main__':
VQA_dir = 'data_RAD'
emb_dims = [300]
weights = [0] * len(emb_dims)
label2ans = cPickle.load(open(VQA_dir + '/cache/trainval_label2ans.pkl', 'rb'))
for idx, emb_dim in enumerate(emb_dims): # available embedding sizes
glove_file = VQA_dir + '/glove/glove.6B.%dd.txt' % emb_dim
weights[idx], word2emb = create_glove_embedding_init(label2ans, glove_file)
np.save(VQA_dir + '/glove6b_emb_%dd.npy' % functools.reduce(operator.add, emb_dims), np.hstack(weights))
| 1,757 | 30.963636 | 108 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.