diff --git a/BioLogic.py b/BioLogic.py new file mode 100644 index 0000000..065201b --- /dev/null +++ b/BioLogic.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +"""Code to read in data files from Bio-Logic instruments""" + +import re +import csv + + +def MPTfile(file_or_path): + """Simple function to open MPT files as csv.DictReader objects + + Checks for the correct headings, skips any comments and returns a + csv.DictReader object and a list of comments + """ + + if isinstance(file_or_path, str): + mpt_file = open(file_or_path, 'r') + else: + mpt_file = file_or_path + + magic = next(mpt_file) + if magic != 'EC-Lab ASCII FILE\n': + raise ValueError("Bad first line for EC-Lab file: '%s'" % magic) + + nb_headers_match = re.match('Nb header lines : (\d+)', next(mpt_file)) + nb_headers = int(nb_headers_match.group(1)) + if nb_headers < 3: + raise ValueError("Too few header lines: %d" % nb_headers) + + ## The 'magic number' line, the 'Nb headers' line and the column headers + ## make three lines. Every additional line is a comment line. + comments = [next(mpt_file) for i in range(nb_headers - 3)] + + mpt_csv = csv.DictReader(mpt_file, dialect='excel-tab') + + expected_fieldnames = ( + ["mode", "ox/red", "error", "control changes", "Ns changes", + "counter inc.", "time/s", "control/V/mA", "Ewe/V", "dq/mA.h", + "P/W", "/mA", "(Q-Qo)/mA.h", "x"], + ["mode", "ox/red", "error", "control changes", "Ns changes", + "counter inc.", "time/s", "control/V", "Ewe/V", "I/mA", + "dQ/mA.h", "P/W"], + ["mode", "ox/red", "error", "control changes", "Ns changes", + "counter inc.", "time/s", "control/V", "Ewe/V", "/mA", + "dQ/mA.h", "P/W"]) + if mpt_csv.fieldnames not in expected_fieldnames: + raise ValueError("Unrecognised headers for MPT file format") + + return mpt_csv, comments diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..0355434 --- /dev/null +++ b/__init__.py @@ -0,0 +1 @@ +from .BioLogic import MPTfile diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_BioLogic.py b/tests/test_BioLogic.py new file mode 100644 index 0000000..08cec0d --- /dev/null +++ b/tests/test_BioLogic.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +import os.path + +from nose.tools import ok_, eq_, raises + +from .. import MPTfile + +testdata_dir = os.path.join(os.path.dirname(__file__), 'testdata') + + +def test_open_MPT(): + mpt1, comments = MPTfile(os.path.join(testdata_dir, 'bio-logic1.mpt')) + eq_(comments, []) + eq_(mpt1.fieldnames, ["mode", "ox/red", "error", "control changes", + "Ns changes", "counter inc.", "time/s", + "control/V/mA", "Ewe/V", "dq/mA.h", "P/W", + "/mA", "(Q-Qo)/mA.h", "x"]) + + +@raises(ValueError) +def test_open_MPT_fails_for_bad_file(): + mpt1 = MPTfile(os.path.join(testdata_dir, 'bio-logic1.mpr'))