This file is indexed.

/usr/lib/python2.7/dist-packages/neo/test/iotest/test_hdf5io.py is in python-neo 0.3.3-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# -*- coding: utf-8 -*-
"""
Tests of neo.io.hdf5io

Usually I run these tests like that. I add neo root folder to the pythonpath
(usually by adding the neo.pth with the path to the cloned repository to, say,
/usr/lib/python2.6/dist-packages/) and run

python <path to the neo repo>/test/io/test_hdf5io.py

For the moment only basic tests are active.

#TODO add performance testing!!
"""

# needed for python 3 compatibility
from __future__ import absolute_import

from datetime import datetime
from hashlib import md5
import logging
import os
import sys

try:
    import unittest2 as unittest
except ImportError:
    import unittest

import numpy as np
import quantities as pq

from neo.core import SpikeTrain, Segment, Block
from neo.test.tools import (assert_neo_object_is_compliant,
                            assert_objects_equivalent,
                            assert_same_sub_schema)
from neo.test.iotest.common_io_test import BaseTestIO
from neo.description import (class_by_name, classes_necessary_attributes,
                             classes_recommended_attributes,
                             implicit_relationship, many_to_many_relationship,
                             name_by_class, one_to_many_relationship)

from neo.io.hdf5io import NeoHdf5IO, HAVE_TABLES


#==============================================================================

TEST_ANNOTATIONS = [1, 0, 1.5, "this is a test", datetime.now(), None]


def get_fake_value(attr):  # attr = (name, type, [dim, [dtype]])
    """ returns default value for a given attribute based on description.py """
    if attr[1] == pq.Quantity or attr[1] == np.ndarray:
        size = []
        for i in range(int(attr[2])):
            size.append(np.random.randint(100) + 1)
        to_set = np.random.random(size) * pq.millisecond  # let it be ms
        if attr[0] == 't_start':
            to_set = 0.0 * pq.millisecond
        if attr[0] == 't_stop':
            to_set = 1.0 * pq.millisecond
        if attr[0] == 'sampling_rate':
            to_set = 10000.0 * pq.Hz
    if attr[1] == np.ndarray:
        to_set = np.array(to_set, dtype=attr[3])
    if attr[1] == str:
        to_set = str(np.random.randint(100000))
    if attr[1] == int:
        to_set = np.random.randint(100)
    if attr[1] == datetime:
        to_set = datetime.now()
    return to_set


def fake_NEO(obj_type="Block", cascade=True, _follow_links=True):
    """ Create a fake NEO object of a given type. Follows one-to-many
    and many-to-many relationships if cascade. RC, when requested cascade, will
    not create RGCs to avoid dead-locks.

    _follow_links - an internal variable, indicates whether to create objects
    with 'implicit' relationships, to avoid duplications. Do not use it. """
    kwargs = {}  # assign attributes
    attrs = classes_necessary_attributes[obj_type] + \
        classes_recommended_attributes[obj_type]
    for attr in attrs:
        kwargs[attr[0]] = get_fake_value(attr)
    obj = class_by_name[obj_type](**kwargs)
    if cascade:
        if obj_type == "Block":
            _follow_links = False
        if obj_type in one_to_many_relationship:
            rels = one_to_many_relationship[obj_type]
            if obj_type == "RecordingChannelGroup":
                rels += many_to_many_relationship[obj_type]
            if not _follow_links and obj_type in implicit_relationship:
                for i in implicit_relationship[obj_type]:
                    if not i in rels:
                        logging.debug("LOOK HERE!!!" + str(obj_type))
                    rels.remove(i)
            for child in rels:
                setattr(obj, child.lower() + "s", [fake_NEO(child, cascade,
                        _follow_links)])

    if obj_type == "Block":  # need to manually create 'implicit' connections
        # connect a unit to the spike and spike train
        u = obj.recordingchannelgroups[0].units[0]
        st = obj.segments[0].spiketrains[0]
        sp = obj.segments[0].spikes[0]
        u.spiketrains.append(st)
        u.spikes.append(sp)
        # connect RCG with ASA
        asa = obj.segments[0].analogsignalarrays[0]
        obj.recordingchannelgroups[0].analogsignalarrays.append(asa)
        # connect RC to AS, IrSAS and back to RGC
        rc = obj.recordingchannelgroups[0].recordingchannels[0]
        rc.recordingchannelgroups.append(obj.recordingchannelgroups[0])
        rc.analogsignals.append(obj.segments[0].analogsignals[0])
        seg = obj.segments[0]
        rc.irregularlysampledsignals.append(seg.irregularlysampledsignals[0])
    # add some annotations, 80%
    at = dict([(str(x), TEST_ANNOTATIONS[x]) for x in
               range(len(TEST_ANNOTATIONS))])
    obj.annotate(**at)
    return obj


class HDF5Commontests(BaseTestIO, unittest.TestCase):
    ioclass = NeoHdf5IO
    files_to_test = ['test.h5']
    files_to_download = files_to_test

    @unittest.skipIf(sys.version_info[0] > 2, "not Python 3 compatible")
    @unittest.skipUnless(HAVE_TABLES, "requires PyTables")
    def setUp(self):
        BaseTestIO.setUp(self)


class hdf5ioTest:  # inherit this class from unittest.TestCase when ready
    """
    Tests for the hdf5 library.
    """

    #@unittest.skipIf(sys.version_info[0] > 2, "not Python 3 compatible")
    #@unittest.skipUnless(HAVE_TABLES, "requires PyTables")
    def setUp(self):
        self.test_file = "test.h5"

    def tearDown(self):
        if os.path.exists(self.test_file):
            os.remove(self.test_file)

    def test_create(self):
        """
        Create test file with signals, segments, blocks etc.
        """
        iom = NeoHdf5IO(filename=self.test_file)
        b1 = fake_NEO()  # creating a structure
        iom.save(b1)  # saving
        # must be assigned after save
        self.assertTrue(hasattr(b1, "hdf5_path"))
        iom.close()
        iom.connect(filename=self.test_file)
        b2 = iom.get(b1.hdf5_path)  # new object
        assert_neo_object_is_compliant(b2)
        assert_same_sub_schema(b1, b2)

    def test_property_change(self):
        """ Make sure all attributes are saved properly after the change,
        including quantities, units, types etc."""
        iom = NeoHdf5IO(filename=self.test_file)
        for obj_type in class_by_name.keys():
            obj = fake_NEO(obj_type, cascade=False)
            iom.save(obj)
            self.assertTrue(hasattr(obj, "hdf5_path"))
            replica = iom.get(obj.hdf5_path, cascade=False)
            assert_objects_equivalent(obj, replica)

    def test_relations(self):
        """
        make sure the change in relationships is saved properly in the file,
        including correct M2M, no redundancy etc. RC -> RCG not tested.
        """
        def assert_children(self, obj, replica):
            obj_type = name_by_class[obj]
            self.assertEqual(md5(str(obj)).hexdigest(),
                             md5(str(replica)).hexdigest())
            if obj_type in one_to_many_relationship:
                rels = one_to_many_relationship[obj_type]
                if obj_type == "RecordingChannelGroup":
                    rels += many_to_many_relationship[obj_type]
                for child_type in rels:
                    ch1 = getattr(obj, child_type.lower() + "s")
                    ch2 = getattr(replica, child_type.lower() + "s")
                    self.assertEqual(len(ch1), len(ch2))
                    for i, v in enumerate(ch1):
                        self.assert_children(ch1[i], ch2[i])
        iom = NeoHdf5IO(filename=self.test_file)
        for obj_type in class_by_name.keys():
            obj = fake_NEO(obj_type, cascade=True)
            iom.save(obj)
            self.assertTrue(hasattr(obj, "hdf5_path"))
            replica = iom.get(obj.hdf5_path, cascade=True)
            self.assert_children(obj, replica)

    def test_errors(self):
        """ some tests for specific errors """
        f = open("thisisafakehdf.h5", "w")  # wrong file type
        f.write("this is not an HDF5 file. sorry.")
        f.close()
        self.assertRaises(TypeError, NeoHdf5IO(filename="thisisafakehdf.h5"))
        iom = NeoHdf5IO(filename=self.test_file)  # wrong object path test
        self.assertRaises(LookupError, iom.get("/wrong_path"))
        some_object = np.array([1, 2, 3])  # non NEO object test
        self.assertRaises(AssertionError, iom.save(some_object))

    def test_attr_changes(self):
        """ gets an object, changes its attributes, saves it, then compares how
        good the changes were saved. """
        iom = NeoHdf5IO(filename=self.test_file)
        for obj_type in class_by_name.keys():
            obj = fake_NEO(obj_type=obj_type, cascade=False)
            iom.save(obj)
            orig_obj = iom.get(obj.hdf5_path)
            attrs = (classes_necessary_attributes[obj_type] +
                     classes_recommended_attributes[obj_type])
            for attr in attrs:
                if hasattr(orig_obj, attr[0]):
                    setattr(obj, attr[0], get_fake_value(attr))
            iom.save(orig_obj)
            test_obj = iom.get(orig_obj.hdf5_path)
            assert_objects_equivalent(orig_obj, test_obj)


        # changes!!! in attr AS WELL AS in relations!!
        # test annotations
        # test naming - paths
        # unicode!!
        # add a child, then remove, then check it's removed
        # update/removal of relations b/w RC and AS which are/not are in the
        # same segment

class HDF5MoreTests(unittest.TestCase):
    @unittest.skipIf(sys.version_info[0] > 2, "not Python 3 compatible")
    @unittest.skipUnless(HAVE_TABLES, "requires PyTables")
    def test_store_empty_spike_train(self):
        spiketrain0 = SpikeTrain([], t_start=0.0, t_stop=100.0, units="ms")
        spiketrain1 = SpikeTrain([23.4, 45.6, 67.8],
                                 t_start=0.0, t_stop=100.0, units="ms")
        segment = Segment(name="a_segment")
        segment.spiketrains.append(spiketrain0)
        segment.spiketrains.append(spiketrain1)
        block = Block(name="a_block")
        block.segments.append(segment)
        iom = NeoHdf5IO(filename="test987.h5")
        iom.save(block)
        iom.close()

        iom = NeoHdf5IO(filename="test987.h5")
        block1 = iom.get("/Block_0")
        self.assertEqual(block1.segments[0].spiketrains[0].t_stop, 100.0)
        self.assertEqual(len(block1.segments[0].spiketrains[0]), 0)
        self.assertEqual(len(block1.segments[0].spiketrains[1]), 3)
        iom.close()
        os.remove("test987.h5")


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