Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • empyre/empyre
  • weber/empyre
  • wessels/empyre
  • bryan/empyre
4 results
Show changes
Showing
with 0 additions and 6333 deletions
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Package for the creation and reconstruction of magnetic distributions and resulting phase maps.
Modules
-------
magcreator
Create simple magnetic distributions.
magdata
Class for the storage of magnetization data.
projector
Class for projecting given magnetization distributions.
kernel
Class for the kernel matrix representing one magnetized pixel.
phasemapper
Create magnetic and electric phase maps from magnetization data.
phasemap
Class for the storage of phase data.
analytic
Create phase maps for magnetic distributions with analytic solutions.
dataset
Class for collecting pairs of phase maps and corresponding projectors.
forwardmodel
Class which represents a phase mapping strategy.
costfunction
Class for the evaluation of the cost of a function.
reconstruction
Reconstruct magnetic distributions from given phasemaps.
regularisator
Class to instantiate different regularisation strategies.
ramp
Class which is used to add polynomial ramps to phasemaps.
diagnostics
Class to calculate diagnostics
quaternion
Class which is used for easy rotations in the Projector classes.
colormap
Class which implements a custom direction encoding colormap.
"""
from . import analytic
from . import reconstruction
from . import fieldconverter
from . import magcreator
from . import colors
from . import plottools # TODO: colors and plottools into "plots" package (maybe with examples?)
from . import utils
from .costfunction import *
from .dataset import *
from .diagnostics import *
from .fielddata import *
from .forwardmodel import *
from .kernel import *
from .phasemap import *
from .phasemapper import *
from .projector import *
from .regularisator import *
from .ramp import *
from .quaternion import *
from .file_io import *
from .version import version as __version__
from .version import hg_revision as __hg_revision__
import logging
_log = logging.getLogger(__name__)
_log.info("Starting Pyramid V{} HG{}".format(__version__, __hg_revision__))
del logging
__all__ = ['analytic', 'magcreator', 'reconstruction', 'fieldconverter',
'load_phasemap', 'load_vectordata', 'load_scalardata', 'load_projector', 'load_dataset',
'colors', 'utils']
__all__.extend(costfunction.__all__)
__all__.extend(dataset.__all__)
__all__.extend(diagnostics.__all__)
__all__.extend(forwardmodel.__all__)
__all__.extend(kernel.__all__)
__all__.extend(fielddata.__all__)
__all__.extend(phasemap.__all__)
__all__.extend(phasemapper.__all__)
__all__.extend(projector.__all__)
__all__.extend(regularisator.__all__)
__all__.extend(ramp.__all__)
__all__.extend(quaternion.__all__)
__all__.extend(file_io.__all__)
# TODO: Test for different systems!
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Create phase maps for magnetic distributions with analytic solutions.
This module provides methods for the calculation of the magnetic phase for simple geometries for
which the analytic solutions are known. These can be used for comparison with the phase
calculated by the functions from the :mod:`~pyramid.phasemapper` module.
"""
import logging
import numpy as np
from numpy import pi
from pyramid.phasemap import PhaseMap
__all__ = ['phase_mag_slab', 'phase_mag_slab', 'phase_mag_sphere', 'phase_mag_vortex']
_log = logging.getLogger(__name__)
PHI_0 = 2067.83 # magnetic flux in T*nm²
def phase_mag_slab(dim, a, phi, center, width, b_0=1):
"""Calculate the analytic magnetic phase for a homogeneously magnetized slab.
Parameters
----------
dim : tuple (N=3)
The dimensions of the grid `(z, y, x)`.
a : float
The grid spacing in nm.
phi : float
The azimuthal angle, describing the direction of the magnetization.
center : tuple (N=3)
The center of the slab in pixel coordinates `(z, y, x)`.
width : tuple (N=3)
The width of the slab in pixel coordinates `(z, y, x)`.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
Returns
-------
phasemap : :class:`~numpy.ndarray` (N=2)
The phase as a 2-dimensional array.
"""
_log.debug('Calling phase_mag_slab')
# Function for the phase:
def _phi_mag(x, y):
def _F_0(x, y):
A = np.log(x ** 2 + y ** 2 + 1E-30)
B = np.arctan(x / (y + 1E-30))
return x * A - 2 * x + 2 * y * B
return coeff * Lz * (- np.cos(phi) * (_F_0(x - x0 - Lx / 2, y - y0 - Ly / 2) -
_F_0(x - x0 + Lx / 2, y - y0 - Ly / 2) -
_F_0(x - x0 - Lx / 2, y - y0 + Ly / 2) +
_F_0(x - x0 + Lx / 2, y - y0 + Ly / 2))
+ np.sin(phi) * (_F_0(y - y0 - Ly / 2, x - x0 - Lx / 2) -
_F_0(y - y0 + Ly / 2, x - x0 - Lx / 2) -
_F_0(y - y0 - Ly / 2, x - x0 + Lx / 2) +
_F_0(y - y0 + Ly / 2, x - x0 + Lx / 2)))
# Process input parameters:
z_dim, y_dim, x_dim = dim
y0 = a * center[1] # y0, x0 define the center of a pixel,
x0 = a * center[2] # hence: (cellindex + 0.5) * grid spacing
Lz, Ly, Lx = a * width[0], a * width[1], a * width[2]
coeff = - b_0 / (4 * PHI_0) # Minus because of negative z-direction
# Create grid:
x = np.linspace(a / 2, x_dim * a - a / 2, num=x_dim)
y = np.linspace(a / 2, y_dim * a - a / 2, num=y_dim)
xx, yy = np.meshgrid(x, y)
# Return phase:
return PhaseMap(a, _phi_mag(xx, yy))
def phase_mag_disc(dim, a, phi, center, radius, height, b_0=1):
"""Calculate the analytic magnetic phase for a homogeneously magnetized disc.
Parameters
----------
dim : tuple (N=3)
The dimensions of the grid `(z, y, x)`.
a : float
The grid spacing in nm.
phi : float
The azimuthal angle, describing the direction of the magnetization.
center : tuple (N=3)
The center of the disc in pixel coordinates `(z, y, x)`.
radius : float
The radius of the disc in pixel coordinates.
height : float
The height of the disc in pixel coordinates.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
Returns
-------
phasemap : :class:`~numpy.ndarray` (N=2)
The phase as a 2-dimensional array.
"""
_log.debug('Calling phase_mag_disc')
# Function for the phase:
def _phi_mag(x, y):
r = np.hypot(x - x0, y - y0)
result = coeff * Lz * ((y - y0) * np.cos(phi) - (x - x0) * np.sin(phi))
result *= np.where(r <= R, 1, (R / (r + 1E-30)) ** 2)
return result
# Process input parameters:
z_dim, y_dim, x_dim = dim
y0 = a * center[1]
x0 = a * center[2]
Lz = a * height
R = a * radius
coeff = pi * b_0 / (2 * PHI_0) # Minus is gone because of negative z-direction
# Create grid:
x = np.linspace(a / 2, x_dim * a - a / 2, num=x_dim)
y = np.linspace(a / 2, y_dim * a - a / 2, num=y_dim)
xx, yy = np.meshgrid(x, y)
# Return phase:
return PhaseMap(a, _phi_mag(xx, yy))
def phase_mag_sphere(dim, a, phi, center, radius, b_0=1):
"""Calculate the analytic magnetic phase for a homogeneously magnetized sphere.
Parameters
----------
dim : tuple (N=3)
The dimensions of the grid `(z, y, x)`.
a : float
The grid spacing in nm.
phi : float
The azimuthal angle, describing the direction of the magnetization.
center : tuple (N=3)
The center of the sphere in pixel coordinates `(z, y, x)`.
radius : float
The radius of the sphere in pixel coordinates.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
Returns
-------
phasemap : :class:`~numpy.ndarray` (N=2)
The phase as a 2-dimensional array.
"""
_log.debug('Calling phase_mag_sphere')
# Function for the phase:
def _phi_mag(x, y):
r = np.hypot(x - x0, y - y0)
result = coeff * R ** 3 / (r + 1E-30) ** 2 * (
(y - y0) * np.cos(phi) - (x - x0) * np.sin(phi))
result *= 1 - np.clip(1 - (r / R) ** 2, 0, 1) ** (3. / 2.)
return result
# Process input parameters:
z_dim, y_dim, x_dim = dim
y0 = a * center[1]
x0 = a * center[2]
R = a * radius
coeff = 2. / 3. * pi * b_0 / PHI_0 # Minus is gone because of negative z-direction
# Create grid:
x = np.linspace(a / 2, x_dim * a - a / 2, num=x_dim)
y = np.linspace(a / 2, y_dim * a - a / 2, num=y_dim)
xx, yy = np.meshgrid(x, y)
# Return phase:
return PhaseMap(a, _phi_mag(xx, yy))
def phase_mag_vortex(dim, a, center, radius, height, b_0=1):
"""Calculate the analytic magnetic phase for a vortex state disc.
Parameters
----------
dim : tuple (N=3)
The dimensions of the grid `(z, y, x)`.
a : float
The grid spacing in nm.
center : tuple (N=3)
The center of the disc in pixel coordinates `(z, y, x)`, which is also the vortex center.
radius : float
The radius of the disc in pixel coordinates.
height : float
The height of the disc in pixel coordinates.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
Returns
-------
phasemap : :class:`~numpy.ndarray` (N=2)
The phase as a 2-dimensional array.
"""
_log.debug('Calling phase_mag_vortex')
# Function for the phase:
def _phi_mag(x, y):
r = np.hypot(x - x0, y - y0)
result = coeff * np.where(r <= R, r - R, 0)
return result
# Process input parameters:
z_dim, y_dim, x_dim = dim
y0 = a * center[1]
x0 = a * center[2]
Lz = a * height
R = a * radius
coeff = - pi * b_0 * Lz / PHI_0 # Minus because of negative z-direction
# Create grid:
x = np.linspace(a / 2, x_dim * a - a / 2, num=x_dim)
y = np.linspace(a / 2, y_dim * a - a / 2, num=y_dim)
xx, yy = np.meshgrid(x, y)
# Return phase:
return PhaseMap(a, _phi_mag(xx, yy))
# -*- coding: utf-8 -*-
# Copyright 2014 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""This module provides the :class:`~.Costfunction` class which represents a strategy to calculate
the so called `cost` of a three dimensional magnetization distribution."""
import logging
import numpy as np
from pyramid.regularisator import NoneRegularisator
__all__ = ['Costfunction']
class Costfunction(object):
"""Class for calculating the cost of a 3D magnetic distributions in relation to 2D phase maps.
Represents a strategy for the calculation of the `cost` of a 3D magnetic distribution in
relation to two-dimensional phase maps. The `cost` is a measure for the difference of the
simulated phase maps from the magnetic distributions to the given set of phase maps and from
a prior knowledge represented by a :class:`~.Regularisator` object. Furthermore this class
provides convenient methods for the calculation of the derivative :func:`~.jac` or the product
with the Hessian matrix :func:`~.hess_dot` of the costfunction, which can be used by
optimizers. All required data should be given in a :class:`~DataSet` object.
Attributes
----------
fwd_model : :class:`~.ForwardModel`
The Forward model instance which should be used for the simulation of the phase maps which
will be compared to `y`.
regularisator : :class:`~.Regularisator`, optional
Regularisator class that's responsible for the regularisation term. If `None` or none is
given, no regularisation will be used.
y : :class:`~numpy.ndarray` (N=1)
Vector which lists all pixel values of all phase maps one after another.
m: int
Size of the image space.
n: int
Size of the input space.
Se_inv : :class:`~numpy.ndarray` (N=2), optional
Inverted covariance matrix of the measurement errors. The matrix has size `m x m` with m
being the length of the target vector y.
"""
_log = logging.getLogger(__name__ + '.Costfunction')
def __init__(self, fwd_model, regularisator=None):
self._log.debug('Calling __init__')
self.fwd_model = fwd_model
if regularisator is None:
self.regularisator = NoneRegularisator()
else:
self.regularisator = regularisator
# Extract information from fwd_model:
self.y = self.fwd_model.y
self.n = self.fwd_model.n
self.m = self.fwd_model.m
self.Se_inv = self.fwd_model.Se_inv
self._log.debug('Created ' + str(self))
def __repr__(self):
self._log.debug('Calling __repr__')
return '%s(fwd_model=%r, regularisator=%r)' % \
(self.__class__, self.fwd_model, self.regularisator)
def __str__(self):
self._log.debug('Calling __str__')
return 'Costfunction(fwd_model=%s, fwd_model=%s, regularisator=%s)' % \
(self.fwd_model, self.fwd_model, self.regularisator)
def __call__(self, x):
delta_y = self.fwd_model(x) - self.y
self.chisq_m = delta_y.dot(self.Se_inv.dot(delta_y))
self.chisq_a = self.regularisator(x)
self.chisq = self.chisq_m + self.chisq_a
return self.chisq
def init(self, x):
"""Initialise the costfunction by calculating the different cost terms.
Parameters
----------
x : :class:`~numpy.ndarray` (N=1)
Vectorized magnetization distribution, for which the cost is calculated.
Returns
-------
None
"""
self._log.debug('Calling init')
self(x)
def jac(self, x):
"""Calculate the derivative of the costfunction for a given magnetization distribution.
Parameters
----------
x : :class:`~numpy.ndarray` (N=1)
Vectorized magnetization distribution, for which the Jacobi vector is calculated.
Returns
-------
result : :class:`~numpy.ndarray` (N=1)
Jacobi vector which represents the cost derivative of all voxels of the magnetization.
"""
assert len(x) == self.n, 'Length of input {} does not match n={}'.format(len(x), self.n)
return (2 * self.fwd_model.jac_T_dot(x, self.Se_inv.dot(self.fwd_model(x) - self.y))
+ self.regularisator.jac(x))
def hess_dot(self, x, vector):
"""Calculate the product of a `vector` with the Hessian matrix of the costfunction.
Parameters
----------
x : :class:`~numpy.ndarray` (N=1)
Vectorized magnetization distribution at which the Hessian is calculated. The Hessian
is constant in this case, thus `x` can be set to None (it is not used int the
computation). It is implemented for the case that in the future nonlinear problems
have to be solved.
vector : :class:`~numpy.ndarray` (N=1)
Vectorized magnetization distribution which is multiplied by the Hessian.
Returns
-------
result : :class:`~numpy.ndarray` (N=1)
Product of the input `vector` with the Hessian matrix of the costfunction.
"""
return (2 * self.fwd_model.jac_T_dot(x, self.Se_inv.dot(self.fwd_model.jac_dot(x, vector)))
+ self.regularisator.hess_dot(x, vector))
def hess_diag(self, _):
""" Return the diagonal of the Hessian.
Parameters
----------
_ : undefined
Unused input
"""
return np.ones(self.n)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# coding=utf-8
"""Convert vector fields.
The :mod:`~.fieldconverter` provides methods for converting a magnetization distribution `M` into
a vector potential `A` and convert this in turn into a magnetic field `B`. The direct way is also
possible.
"""
import logging
import numpy as np
from jutil import fft
from pyramid.fielddata import VectorData
__all__ = ['convert_M_to_A', 'convert_A_to_B', 'convert_M_to_B']
_log = logging.getLogger(__name__)
def convert_M_to_A(magdata, b_0=1.0):
"""Convert a magnetic vector distribution into a vector potential `A`.
Parameters
----------
magdata: :class:`~pyramid.magdata.VectorData` object
The magnetic vector field from which the A-field is calculated.
b_0: float, optional
The saturation magnetization which is used in the calculation.
Returns
-------
b_data: :class:`~pyramid.magdata.VectorData` object
The calculated B-field.
"""
_log.debug('Calling convert_M_to_A')
# Preparations of variables:
assert isinstance(magdata, VectorData), 'Only VectorData objects can be mapped!'
dim = magdata.dim
dim_kern = tuple(2 * np.array(dim) - 1) # Dimensions of the kernel
if fft.HAVE_FFTW:
dim_pad = tuple(2 * np.array(dim)) # is at least even (not neccessary a power of 2)
else:
dim_pad = tuple(2 ** np.ceil(np.log2(2 * np.array(dim))).astype(int)) # pow(2)
slice_B = (slice(dim[0] - 1, dim_kern[0]), # Shift because kernel center
slice(dim[1] - 1, dim_kern[1]), # is not at (0, 0, 0)!
slice(dim[2] - 1, dim_kern[2]))
slice_M = (slice(0, dim[0]), # Magnetization is padded on the far end!
slice(0, dim[1]), # B-field cutout is shifted as listed above
slice(0, dim[2])) # because of the kernel center!
# Set up kernels
coeff = magdata.a * b_0 / (4 * np.pi)
zzz, yyy, xxx = np.indices(dim_kern)
xxx -= dim[2] - 1
yyy -= dim[1] - 1
zzz -= dim[0] - 1
k_x = np.empty(dim_kern, dtype=magdata.field.dtype)
k_y = np.empty(dim_kern, dtype=magdata.field.dtype)
k_z = np.empty(dim_kern, dtype=magdata.field.dtype)
k_x[...] = coeff * xxx / np.abs(xxx ** 2 + yyy ** 2 + zzz ** 2 + 1E-30) ** 3
k_y[...] = coeff * yyy / np.abs(xxx ** 2 + yyy ** 2 + zzz ** 2 + 1E-30) ** 3
k_z[...] = coeff * zzz / np.abs(xxx ** 2 + yyy ** 2 + zzz ** 2 + 1E-30) ** 3
# Calculate Fourier trafo of kernel components:
k_x_fft = fft.rfftn(k_x, dim_pad)
k_y_fft = fft.rfftn(k_y, dim_pad)
k_z_fft = fft.rfftn(k_z, dim_pad)
# Prepare magnetization:
x_mag = np.zeros(dim_pad, dtype=magdata.field.dtype)
y_mag = np.zeros(dim_pad, dtype=magdata.field.dtype)
z_mag = np.zeros(dim_pad, dtype=magdata.field.dtype)
x_mag[slice_M] = magdata.field[0, ...]
y_mag[slice_M] = magdata.field[1, ...]
z_mag[slice_M] = magdata.field[2, ...]
# Calculate Fourier trafo of magnetization components:
x_mag_fft = fft.rfftn(x_mag)
y_mag_fft = fft.rfftn(y_mag)
z_mag_fft = fft.rfftn(z_mag)
# Convolve:
a_x_fft = y_mag_fft * k_z_fft - z_mag_fft * k_y_fft
a_y_fft = z_mag_fft * k_x_fft - x_mag_fft * k_z_fft
a_z_fft = x_mag_fft * k_y_fft - y_mag_fft * k_x_fft
a_x = fft.irfftn(a_x_fft)[slice_B]
a_y = fft.irfftn(a_y_fft)[slice_B]
a_z = fft.irfftn(a_z_fft)[slice_B]
# Return A-field:
return VectorData(magdata.a, np.asarray((a_x, a_y, a_z)))
def convert_A_to_B(a_data):
"""Convert a vector potential `A` into a B-field distribution.
Parameters
----------
a_data: :class:`~pyramid.magdata.VectorData` object
The vector potential field from which the A-field is calculated.
Returns
-------
b_data: :class:`~pyramid.magdata.VectorData` object
The calculated B-field.
"""
_log.debug('Calling convert_A_to_B')
assert isinstance(a_data, VectorData), 'Only VectorData objects can be mapped!'
#
axis = tuple([i for i in range(3) if a_data.dim[i] > 1])
#
x_grads = np.gradient(a_data.field[0, ...], axis=axis) #/ a_data.a
y_grads = np.gradient(a_data.field[1, ...], axis=axis) #/ a_data.a
z_grads = np.gradient(a_data.field[2, ...], axis=axis) #/ a_data.a
#
x_gradii = np.zeros(a_data.shape)
y_gradii = np.zeros(a_data.shape)
z_gradii = np.zeros(a_data.shape)
#
for i, axis in enumerate(axis):
x_gradii[axis] = x_grads[i]
y_gradii[axis] = y_grads[i]
z_gradii[axis] = z_grads[i]
#
x_grad_z, x_grad_y, x_grad_x = x_gradii
y_grad_z, y_grad_y, y_grad_x = y_gradii
z_grad_z, z_grad_y, z_grad_x = z_gradii
# Calculate cross product:
b_x = (z_grad_y - y_grad_z)
b_y = (x_grad_z - z_grad_x)
b_z = (y_grad_x - x_grad_y)
# Return B-field:
return VectorData(a_data.a, np.asarray((b_x, b_y, b_z)))
# Calculate gradients:
x_mag, y_mag, z_mag = a_data.field
x_grad_z, x_grad_y, x_grad_x = np.gradient(x_mag)
y_grad_z, y_grad_y, y_grad_x = np.gradient(y_mag)
z_grad_z, z_grad_y, z_grad_x = np.gradient(z_mag)
# Calculate cross product:
b_x = (z_grad_y - y_grad_z)
b_y = (x_grad_z - z_grad_x)
b_z = (y_grad_x - x_grad_y)
# Return B-field:
return VectorData(a_data.a, np.asarray((b_x, b_y, b_z)))
def convert_M_to_B(magdata, b_0=1.0):
"""Convert a magnetic vector distribution into a B-field distribution.
Parameters
----------
magdata: :class:`~pyramid.magdata.VectorData` object
The magnetic vector field from which the B-field is calculated.
b_0: float, optional
The saturation magnetization which is used in the calculation.
Returns
-------
b_data: :class:`~pyramid.magdata.VectorData` object
The calculated B-field.
"""
_log.debug('Calling convert_M_to_B')
assert isinstance(magdata, VectorData), 'Only VectorData objects can be mapped!'
return convert_A_to_B(convert_M_to_A(magdata, b_0=b_0))
This diff is collapsed.
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Subpackage containing Pyramid IO functionality."""
from .io_phasemap import load_phasemap
from .io_vectordata import load_vectordata
from .io_scalardata import load_scalardata
from .io_projector import load_projector
from .io_dataset import load_dataset
__all__ = ['load_phasemap', 'load_vectordata', 'load_scalardata', 'load_projector', 'load_dataset']
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""IO functionality for DataSet objects."""
import logging
import os
import h5py
import numpy as np
import scipy as sp
from ..dataset import DataSet
from ..file_io.io_projector import load_projector
from ..file_io.io_phasemap import load_phasemap
__all__ = ['load_projector']
_log = logging.getLogger(__name__)
def save_dataset(dataset, filename, overwrite=True):
"""%s"""
_log.debug('Calling save_dataset')
path, filename = os.path.split(filename)
name, extension = os.path.splitext(filename)
assert extension in ['.hdf5', ''], 'For now only HDF5 format is supported!'
if name.startswith('dataset_'):
name = name.split('dataset_')[1]
# Header file:
header_name = os.path.join(path, 'dataset_{}.hdf5'.format(name))
if not os.path.isfile(header_name) or overwrite: # Write if file does not exist or if forced:
with h5py.File(header_name, 'w') as f:
f.attrs['a'] = dataset.a
f.attrs['dim'] = dataset.dim
f.attrs['b_0'] = dataset.b_0
if dataset.mask is not None:
f.create_dataset('mask', data=dataset.mask)
if dataset.Se_inv is not None:
f.create_dataset('Se_inv', data=dataset.Se_inv.diagonal()) # Save only diagonal!
# PhaseMaps and Projectors:
for i, projector in enumerate(dataset.projectors):
projector_name = 'projector_{}_{}_{}{}'.format(name, i, projector.get_info(), extension)
projector.save(os.path.join(path, projector_name), overwrite=overwrite)
phasemap_name = 'phasemap_{}_{}_{}{}'.format(name, i, projector.get_info(), extension)
dataset.phasemaps[i].save(os.path.join(path, phasemap_name), overwrite=overwrite)
save_dataset.__doc__ %= DataSet.save.__doc__
def load_dataset(filename):
"""Load HDF5 file into a :class:`~pyramid.dataset.DataSet` instance.
Parameters
----------
filename: str
The filename to be loaded.
Returns
-------
projector : :class:`~.Projector`
A :class:`~.Projector` object containing the loaded data.
Notes
-----
This loads a header file and all matching HDF5 files which can be found. The filename
conventions have to be strictly followed for the process to be successful!
"""
_log.debug('Calling load_dataset')
path, filename = os.path.split(filename)
if path == '':
path = '.' # Make sure this can be used later!
name, extension = os.path.splitext(filename)
assert extension in ['.hdf5', ''], 'For now only HDF5 format is supported!'
if name.startswith('dataset_'):
name = name.split('dataset_')[1]
# Header file:
header_name = os.path.join(path, 'dataset_{}.hdf5'.format(name))
with h5py.File(header_name, 'r') as f:
a = f.attrs.get('a')
dim = f.attrs.get('dim')
b_0 = f.attrs.get('b_0')
mask = np.copy(f.get('mask', None))
Se_inv_diag = np.copy(f.get('Se_inv', None))
Se_inv = sp.sparse.diags(Se_inv_diag).tocsr()
dataset = DataSet(a, dim, b_0, mask, Se_inv)
# Projectors:
projectors = []
for f in os.listdir(path):
if f.startswith('projector') and f.endswith('.hdf5'):
projector_name, i = f.split('_')[1:3]
if projector_name == name:
projector = load_projector(os.path.join(path, f))
projectors.append((int(i), projector))
projectors = [p[1] for p in sorted(projectors, key=lambda x: x[0])]
# PhaseMaps:
phasemaps = []
for f in os.listdir(path):
if f.startswith('phasemap') and f.endswith('.hdf5'):
phasemap_name, i = f.split('_')[1:3]
if phasemap_name == name:
phasemap = load_phasemap(os.path.join(path, f))
phasemaps.append((int(i), phasemap))
phasemaps = [p[1] for p in sorted(phasemaps, key=lambda x: x[0])]
dataset.append(phasemaps, projectors)
# Return DataSet:
return dataset
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Subpackage containing functionality for creating magnetic distributions."""
from . import shapes
from . import examples
from .magcreator import *
__all__ = ['shapes', 'examples']
__all__.extend(magcreator.__all__)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.