Skip to content

Commit

Permalink
Fixes #115, save/load order for numpy and txt
Browse files Browse the repository at this point in the history
  • Loading branch information
fzeiser committed Mar 27, 2020
1 parent aec84c1 commit e5952b5
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 9 deletions.
48 changes: 43 additions & 5 deletions ompy/filehandling.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,25 +257,63 @@ def load_numpy_2D(path: Union[str, Path]
return mat[1:, 1:], mat[0, 1:], mat[1:, 0]


def save_txt_2D(matrix: np.ndarray, Eg: np.ndarray,
Ex: np.ndarray, path: Union[str, Path],
header=None):
if header is None:
header = ("Format:\n"
" Eg0 Eg1 Eg2 ...\n"
"Ex0 val00 val01 val02\n"
"Ex1 val10 val11 ...\n"
"Ex2 ...\n"
"...")
elif header is False:
header = None
mat = np.empty((matrix.shape[0] + 1, matrix.shape[1] + 1))
mat[0, 0] = -0
mat[0, 1:] = Eg
mat[1:, 0] = Ex
mat[1:, 1:] = matrix
np.savetxt(path, mat, header=header)


def load_txt_2D(path: Union[str, Path]
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
mat = np.loadtxt(path)
return mat[1:, 1:], mat[0, 1:], mat[1:, 0]


def load_numpy_1D(path: Union[str, Path]) -> Tuple[np.ndarray, np.ndarray]:
mat = np.load(path)
half = int(mat.shape[0] / 2)
return mat[:half], mat[half:]
E, values = np.load(path)
return values, E


def save_numpy_1D(values: np.ndarray, E: np.ndarray,
path: Union[str, Path]) -> None:
mat = np.append(values, E)
assert mat.size % 2 == 0
mat = np.vstack(E, values)
np.save(path, mat)


def load_txt_1D(path: Union[str, Path]) -> Tuple[np.ndarray, np.ndarray]:
E, values = np.loadtxt(path)
return values, E


def save_txt_1D(values: np.ndarray, E: np.ndarray,
path: Union[str, Path], header='E[keV] values') -> None:
""" E default in keV """
mat = np.vstack(E, values)
np.savetxt(path, mat, header=header)


def filetype_from_suffix(path: Path) -> str:
suffix = path.suffix
if suffix == '.tar':
return 'tar'
elif suffix == '.npy':
return 'numpy'
elif suffix == '.txt':
return 'txt'
elif suffix == '.m':
return 'mama'
else:
Expand Down
11 changes: 9 additions & 2 deletions ompy/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
from .abstractarray import AbstractArray, to_plot_axis
from .decomposition import index
from .filehandling import (mama_read, mama_write,
save_numpy_2D, load_numpy_2D, save_tar, load_tar,
save_numpy_2D, load_numpy_2D,
save_txt_2D, load_txt_2D, save_tar, load_tar,
filetype_from_suffix)
from .library import div0, fill_negative_gauss, diagonal_elements
from .matrixstate import MatrixState
Expand Down Expand Up @@ -211,6 +212,8 @@ def load(self, path: Union[str, Path],

if filetype == 'numpy':
self.values, self.Eg, self.Ex = load_numpy_2D(path)
elif filetype == 'txt':
self.values, self.Eg, self.Eg = load_txt_2D(path)
elif filetype == 'tar':
self.values, self.Eg, self.Eg = load_tar(path)
elif filetype == 'mama':
Expand All @@ -222,13 +225,15 @@ def load(self, path: Union[str, Path],
raise ValueError(f"Unknown filetype {filetype}")
self.verify_integrity()

def save(self, path: Union[str, Path], filetype: Optional[str] = None):
def save(self, path: Union[str, Path], filetype: Optional[str] = None,
**kwargs):
"""Save matrix to file
Args:
path (str or Path): path to file to save
filetype (str, optional): Filetype to save. Has an
auto-recognition. Options: ["numpy", "tar", "mama"]
**kwargs: additional keyword arguments
Raises:
ValueError: If filetype is unknown
Expand All @@ -240,6 +245,8 @@ def save(self, path: Union[str, Path], filetype: Optional[str] = None):

if filetype == 'numpy':
save_numpy_2D(self.values, self.Eg, self.Ex, path)
elif filetype == 'txt':
save_txt_2D(self.values, self.Eg, self.Ex, path, **kwargs)
elif filetype == 'tar':
save_tar([self.values, self.Eg, self.Ex], path)
elif filetype == 'mama':
Expand Down
12 changes: 10 additions & 2 deletions ompy/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import numpy as np
from numpy import ndarray
from .filehandling import (load_numpy_1D, save_numpy_1D,
load_txt_1D, save_txt_1D,
mama_read, mama_write,
filetype_from_suffix,
load_tar, save_tar)
Expand Down Expand Up @@ -145,13 +146,16 @@ def plot(self, ax: Optional[Any] = None,
return fig, ax

def save(self, path: Union[str, Path],
filetype: Optional[str] = None) -> None:
filetype: Optional[str] = None,
**kwargs) -> None:
"""Save to a file of specified format
Args:
path (str or Path): Path to save
filetype (str, optional): Filetype. Default uses
auto-recognition from suffix. Options: ["numpy", "tar", "mama"]
auto-recognition from suffix.
Options: ["numpy", "txt", "tar", "mama"]
**kwargs: additional keyword arguments
Raises:
ValueError: Filetype is not supported
Expand All @@ -164,6 +168,8 @@ def save(self, path: Union[str, Path],
filetype = filetype.lower()
if filetype == 'numpy':
save_numpy_1D(vector.values, vector.E, path)
elif filetype == 'txt':
save_txt_1D(vector.values, vector.E, path, **kwargs)
elif filetype == 'tar':
save_tar([vector.values, vector.E], path)
elif filetype == 'mama':
Expand All @@ -190,6 +196,8 @@ def load(self, path: Union[str, Path],

if filetype == 'numpy':
self.values, self.E = load_numpy_1D(path)
elif filetype == 'txt':
self.values, self.E = load_txt_1D(path)
elif filetype == 'tar':
self.values, self.E = load_tar(path)
elif filetype == 'mama':
Expand Down

0 comments on commit e5952b5

Please sign in to comment.