From 760d173e8b96de6a9514d7b926c2172378d042ff Mon Sep 17 00:00:00 2001
From: Jan Caron <j.caron@fz-juelich.de>
Date: Fri, 20 Feb 2015 22:31:17 +0100
Subject: [PATCH] Added config.py and changed file saving mechanism
 magdata/phasemap: load and save methods now dynamically save with absolute
 and         relative paths. Relative paths are defined in the config.py file!

---
 pyramid/__init__.py |  1 +
 pyramid/config.py   | 18 ++++++++++++++++
 pyramid/magdata.py  | 52 ++++++++++++++++++++++++++++++++++++---------
 pyramid/phasemap.py | 34 +++++++++++++++++++++++++++--
 4 files changed, 93 insertions(+), 12 deletions(-)
 create mode 100644 pyramid/config.py

diff --git a/pyramid/__init__.py b/pyramid/__init__.py
index 47aba58..5a4b786 100644
--- a/pyramid/__init__.py
+++ b/pyramid/__init__.py
@@ -57,6 +57,7 @@ from .phasemap import *  # analysis:ignore
 from .phasemapper import *  # analysis:ignore
 from .projector import *  # analysis:ignore
 from .regularisator import *  # analysis:ignore
+from .config import *  # analysis:ignore
 from .version import version as __version__
 from .version import hg_revision as __hg_revision__
 
diff --git a/pyramid/config.py b/pyramid/config.py
new file mode 100644
index 0000000..9f45e1f
--- /dev/null
+++ b/pyramid/config.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+"""
+Created on Fri Feb 20 10:59:42 2015
+
+@author: Jan
+"""
+
+import os
+
+
+__all__ = ['DIR_PACKAGE', 'DIR_MAGDATA', 'DIR_PHASEMAP']
+
+
+DIR_PACKAGE = os.path.join(os.path.dirname(os.path.realpath(__file__)))
+DIR_MAGDATA = os.path.abspath(os.path.join(DIR_PACKAGE, os.pardir, 'files', 'magdata'))
+DIR_PHASEMAP = os.path.abspath(os.path.join(DIR_PACKAGE, os.pardir, 'files', 'phasemap'))
+
+del os
diff --git a/pyramid/magdata.py b/pyramid/magdata.py
index 02920ee..936e4e5 100644
--- a/pyramid/magdata.py
+++ b/pyramid/magdata.py
@@ -331,7 +331,7 @@ class MagData(object):
         else:
             self.mag_vec = vector
 
-    def save_to_llg(self, filename='..\output\magdata_output.txt'):
+    def save_to_llg(self, filename='magdata.txt'):
         '''Save magnetization data in a file with LLG-format.
 
         Parameters
@@ -344,16 +344,22 @@ class MagData(object):
         -------
         None
 
-        '''  # TODO: Implement default folder for all mag_data and phasemaps!!!
+        '''
         self._log.debug('Calling save_to_llg')
-        a = self.a * 1.0E-9 / 1.0E-2  # from nm to cm
+        SCALE = 1.0E-9 / 1.0E-2  # from nm to cm
         # Create 3D meshgrid and reshape it and the magnetization into a list where x varies first:
-        zz, yy, xx = (np.indices(self.dim)-a/2).reshape(3, -1)
+        zz, yy, xx = self.a * SCALE * (np.indices(self.dim)+0.5).reshape(3, -1)
         x_vec, y_vec, z_vec = self.magnitude.reshape(3, -1)
-        # Save data to file:
         data = np.array([xx, yy, zz, x_vec, y_vec, z_vec]).T
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_MAGDATA
+            if not os.path.exists(DIR_MAGDATA):
+                os.makedirs(DIR_MAGDATA)
+            filename = os.path.join(DIR_MAGDATA, filename)
+        # Save data to file:
         with open(filename, 'w') as mag_file:
-            mag_file.write('LLGFileCreator: %s\n' % filename.replace('.txt', ''))
+            mag_file.write('LLGFileCreator: %s\n' % filename)
             mag_file.write('    %d    %d    %d\n' % (self.dim[2], self.dim[1], self.dim[0]))
             mag_file.writelines('\n'.join('   '.join('{:7.6e}'.format(cell)
                                           for cell in row) for row in data))
@@ -375,13 +381,20 @@ class MagData(object):
         '''
         cls._log.debug('Calling load_from_llg')
         SCALE = 1.0E-9 / 1.0E-2  # From cm to nm
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_MAGDATA
+            if not os.path.exists(DIR_MAGDATA):
+                os.makedirs(DIR_MAGDATA)
+            filename = os.path.join(DIR_MAGDATA, filename)
+        # Load data from file:
         data = np.genfromtxt(filename, skip_header=2)
         dim = tuple(np.genfromtxt(filename, dtype=int, skip_header=1, skip_footer=len(data[:, 0])))
         a = (data[1, 0] - data[0, 0]) / SCALE
         magnitude = data[:, 3:6].T.reshape((3,)+dim)
         return MagData(a, magnitude)
 
-    def save_to_netcdf4(self, filename='..\output\magdata_output.nc'):
+    def save_to_netcdf4(self, filename='magdata.nc'):
         '''Save magnetization data in a file with NetCDF4-format.
 
         Parameters
@@ -396,6 +409,13 @@ class MagData(object):
 
         '''
         self._log.debug('Calling save_to_netcdf4')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_MAGDATA
+            if not os.path.exists(DIR_MAGDATA):
+                os.makedirs(DIR_MAGDATA)
+            filename = os.path.join(DIR_MAGDATA, filename)
+        # Save data to file:
         mag_file = netCDF4.Dataset(filename, 'w', format='NETCDF4')
         mag_file.a = self.a
         mag_file.createDimension('comp', 3)  # Number of components
@@ -421,14 +441,21 @@ class MagData(object):
             A :class:`~.MagData` object containing the loaded data.
 
         '''
-        cls._log.debug('Calling copy')
+        cls._log.debug('Calling load_from_netcdf4')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_MAGDATA
+            if not os.path.exists(DIR_MAGDATA):
+                os.makedirs(DIR_MAGDATA)
+            filename = os.path.join(DIR_MAGDATA, filename)
+        # Load data from file:
         mag_file = netCDF4.Dataset(filename, 'r', format='NETCDF4')
         a = mag_file.a
         magnitude = mag_file.variables['magnitude'][...]
         mag_file.close()
         return MagData(a, magnitude)
 
-    def save_to_x3d(self, filename='..\..\output\magdata_output.x3d', maximum=1):
+    def save_to_x3d(self, filename='magdata.x3d', maximum=1):
         '''Output the magnetization in the .x3d format for the Fraunhofer InstantReality Player.
 
         Parameters
@@ -442,7 +469,6 @@ class MagData(object):
         '''
         self._log.debug('Calling save_to_x3d')
         from lxml import etree
-
         dim = self.dim
         # Create points and vector components as lists:
         zz, yy, xx = (np.indices(dim)-0.5).reshape(3, -1)
@@ -483,6 +509,12 @@ class MagData(object):
                                  value='{} {} {}'.format(*spin_color))
                 etree.SubElement(spin, 'fieldValue', name='spin_scale',
                                  value='{} {} {}'.format(*spin_scale))
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_MAGDATA
+            if not os.path.exists(DIR_MAGDATA):
+                os.makedirs(DIR_MAGDATA)
+            filename = os.path.join(DIR_MAGDATA, filename)
         # Write the tree into the file in pretty print format:
         tree.write(filename, pretty_print=True)
 
diff --git a/pyramid/phasemap.py b/pyramid/phasemap.py
index ce5c45a..047c275 100644
--- a/pyramid/phasemap.py
+++ b/pyramid/phasemap.py
@@ -5,6 +5,8 @@
 """This module provides the :class:`~.PhaseMap` class for storing phase map data."""
 
 
+import os
+
 import numpy as np
 from numpy import pi
 
@@ -215,7 +217,7 @@ class PhaseMap(object):
         self._log.debug('Calling __imul__')
         return self.__mul__(other)
 
-    def save_to_txt(self, filename='..\output\phasemap_output.txt'):
+    def save_to_txt(self, filename='phasemap.txt'):
         '''Save :class:`~.PhaseMap` data in a file with txt-format.
 
         Parameters
@@ -230,6 +232,13 @@ class PhaseMap(object):
 
         '''
         self._log.debug('Calling save_to_txt')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_PHASEMAP
+            if not os.path.exists(DIR_PHASEMAP):
+                os.makedirs(DIR_PHASEMAP)
+            filename = os.path.join(DIR_PHASEMAP, filename)
+        # Save data to file:
         with open(filename, 'w') as phase_file:
             phase_file.write('{}\n'.format(filename.replace('.txt', '')))
             phase_file.write('grid spacing = {} nm\n'.format(self.a))
@@ -251,13 +260,20 @@ class PhaseMap(object):
 
         '''
         cls._log.debug('Calling load_from_txt')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_PHASEMAP
+            if not os.path.exists(DIR_PHASEMAP):
+                os.makedirs(DIR_PHASEMAP)
+            filename = os.path.join(DIR_PHASEMAP, filename)
+        # Load data from file:
         with open(filename, 'r') as phase_file:
             phase_file.readline()  # Headerline is not used
             a = float(phase_file.readline()[15:-4])
             phase = np.loadtxt(filename, delimiter='\t', skiprows=2)
         return PhaseMap(a, phase)
 
-    def save_to_netcdf4(self, filename='..\output\phasemap_output.nc'):
+    def save_to_netcdf4(self, filename='phasemap.nc'):
         '''Save :class:`~.PhaseMap` data in a file with NetCDF4-format.
 
         Parameters
@@ -272,6 +288,13 @@ class PhaseMap(object):
 
         '''
         self._log.debug('Calling save_to_netcdf4')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_PHASEMAP
+            if not os.path.exists(DIR_PHASEMAP):
+                os.makedirs(DIR_PHASEMAP)
+            filename = os.path.join(DIR_PHASEMAP, filename)
+        # Save data to file:
         phase_file = netCDF4.Dataset(filename, 'w', format='NETCDF4')
         phase_file.a = self.a
         phase_file.createDimension('v_dim', self.dim_uv[0])
@@ -296,6 +319,13 @@ class PhaseMap(object):
 
         '''
         cls._log.debug('Calling load_from_netcdf4')
+        # Construct path if filename isn't already absolute:
+        if not os.path.isabs(filename):
+            from pyramid import DIR_PHASEMAP
+            if not os.path.exists(DIR_PHASEMAP):
+                os.makedirs(DIR_PHASEMAP)
+            filename = os.path.join(DIR_PHASEMAP, filename)
+        # Load data from file:
         phase_file = netCDF4.Dataset(filename, 'r', format='NETCDF4')
         a = phase_file.a
         phase = phase_file.variables['phase'][:]
-- 
GitLab