# Path: wyrm/io.py
# def load_mushu_data(meta):
#     """Load saved EEG data in Mushu's format.
# 
#     This method loads saved data in Mushu's format and returns a
#     continuous ``Data`` object.
# 
#     Parameters
#     ----------
#     meta : str
#         Path to `.meta` file. A Mushu recording consists of three
#         different files: `.eeg`, `.marker`, and `.meta`.
# 
#     Returns
#     -------
#     dat : Data
#         Continuous Data object
# 
#     Examples
#     --------
# 
#     >>> dat = load_mushu_data('testrecording.meta')
# 
#     """
#     # reverse and replace and reverse again to replace only the last
#     # (occurrence of .meta)
#     datafile = meta[::-1].replace('atem.', 'gee.', 1)[::-1]
#     markerfile = meta[::-1].replace('atem.', 'rekram.', 1)[::-1]
#     assert path.exists(meta) and path.exists(datafile) and path.exists(markerfile)
#     # load meta data
#     with open(meta, 'r') as fh:
#         metadata = json.load(fh)
#     fs = metadata['Sampling Frequency']
#     channels = np.array(metadata['Channels'])
#     # load eeg data
#     data = np.fromfile(datafile, np.float32)
#     data = data.reshape((-1, len(channels)))
#     # load markers
#     markers = []
#     with open(markerfile, 'r') as fh:
#         for line in fh:
#             ts, m = line.split(' ', 1)
#             markers.append([float(ts), str(m).strip()])
#     # construct Data
#     duration = len(data) * 1000 / fs
#     axes = [np.linspace(0, duration, len(data), endpoint=False), channels]
#     names = ['time', 'channels']
#     units = ['ms', '#']
#     dat = Data(data=data, axes=axes, names=names, units=units)
#     dat.fs = fs
#     dat.markers = markers
#     return dat


import unittest
import os
import json
import struct
import numpy as np
from wyrm.io import load_mushu_data
class TestLoadMushuData(unittest.TestCase):

    def setUp(self):
        with open('foo.meta', 'w') as fh:
            json.dump({'Sampling Frequency' : 1,
                       'Channels' : ['ch1', 'ch2'],
                       'Amp': 'Dummy Amp'}, fh)
        with open('foo.marker', 'w') as fh:
            fh.write('0.0 Marker 0\n')
            fh.write('500.0 Marker 500\n')
            fh.write('666.666 Marker 666.666\n')
        with open('foo.eeg', 'wb') as fh:
            for i in (0, 1, 33, 66, .1, .2):
                fh.write(struct.pack('f', i))

    def tearDown(self):
        for fname in 'foo.meta', 'foo.eeg', 'foo.markers':
            try:
                os.remove(fname)
            except:
                pass

    def test_incomplete_fileset(self):
        """Must raise an error if not all files are available."""
        os.remove('foo.marker')
        with self.assertRaises(AssertionError):
            load_mushu_data('foo.meta')

    def test_loading(self):
        """Loads data correctly."""

# Path: wyrm/io.py
# def load_mushu_data(meta):
#     """Load saved EEG data in Mushu's format.
# 
#     This method loads saved data in Mushu's format and returns a
#     continuous ``Data`` object.
# 
#     Parameters
#     ----------
#     meta : str
#         Path to `.meta` file. A Mushu recording consists of three
#         different files: `.eeg`, `.marker`, and `.meta`.
# 
#     Returns
#     -------
#     dat : Data
#         Continuous Data object
# 
#     Examples
#     --------
# 
#     >>> dat = load_mushu_data('testrecording.meta')
# 
#     """
#     # reverse and replace and reverse again to replace only the last
#     # (occurrence of .meta)
#     datafile = meta[::-1].replace('atem.', 'gee.', 1)[::-1]
#     markerfile = meta[::-1].replace('atem.', 'rekram.', 1)[::-1]
#     assert path.exists(meta) and path.exists(datafile) and path.exists(markerfile)
#     # load meta data
#     with open(meta, 'r') as fh:
#         metadata = json.load(fh)
#     fs = metadata['Sampling Frequency']
#     channels = np.array(metadata['Channels'])
#     # load eeg data
#     data = np.fromfile(datafile, np.float32)
#     data = data.reshape((-1, len(channels)))
#     # load markers
#     markers = []
#     with open(markerfile, 'r') as fh:
#         for line in fh:
#             ts, m = line.split(' ', 1)
#             markers.append([float(ts), str(m).strip()])
#     # construct Data
#     duration = len(data) * 1000 / fs
#     axes = [np.linspace(0, duration, len(data), endpoint=False), channels]
#     names = ['time', 'channels']
#     units = ['ms', '#']
#     dat = Data(data=data, axes=axes, names=names, units=units)
#     dat.fs = fs
#     dat.markers = markers
#     return dat


# Path: test/test_load_mushu_data.py
import unittest
import os
import json
import struct
import numpy as np
from wyrm.io import load_mushu_data

class TestLoadMushuData(unittest.TestCase):

    def setUp(self):
        with open('foo.meta', 'w') as fh:
            json.dump({'Sampling Frequency' : 1,
                       'Channels' : ['ch1', 'ch2'],
                       'Amp': 'Dummy Amp'}, fh)
        with open('foo.marker', 'w') as fh:
            fh.write('0.0 Marker 0\n')
            fh.write('500.0 Marker 500\n')
            fh.write('666.666 Marker 666.666\n')
        with open('foo.eeg', 'wb') as fh:
            for i in (0, 1, 33, 66, .1, .2):
                fh.write(struct.pack('f', i))

    def tearDown(self):
        for fname in 'foo.meta', 'foo.eeg', 'foo.markers':
            try:
                os.remove(fname)
            except:
                pass

    def test_incomplete_fileset(self):
        """Must raise an error if not all files are available."""
        os.remove('foo.marker')
        with self.assertRaises(AssertionError):
            load_mushu_data('foo.meta')

    def test_loading(self):
        """Loads data correctly."""

        dat = load_mushu_data('foo.meta')