Skip to content
Snippets Groups Projects
Commit bce38269 authored by Jan Caron's avatar Jan Caron
Browse files

Hopefully made hyperspy import (now at beginning of pyramid package) work!

Added PyCharm files!
Commit before Reformatting with PyCharms!
parent 7aae4499
No related branches found
No related tags found
No related merge requests found
Showing
with 1352 additions and 139 deletions
Pyramid
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/pyramid" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/scripts" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="Python 2.7.11 (C:\Anaconda2\python.exe)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="HyperSpy" />
<orderEntry type="module" module-name="Jutil" />
<orderEntry type="module" module-name="Publications" />
<orderEntry type="module" module-name="Script-Vault" />
</component>
<component name="TestRunnerService">
<option name="projectConfiguration" value="Nosetests" />
<option name="PROJECT_TEST_RUNNER" value="Nosetests" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
<OptionsSetting value="true" id="Remove" />
<OptionsSetting value="true" id="Checkout" />
<OptionsSetting value="true" id="Update" />
<OptionsSetting value="true" id="Status" />
<OptionsSetting value="true" id="Edit" />
<ConfirmationsSetting value="0" id="Add" />
<ConfirmationsSetting value="0" id="Remove" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.11 (C:\Anaconda2\python.exe)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/../HyperSpy/.idea/HyperSpy.iml" filepath="$PROJECT_DIR$/../HyperSpy/.idea/HyperSpy.iml" />
<module fileurl="file://$PROJECT_DIR$/../Jutil/.idea/Jutil.iml" filepath="$PROJECT_DIR$/../Jutil/.idea/Jutil.iml" />
<module fileurl="file://$PROJECT_DIR$/../Publications/.idea/Publications.iml" filepath="$PROJECT_DIR$/../Publications/.idea/Publications.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/Pyramid.iml" filepath="$PROJECT_DIR$/.idea/Pyramid.iml" />
<module fileurl="file://$PROJECT_DIR$/../Script-Vault/.idea/Script-Vault.iml" filepath="$PROJECT_DIR$/../Script-Vault/.idea/Script-Vault.iml" />
</modules>
</component>
</project>
\ No newline at end of file
This diff is collapsed.
[.ShellClassInfo]
IconResource=C:\Users\Jan\Home\PhD Thesis\Spyder\Pyramid\docs\icon.ico,0
IconResource=C:\Users\Jan\Home\PhD Thesis\Projects\Pyramid\docs\icon.ico,0
[ViewState]
Mode=
Vid=
......
......@@ -47,30 +47,17 @@ numcore
Provides fast numerical functions for core routines.
"""
import logging
_log = logging.getLogger(__name__)
try: # Try importing HyperSpy (here because otherwise API Errors might occur):
import hyperspy.api
except ImportError:
_log.error('Could not load hyperspy package!')
from . import analytic
from . import magcreator
from . import reconstruction
from . import fft
from .costfunction import * # analysis:ignore
from .dataset import * # analysis:ignore
from .diagnostics import * # analysis:ignore
from .forwardmodel import * # analysis:ignore
from .kernel import * # analysis:ignore
from .magdata import * # analysis:ignore
from .phasemap import * # analysis:ignore
from .phasemapper import * # analysis:ignore
from .projector import * # analysis:ignore
from .regularisator import * # analysis:ignore
from .ramp import * # analysis:ignore
from .quaternion import * # analysis:ignore
from .colormap import * # analysis:ignore
from .config import * # analysis:ignore
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
......
......@@ -5,15 +5,13 @@
"""This module provides a custom :class:`~.DirectionalColormap` colormap class which has a few
additional functions and can encode three-dimensional directions."""
import logging
from numbers import Number
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from numbers import Number
import logging
__all__ = ['DirectionalColormap', 'TransparentColormap']
......@@ -245,7 +243,9 @@ class TransparentColormap(mpl.colors.LinearSegmentedColormap):
_log = logging.getLogger(__name__+'.TransparentColormap')
def __init__(self, r=1., g=0., b=0., alpha_range=[0., 1.]):
def __init__(self, r=1., g=0., b=0., alpha_range=None):
if alpha_range is None:
alpha_range = [0., 1.]
self._log.debug('Calling __create_directional_colormap')
red = [(0., 0., r), (1., r, 1.)]
green = [(0., 0., g), (1., g, 1.)]
......
......@@ -18,12 +18,18 @@ from scipy.ndimage.interpolation import zoom
from pyramid import fft
from pyramid.colormap import DirectionalColormap
_log = logging.getLogger(__name__)
try: # Try importing HyperSpy:
import hyperspy.api as hs
except ImportError:
hs = None
_log.error('Could not load hyperspy package!')
__all__ = ['MagData']
class MagData(object):
'''Class for storing magnetization data.
"""Class for storing magnetization data.
Represents 3-dimensional magnetic distributions with 3 components which are stored as a
2-dimensional numpy array in `magnitude`, but which can also be accessed as a vector via
......@@ -47,7 +53,7 @@ class MagData(object):
mag_vec: :class:`~numpy.ndarray` (N=1)
Vector containing the magnetic distribution.
'''
"""
_log = logging.getLogger(__name__+'.MagData')
......@@ -194,7 +200,7 @@ class MagData(object):
'''
self._log.debug('Calling scale_down')
assert n > 0 and isinstance(n, (int, long)), 'n must be a positive integer!'
self.a = self.a * 2**n
self.a *= 2 ** n
for t in range(n):
# Pad if necessary:
pz, py, px = self.dim[0] % 2, self.dim[1] % 2, self.dim[2] % 2
......@@ -229,7 +235,7 @@ class MagData(object):
assert n > 0 and isinstance(n, (int, long)), 'n must be a positive integer!'
assert 5 > order >= 0 and isinstance(order, (int, long)), \
'order must be a positive integer between 0 and 5!'
self.a = self.a / 2**n
self.a /= 2 ** n
self.magnitude = np.array((zoom(self.magnitude[0], zoom=2**n, order=order),
zoom(self.magnitude[1], zoom=2**n, order=order),
zoom(self.magnitude[2], zoom=2**n, order=order)))
......@@ -484,10 +490,8 @@ class MagData(object):
'''
self._log.debug('Calling to_signal')
# Try importing HyperSpy:
try:
import hyperspy.api as hs
except ImportError:
self._log.error('Could not load hyperspy package!')
if hs is None:
self._log.error('This method recquires the hyperspy package!')
return
# Create signal:
signal = hs.signals.Signal(np.rollaxis(self.magnitude, 0, 4))
......@@ -575,18 +579,16 @@ class MagData(object):
'''
cls._log.debug('Calling load_from_hdf5')
if hs is None:
self._log.error('This method recquires the hyperspy package!')
return
# Use relative path if filename isn't already absolute:
if not os.path.isabs(filename):
from pyramid import DIR_FILES
directory = os.path.join(DIR_FILES, 'magdata')
filename = os.path.join(directory, filename)
# Load data from file:
try:
import hyperspy.api as hs
return MagData.from_signal(hs.load(filename))
except ImportError:
cls._log.error('Could not load hyperspy package!')
return
return MagData.from_signal(hs.load(filename))
def save_to_llg(self, filename='magdata.txt'):
'''Save magnetization data in a file with LLG-format.
......
......@@ -4,21 +4,26 @@
#
"""This module provides the :class:`~.PhaseMap` class for storing phase map data."""
import logging
import os
import numpy as np
from scipy.ndimage.interpolation import zoom
from numbers import Number
from PIL import Image
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from PIL import Image
from matplotlib.ticker import MaxNLocator, FuncFormatter
from mpl_toolkits.mplot3d import Axes3D
from scipy.ndimage.interpolation import zoom
from pyramid.colormap import DirectionalColormap, TransparentColormap
import logging
_log = logging.getLogger(__name__)
try: # Try importing HyperSpy:
import hyperspy.api as hs
except ImportError:
hs = None
_log.error('Could not load hyperspy package!')
__all__ = ['PhaseMap']
......@@ -287,7 +292,7 @@ class PhaseMap(object):
'''
self._log.debug('Calling scale_down')
assert n > 0 and isinstance(n, (int, long)), 'n must be a positive integer!'
self.a = self.a * 2**n
self.a *= 2 ** n
for t in range(n):
# Pad if necessary:
pv, pu = self.dim_uv[0] % 2, self.dim_uv[1] % 2
......@@ -326,7 +331,7 @@ class PhaseMap(object):
assert n > 0 and isinstance(n, (int, long)), 'n must be a positive integer!'
assert 5 > order >= 0 and isinstance(order, (int, long)), \
'order must be a positive integer between 0 and 5!'
self.a = self.a / 2**n
self.a /= 2 ** n
self.phase = zoom(self.phase, zoom=2**n, order=order)
self.mask = zoom(self.mask, zoom=2**n, order=0)
self.confidence = zoom(self.confidence, zoom=2**n, order=order)
......@@ -418,11 +423,8 @@ class PhaseMap(object):
'''
self._log.debug('Calling to_signal')
# Try importing HyperSpy:
try:
import hyperspy.api as hs
except ImportError:
self._log.error('Could not load hyperspy package!')
if hs is None:
self._log.error('This method recquires the hyperspy package!')
return
# Create signal:
signal = hs.signals.Image(self.phase)
......@@ -476,7 +478,7 @@ class PhaseMap(object):
return cls(a, phase, mask, confidence, unit)
def save_to_hdf5(self, filename='phasemap.hdf5'):
'''Save magnetization data in a file with HyperSpys HDF5-format.
"""Save magnetization data in a file with HyperSpys HDF5-format.
Parameters
----------
......@@ -488,7 +490,7 @@ class PhaseMap(object):
-------
None
'''
"""
self._log.debug('Calling save_to_hdf5')
# Construct path if filename isn't already absolute:
if not os.path.isabs(filename):
......@@ -516,18 +518,16 @@ class PhaseMap(object):
'''
cls._log.debug('Calling load_from_hdf5')
if hs is None:
cls._log.error('This method recquires the hyperspy package!')
return
# Use relative path if filename isn't already absolute:
if not os.path.isabs(filename):
from pyramid import DIR_FILES
directory = os.path.join(DIR_FILES, 'phasemap')
filename = os.path.join(directory, filename)
# Load data from file:
try:
import hyperspy.api as hs
return PhaseMap.from_signal(hs.load(filename))
except ImportError:
cls._log.error('Could not load hyperspy package!')
return
return PhaseMap.from_signal(hs.load(filename))
def save_to_txt(self, filename='phasemap.txt', skip_header=False):
'''Save :class:`~.PhaseMap` data in a file with txt-format.
......
# -*- coding: utf-8 -*-
"""Testcase for the compliance with PEP8."""
import os
import sys
import datetime
import unittest
import re
import pep8
class TestCaseCompliance(unittest.TestCase):
"""TestCase for checking the pep8 compliance of the pyramid package."""
# Pyramid directory:
path = os.path.abspath(os.path.join(os.path.split(os.path.realpath(__file__))[0], '..', '..'))
def get_files_to_check(self, rootdir):
filepaths = []
for root, dirs, files in os.walk(rootdir):
for filename in files:
if ((filename.endswith('.py') or filename.endswith('.pyx'))
and root != os.path.join(self.path, 'scripts', 'gui')):
filepaths.append(os.path.join(root, filename))
return filepaths
def test_pep8(self):
'''Test for pep8 compliance.'''
files = self.get_files_to_check(os.path.join(self.path, 'pyramid')) \
+ self.get_files_to_check(os.path.join(self.path, 'scripts')) \
+ self.get_files_to_check(os.path.join(self.path, 'pyramid', 'tests'))
ignores = ('E125', 'E226', 'E228', 'W503')
pep8.MAX_LINE_LENGTH = 99
pep8style = pep8.StyleGuide(quiet=False)
pep8style.options.ignore = ignores
stdout_buffer = sys.stdout
with open(os.path.join(self.path, 'pyramid', 'tests', 'pep8_log.txt'), 'w+') as sys.stdout:
print '<<< PEP8 LOGFILE >>>'
print 'RUN:', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print 'IGNORED RULES:', ', '.join(ignores)
print 'MAX LINE LENGTH:', pep8.MAX_LINE_LENGTH
print '\nERRORS AND WARNINGS:'
result = pep8style.check_files(files)
if result.total_errors == 0:
print 'No PEP8 violations detected!'
else:
print '----> {} PEP8 violations detected!'.format(result.total_errors)
print '\nTODOS:'
todos_found = False
todo_count = 0
regex = ur'# TODO: (.*)'
for py_file in files:
with open(py_file) as f:
for line in f:
todo = re.findall(regex, line)
if todo and not todo[0] == "(.*)'":
todos_found = True
todo_count += 1
print '{}: {}'.format(f.name, todo[0])
if todos_found:
print '----> {} TODOs found!'.format(todo_count)
else:
print 'No TODOS found!'
sys.stdout = stdout_buffer
error_message = 'Found {} PEP8 violations!'.format(result.total_errors)
if todo_count > 0:
error_message += ' Found {} TODOs!'.format(todo_count)
self.assertEqual(result.total_errors, 0, error_message)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseCompliance)
unittest.TextTestRunner(verbosity=2).run(suite)
File added
File deleted
File added
File deleted
File added
File deleted
File added
File deleted
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment