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

create_random_slabs: Added script to create a random slab distribution

test_compliance: Added PEP8 TestCase
parent c9e6285f
No related branches found
No related tags found
No related merge requests found
...@@ -17,8 +17,8 @@ def phase_mag_slab(dim, res, beta, center, width, b_0): ...@@ -17,8 +17,8 @@ def phase_mag_slab(dim, res, beta, center, width, b_0):
x0 = res * (center[2] + 0.5) x0 = res * (center[2] + 0.5)
# Ly, Lx have to be odd, because the slab borders should not lie in the # Ly, Lx have to be odd, because the slab borders should not lie in the
# center of a pixel (so L/2 can't be an integer) # center of a pixel (so L/2 can't be an integer)
Ly = res * ( width[1] + (width[1]+1)%2) Ly = res * (width[1] + (width[1]+1)%2)
Lx = res * ( width[2] + (width[2]+1)%2) Lx = res * (width[2] + (width[2]+1)%2)
'''COMPUTATION MAGNETIC PHASE SHIFT (REAL SPACE) SLAB''' '''COMPUTATION MAGNETIC PHASE SHIFT (REAL SPACE) SLAB'''
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Testcase for the magcreator module.""" """Testcase for the magcreator module."""
import datetime
import sys
import os import os
import unittest import unittest
import pep8
class TestCaseCompliance(unittest.TestCase): class TestCaseCompliance(unittest.TestCase):
""" """
Class for checking compliance of pyjurassic. Class for checking compliance of pyjurassic.
""" """
def setUp(self): def setUp(self):
# self.getPaths() pass
# self.data_dir = "test_jrp_data"
# self.src_ctl = "ctl.py" def tearDown(self):
# remove E201 to get a working version of str(- b) pass
# remove E203 to get a working version of a[:, :]
# remove E501 as 80 chars are not enough
self.ignores = ["E201", "E203", "E501"] def get_files_to_check(self, rootdir):
self.options = ["dummy_name", "--ignore", ",".join(self.ignores), "--repeat"] filepaths = []
self.options += ["--exclude", "collections_python27.py"] for root, dirs, files in os.walk(rootdir):
try: for filename in files:
import pep8 if filename.endswith('.py'):
self.pep8 = pep8 filepaths.append(os.path.join(root,filename))
except ImportError: return filepaths
self.pep8 = None
print("\nWARNING: You do not have package pep8!")
def countErrors(self):
"""
Counts the relevant errors from the pep8 counter structure.
"""
return sum([self.pep8.options.counters[key]
for key in self.pep8.options.messages.keys()
if key not in self.ignores])
def checkDirectory(self, dir_name):
"""
Checks all python files in the supplied directory and subdirectories.
"""
self.pep8.process_options(self.options)
self.pep8.input_dir(dir_name)
return self.countErrors()
def test_pep8(self): def test_pep8(self):
""" # TODO: Docstring
Tests all directories containing python files for PEP8 compliance. files = self.get_files_to_check('..') # search in pyramid package
""" ignores = ('E226',)# 'E201', 'E203')
self.assertTrue(self.pep8 is not None, pep8.MAX_LINE_LENGTH = 99
msg="Install Python pep8 module to fully execute testbench!") pep8style = pep8.StyleGuide(quiet=False)
errors = 0 pep8style.options.ignore = ignores
for dir_name in "./":
errors += self.checkDirectory(dir_name) stdout_buffer = sys.stdout
self.assertEqual(errors, 0) with open(os.path.join('..','..','output','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:', 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 Warnings or Errors detected!'
sys.stdout = stdout_buffer
error_message = 'Found %s Errors and Warnings!' % result.total_errors
self.assertEqual(result.total_errors, 0, error_message)
if __name__ == '__main__': if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseCompliance) suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseCompliance)
unittest.TextTestRunner(verbosity=2).run(suite) unittest.TextTestRunner(verbosity=2).run(suite)
\ No newline at end of file
# def test_variables(self):
# """
# Function for checking that all attributes are present.
# """
# try:
# import gloripy
## for name in ['X', 'Y', 'B',
## 'APR_VAL', 'APR_STD', 'FINAL_VAL', 'FINAL_STD',
## 'IG_VAL', 'TRUE_VAL',
## 'CARTESIAN', 'GEO', 'SPHERICAL',
## 'P', 'T', 'C']:
## self.assertTrue(hasattr(j, name), msg=str(name) + " is missing.")
# except ImportError:
# self.assertTrue(False, msg="could not import gloripy")
# def test_import(self):
# """
# Checks that all modules are importable.
# """
# module_list = ["gloripy",
# "gloripy.pylevel0",
# ]
# for module in module_list:
# try:
# exec("import " + module)
# importable = True
# except ImportError:
# importable = False
# self.assertTrue(importable, msg="importing " + module + " failed")
...@@ -28,8 +28,8 @@ def phase_from_mag(): ...@@ -28,8 +28,8 @@ def phase_from_mag():
# Input parameters: # Input parameters:
b_0 = 1 # in T b_0 = 1 # in T
res = 10.0 # in nm res = 10.0 # in nm
beta = pi/4#np.linspace(0, 2*pi, endpoint=False, num=72) betas = pi/4#np.linspace(0, 2*pi, endpoint=False, num=72)
padding = range(26) paddings = range(26)
dim = (1, 100, 100) # in px (z, y, x) dim = (1, 100, 100) # in px (z, y, x)
# Create magnetic shape: # Create magnetic shape:
geometry = 'slab' geometry = 'slab'
...@@ -48,25 +48,25 @@ def phase_from_mag(): ...@@ -48,25 +48,25 @@ def phase_from_mag():
mag_data = MagData(res, mc.create_mag_dist(mag_shape, beta)) mag_data = MagData(res, mc.create_mag_dist(mag_shape, beta))
projection = pj.simple_axis_projection(mag_data) projection = pj.simple_axis_projection(mag_data)
# '''FOURIER''' '''FOURIER'''
# #padding #padding
# RMS = np.zeros(len(padding)) RMS = np.zeros(len(paddings))
# duration = np.zeros(len(padding)) duration = np.zeros(len(paddings))
# for i in range(len(padding)): for (i, padding) in enumerate(paddings):
# print 'padding =', padding[i] print 'padding =', padding[i]
# start_time = time.time() start_time = time.time()
# phase_num = pm.phase_mag_fourier(res, projection, b_0, padding[i]) phase_num = pm.phase_mag_fourier(res, projection, b_0, padding[i])
# duration[i] = time.time() - start_time duration[i] = time.time() - start_time
# phase_diff = phase_ana - phase_num phase_diff = phase_ana - phase_num
# RMS[i] = np.std(phase_diff) RMS[i] = np.std(phase_diff)
#
# fig = plt.figure() fig = plt.figure()
# fig.add_subplot(111) fig.add_subplot(111)
# plt.plot(padding, RMS) plt.plot(padding, RMS)
#
# fig = plt.figure() fig = plt.figure()
# fig.add_subplot(111) fig.add_subplot(111)
# plt.plot(padding, duration) plt.plot(padding, duration)
'''REAL SLAB ''' '''REAL SLAB '''
......
...@@ -14,7 +14,7 @@ import pyramid.holoimage as hi ...@@ -14,7 +14,7 @@ import pyramid.holoimage as hi
from pyramid.phasemap import PhaseMap from pyramid.phasemap import PhaseMap
def create_random_distribution(): def create_random_pixels():
'''Calculate, display and save a random magnetic distribution to file. '''Calculate, display and save a random magnetic distribution to file.
Arguments: Arguments:
None None
...@@ -40,7 +40,7 @@ def create_random_distribution(): ...@@ -40,7 +40,7 @@ def create_random_distribution():
magnitude = mc.create_mag_dist_comb(mag_shape_list, beta_list, magnitude_list) magnitude = mc.create_mag_dist_comb(mag_shape_list, beta_list, magnitude_list)
mag_data = MagData(res, magnitude) mag_data = MagData(res, magnitude)
mag_data.quiver_plot() mag_data.quiver_plot()
mag_data.save_to_llg('../output/mag_dist_random_pixel.txt') mag_data.save_to_llg('../output/mag_dist_random_pixels.txt')
projection = pj.simple_axis_projection(mag_data) projection = pj.simple_axis_projection(mag_data)
phase_map = PhaseMap(res, pm.phase_mag_real(res, projection, 'slab')) phase_map = PhaseMap(res, pm.phase_mag_real(res, projection, 'slab'))
hi.display(hi.holo_image(phase_map, 10)) hi.display(hi.holo_image(phase_map, 10))
...@@ -48,7 +48,7 @@ def create_random_distribution(): ...@@ -48,7 +48,7 @@ def create_random_distribution():
if __name__ == "__main__": if __name__ == "__main__":
try: try:
create_random_distribution() create_random_pixels()
except: except:
type, value, tb = sys.exc_info() type, value, tb = sys.exc_info()
traceback.print_exc() traceback.print_exc()
......
# -*- coding: utf-8 -*-
"""Create random magnetic distributions."""
import random as rnd
import pdb, traceback, sys
import numpy as np
from numpy import pi
import pyramid.magcreator as mc
from pyramid.magdata import MagData
import pyramid.phasemapper as pm
import pyramid.projector as pj
import pyramid.holoimage as hi
from pyramid.phasemap import PhaseMap
def create_random_slabs():
'''Calculate, display and save a random magnetic distribution to file.
Arguments:
None
Returns:
None
'''
# Input parameters:
count = 10
dim = (1, 128, 128)
res = 10 # in nm
rnd.seed(42)
w_max = 10
# Create lists for magnetic objects:
mag_shape_list = np.zeros((count,) + dim)
beta_list = np.zeros(count)
magnitude_list = np.zeros(count)
for i in range(count):
width = (1, rnd.randint(1, w_max), rnd.randint(1, w_max))
center = (rnd.randrange(int(width[0]/2), dim[0]-int(width[0]/2)),
rnd.randrange(int(width[1]/2), dim[1]-int(width[1]/2)),
rnd.randrange(int(width[2]/2), dim[2]-int(width[2]/2)))
mag_shape_list[i,...] = mc.Shapes.slab(dim, center, width)
beta_list[i] = 2*pi*rnd.random()
magnitude_list[i] = 1#rnd.random()
# Create magnetic distribution
magnitude = mc.create_mag_dist_comb(mag_shape_list, beta_list, magnitude_list)
mag_data = MagData(res, magnitude)
mag_data.quiver_plot()
mag_data.save_to_llg('../output/mag_dist_random_slabs.txt')
projection = pj.simple_axis_projection(mag_data)
phase_map = PhaseMap(res, pm.phase_mag_real(res, projection, 'slab'))
hi.display(hi.holo_image(phase_map, 10))
if __name__ == "__main__":
try:
create_random_slabs()
except:
type, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
\ No newline at end of file
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