From cb7366872159a9b4e07eeaec0476da3a53203cfe Mon Sep 17 00:00:00 2001 From: Jan Caron <j.caron@fz-juelich.de> Date: Fri, 24 May 2013 16:22:31 +0200 Subject: [PATCH] create_random_slabs: Added script to create a random slab distribution test_compliance: Added PEP8 TestCase --- pyramid/analytic.py | 4 +- pyramid/test/test_compliance.py | 116 +++++++----------- scripts/compare_method_errors.py | 42 +++---- ...istribution.py => create_random_pixels.py} | 6 +- scripts/create_random_slabs.py | 59 +++++++++ 5 files changed, 126 insertions(+), 101 deletions(-) rename scripts/{create_random_distribution.py => create_random_pixels.py} (89%) create mode 100644 scripts/create_random_slabs.py diff --git a/pyramid/analytic.py b/pyramid/analytic.py index b4a7dfb..1c7cde3 100644 --- a/pyramid/analytic.py +++ b/pyramid/analytic.py @@ -17,8 +17,8 @@ def phase_mag_slab(dim, res, beta, center, width, b_0): x0 = res * (center[2] + 0.5) # 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) - Ly = res * ( width[1] + (width[1]+1)%2) - Lx = res * ( width[2] + (width[2]+1)%2) + Ly = res * (width[1] + (width[1]+1)%2) + Lx = res * (width[2] + (width[2]+1)%2) '''COMPUTATION MAGNETIC PHASE SHIFT (REAL SPACE) SLAB''' diff --git a/pyramid/test/test_compliance.py b/pyramid/test/test_compliance.py index f6d438f..2df2504 100644 --- a/pyramid/test/test_compliance.py +++ b/pyramid/test/test_compliance.py @@ -1,91 +1,57 @@ # -*- coding: utf-8 -*- """Testcase for the magcreator module.""" - +import datetime +import sys import os import unittest +import pep8 class TestCaseCompliance(unittest.TestCase): """ Class for checking compliance of pyjurassic. """ - + def setUp(self): - # self.getPaths() - # self.data_dir = "test_jrp_data" - # self.src_ctl = "ctl.py" - # remove E201 to get a working version of str(- b) - # remove E203 to get a working version of a[:, :] - # remove E501 as 80 chars are not enough - self.ignores = ["E201", "E203", "E501"] - self.options = ["dummy_name", "--ignore", ",".join(self.ignores), "--repeat"] - self.options += ["--exclude", "collections_python27.py"] - try: - import pep8 - self.pep8 = pep8 - except ImportError: - 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() - + pass + + def tearDown(self): + pass + + + def get_files_to_check(self, rootdir): + filepaths = [] + for root, dirs, files in os.walk(rootdir): + for filename in files: + if filename.endswith('.py'): + filepaths.append(os.path.join(root,filename)) + return filepaths + def test_pep8(self): - """ - Tests all directories containing python files for PEP8 compliance. - """ - self.assertTrue(self.pep8 is not None, - msg="Install Python pep8 module to fully execute testbench!") - errors = 0 - for dir_name in "./": - errors += self.checkDirectory(dir_name) - self.assertEqual(errors, 0) - + # TODO: Docstring + files = self.get_files_to_check('..') # search in pyramid package + ignores = ('E226',)# 'E201', 'E203') + pep8.MAX_LINE_LENGTH = 99 + pep8style = pep8.StyleGuide(quiet=False) + pep8style.options.ignore = ignores + + stdout_buffer = sys.stdout + 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__': suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseCompliance) - unittest.TextTestRunner(verbosity=2).run(suite) - -# 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") + unittest.TextTestRunner(verbosity=2).run(suite) \ No newline at end of file diff --git a/scripts/compare_method_errors.py b/scripts/compare_method_errors.py index 9dd6357..9aa38ff 100644 --- a/scripts/compare_method_errors.py +++ b/scripts/compare_method_errors.py @@ -28,8 +28,8 @@ def phase_from_mag(): # Input parameters: b_0 = 1 # in T res = 10.0 # in nm - beta = pi/4#np.linspace(0, 2*pi, endpoint=False, num=72) - padding = range(26) + betas = pi/4#np.linspace(0, 2*pi, endpoint=False, num=72) + paddings = range(26) dim = (1, 100, 100) # in px (z, y, x) # Create magnetic shape: geometry = 'slab' @@ -48,25 +48,25 @@ def phase_from_mag(): mag_data = MagData(res, mc.create_mag_dist(mag_shape, beta)) projection = pj.simple_axis_projection(mag_data) -# '''FOURIER''' -# #padding -# RMS = np.zeros(len(padding)) -# duration = np.zeros(len(padding)) -# for i in range(len(padding)): -# print 'padding =', padding[i] -# start_time = time.time() -# phase_num = pm.phase_mag_fourier(res, projection, b_0, padding[i]) -# duration[i] = time.time() - start_time -# phase_diff = phase_ana - phase_num -# RMS[i] = np.std(phase_diff) -# -# fig = plt.figure() -# fig.add_subplot(111) -# plt.plot(padding, RMS) -# -# fig = plt.figure() -# fig.add_subplot(111) -# plt.plot(padding, duration) + '''FOURIER''' + #padding + RMS = np.zeros(len(paddings)) + duration = np.zeros(len(paddings)) + for (i, padding) in enumerate(paddings): + print 'padding =', padding[i] + start_time = time.time() + phase_num = pm.phase_mag_fourier(res, projection, b_0, padding[i]) + duration[i] = time.time() - start_time + phase_diff = phase_ana - phase_num + RMS[i] = np.std(phase_diff) + + fig = plt.figure() + fig.add_subplot(111) + plt.plot(padding, RMS) + + fig = plt.figure() + fig.add_subplot(111) + plt.plot(padding, duration) '''REAL SLAB ''' diff --git a/scripts/create_random_distribution.py b/scripts/create_random_pixels.py similarity index 89% rename from scripts/create_random_distribution.py rename to scripts/create_random_pixels.py index 97c8f52..e7e01a3 100644 --- a/scripts/create_random_distribution.py +++ b/scripts/create_random_pixels.py @@ -14,7 +14,7 @@ import pyramid.holoimage as hi from pyramid.phasemap import PhaseMap -def create_random_distribution(): +def create_random_pixels(): '''Calculate, display and save a random magnetic distribution to file. Arguments: None @@ -40,7 +40,7 @@ def create_random_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_pixel.txt') + mag_data.save_to_llg('../output/mag_dist_random_pixels.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)) @@ -48,7 +48,7 @@ def create_random_distribution(): if __name__ == "__main__": try: - create_random_distribution() + create_random_pixels() except: type, value, tb = sys.exc_info() traceback.print_exc() diff --git a/scripts/create_random_slabs.py b/scripts/create_random_slabs.py new file mode 100644 index 0000000..4e9498a --- /dev/null +++ b/scripts/create_random_slabs.py @@ -0,0 +1,59 @@ +# -*- 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 -- GitLab