Repository: CORE-GATECH-GROUP/serpent-tools
Pull request #285 (2019-03-02 18:54:21)

API DepletionMatrix to Matlab
Related to #282 by implementing methods for exporting data from depletion matrix files to matlab. Writes a full matrix, regardless of if the matrix is stored in sparse format.


Patch:
diff --git a/.gitignore b/.gitignore
index 5dbdde9..924c6e3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -46,62 +46,25 @@ coverage.xml
 *.cover
 .hypothesis/
 
-# Translations
-*.mo
-*.pot
-
-# Django stuff:
-*.log
-local_settings.py
-
-# Flask stuff:
-instance/
-.webassets-cache
-
-# Scrapy stuff:
-.scrapy
-
 # Sphinx documentation
 docs/_build/
 
-# PyBuilder
-target/
-
 # Jupyter Notebook
 .ipynb_checkpoints
 
 # pyenv
 .python-version
 
-# celery beat schedule file
-celerybeat-schedule
-
-# SageMath parsed files
-*.sage.py
-
-# dotenv
-.env
-
 # virtualenv
 .venv
 venv/
 ENV/
 
-# Spyder project settings
-.spyderproject
-.spyproject
-
-# Rope project settings
-.ropeproject
-
-# mkdocs documentation
-/site
-
-# mypy
-.mypy_cache/
-
 # pycharm
 .idea/*
 
 # vim
 .*.swp
+
+# Ctag file
+tags
diff --git a/serpentTools/parsers/depmatrix.py b/serpentTools/parsers/depmatrix.py
index c7d02ee..8cf200e 100644
--- a/serpentTools/parsers/depmatrix.py
+++ b/serpentTools/parsers/depmatrix.py
@@ -238,6 +238,22 @@ class DepmtxReader(BaseReader, SparseReaderMixin):
                    )
         return ax
 
+    def _gather_matlab(self, reconvert):
+        out = {'t': self.deltaT}
+        if reconvert:
+            out['N0'] = self.n0
+            out['N1'] = self.n1
+            out['ZAI'] = self.zai
+        else:
+            out['n0'] = self.n0
+            out['n1'] = self.n1
+            out['zai'] = self.zai
+        if self.sparse:
+            out['A'] = self.depmtx.toarray()
+        else:
+            out['A'] = self.depmtx
+        return out
+
 
 def _parseIsoBlock(stream, storage, match, line, regex):
     """Read through the N0, N1 block and add data to storage"""


Test patch:
diff --git a/serpentTools/tests/test_toMatlab.py b/serpentTools/tests/test_toMatlab.py
index 92514be..33be5fc 100644
--- a/serpentTools/tests/test_toMatlab.py
+++ b/serpentTools/tests/test_toMatlab.py
@@ -2,18 +2,30 @@
 Tests for testing the MATLAB conversion functions
 """
 
-from os import remove
 from unittest import TestCase, SkipTest
+from six import BytesIO, iteritems
 from numpy import arange
 from numpy.testing import assert_array_equal
 from serpentTools.objects import Detector
 from serpentTools.utils import checkScipy
 from serpentTools.io import toMatlab
+from serpentTools.data import getFile
+from serpentTools.parsers import DepmtxReader
 
 HAS_SCIPY = checkScipy('1.0')
 
 
-class Det2MatlabHelper(TestCase):
+class MatlabTesterHelper(TestCase):
+    """Helper class for matlab conversion"""
+
+    def setUp(self):
+        """Call this from subclasses to skip if scipy is unavailable"""
+        # skip tests if scipy not installed
+        if not HAS_SCIPY:
+            raise SkipTest("scipy needed to test matlab conversion")
+
+
+class Det2MatlabHelper(MatlabTesterHelper):
     """Helper class for testing detector to matlab conversion"""
 
     NBINS = 10
@@ -32,9 +44,7 @@ class Det2MatlabHelper(TestCase):
         cls.detector.grids[cls.GRID_KEY] = cls.GRID
 
     def setUp(self):
-        # skip tests if scipy not installed
-        if not HAS_SCIPY:
-            raise SkipTest("scipy needed to test matlab conversion")
+        MatlabTesterHelper.setUp(self)
 
         from serpentTools.objects.detectors import deconvert, prepToMatlab
         # instance methods and/or rename them
@@ -46,10 +56,9 @@ class Det2MatlabHelper(TestCase):
     def test_det2Matlab(self):
         """Test the conversion to matlab files"""
         from scipy.io import loadmat
-        filePath = 'detector_{}.mat'.format(
-            'conv' if self.CONVERT else 'unconv')
-        toMatlab(self.detector, filePath, self.CONVERT, append=False)
-        fromMatlab = loadmat(filePath)
+        writer = BytesIO()
+        toMatlab(self.detector, writer, self.CONVERT, append=False)
+        fromMatlab = loadmat(writer)
 
         binsKey = self.converterFunc(self.detector.name, 'bins')
         self.assertTrue(binsKey in fromMatlab)
@@ -60,8 +69,6 @@ class Det2MatlabHelper(TestCase):
         assert_array_equal(fromMatlab[gridKey],
                            self.detector.grids[self.GRID_KEY])
 
-        remove(filePath)
-
 
 class ConvertedDet2MatlabTester(Det2MatlabHelper):
     """Test the process of writing detector data w/ original names"""
@@ -75,7 +82,63 @@ class UnconvertedDet2MatlabTester(Det2MatlabHelper):
     CONVERT = False
 
 
-del Det2MatlabHelper
+class DepmtxMatlabHelper(MatlabTesterHelper):
+    """Class for setting up and testing"""
+
+    @classmethod
+    def setUpClass(cls):
+        cls.depFile = getFile('depmtx_ref.m')
+
+    def setUp(self):
+        MatlabTesterHelper.setUp(self)
+        self.outFile = BytesIO()
+        self.reader = DepmtxReader(self.depFile, self.SPARSE)
+        self.reader.read()
+        if self.SPARSE:
+            self.expected = {'A': self.reader.depmtx.toarray()}
+        else:
+            self.expected = {'A': self.reader.depmtx}
+
+        n0 = self.reader.n0.reshape(1, self.reader.n0.size)
+        n1 = self.reader.n1.reshape(1, self.reader.n1.size)
+        zai = self.reader.zai.reshape(1, self.reader.zai.size)
+
+        if self.RECONVERT:
+            self.expected['ZAI'] = zai
+            self.expected['N0'] = n0
+            self.expected['N1'] = n1
+        else:
+            self.expected['zai'] = zai
+            self.expected['n0'] = n0
+            self.expected['n1'] = n1
+
+    def test_depmtxToMatlab(self):
+        """Verify the depmtx reader can be written to matlab file"""
+        from scipy.io import loadmat
+        toMatlab(self.reader, self.outFile, self.RECONVERT)
+        written = loadmat(self.outFile)
+        self.assertEqual(self.reader.deltaT, written['t'])
+        for expKey, expValue in iteritems(self.expected):
+            self.assertTrue(expKey in written, msg=expKey)
+            assert_array_equal(expValue, written[expKey], err_msg=expKey)
+
+
+class ConvertedDepmtxMatlabTester(DepmtxMatlabHelper):
+    RECONVERT = True
+    SPARSE = True
+
+
+class UnconvertedDepmtxMatlabTester(DepmtxMatlabHelper):
+    RECONVERT = False
+    SPARSE = True
+
+
+class ConvertedFullDepmtxMatlabTester(DepmtxMatlabHelper):
+    RECONVERT = True
+    SPARSE = False
+
+
+del Det2MatlabHelper, DepmtxMatlabHelper
 
 if __name__ == '__main__':
     from unittest import main