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 43 additions and 1297 deletions
File deleted
File deleted
File deleted
File deleted
File deleted
File deleted
File deleted
# -*- coding: utf-8 -*-
"""Testcase for the regularisator module"""
import os
import unittest
import numpy as np
from numpy.testing import assert_allclose
from pyramid.regularisator import FirstOrderRegularisator
from pyramid.regularisator import NoneRegularisator
from pyramid.regularisator import ZeroOrderRegularisator
class TestCaseNoneRegularisator(unittest.TestCase):
def setUp(self):
self.n = 9
self.reg = NoneRegularisator()
def tearDown(self):
self.n = None
self.reg = None
def test_call(self):
assert_allclose(self.reg(np.arange(self.n)), 0,
err_msg='Unexpected behaviour in __call__()!')
def test_jac(self):
assert_allclose(self.reg.jac(np.arange(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in jac()!')
def test_hess_dot(self):
assert_allclose(self.reg.hess_dot(None, np.arange(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in jac()!')
def test_hess_diag(self):
assert_allclose(self.reg.hess_diag(np.arange(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in hess_diag()!')
class TestCaseZeroOrderRegularisator(unittest.TestCase):
def setUp(self):
self.n = 9
self.lam = 1
self.reg = ZeroOrderRegularisator(lam=self.lam)
def tearDown(self):
self.n = None
self.lam = None
self.reg = None
def test_call(self):
assert_allclose(self.reg(np.arange(self.n)), np.sum(np.arange(self.n) ** 2),
err_msg='Unexpected behaviour in __call__()!')
def test_jac(self):
assert_allclose(self.reg.jac(np.arange(self.n)), 2 * np.arange(self.n),
err_msg='Unexpected behaviour in jac()!')
jac = np.array([self.reg.jac(np.eye(self.n)[:, i]) for i in range(self.n)]).T
assert_allclose(jac, 2 * np.eye(self.n), err_msg='Unexpected behaviour in jac()!')
def test_hess_dot(self):
assert_allclose(self.reg.hess_dot(None, np.arange(self.n)), 2 * np.arange(self.n),
err_msg='Unexpected behaviour in jac()!')
hess = np.array([self.reg.hess_dot(None, np.eye(self.n)[:, i]) for i in range(self.n)]).T
assert_allclose(hess, 2 * np.eye(self.n), err_msg='Unexpected behaviour in hess_dot()!')
def test_hess_diag(self):
assert_allclose(self.reg.hess_diag(np.arange(self.n)), 2 * np.ones(self.n),
err_msg='Unexpected behaviour in hess_diag()!')
class TestCaseFirstOrderRegularisator(unittest.TestCase):
def setUp(self):
self.path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test_regularisator')
self.dim = (4, 5, 6)
self.mask = np.zeros(self.dim, dtype=bool)
self.mask[1:-1, 1:-1, 1:-1] = True
self.n = 3 * self.mask.sum()
self.lam = 1.
self.reg = FirstOrderRegularisator(self.mask, lam=self.lam)
def tearDown(self):
self.path = None
self.dim = None
self.mask = None
self.n = None
self.lam = None
self.reg = None
def test_call(self):
assert_allclose(self.reg(np.ones(self.n)), 0.,
err_msg='Unexpected behaviour in __call__()!')
assert_allclose(self.reg(np.zeros(self.n)), 0.,
err_msg='Unexpected behaviour in __call__()!')
cost_ref = np.load(os.path.join(self.path, 'first_order_cost_ref.npy'))
assert_allclose(self.reg(np.arange(self.n)), cost_ref,
err_msg='Unexpected behaviour in __call__()!')
def test_jac(self):
assert_allclose(self.reg.jac(np.ones(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in jac()!')
assert_allclose(self.reg.jac(np.zeros(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in jac()!')
jac_vec_ref = np.load(os.path.join(self.path, 'first_order_jac_vec_ref.npy'))
assert_allclose(self.reg.jac(np.arange(self.n)), jac_vec_ref, atol=1E-7,
err_msg='Unexpected behaviour in jac()!')
jac = np.array([self.reg.jac(np.eye(self.n)[:, i]) for i in range(self.n)]).T
jac_ref = np.load(os.path.join(self.path, 'first_order_jac_ref.npy'))
assert_allclose(jac, jac_ref, atol=1E-7,
err_msg='Unexpected behaviour in jac()!')
def test_hess_dot(self):
assert_allclose(self.reg.hess_dot(None, np.ones(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in hess_dot()!')
assert_allclose(self.reg.hess_dot(None, np.zeros(self.n)), np.zeros(self.n),
err_msg='Unexpected behaviour in hess_dot()!')
hess_vec_ref = np.load(os.path.join(self.path, 'first_order_jac_vec_ref.npy'))
assert_allclose(self.reg.hess_dot(None, np.arange(self.n)), hess_vec_ref, atol=1E-7,
err_msg='Unexpected behaviour in hess_dot()!')
hess = np.array([self.reg.hess_dot(None, np.eye(self.n)[:, i]) for i in range(self.n)]).T
hess_ref = np.load(os.path.join(self.path, 'first_order_jac_ref.npy'))
assert_allclose(hess, hess_ref, atol=1E-7,
err_msg='Unexpected behaviour in hess_dot()!')
def test_hess_diag(self):
hess_diag = self.reg.hess_diag(np.ones(self.n))
hess_diag_ref = np.diag(np.load(os.path.join(self.path, 'first_order_jac_ref.npy')))
assert_allclose(hess_diag, hess_diag_ref, atol=1E-7,
err_msg='Unexpected behaviour in hess_diag()!')
if __name__ == '__main__':
import nose
nose.run(defaultTest=__name__)
File deleted
File deleted
File deleted
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Subpackage containing Pyramid utility functions."""
from .pm import pm
from .reconstruction_2d_from_phasemap import reconstruction_2d_from_phasemap
from .reconstruction_3d_from_magdata import reconstruction_3d_from_magdata
from .phasemap_creator import gui_phasemap_creator
from .mag_slicer import gui_mag_slicer
__all__ = ['pm', 'reconstruction_2d_from_phasemap', 'reconstruction_3d_from_magdata',
'gui_phasemap_creator', 'gui_mag_slicer']
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mag_slicer.ui'
#
# Created: Sun Aug 31 20:39:52 2014
# by: PyQt4 UI code generator 4.9.6
#
# WARNING! All changes made in this file will be lost!
"""GUI for slicing 3D magnetization distributions."""
import logging
import os
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.uic import loadUiType
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from ..projector import SimpleProjector
from ..kernel import Kernel
from ..phasemapper import PhaseMapperRDFC
from ..file_io.io_vectordata import load_vectordata
__all__ = ['gui_mag_slicer']
_log = logging.getLogger(__name__)
ui_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mag_slicer.ui')
UI_MainWindow, QMainWindow = loadUiType(ui_location)
class Main(QMainWindow, UI_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.connect(self.checkBoxLog, QtCore.SIGNAL('clicked()'),
self.update_slice)
self.connect(self.checkBoxScale, QtCore.SIGNAL('clicked()'),
self.update_slice)
self.connect(self.spinBoxSlice, QtCore.SIGNAL('valueChanged(int)'),
self.update_slice)
self.connect(self.comboBoxSlice, QtCore.SIGNAL('currentIndexChanged(int)'),
self.update_phase)
self.connect(self.spinBoxGain, QtCore.SIGNAL('valueChanged(double)'),
self.update_phase)
self.connect(self.checkBoxAuto, QtCore.SIGNAL('toggled(bool)'),
self.update_phase)
self.connect(self.checkBoxSmooth, QtCore.SIGNAL('toggled(bool)'),
self.update_phase)
self.connect(self.pushButtonLoad, QtCore.SIGNAL('clicked()'),
self.load)
self.is_magdata_loaded = False
self.magdata = None
def addmpl(self):
fig = Figure()
fig.add_subplot(111, aspect='equal')
self.canvasMag = FigureCanvas(fig)
self.layoutMag.addWidget(self.canvasMag)
self.canvasMag.draw()
self.toolbarMag = NavigationToolbar(self.canvasMag, self, coordinates=True)
self.layoutMag.addWidget(self.toolbarMag)
fig = Figure()
fig.add_subplot(111, aspect='equal')
self.canvasPhase = FigureCanvas(fig)
self.layoutPhase.addWidget(self.canvasPhase)
self.canvasPhase.draw()
self.toolbarPhase = NavigationToolbar(self.canvasPhase, self, coordinates=True)
self.layoutPhase.addWidget(self.toolbarPhase)
fig = Figure()
fig.add_subplot(111, aspect='equal')
self.canvasHolo = FigureCanvas(fig)
self.layoutHolo.addWidget(self.canvasHolo)
self.canvasHolo.draw()
self.toolbarHolo = NavigationToolbar(self.canvasHolo, self, coordinates=True)
self.layoutHolo.addWidget(self.toolbarHolo)
def update_phase(self):
if self.is_magdata_loaded:
mode_ind = self.comboBoxSlice.currentIndex()
if mode_ind == 0:
self.mode = 'z'
length = self.magdata.dim[0] - 1
elif mode_ind == 1:
self.mode = 'y'
length = self.magdata.dim[1] - 1
else:
self.mode = 'x'
length = self.magdata.dim[2] - 1
if self.checkBoxAuto.isChecked():
gain = 'auto'
else:
gain = self.spinBoxGain.value()
self.projector = SimpleProjector(self.magdata.dim, axis=self.mode)
self.spinBoxSlice.setMaximum(length)
self.scrollBarSlice.setMaximum(length)
self.spinBoxSlice.setValue(int(length / 2.))
self.update_slice()
kernel = Kernel(self.magdata.a, self.projector.dim_uv)
self.phasemapper = PhaseMapperRDFC(kernel)
self.phasemap = self.phasemapper(self.projector(self.magdata))
self.canvasPhase.figure.axes[0].clear()
self.phasemap.plot_phase(axis=self.canvasPhase.figure.axes[0], cbar=False)
if self.checkBoxSmooth.isChecked():
interpolation = 'bilinear'
else:
interpolation = 'none'
self.canvasHolo.figure.axes[0].clear()
self.phasemap.plot_holo(axis=self.canvasHolo.figure.axes[0], gain=gain,
interpolation=interpolation)
self.canvasPhase.draw()
self.canvasHolo.draw()
def update_slice(self):
if self.is_magdata_loaded:
self.canvasMag.figure.axes[0].clear()
self.magdata.plot_quiver(axis=self.canvasMag.figure.axes[0], proj_axis=self.mode,
ax_slice=self.spinBoxSlice.value(),
log=self.checkBoxLog.isChecked(),
scaled=self.checkBoxScale.isChecked())
self.canvasMag.draw()
def load(self):
try:
mag_file = QtGui.QFileDialog.getOpenFileName(self, 'Open Data File', '',
'HDF5 files (*.hdf5)')
except ValueError:
return # Abort if no conf_path is selected!
import hyperspy.api as hs
print(hs.load(mag_file))
self.magdata = load_vectordata(mag_file)
if not self.is_magdata_loaded:
self.addmpl()
self.is_magdata_loaded = True
self.comboBoxSlice.setCurrentIndex(0)
self.update_phase()
def gui_mag_slicer():
"""Call the GUI for viewing magnetic distributions."""
_log.debug('Calling gui_mag_slicer')
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
app.exec()
return main.magdata
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1222</width>
<height>480</height>
</rect>
</property>
<property name="windowTitle">
<string>MagSlicer</string>
</property>
<widget class="QWidget" name="centralwidget">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Mag Slicer</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButtonLoad">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Laden</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxScale">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Scaled</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="tristate">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxLog">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Log</string>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBoxSlice">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>xy-plane</string>
</property>
</item>
<item>
<property name="text">
<string>xz-plane</string>
</property>
</item>
<item>
<property name="text">
<string>zy-plane</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QLabel" name="labelSlice">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Slice:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinBoxSlice">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item>
<widget class="QScrollBar" name="scrollBarSlice">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>400</width>
<height>0</height>
</size>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxSmooth">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Smooth</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxAuto">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Auto</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelGain">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Gain:</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="spinBoxGain">
<property name="enabled">
<bool>false</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximum">
<double>1000000.000000000000000</double>
</property>
<property name="singleStep">
<double>0.100000000000000</double>
</property>
<property name="value">
<double>1.000000000000000</double>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QWidget" name="layoutPlots" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayoutPlots">
<item>
<layout class="QVBoxLayout" name="layoutMag"/>
</item>
<item>
<layout class="QVBoxLayout" name="layoutPhase"/>
</item>
<item>
<layout class="QVBoxLayout" name="layoutHolo"/>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>spinBoxSlice</sender>
<signal>valueChanged(int)</signal>
<receiver>scrollBarSlice</receiver>
<slot>setValue(int)</slot>
<hints>
<hint type="sourcelabel">
<x>322</x>
<y>19</y>
</hint>
<hint type="destinationlabel">
<x>386</x>
<y>20</y>
</hint>
</hints>
</connection>
<connection>
<sender>scrollBarSlice</sender>
<signal>sliderMoved(int)</signal>
<receiver>spinBoxSlice</receiver>
<slot>setValue(int)</slot>
<hints>
<hint type="sourcelabel">
<x>431</x>
<y>24</y>
</hint>
<hint type="destinationlabel">
<x>321</x>
<y>20</y>
</hint>
</hints>
</connection>
<connection>
<sender>checkBoxAuto</sender>
<signal>toggled(bool)</signal>
<receiver>spinBoxGain</receiver>
<slot>setDisabled(bool)</slot>
<hints>
<hint type="sourcelabel">
<x>1065</x>
<y>22</y>
</hint>
<hint type="destinationlabel">
<x>1166</x>
<y>21</y>
</hint>
</hints>
</connection>
</connections>
</ui>
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'phasemap_creator.ui'
#
# Created: Thu Sep 24 11:42:11 2015
# by: PyQt4 UI code generator 4.9.6
#
# WARNING! All changes made in this file will be lost!
"""GUI for setting up PhasMaps from existing data in different formats."""
import logging
import os
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.uic import loadUiType
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from PIL import Image
import numpy as np
import hyperspy.api as hs
import pyramid as pr
__all__ = ['gui_phasemap_creator']
_log = logging.getLogger(__name__)
ui_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'phasemap_creator.ui')
UI_MainWindow, QMainWindow = loadUiType(ui_location)
class Main(QMainWindow, UI_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.connect(self.pushButton_phase, QtCore.SIGNAL('clicked()'),
self.load_phase)
self.connect(self.pushButton_mask, QtCore.SIGNAL('clicked()'),
self.load_mask)
self.connect(self.pushButton_conf, QtCore.SIGNAL('clicked()'),
self.load_conf)
self.connect(self.pushButton_export, QtCore.SIGNAL('clicked()'),
self.export)
self.connect(self.horizontalScrollBar, QtCore.SIGNAL('valueChanged(int)'),
self.doubleSpinBox_thres.setValue)
self.connect(self.doubleSpinBox_thres, QtCore.SIGNAL('valueChanged(double)'),
self.horizontalScrollBar.setValue)
self.connect(self.checkBox_mask, QtCore.SIGNAL('clicked()'),
self.update_phasemap)
self.connect(self.checkBox_conf, QtCore.SIGNAL('clicked()'),
self.update_phasemap)
self.connect(self.doubleSpinBox_a, QtCore.SIGNAL('editingFinished()'),
self.update_phasemap)
self.connect(self.doubleSpinBox_thres, QtCore.SIGNAL('valueChanged(double)'),
self.update_mask)
self.phase_loaded = False
self.mask_loaded = False
self.dir = ''
self.phasemap = None
def addmpl(self):
fig = Figure()
fig.add_subplot(111, aspect='equal')
self.canvas = FigureCanvas(fig)
self.mplLayout.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas, self, coordinates=True)
self.mplLayout.addWidget(self.toolbar)
def update_phasemap(self):
if self.phase_loaded:
self.phasemap.a = self.doubleSpinBox_a.value()
show_mask = self.checkBox_mask.isChecked()
show_conf = self.checkBox_conf.isChecked()
self.canvas.figure.axes[0].clear()
self.canvas.figure.axes[0].hold(True)
self.phasemap.plot_phase('PhaseMap', axis=self.canvas.figure.axes[0],
show_mask=show_mask, show_conf=show_conf, cbar=False)
self.canvas.draw()
def update_mask(self):
if self.mask_loaded:
threshold = self.doubleSpinBox_thres.value()
mask_img = Image.fromarray(self.raw_mask)
mask = np.asarray(mask_img.resize(list(reversed(self.phasemap.dim_uv))))
self.phasemap.mask = np.where(mask >= threshold, True, False)
self.update_phasemap()
def load_phase(self):
try:
self.phase_path = QtGui.QFileDialog.getOpenFileName(self, 'Load Phase', self.dir)
self.phasemap = pr.file_io.io_phasemap._load(self.phase_path, as_phasemap=True)
except ValueError:
return # Abort if no phase_path is selected!
self.doubleSpinBox_a.setValue(self.phasemap.a)
self.dir = os.path.join(os.path.dirname(self.phase_path))
if not self.phase_loaded:
self.addmpl()
self.pushButton_mask.setEnabled(True)
self.pushButton_conf.setEnabled(True)
self.pushButton_export.setEnabled(True)
self.phase_loaded = True
self.horizontalScrollBar.setMinimum(0)
self.horizontalScrollBar.setMaximum(0)
self.horizontalScrollBar.setEnabled(False)
self.doubleSpinBox_thres.setMinimum(0)
self.doubleSpinBox_thres.setMaximum(0)
self.doubleSpinBox_thres.setValue(0)
self.doubleSpinBox_thres.setEnabled(False)
self.mask_loaded = False
self.update_phasemap()
def load_mask(self):
try:
mask_path = QtGui.QFileDialog.getOpenFileName(self, 'Load Mask', self.dir)
self.raw_mask = pr.file_io.io_phasemap._load(mask_path)
except ValueError:
return # Abort if no mask_path is selected!
mask_min = self.raw_mask.min()
mask_max = self.raw_mask.max()
self.horizontalScrollBar.setEnabled(True)
self.horizontalScrollBar.setMinimum(mask_min)
self.horizontalScrollBar.setMaximum(mask_max)
self.horizontalScrollBar.setSingleStep((mask_max - mask_min) / 255.)
self.horizontalScrollBar.setValue((mask_max - mask_min) / 2.)
self.doubleSpinBox_thres.setEnabled(True)
self.doubleSpinBox_thres.setMinimum(mask_min)
self.doubleSpinBox_thres.setMaximum(mask_max)
self.doubleSpinBox_thres.setSingleStep((mask_max - mask_min) / 255.)
self.doubleSpinBox_thres.setValue((mask_max - mask_min) / 2.)
self.mask_loaded = True
self.update_mask()
def load_conf(self):
try:
conf_path = QtGui.QFileDialog.getOpenFileName(self, 'Load Confidence', self.dir)
confidence = pr.file_io.io_phasemap._load(conf_path)
except ValueError:
return # Abort if no conf_path is selected!
confidence /= confidence.max() + 1e-30
self.phasemap.confidence = confidence
self.update_phasemap()
def export(self):
try:
export_name = os.path.splitext(os.path.basename(self.phase_path))[0]
export_default = os.path.join(self.dir, 'phasemap_gui_{}.hdf5'.format(export_name))
export_path = QtGui.QFileDialog.getSaveFileName(self, 'Export PhaseMap',
export_default, 'HDF5 (*.hdf5)')
self.phasemap.to_signal().save(export_path, overwrite=True)
except (ValueError, AttributeError):
return # Abort if no export_path is selected or self.phasemap doesn't exist yet!
def gui_phasemap_creator():
"""Call the GUI for phasemap creation."""
_log.debug('Calling gui_phasemap_creator')
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
app.exec()
return main.phasemap
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>726</width>
<height>632</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QWidget" name="mplwidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QVBoxLayout" name="mplLayout"/>
</item>
</layout>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton_phase">
<property name="text">
<string>Load Phase</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_mask">
<property name="text">
<string>Load Mask</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_conf">
<property name="text">
<string>Load Confidence</string>
</property>
<property name="checkable">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButton_export">
<property name="text">
<string>Export Phasemap</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Grid spacing [nm]:</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="doubleSpinBox_a">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="maximum">
<double>1000.000000000000000</double>
</property>
<property name="value">
<double>1.000000000000000</double>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Mask Threshold:</string>
</property>
</widget>
</item>
<item>
<widget class="QDoubleSpinBox" name="doubleSpinBox_thres">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="baseSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="prefix">
<string/>
</property>
<property name="decimals">
<number>2</number>
</property>
<property name="maximum">
<double>0.000000000000000</double>
</property>
</widget>
</item>
<item>
<widget class="QScrollBar" name="horizontalScrollBar">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maximum">
<number>0</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_mask">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>show mask</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox_conf">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>show confidence</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Convenience function for phase mapping magnetic distributions."""
import logging
from ..kernel import Kernel
from ..phasemapper import PhaseMapperRDFC
from ..projector import RotTiltProjector, XTiltProjector, YTiltProjector, SimpleProjector
__all__ = ['pm']
_log = logging.getLogger(__name__)
def pm(magdata, mode='z', b_0=1, **kwargs):
"""Convenience function for fast magnetic phase mapping.
Parameters
----------
magdata : :class:`~.VectorData`
A :class:`~.VectorData` object, from which the projected phase map should be calculated.
mode: {'z', 'y', 'x', 'x-tilt', 'y-tilt', 'rot-tilt'}, optional
Projection mode which determines the :class:`~.pyramid.projector.Projector` subclass, which
is used for the projection. Default is a simple projection along the `z`-direction.
b_0 : float, optional
Saturation magnetization in Tesla, which is used for the phase calculation. Default is 1.
**kwargs : additional arguments
Additional arguments like `dim_uv`, 'tilt' or 'rotation', which are passed to the
projector-constructor, defined by the `mode`.
Returns
-------
phasemap : :class:`~pyramid.phasemap.PhaseMap`
The calculated phase map as a :class:`~.PhaseMap` object.
"""
_log.debug('Calling pm')
# Determine projection mode:
if mode == 'rot-tilt':
projector = RotTiltProjector(magdata.dim, **kwargs)
elif mode == 'x-tilt':
projector = XTiltProjector(magdata.dim, **kwargs)
elif mode == 'y-tilt':
projector = YTiltProjector(magdata.dim, **kwargs)
elif mode in ['x', 'y', 'z']:
projector = SimpleProjector(magdata.dim, axis=mode, **kwargs)
else:
raise ValueError("Invalid mode (use 'x', 'y', 'z', 'x-tilt', 'y-tilt' or 'rot-tilt')")
# Project:
mag_proj = projector(magdata)
# Set up phasemapper and map phase:
phasemapper = PhaseMapperRDFC(Kernel(magdata.a, projector.dim_uv, b_0=b_0))
phasemap = phasemapper(mag_proj)
# Get mask from magdata:
phasemap.mask = mag_proj.get_mask()[0, ...]
# Return phase:
return phasemap
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Reconstruct a magnetization distributions from a single phase map."""
import logging
import numpy as np
from jutil.taketime import TakeTime
from .. import reconstruction
from ..dataset import DataSet
from ..projector import SimpleProjector
from ..regularisator import FirstOrderRegularisator
from ..forwardmodel import ForwardModel
from ..costfunction import Costfunction
from .pm import pm
__all__ = ['reconstruction_2d_from_phasemap']
_log = logging.getLogger(__name__)
def reconstruction_2d_from_phasemap(phasemap, b_0=1, lam=1E-3, max_iter=100, ramp_order=1,
plot_results=False, ar_dens=None):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
phasemap: :class:`~PhaseMap`
The phasemap which is used for the reconstruction.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
lam : float
Regularisation parameter determining the weighting between measurements and regularisation.
max_iter : int, optional
The maximum number of iterations for the opimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
ar_dens: int, optional
Number defining the arrow density which is plotted. A higher ar_dens number skips more
arrows (a number of 2 plots every second arrow). Default is 1.
Returns
-------
magdata_rec, cost: :class:`~.VectorData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_2d_from_phasemap')
# Construct DataSet, Regularisator, ForwardModel and Costfunction:
dim = (1,) + phasemap.dim_uv
data = DataSet(phasemap.a, dim, b_0)
data.append(phasemap, SimpleProjector(dim))
data.set_3d_mask()
fwd_model = ForwardModel(data, ramp_order)
reg = FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct:
with TakeTime('reconstruction time'):
magdata_rec = reconstruction.optimize_linear(cost, max_iter=max_iter)
param_cache = cost.fwd_model.ramp.param_cache
if ramp_order is None:
offset, ramp = 0, (0, 0)
elif ramp_order >= 1:
offset, ramp = param_cache[0][0], (param_cache[1][0], param_cache[2][0])
elif ramp_order == 0:
offset, ramp = param_cache[0][0], (0, 0)
else:
raise ValueError('ramp_order has to be a positive integer or None!')
# Plot stuff:
if plot_results:
if ar_dens is None:
ar_dens = np.max([1, np.max(dim) // 64])
axis = magdata_rec.plot_field('Reconstructed Distribution', figsize=(15, 15))
magdata_rec.plot_quiver(axis=axis, ar_dens=ar_dens, coloring='uniform')
phasemap.plot_combined('Input Phase')
phasemap -= fwd_model.ramp(index=0)
phasemap.plot_combined('Input Phase (ramp corrected)')
phasemap_rec = pm(magdata_rec)
title = 'Reconstructed Phase'
if ramp_order is not None:
if ramp_order >= 0:
print('offset:', offset)
title += ', fitted Offset: {:.2g} [rad]'.format(offset)
if ramp_order >= 1:
print('ramp:', ramp)
title += ', (Fitted Ramp: (u:{:.2g}, v:{:.2g}) [rad/nm]'.format(*ramp)
phasemap_rec.plot_combined(title)
diff = (phasemap_rec - phasemap).phase
diff_name = 'Difference (mean: {:.2g})'.format(diff.mean())
(phasemap_rec - phasemap).plot_phase(diff_name, sigma_clip=3)
if ramp_order is not None:
fwd_model.ramp(0).plot_combined('Fitted Ramp')
# Return reconstructed magnetisation distribution and cost function:
return magdata_rec, cost
# -*- coding: utf-8 -*-
# Copyright 2016 by Forschungszentrum Juelich GmbH
# Author: J. Caron
#
"""Reconstruct a magnetization distributions from phase maps created from it."""
import logging
import numpy as np
import multiprocessing as mp
from jutil.taketime import TakeTime
from .. import reconstruction
from ..dataset import DataSet
from ..projector import XTiltProjector, YTiltProjector
from ..ramp import Ramp
from ..regularisator import FirstOrderRegularisator
from ..forwardmodel import ForwardModel, DistributedForwardModel
from ..costfunction import Costfunction
__all__ = ['reconstruction_3d_from_magdata']
_log = logging.getLogger(__name__)
def reconstruction_3d_from_magdata(magdata, b_0=1, lam=1E-3, max_iter=100, ramp_order=1,
angles=np.linspace(-90, 90, num=19), dim_uv=None,
axes=(True, True), noise=0, offset_max=0, ramp_max=0,
use_internal_mask=True, plot_results=False, plot_input=False,
ar_dens=None, multicore=True):
"""Convenience function for reconstructing a projected distribution from a single phasemap.
Parameters
----------
magdata: :class:`~.VectorData`
The magnetisation distribution which should be used for the reconstruction.
b_0 : float, optional
The magnetic induction corresponding to a magnetization `M`\ :sub:`0` in T.
The default is 1.
lam : float
Regularisation parameter determining the weighting between measurements and regularisation.
max_iter : int, optional
The maximum number of iterations for the opimization.
ramp_order : int or None (default)
Polynomial order of the additional phase ramp which will be added to the phase maps.
All ramp parameters have to be at the end of the input vector and are split automatically.
Default is None (no ramps are added).
angles: :class:`~numpy.ndarray` (N=1), optional
Numpy array determining the angles which should be used for the projectors in x- and
y-direction. This implicitly sets the number of images per rotation axis. Defaults to a
range from -90° to 90° degrees, in 10° steps.
dim_uv: int or None (default)
Determines if the phasemaps should be padded to a certain size while calculating.
axes: tuple of booleans (N=2), optional
Determines if both tilt axes should be calculated. The order is (x, y), both are True by
default.
noise: float, optional
If this is not zero, random gaussian noise with this as a maximum value will be applied
to all calculated phasemaps. The default is 0.
offset_max: float, optional
if this is not zero, a random offset with this as a maximum value will be applied to all
calculated phasemaps. The default is 0.
ramp_max: float, optional
if this is not zero, a random linear ramp with this as a maximum value will be applied
to both axes of all calculated phasemaps. The default is 0.
use_internal_mask: boolean, optional
If True, the mask from the input magnetization distribution is taken for the
reconstruction. If False, the mask is calculated via logic backprojection from the 2D-masks
of the input phasemaps.
plot_results: boolean, optional
If True, the results are plotted after reconstruction.
plot_input:
If True, the input phasemaps are plotted after reconstruction.
ar_dens: int, optional
Number defining the arrow density which is plotted. A higher ar_dens number skips more
arrows (a number of 2 plots every second arrow). Default is 1.
multicore: boolean, optional
Determines if multiprocessing should be used. Default is True. Phasemap calculations
will be divided onto the separate cores.
Returns
-------
magdata_rec, cost: :class:`~.VectorData`, :class:`~.Costfunction`
The reconstructed magnetisation distribution and the used costfunction.
"""
_log.debug('Calling reconstruction_3d_from_magdata')
# Construct DataSet:
dim = magdata.dim
if ar_dens is None:
ar_dens = np.max([1, np.max(dim) // 128])
data = DataSet(magdata.a, magdata.dim, b_0)
# Construct projectors:
projectors = []
# Construct data set and regularisator:
for angle in angles:
angle_rad = angle * np.pi / 180
if axes[0]:
projectors.append(XTiltProjector(magdata.dim, angle_rad, dim_uv))
if axes[1]:
projectors.append(YTiltProjector(magdata.dim, angle_rad, dim_uv))
data.projectors = projectors
data.phasemaps = data.create_phasemaps(magdata)
# Add projectors and construct according phase maps:
for i, phasemap in enumerate(data.phasemaps):
offset = np.random.uniform(-offset_max, offset_max)
ramp_u = np.random.uniform(-ramp_max, ramp_max)
ramp_v = np.random.uniform(-ramp_max, ramp_max)
phasemap += Ramp.create_ramp(phasemap.a, phasemap.dim_uv, (offset, ramp_u, ramp_v))
# Add noise if necessary:
if noise != 0:
for i, phasemap in enumerate(data.phasemaps):
phasemap.phase += np.random.normal(0, noise, phasemap.dim_uv)
data.phasemaps[i] = phasemap
# Construct mask:
if use_internal_mask:
data.mask = magdata.get_mask() # Use perfect mask from magdata!
else:
data.set_3d_mask() # Construct mask from 2D phase masks!
# Construct regularisator, forward model and costfunction:
if multicore:
mp.freeze_support()
fwd_model = DistributedForwardModel(data, ramp_order=ramp_order, nprocs=mp.cpu_count())
else:
fwd_model = ForwardModel(data, ramp_order=ramp_order)
reg = FirstOrderRegularisator(data.mask, lam, add_params=fwd_model.ramp.n)
cost = Costfunction(fwd_model, reg)
# Reconstruct and save:
with TakeTime('reconstruction time'):
magdata_rec = reconstruction.optimize_linear(cost, max_iter=max_iter)
# Finalize ForwardModel (returns workers if multicore):
fwd_model.finalize()
# Plot input:
if plot_input:
data.phase_plots()
# Plot results:
if plot_results:
data.display_mask(ar_dens=ar_dens)
magdata.plot_quiver3d('Original Distribution', ar_dens=ar_dens)
magdata_rec.plot_quiver3d('Reconstructed Distribution (angle)', ar_dens=ar_dens)
magdata_rec.plot_quiver3d('Reconstructed Distribution (amplitude)',
ar_dens=ar_dens, coloring='amplitude')
# Return reconstructed magnetisation distribution and cost function:
return magdata_rec, cost
# -*- coding: utf-8 -*-
# setup.cfg
# :copyright: Copyright 2020 Jan Caron
# TODO: pip install .[io] is not working because hyperspy depends on trait which has no wheels on PyPI at the moment...
# TODO: See https://github.com/hyperspy/hyperspy/issues/2315 and https://github.com/enthought/traits/issues/357
# TODO: Add hyperspy back as soon (if?) this is resolved... Until then: install hyperspy with conda!
# TODO: mayavi has the same exact problem and tvtk is apparently also a problem...
# CONFIGURATION FOR TESTING:
[aliases]
test = pytest
[coverage:run]
branch = True
source = src/empyre
omit =
tests/*
[flake8]
max-line-length = 120
ignore =
# module import not at top of file
E402
# closing bracket does not match visual indentation
E124
# continuation line with same indent as next logical line
E125
# missing whitespace around arithmetic operator
E226
# line break before binary operator
W503
# line break after binary operator
W504
# do not use variables named ‘l’, ‘O’, or ‘I’
E741
per-file-ignores =
*/__init__.py: F401, F403, F405, F821
# F401: module imported but unused
# F403: 'from module import *' used; unable to detect undefined names
# F405: Name may be undefined, or defined from star imports: module
# F821: undefined name 'name'