test_brainwaref32io.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # -*- coding: utf-8 -*-
  2. """
  3. Tests of neo.io.brainwaref32io
  4. """
  5. # needed for python 3 compatibility
  6. from __future__ import absolute_import, division, print_function
  7. import os.path
  8. import sys
  9. import unittest
  10. import numpy as np
  11. import quantities as pq
  12. from neo.core import Block, ChannelIndex, Segment, SpikeTrain, Unit
  13. from neo.io import BrainwareF32IO
  14. from neo.test.iotest.common_io_test import BaseTestIO
  15. from neo.test.tools import (assert_same_sub_schema,
  16. assert_neo_object_is_compliant)
  17. from neo.test.iotest.tools import create_generic_reader
  18. PY_VER = sys.version_info[0]
  19. def proc_f32(filename):
  20. '''Load an f32 file that has already been processed by the official matlab
  21. file converter. That matlab data is saved to an m-file, which is then
  22. converted to a numpy '.npz' file. This numpy file is the file actually
  23. loaded. This function converts it to a neo block and returns the block.
  24. This block can be compared to the block produced by BrainwareF32IO to
  25. make sure BrainwareF32IO is working properly
  26. block = proc_f32(filename)
  27. filename: The file name of the numpy file to load. It should end with
  28. '*_f32_py?.npz'. This will be converted to a neo 'file_origin' property
  29. with the value '*.f32', so the filename to compare should fit that pattern.
  30. 'py?' should be 'py2' for the python 2 version of the numpy file or 'py3'
  31. for the python 3 version of the numpy file.
  32. example: filename = 'file1_f32_py2.npz'
  33. f32 file name = 'file1.f32'
  34. '''
  35. filenameorig = os.path.basename(filename[:-12]+'.f32')
  36. # create the objects to store other objects
  37. block = Block(file_origin=filenameorig)
  38. chx = ChannelIndex(file_origin=filenameorig,
  39. index=np.array([], dtype=np.int),
  40. channel_names=np.array([], dtype='S'))
  41. unit = Unit(file_origin=filenameorig)
  42. # load objects into their containers
  43. block.channel_indexes.append(chx)
  44. chx.units.append(unit)
  45. try:
  46. with np.load(filename) as f32obj:
  47. f32file = f32obj.items()[0][1].flatten()
  48. except IOError as exc:
  49. if 'as a pickle' in exc.message:
  50. block.create_many_to_one_relationship()
  51. return block
  52. else:
  53. raise
  54. sweeplengths = [res[0, 0].tolist() for res in f32file['sweeplength']]
  55. stims = [res.flatten().tolist() for res in f32file['stim']]
  56. sweeps = [res['spikes'].flatten() for res in f32file['sweep'] if res.size]
  57. fullf32 = zip(sweeplengths, stims, sweeps)
  58. for sweeplength, stim, sweep in fullf32:
  59. for trainpts in sweep:
  60. if trainpts.size:
  61. trainpts = trainpts.flatten().astype('float32')
  62. else:
  63. trainpts = []
  64. paramnames = ['Param%s' % i for i in range(len(stim))]
  65. params = dict(zip(paramnames, stim))
  66. train = SpikeTrain(trainpts, units=pq.ms,
  67. t_start=0, t_stop=sweeplength,
  68. file_origin=filenameorig)
  69. segment = Segment(file_origin=filenameorig, **params)
  70. segment.spiketrains = [train]
  71. unit.spiketrains.append(train)
  72. block.segments.append(segment)
  73. block.create_many_to_one_relationship()
  74. return block
  75. class BrainwareF32IOTestCase(BaseTestIO, unittest.TestCase):
  76. '''
  77. Unit test testcase for neo.io.BrainwareF32IO
  78. '''
  79. ioclass = BrainwareF32IO
  80. read_and_write_is_bijective = False
  81. # These are the files it tries to read and test for compliance
  82. files_to_test = ['block_300ms_4rep_1clust_part_ch1.f32',
  83. 'block_500ms_5rep_empty_fullclust_ch1.f32',
  84. 'block_500ms_5rep_empty_partclust_ch1.f32',
  85. 'interleaved_500ms_5rep_ch2.f32',
  86. 'interleaved_500ms_5rep_nospikes_ch1.f32',
  87. 'multi_500ms_mulitrep_ch1.f32',
  88. 'random_500ms_12rep_noclust_part_ch2.f32',
  89. 'sequence_500ms_5rep_ch2.f32']
  90. # add the appropriate suffix depending on the python version
  91. suffix = '_f32_py%s.npz' % PY_VER
  92. files_to_download = files_to_test[:]
  93. # add the reference files to the list of files to download
  94. files_to_compare = []
  95. for fname in files_to_test:
  96. if fname:
  97. files_to_compare.append(os.path.splitext(fname)[0] + suffix)
  98. # Will fetch from g-node if they don't already exist locally
  99. # How does it know to do this before any of the other tests?
  100. files_to_download = files_to_test + files_to_compare
  101. def test_reading_same(self):
  102. for ioobj, path in self.iter_io_objects(return_path=True):
  103. obj_reader_base = create_generic_reader(ioobj, target=False)
  104. obj_reader_single = create_generic_reader(ioobj)
  105. obj_base = obj_reader_base()
  106. obj_single = obj_reader_single()
  107. try:
  108. assert_same_sub_schema(obj_base, obj_single)
  109. except BaseException as exc:
  110. exc.args += ('from ' + os.path.basename(path),)
  111. raise
  112. def test_against_reference(self):
  113. for obj, path in self.iter_objects(return_path=True):
  114. filename = os.path.basename(path)
  115. refpath = os.path.splitext(path)[0] + self.suffix
  116. refobj = proc_f32(refpath)
  117. try:
  118. assert_neo_object_is_compliant(obj)
  119. assert_neo_object_is_compliant(refobj)
  120. assert_same_sub_schema(obj, refobj)
  121. except BaseException as exc:
  122. exc.args += ('from ' + filename,)
  123. raise
  124. if __name__ == '__main__':
  125. unittest.main()