diff --git a/gwygsf/GSF.py b/gwygsf/GSF.py new file mode 100644 index 0000000..72c4af4 --- /dev/null +++ b/gwygsf/GSF.py @@ -0,0 +1,17 @@ +"""This is the skeleton for the GSF container class. + +Methods in the GSF class are spread out across other files. +""" +import numpy.typing as npt +import numpy as np +class GSF: + """Container for GSF files.""" + from .readfile import fromfile + + attr : dict + d : npt.NDArray[np.float32] + + def __init__(self): + """Initialize class attributes to unusable values.""" + self.d = None + self.attr = {} diff --git a/gwygsf/__init__.py b/gwygsf/__init__.py index 9a04856..eb8630b 100644 --- a/gwygsf/__init__.py +++ b/gwygsf/__init__.py @@ -1 +1,2 @@ +"""gwygsf: Gwyddion Simple Field File Format Parser""" from .readfile import * diff --git a/gwygsf/readfile.py b/gwygsf/readfile.py index 645cbbd..765a6f6 100644 --- a/gwygsf/readfile.py +++ b/gwygsf/readfile.py @@ -1,31 +1,24 @@ -import io +"""This module is code for reading and writing GSF files.""" import numpy as np class ParseError(Exception): - def __init__(self, s): - self.s = s - def __str__(self): - return self.s + """Exception thrown when an error occurs when parsing a GSF file.""" -class GSF: - def fromfile(self, s): - with open(s, 'rb') as f: - magic = f.readline() - self.dic = {} - if magic != b"Gwyddion Simple Field 1.0\n": - raise ParseError("Magic line not found") - while f.peek(1) != b'\0': - l = f.readline().split(b'=') - dic[str(l[0].strip())] = l[1].strip() - while f.read(1) == b'\0': - pass +def fromfile(self, filename): + """Parse the GSF file into the class. Throws ParseError.""" + with open(filename, 'rb') as f: + magic = f.readline() + self.attr = {} + if magic != b"Gwyddion Simple Field 1.0\n": + raise ParseError("Magic line not found") + while f.peek(1) != b'\0': + line = f.readline().split(b'=') + if len(line) != 2: + raise ParseError("Malformed attribute line") + self.attr[str(line[0].strip())] = line[1].strip() + while f.read(1) == b'\0': + pass - self.x = int(dic["XRes"]) - self.y = int(dic["YRes"]) - self.d = np.reshape(np.fromfile(f,type=np.float32), (self.y, self.x)) - - def __init__(self): - self.x = None - self.y = None - self.d = None - self.dic = {} + self.x = int(self.attr["XRes"]) + self.y = int(self.attr["YRes"]) + self.d = np.reshape(np.fromfile(f,type=np.float32), (self.y, self.x))