Created
April 11, 2016 23:38
-
-
Save daskol/10c87b29953a7fafa46efb6f0d316fd3 to your computer and use it in GitHub Desktop.
Common routines in order to share solutions of NLSe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# nlsio.py | |
# This module provide common routines in order to share solutions of NLSe. | |
# (c) Daniel Bershatsky, 2016 | |
# See LICENSE for details | |
from __future__ import absolute_import, print_function | |
from datetime import datetime | |
from scipy.io import savemat, loadmat | |
def store(solution, where=None, label=None, date=None): | |
"""Save solution to mat-file with `label` and `date`. Filename could be a string or a file | |
object. If `filename` is not passed then `date` is used as file name. If `date` is not, then | |
it sets current time to `date`. Label is optional value that could somehow describe solution. | |
:param solution: numpy.ndarray | |
:param where: basestring or file | |
:param label: basestring | |
:param date: datetime.datetime | |
""" | |
if not date: | |
date = datetime.now() | |
if not where: | |
where = date.isoformat() + '.mat' | |
what = dict(solution=solution, date=date.isoformat()) | |
if label: | |
what['label'] = label | |
savemat(where, what) | |
def restore(where): | |
"""Load solution from mat-file and return tuple of solution, date and label. File could be a | |
string or a file. If mat-file does not contain label, then label is empty string. | |
:param where: basestring or file | |
""" | |
matfile = loadmat(where) | |
if 'solution' not in matfile or 'date' not in matfile: | |
raise Exception('Wrong file content: solution or date is absent!') | |
solution = matfile['solution'] | |
if solution.shape[0] == 1: | |
solution = solution[0, :] | |
elif solution.shape[1] == 1: | |
solution = solution[:, 0] | |
date = datetime.strptime(matfile['date'][0], '%Y-%m-%dT%H:%M:%S.%f') | |
label = str(matfile['label'][0]) if 'label' in matfile else '' | |
return solution, date, label |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment