Skip to content

Commit

Permalink
Issue/204/is qp file (#205)
Browse files Browse the repository at this point in the history
* added is_qp_file function

* added is_qp_file function

* added inline comments

* added print statement about exception

* fix up temp file
  • Loading branch information
eacharles authored and drewoldag committed Nov 8, 2023
1 parent 74dc32e commit 638a0ee
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/qp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .scipy_pdfs import *
from .packed_interp_pdf import *
from .ensemble import Ensemble
from .factory import instance, add_class, create, read, read_metadata, convert, concatenate, iterator, data_length, from_tables
from .factory import instance, add_class, create, read, read_metadata, convert, concatenate, iterator, data_length, from_tables, is_qp_file
from .lazy_modules import *

from . import utils
Expand Down
24 changes: 24 additions & 0 deletions src/qp/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,29 @@ def read_metadata(self, filename):
tables = io.read(filename, NUMPY_DICT, keys=['meta'])
return tables["meta"]

def is_qp_file(self, filename):
"""Test if a file is a qp file
Parameters
----------
filename : `str`
File to test
Returns
-------
value : bool
True if the file is a qp file
"""
try:
# If this isn't a table-like file with a 'meta' table this will throw an exception
tables = io.readNative(filename, keys=['meta'])
# If the 'meta' tables doesn't have 'pdf_name' or it is empty this will throw an exception or fail
return len(tables['meta']['pdf_name']) > 0
except Exception as msg:
# Any exception means it isn't a qp file
print(f"This is not a qp file because {msg}")
return False

def read(self, filename):
"""Read this ensemble from a file
Expand Down Expand Up @@ -343,3 +366,4 @@ def instance():
concatenate = _FACTORY.concatenate
data_length = _FACTORY.data_length
from_tables = _FACTORY.from_tables
is_qp_file = _FACTORY.is_qp_file
10 changes: 9 additions & 1 deletion tests/qp/test_infrastructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import os
import unittest
import qp

from qp.test_funcs import build_ensemble
from qp import test_data


Expand Down Expand Up @@ -55,6 +55,14 @@ def test_get_val_or_default():
test_dict.pop(None)
assert qp.dict_utils.get_val_or_default(test_dict, 'nokey') is None

def test_is_qp_file(self):
fname = 'norm_ensemble.hdf5'
norm_test_data = qp.stats.norm_gen.test_data['norm']
ens_norm = build_ensemble(norm_test_data)
ens_norm.write_to(fname)
self.files.append(fname)
assert qp.instance().is_qp_file(fname)
assert not qp.instance().is_qp_file('test_pit.py')

if __name__ == '__main__':
unittest.main()

0 comments on commit 638a0ee

Please sign in to comment.