Exemple #1
0
class OpticalSeries(ImageSeries):
    '''
    Image data that is presented or recorded. A stimulus template movie will be stored only as an
    image. When the image is presented as stimulus, additional data is required, such as field of
    view (eg, how much of the visual field the image covers, or how what is the area of the target
    being imaged). If the OpticalSeries represents acquired imaging data, orientation is also
    important.
    '''

    __nwbfields__ = ('distance',
                     'field_of_view',
                     'orientation')

    @docval(*get_docval(ImageSeries.__init__, 'name'),
            {'name': 'data', 'type': ('array_data', 'data'), 'shape': ([None] * 3, [None, None, None, 3]),
             'doc': ('Images presented to subject, either grayscale or RGB. May be 3D or 4D. The first dimension must '
                     'be time (frame). The second and third dimensions represent x and y. The optional fourth '
                     'dimension must be length 3 and represents the RGB value for color images.')},
            *get_docval(ImageSeries.__init__, 'unit', 'format'),
            {'name': 'distance', 'type': 'float', 'doc': 'Distance from camera/monitor to target/eye.'},  # required
            {'name': 'field_of_view', 'type': ('array_data', 'data', 'TimeSeries'), 'shape': ((2, ), (3, )),  # required
             'doc': 'Width, height and depth of image, or imaged area (meters).'},
            {'name': 'orientation', 'type': str,  # required
             'doc': 'Description of image relative to some reference frame (e.g., which way is up). '
                    'Must also specify frame of reference.'},
            *get_docval(ImageSeries.__init__, 'external_file', 'starting_frame', 'bits_per_pixel',
                        'dimension', 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate', 'comments',
                        'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        distance, field_of_view, orientation = popargs('distance', 'field_of_view', 'orientation', kwargs)
        super(OpticalSeries, self).__init__(**kwargs)
        self.distance = distance
        self.field_of_view = field_of_view
        self.orientation = orientation
Exemple #2
0
class RoiResponseSeries(TimeSeries):
    '''
    ROI responses over an imaging plane. Each row in data[] should correspond to the signal from one ROI.
    '''

    __nwbfields__ = ({'name': 'rois', 'child': True}, )

    @docval(
        *get_docval(TimeSeries.__init__, 'name'),  # required
        {
            'name':
            'data',
            'type': ('array_data', 'data', TimeSeries),  # required
            'shape': ((None, ), (None, None)),
            'doc':
            'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames'
        },
        *get_docval(TimeSeries.__init__, 'unit'),
        {
            'name':
            'rois',
            'type':
            DynamicTableRegion,  # required
            'doc':
            'a table region corresponding to the ROIs that were used to generate this data'
        },
        *get_docval(TimeSeries.__init__, 'resolution', 'conversion',
                    'timestamps', 'starting_time', 'rate', 'comments',
                    'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        rois = popargs('rois', kwargs)
        pargs, pkwargs = fmt_docval_args(
            super(RoiResponseSeries, self).__init__, kwargs)
        super(RoiResponseSeries, self).__init__(*pargs, **pkwargs)
        self.rois = rois
Exemple #3
0
class IndexSeries(TimeSeries):
    '''
    Stores indices to image frames stored in an ImageSeries. The purpose of the IndexSeries is to allow
    a static image stack to be stored somewhere, and the images in the stack to be referenced out-of-order.
    This can be for the display of individual images, or of movie segments (as a movie is simply a series of
    images). The data field stores the index of the frame in the referenced ImageSeries, and the timestamps
    array indicates when that image was displayed.
    '''

    __nwbfields__ = ('indexed_timeseries',)

    # # value used when an ImageSeries is read and missing data
    # DEFAULT_UNIT = 'N/A'

    @docval(*get_docval(TimeSeries.__init__, 'name'),  # required
            {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': (None, ),  # required
            'doc': ('The data values. Must be 1D, where the first dimension must be time (frame)')},
            *get_docval(TimeSeries.__init__, 'unit'),  # required
            {'name': 'indexed_timeseries', 'type': TimeSeries,  # required
             'doc': 'HDF5 link to TimeSeries containing images that are indexed.'},
            *get_docval(TimeSeries.__init__, 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate',
                        'comments', 'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        indexed_timeseries = popargs('indexed_timeseries', kwargs)
        super(IndexSeries, self).__init__(**kwargs)
        self.indexed_timeseries = indexed_timeseries
Exemple #4
0
class ImageMaskSeries(ImageSeries):
    '''
    An alpha mask that is applied to a presented visual stimulus. The data[] array contains an array
    of mask values that are applied to the displayed image. Mask values are stored as RGBA. Mask
    can vary with time. The timestamps array indicates the starting time of a mask, and that mask
    pattern continues until it's explicitly changed.
    '''

    __nwbfields__ = ('masked_imageseries', )

    @docval(
        *get_docval(ImageSeries.__init__, 'name'),  # required
        {
            'name':
            'data',
            'type': ('array_data', 'data', TimeSeries),  # required
            'doc':
            'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames'
        },
        *get_docval(ImageSeries.__init__, 'unit'),
        {
            'name': 'masked_imageseries',
            'type': ImageSeries,  # required
            'doc': 'Link to ImageSeries that mask is applied to.'
        },
        *get_docval(ImageSeries.__init__, 'format', 'external_file',
                    'starting_frame', 'bits_per_pixel', 'dimension',
                    'resolution', 'conversion', 'timestamps', 'starting_time',
                    'rate', 'comments', 'description', 'control',
                    'control_description'))
    def __init__(self, **kwargs):
        name, data = popargs('name', 'data', kwargs)
        masked_imageseries = popargs('masked_imageseries', kwargs)
        super(ImageMaskSeries, self).__init__(name, data, **kwargs)
        self.masked_imageseries = masked_imageseries
Exemple #5
0
class ElectricalSeries(TimeSeries):
    """
    Stores acquired voltage data from extracellular recordings. The data field of an ElectricalSeries
    is an int or float array storing data in Volts. TimeSeries::data array structure: [num times] [num
    channels] (or [num_times] for single electrode).
    """

    __nwbfields__ = ({'name': 'electrodes', 'required_name': 'electrodes',
                      'doc': 'the electrodes that generated this electrical series', 'child': True},
                     'channel_conversion')

    @docval(*get_docval(TimeSeries.__init__, 'name'),  # required
            {'name': 'data', 'type': ('array_data', 'data', TimeSeries),  # required
             'shape': ((None, ), (None, None), (None, None, None)),
             'doc': ('The data values. Can be 1D or 2D. The first dimension must be time. The second dimension '
                     'represents electrodes/channels.')},
            {'name': 'electrodes', 'type': DynamicTableRegion,  # required
             'doc': 'the table region corresponding to the electrodes from which this series was recorded'},
            {'name': 'channel_conversion', 'type': ('array_data', 'data'), 'shape': (None,), 'doc':
             "Channel-specific conversion factor. Multiply the data in the 'data' dataset by these values along the "
             "channel axis (as indicated by axis attribute) AND by the global conversion factor in the 'conversion' "
             "attribute of 'data' to get the data values in Volts, i.e, data in Volts = data * data.conversion * "
             "channel_conversion. This approach allows for both global and per-channel data conversion factors needed "
             "to support the storage of electrical recordings as native values generated by data acquisition systems. "
             "If this dataset is not present, then there is no channel-specific conversion factor, i.e. it is 1 for all"
             " channels.", 'default': None},
            *get_docval(TimeSeries.__init__, 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate',
                        'comments', 'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        name, electrodes, data, channel_conversion = popargs('name', 'electrodes', 'data', 'channel_conversion', kwargs)
        super(ElectricalSeries, self).__init__(name, data, 'volts', **kwargs)
        self.electrodes = electrodes
        self.channel_conversion = channel_conversion
Exemple #6
0
class CurrentClampStimulusSeries(PatchClampSeries):
    '''
    Alias to standard PatchClampSeries. Its functionality is to better tag PatchClampSeries for
    machine (and human) readability of the file.
    '''

    __nwbfields__ = ()

    @docval(
        *get_docval(PatchClampSeries.__init__, 'name', 'data', 'electrode',
                    'gain'),  # required
        *get_docval(PatchClampSeries.__init__, 'stimulus_description',
                    'resolution', 'conversion', 'timestamps', 'starting_time',
                    'rate', 'comments', 'description', 'control',
                    'control_description', 'sweep_number'),
        {
            'name': 'unit',
            'type': str,
            'doc': "The base unit of measurement (must be 'amperes')",
            'default': 'amperes'
        })
    def __init__(self, **kwargs):
        name, data, unit, electrode, gain = popargs('name', 'data', 'unit',
                                                    'electrode', 'gain',
                                                    kwargs)
        unit = ensure_unit(self, name, unit, 'amperes', '2.1.0')
        super().__init__(name, data, unit, electrode, gain, **kwargs)
Exemple #7
0
class AnnotationSeries(TimeSeries):
    """
    Stores text-based records about the experiment. To use the
    AnnotationSeries, add records individually through
    add_annotation() and then call finalize(). Alternatively, if
    all annotations are already stored in a list, use set_data()
    and set_timestamps()
    """

    __nwbfields__ = ()

    @docval(*get_docval(TimeSeries.__init__, 'name'),  # required
            {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': (None,),
             'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames',
             'default': list()},
            *get_docval(TimeSeries.__init__, 'timestamps', 'comments', 'description'))
    def __init__(self, **kwargs):
        name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)
        super(AnnotationSeries, self).__init__(name, data, 'n/a', resolution=-1.0, timestamps=timestamps, **kwargs)

    @docval({'name': 'time', 'type': 'float', 'doc': 'The time for the annotation'},
            {'name': 'annotation', 'type': str, 'doc': 'the annotation'})
    def add_annotation(self, **kwargs):
        '''
        Add an annotation
        '''
        time, annotation = getargs('time', 'annotation', kwargs)
        self.fields['timestamps'].append(time)
        self.fields['data'].append(annotation)
Exemple #8
0
class RoiResponseSeries(TimeSeries):
    '''
    ROI responses over an imaging plane. Each column in data should correspond to
    the signal from one ROI.
    '''

    __nwbfields__ = ({'name': 'rois', 'child': True}, )

    @docval(
        *get_docval(TimeSeries.__init__, 'name'),  # required
        {
            'name':
            'data',
            'type': ('array_data', 'data', TimeSeries),  # required
            'shape': ((None, ), (None, None)),
            'doc':
            ('The data values. May be 1D or 2D. The first dimension must be time. The optional second '
             'dimension represents ROIs')
        },
        *get_docval(TimeSeries.__init__, 'unit'),
        {
            'name':
            'rois',
            'type':
            DynamicTableRegion,  # required
            'doc':
            'a table region corresponding to the ROIs that were used to generate this data'
        },
        *get_docval(TimeSeries.__init__, 'resolution', 'conversion',
                    'timestamps', 'starting_time', 'rate', 'comments',
                    'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        rois = popargs('rois', kwargs)
        call_docval_func(super(RoiResponseSeries, self).__init__, kwargs)
        self.rois = rois
Exemple #9
0
class SpatialSeries(TimeSeries):
    """
    Direction, e.g., of gaze or travel, or position. The TimeSeries::data field is a 2D array storing
    position or direction relative to some reference frame. Array structure: [num measurements]
    [num dimensions]. Each SpatialSeries has a text dataset reference_frame that indicates the
    zero-position, or the zero-axes for direction. For example, if representing gaze direction,
    "straight-ahead" might be a specific pixel on the monitor, or some other point in space. For
    position data, the 0,0 point might be the top-left corner of an enclosure, as viewed from the
    tracking camera. The unit of data will indicate how to interpret SpatialSeries values.
    """

    __nwbfields__ = ('reference_frame',)

    @docval(*get_docval(TimeSeries.__init__, 'name'),  # required
            {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': ((None, ), (None, None)),  # required
             'doc': 'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames'},
            {'name': 'reference_frame', 'type': str,   # required
             'doc': 'description defining what the zero-position is'},
            *get_docval(TimeSeries.__init__, 'conversion', 'resolution', 'timestamps', 'starting_time', 'rate',
                        'comments', 'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        """
        Create a SpatialSeries TimeSeries dataset
        """
        name, data, reference_frame = popargs('name', 'data', 'reference_frame', kwargs)
        super(SpatialSeries, self).__init__(name, data, 'meters', **kwargs)
        self.reference_frame = reference_frame
Exemple #10
0
class TwoPhotonSeries(ImageSeries):
    """Image stack recorded over time from 2-photon microscope."""

    __nwbfields__ = ('field_of_view',
                     'imaging_plane',
                     'pmt_gain',
                     'scan_line_rate')

    @docval(*get_docval(ImageSeries.__init__, 'name'),  # required
            {'name': 'imaging_plane', 'type': ImagingPlane, 'doc': 'Imaging plane class/pointer.'},  # required
            *get_docval(ImageSeries.__init__, 'data', 'unit', 'format'),
            {'name': 'field_of_view', 'type': (Iterable, TimeSeries), 'shape': ((2, ), (3, )),
             'doc': 'Width, height and depth of image, or imaged area (meters).', 'default': None},
            {'name': 'pmt_gain', 'type': 'float', 'doc': 'Photomultiplier gain.', 'default': None},
            {'name': 'scan_line_rate', 'type': 'float',
             'doc': 'Lines imaged per second. This is also stored in /general/optophysiology but is kept '
                    'here as it is useful information for analysis, and so good to be stored w/ the actual data.',
             'default': None},
            *get_docval(ImageSeries.__init__, 'external_file', 'starting_frame', 'bits_per_pixel',
                        'dimension', 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate',
                        'comments', 'description', 'control', 'control_description', 'device'))
    def __init__(self, **kwargs):
        field_of_view, imaging_plane, pmt_gain, scan_line_rate = popargs(
            'field_of_view', 'imaging_plane', 'pmt_gain', 'scan_line_rate', kwargs)
        call_docval_func(super(TwoPhotonSeries, self).__init__, kwargs)
        self.field_of_view = field_of_view
        self.imaging_plane = imaging_plane
        self.pmt_gain = pmt_gain
        self.scan_line_rate = scan_line_rate
Exemple #11
0
class OptogeneticSeries(TimeSeries):
    '''
    Optogenetic stimulus. The data field is in unit of watts.
    '''

    __nwbfields__ = ('site', )

    @docval(
        *get_docval(TimeSeries.__init__, 'name'),  # required
        {
            'name':
            'data',
            'type': ('array_data', 'data', TimeSeries),
            'shape': (None, ),  # required
            'doc':
            'The data this TimeSeries dataset stores. Can also store binary data e.g. image frames'
        },
        {
            'name': 'site',
            'type': OptogeneticStimulusSite,  # required
            'doc': 'The site to which this stimulus was applied.'
        },
        *get_docval(TimeSeries.__init__, 'resolution', 'conversion',
                    'timestamps', 'starting_time', 'rate', 'comments',
                    'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        name, data, site = popargs('name', 'data', 'site', kwargs)
        super(OptogeneticSeries, self).__init__(name, data, 'watts', **kwargs)
        self.site = site
Exemple #12
0
 def test_get_docval_missing_arg_of_many_ok(self):
     """Test that get_docval throws error if the matching docval arguments is not found
     """
     with self.assertRaisesWith(
             ValueError,
             "Function basic_add2 does not have docval argument 'arg3'"):
         get_docval(self.test_obj.basic_add2, 'arg2', 'arg3')
Exemple #13
0
class VoltageClampStimulusSeries(PatchClampSeries):
    '''
    Alias to standard PatchClampSeries. Its functionality is to better tag PatchClampSeries for
    machine (and human) readability of the file.
    '''

    __nwbfields__ = ()

    @docval(
        *get_docval(PatchClampSeries.__init__, 'name', 'data', 'electrode',
                    'gain'),  # required
        *get_docval(PatchClampSeries.__init__, 'stimulus_description',
                    'resolution', 'conversion', 'timestamps', 'starting_time',
                    'rate', 'comments', 'description', 'control',
                    'control_description', 'sweep_number'),
        {
            'name': 'unit',
            'type': str,
            'doc': "The base unit of measurement (must be 'volts')",
            'default': 'volts'
        })
    def __init__(self, **kwargs):
        name, data, unit, electrode, gain = popargs('name', 'data', 'unit',
                                                    'electrode', 'gain',
                                                    kwargs)
        if unit != 'volts':
            warnings.warn(
                "Unit for %s '%s' is ignored and will be set to 'volts' as per "
                "NWB 2.1.0." % (self.__class__.__name__, name))
        unit = 'volts'
        super().__init__(name, data, unit, electrode, gain, **kwargs)
Exemple #14
0
class IZeroClampSeries(CurrentClampSeries):
    '''
    Stores recorded voltage data from intracellular recordings when all current and amplifier settings
    are off (i.e., CurrentClampSeries fields will be zero). There is no CurrentClampStimulusSeries
    associated with an IZero series because the amplifier is disconnected and no stimulus can reach
    the cell.
    '''

    __nwbfields__ = ()

    @docval(
        *get_docval(CurrentClampSeries.__init__, 'name', 'data', 'electrode',
                    'gain'),  # required
        *get_docval(CurrentClampSeries.__init__, 'stimulus_description',
                    'resolution', 'conversion', 'timestamps', 'starting_time',
                    'rate', 'comments', 'description', 'control',
                    'control_description', 'sweep_number'))
    def __init__(self, **kwargs):
        name, data, electrode, gain = popargs('name', 'data', 'electrode',
                                              'gain', kwargs)
        bias_current, bridge_balance, capacitance_compensation = (0.0, 0.0,
                                                                  0.0)
        super(IZeroClampSeries,
              self).__init__(name, data, electrode, gain, bias_current,
                             bridge_balance, capacitance_compensation,
                             **kwargs)
Exemple #15
0
class SpikeEventSeries(ElectricalSeries):
    """
    Stores "snapshots" of spike events (i.e., threshold crossings) in data. This may also be raw data,
    as reported by ephys hardware. If so, the TimeSeries::description field should describing how
    events were detected. All SpikeEventSeries should reside in a module (under EventWaveform
    interface) even if the spikes were reported and stored by hardware. All events span the same
    recording channels and store snapshots of equal duration. TimeSeries::data array structure:
    [num events] [num channels] [num samples] (or [num events] [num samples] for single
    electrode).
    """

    __nwbfields__ = ()

    @docval(*get_docval(ElectricalSeries.__init__, 'name', 'data'),  # required
            {'name': 'timestamps', 'type': ('array_data', 'data', TimeSeries),  # required
             'doc': 'Timestamps for samples stored in data'},
            *get_docval(ElectricalSeries.__init__, 'electrodes'),  # required
            *get_docval(ElectricalSeries.__init__, 'resolution', 'conversion', 'comments', 'description', 'control',
                        'control_description'))
    def __init__(self, **kwargs):
        name, data, electrodes = popargs('name', 'data', 'electrodes', kwargs)
        timestamps = getargs('timestamps', kwargs)
        if not (isinstance(data, TimeSeries) or isinstance(timestamps, TimeSeries)):
            if not (isinstance(data, DataChunkIterator) or isinstance(timestamps, DataChunkIterator)):
                if len(data) != len(timestamps):
                    raise Exception('Must provide the same number of timestamps and spike events')
            else:
                # TODO: add check when we have DataChunkIterators
                pass
        super(SpikeEventSeries, self).__init__(name, data, electrodes, **kwargs)
Exemple #16
0
class CurrentClampSeries(PatchClampSeries):
    '''
    Stores voltage data recorded from intracellular current-clamp recordings. A corresponding
    CurrentClampStimulusSeries (stored separately as a stimulus) is used to store the current
    injected.
    '''

    __nwbfields__ = ('bias_current', 'bridge_balance',
                     'capacitance_compensation')

    @docval(
        *get_docval(PatchClampSeries.__init__, 'name', 'data',
                    'electrode'),  # required
        {
            'name': 'gain',
            'type': 'float',
            'doc': 'Units: Volt/Volt'
        },
        *get_docval(PatchClampSeries.__init__, 'stimulus_description'),
        {
            'name': 'bias_current',
            'type': 'float',
            'doc': 'Unit: Amp',
            'default': None
        },
        {
            'name': 'bridge_balance',
            'type': 'float',
            'doc': 'Unit: Ohm',
            'default': None
        },
        {
            'name': 'capacitance_compensation',
            'type': 'float',
            'doc': 'Unit: Farad',
            'default': None
        },
        *get_docval(PatchClampSeries.__init__, 'resolution', 'conversion',
                    'timestamps', 'starting_time', 'rate', 'comments',
                    'description', 'control', 'control_description',
                    'sweep_number'),
        {
            'name': 'unit',
            'type': str,
            'doc': "The base unit of measurement (must be 'volts')",
            'default': 'volts'
        })
    def __init__(self, **kwargs):
        name, data, unit, electrode, gain = popargs('name', 'data', 'unit',
                                                    'electrode', 'gain',
                                                    kwargs)
        unit = ensure_unit(self, name, unit, 'volts', '2.1.0')
        bias_current, bridge_balance, capacitance_compensation = popargs(
            'bias_current', 'bridge_balance', 'capacitance_compensation',
            kwargs)
        super().__init__(name, data, unit, electrode, gain, **kwargs)
        self.bias_current = bias_current
        self.bridge_balance = bridge_balance
        self.capacitance_compensation = capacitance_compensation
Exemple #17
0
class GrayscaleImage(Image):

    @docval(*get_docval(Image.__init__, 'name'),
            {'name': 'data', 'type': ('array_data', 'data'), 'doc': 'Data of image. Must be 2D',
             'shape': (None, None)},
            *get_docval(Image.__init__, 'resolution', 'description'))
    def __init__(self, **kwargs):
        call_docval_func(super(GrayscaleImage, self).__init__, kwargs)
Exemple #18
0
class ImageSeries(TimeSeries):
    '''
    General image data that is common between acquisition and stimulus time series.
    The image data can be stored in the HDF5 file or it will be stored as an external image file.
    '''

    __nwbfields__ = ('dimension',
                     'external_file',
                     'starting_frame',
                     'format')

    @docval(*get_docval(TimeSeries.__init__, 'name'),  # required
            {'name': 'data', 'type': ('array_data', 'data', TimeSeries), 'shape': ([None] * 3, [None] * 4),
             'doc': ('The data values. Can be 3D or 4D. The first dimension must be time (frame). The second and third '
                     'dimensions represent x and y. The optional fourth dimension represents z.'),
             'default': None},
            *get_docval(TimeSeries.__init__, 'unit'),
            {'name': 'format', 'type': str,
             'doc': 'Format of image. Three types: 1) Image format; tiff, png, jpg, etc. 2) external 3) raw.',
             'default': None},
            {'name': 'external_file', 'type': ('array_data', 'data'),
             'doc': 'Path or URL to one or more external file(s). Field only present if format=external. '
                    'Either external_file or data must be specified, but not both.', 'default': None},
            {'name': 'starting_frame', 'type': Iterable,
             'doc': 'Each entry is the frame number in the corresponding external_file variable. '
                    'This serves as an index to what frames each file contains. If external_file is not '
                    'provided, then this value will be None', 'default': [0]},
            {'name': 'bits_per_pixel', 'type': int, 'doc': 'DEPRECATED: Number of bits per image pixel',
             'default': None},
            {'name': 'dimension', 'type': Iterable,
             'doc': 'Number of pixels on x, y, (and z) axes.', 'default': None},
            *get_docval(TimeSeries.__init__, 'resolution', 'conversion', 'timestamps', 'starting_time', 'rate',
                        'comments', 'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        bits_per_pixel, dimension, external_file, starting_frame, format = popargs(
            'bits_per_pixel', 'dimension', 'external_file', 'starting_frame', 'format', kwargs)
        call_docval_func(super(ImageSeries, self).__init__, kwargs)
        if external_file is None and self.data is None:
            raise ValueError("Must supply either external_file or data to %s '%s'."
                             % (self.__class__.__name__, self.name))
        self.bits_per_pixel = bits_per_pixel
        self.dimension = dimension
        self.external_file = external_file
        if external_file is not None:
            self.starting_frame = starting_frame
        else:
            self.starting_frame = None
        self.format = format

    @property
    def bits_per_pixel(self):
        return self.fields.get('bits_per_pixel')

    @bits_per_pixel.setter
    def bits_per_pixel(self, val):
        if val is not None:
            warnings.warn("bits_per_pixel is no longer used", DeprecationWarning)
            self.fields['bits_per_pixel'] = val
Exemple #19
0
class IntervalSeries(TimeSeries):
    """
    Stores intervals of data. The timestamps field stores the beginning and end of intervals. The
    data field stores whether the interval just started (>0 value) or ended (<0 value). Different interval
    types can be represented in the same series by using multiple key values (eg, 1 for feature A, 2
    for feature B, 3 for feature C, etc). The field data stores an 8-bit integer. This is largely an alias
    of a standard TimeSeries but that is identifiable as representing time intervals in a machine-readable
    way.
    """

    __nwbfields__ = ()

    @docval(
        *get_docval(TimeSeries.__init__, 'name'),  # required
        {
            'name': 'data',
            'type': ('array_data', 'data', TimeSeries),
            'shape': (None, ),
            'doc': '>0 if interval started, <0 if interval ended.',
            'default': list()
        },
        *get_docval(TimeSeries.__init__, 'timestamps', 'comments',
                    'description', 'control', 'control_description'))
    def __init__(self, **kwargs):
        name, data, timestamps = popargs('name', 'data', 'timestamps', kwargs)
        self.__interval_timestamps = timestamps
        self.__interval_data = data
        super(IntervalSeries, self).__init__(name,
                                             data,
                                             'n/a',
                                             resolution=-1.0,
                                             timestamps=timestamps,
                                             **kwargs)

    @docval(
        {
            'name': 'start',
            'type': 'float',
            'doc': 'The name of this TimeSeries dataset'
        }, {
            'name': 'stop',
            'type': 'float',
            'doc': 'The name of this TimeSeries dataset'
        })
    def add_interval(self, **kwargs):
        start, stop = getargs('start', 'stop', kwargs)
        self.__interval_timestamps.append(start)
        self.__interval_timestamps.append(stop)
        self.__interval_data.append(1)
        self.__interval_data.append(-1)

    @property
    def data(self):
        return self.__interval_data

    @property
    def timestamps(self):
        return self.__interval_timestamps
Exemple #20
0
class RGBAImage(Image):

    @docval(*get_docval(Image.__init__, 'name'),
            {'name': 'data', 'type': ('array_data', 'data'),
             'doc': 'Data of image. Must be 3D where the third dimension has length 4 and represents the RGBA value',
             'shape': (None, None, 4)},
            *get_docval(Image.__init__, 'resolution', 'description'))
    def __init__(self, **kwargs):
        call_docval_func(super(RGBAImage, self).__init__, kwargs)
Exemple #21
0
class GrayscaleImage(Image):
    @docval(
        *get_docval(Image.__init__, 'name'),  # required
        {
            'name': 'data',
            'type': ('array_data', 'data'),
            'doc': 'data of image',  # required
            'shape': (None, None)
        },
        *get_docval(Image.__init__, 'resolution', 'description'))
    def __init__(self, **kwargs):
        super(GrayscaleImage, self).__init__(**kwargs)
Exemple #22
0
class RGBAImage(Image):
    @docval(
        *get_docval(Image.__init__, 'name'),
        {
            'name': 'data',
            'type': ('array_data', 'data'),
            'doc': 'data of image',  # required
            'shape': (None, None, 4)
        },
        *get_docval(Image.__init__, 'resolution', 'description'))
    def __init__(self, **kwargs):
        call_docval_func(super(RGBAImage, self).__init__, kwargs)
class NwbElectrodeGroup(ElectrodeGroup):
    ''' Representation of custom ElectrodeGroup object in NWB '''

    __nwbfields__ = ('targeted_location', 'targeted_x', 'targeted_y', 'targeted_z', 'units')

    @docval(*get_docval(ElectrodeGroup.__init__) + (
            {'name': 'targeted_location', 'type': 'str', 'doc': 'predicted location'},
            {'name': 'targeted_x', 'type': 'float', 'doc': 'predicted x coordinates'},
            {'name': 'targeted_y', 'type': 'float', 'doc': 'predicted y coordinates'},
            {'name': 'targeted_z', 'type': 'float', 'doc': 'predicted z coordinates'},
            {'name': 'units', 'type': 'str', 'doc': 'units of fields, possible value: um or mm'}))
    def __init__(self, **kwargs):
        super().__init__(**{kwargs_item: kwargs[kwargs_item]
                            for kwargs_item in kwargs.copy()
                            if kwargs_item != 'targeted_location'
                            if kwargs_item != 'targeted_x'
                            if kwargs_item != 'targeted_y'
                            if kwargs_item != 'targeted_z'
                            if kwargs_item != 'units'
                            })
        call_docval_func(super(NwbElectrodeGroup, self).__init__, kwargs)
        self.targeted_location = kwargs['targeted_location']
        self.targeted_x = kwargs['targeted_x']
        self.targeted_y = kwargs['targeted_y']
        self.targeted_z = kwargs['targeted_z']
        self.units = kwargs['units']
Exemple #24
0
class AbstractSequenceTable(DynamicTable, TorchableMixin, metaclass=ABCMeta):

    @abstractmethod
    def get_sequence_index(self, data, target):
        pass

    @abstractmethod
    def get_sequence_data(self, data):
        pass

    @docval(*get_docval(DynamicTable.__init__),
            {'name': 'sequence_name', 'type': ('array_data', 'data', VectorData), 'doc': 'sequence names'},
            {'name': 'sequence', 'type': ('array_data', 'data', VectorData), 'doc': 'bitpacked DNA sequence'},
            {'name': 'sequence_index', 'type': ('array_data', 'data', VectorIndex), 'doc': 'index for sequence'},
            {'name': 'length', 'type': ('array_data', 'data', VectorData), 'doc': 'lengths of sequence'},
            {'name': 'taxon', 'type': ('array_data', 'data', VectorData), 'doc': 'index for sequence'},
            {'name': 'taxon_table', 'type': DynamicTable, 'doc': "target for 'taxon'", 'default': None},
            {'name': 'pad', 'type': bool, 'doc': 'pad sequences to the maximum length sequence', 'default': False},
            {'name': 'bitpacked', 'type': bool, 'doc': 'sequence data are packed', 'default': True},
            {'name': 'vocab', 'type': 'array_data', 'doc': 'the characters in the sequence vocabulary.', 'default': None})
    def __init__(self, **kwargs):
        sequence_name, index, sequence, taxon, taxon_table = popargs('sequence_name',
                                                             'sequence_index',
                                                             'sequence',
                                                             'taxon',
                                                             'taxon_table',
                                                             kwargs)
        self._bitpacked = popargs('bitpacked', kwargs)
        vocab = popargs('vocab', kwargs)

        self.pad = popargs('pad', kwargs)
        seqlens = popargs('length', kwargs)
        columns = list()
        self.maxlen = None
        if isinstance(sequence_name, VectorData):      # data is being read -- here we assume that everything is a VectorData
            columns.append(sequence_name)
            columns.append(index)
            columns.append(sequence)
            columns.append(seqlens)
            columns.append(taxon)
            if self.pad:   # if we need to pad, compute the maxlen
                self.maxlen = np.max(seqlens.data[:])
        else:
            columns.append(VectorData('sequence_name', 'sequence names', data=sequence_name))
            seq = self.get_sequence_data(sequence)
            columns.append(self.get_sequence_index(index, seq))
            columns.append(seq)
            columns.append(VectorData('length', 'sequence lengths', data=seqlens))
            columns.append(DynamicTableRegion('taxon', taxon, 'taxa for each sequence', taxon_table))
        kwargs['columns'] = columns
        call_docval_func(super().__init__, kwargs)
        self.convert = self.get_numpy_conversion(maxlen=self.maxlen)

    def __getitem__(self, key):
        if isinstance(key, str):
            return super().__getitem__(key)
        else:
            ret = list(super().__getitem__(key))
            # sequence data will come from the third column
            return tuple(ret)
Exemple #25
0
class PointCloudTable(DynamicTable):
    """
    Table for storing point cloud data
    """

    __columns__ = ({
        'name': 'point_cloud',
        'description': 'datapoints locations over time',
        'required': True,
        'index': True
    }, {
        'name': 'timestamps',
        'description': 'time of each frame in seconds',
        'required': True,
        'index': False
    }, {
        'name': 'color',
        'description': 'datapoints color',
        'required': False,
        'index': True
    })

    @docval(
        dict(name='name',
             type=str,
             doc='name of this PointCloudTable',
             default='PointCloudTable'),  # required
        dict(name='description',
             type=str,
             doc='Description of this TimeIntervals',
             default="points from a tracking system"),
        *get_docval(DynamicTable.__init__, 'id', 'columns', 'colnames'))
    def __init__(self, **kwargs):
        call_docval_func(super(PointCloudTable, self).__init__, kwargs)
Exemple #26
0
 def test_load_namespace_with_reftype_attribute_check_autoclass_const(self):
     ns_builder = NWBNamespaceBuilder('Extension for use in my Lab',
                                      self.prefix,
                                      version='0.1.0')
     test_ds_ext = NWBDatasetSpec(
         doc='test dataset to add an attr',
         name='test_data',
         shape=(None, ),
         attributes=[
             NWBAttributeSpec(name='target_ds',
                              doc='the target the dataset applies to',
                              dtype=RefSpec('TimeSeries', 'object'))
         ],
         neurodata_type_def='my_new_type')
     ns_builder.add_spec(self.ext_source, test_ds_ext)
     ns_builder.export(self.ns_path, outdir=self.tempdir)
     type_map = get_type_map(
         extensions=os.path.join(self.tempdir, self.ns_path))
     my_new_type = type_map.get_container_cls(self.prefix, 'my_new_type')
     docval = None
     for tmp in get_docval(my_new_type.__init__):
         if tmp['name'] == 'target_ds':
             docval = tmp
             break
     self.assertIsNotNone(docval)
     self.assertEqual(docval['type'], TimeSeries)
 def test_init_docval(self):
     """Test that the docval for the __init__ method is set correctly."""
     dv = get_docval(Foo.__init__)
     self.assertEqual(dv[0]['name'], 'containers')
     self.assertEqual(dv[1]['name'], 'data')
     self.assertEqual(dv[2]['name'], 'foo_data')
     self.assertEqual(dv[3]['name'], 'things')
     self.assertTupleEqual(dv[0]['type'], (list, tuple, dict, Container))
     self.assertTupleEqual(dv[1]['type'], (list, tuple, dict, Data, OData))
     self.assertTupleEqual(dv[2]['type'], (list, tuple, dict, OData))
     self.assertTupleEqual(dv[3]['type'],
                           (list, tuple, dict, Container, Data, OData))
     self.assertEqual(dv[0]['doc'], 'Container to store in this interface')
     self.assertEqual(dv[1]['doc'],
                      'Data or OData to store in this interface')
     self.assertEqual(dv[2]['doc'], 'OData to store in this interface')
     self.assertEqual(
         dv[3]['doc'],
         'Container, Data, or OData to store in this interface')
     for i in range(4):
         self.assertDictEqual(dv[i]['default'], {})
     self.assertEqual(dv[4]['name'], 'name')
     self.assertEqual(dv[4]['type'], str)
     self.assertEqual(dv[4]['doc'], 'the name of this container')
     self.assertEqual(dv[4]['default'], 'Foo')
 def test_add_docval(self):
     """Test that the docval for the add method is set correctly."""
     dv = get_docval(Foo.add_container)
     self.assertEqual(dv[0]['name'], 'containers')
     self.assertTupleEqual(dv[0]['type'], (list, tuple, dict, Container))
     self.assertEqual(dv[0]['doc'], 'the Container to add')
     self.assertFalse('default' in dv[0])
Exemple #29
0
class AssociatedFiles(NWBDataInterface):
    """ Representation of associated files in NWB """

    __nwbfields__ = ('description', 'content')

    @docval(*get_docval(NWBDataInterface.__init__) + (
        {
            'name': 'description',
            'type': 'str',
            'doc': 'description of associated file'
        },
        {
            'name': 'content',
            'type': 'str',
            'doc': 'content of associated file'
        },
    ))
    def __init__(self, **kwargs):
        super().__init__(
            **{
                kwargs_item: kwargs[kwargs_item]
                for kwargs_item in kwargs.copy()
                if kwargs_item not in ['description', 'content']
            })
        call_docval_func(super(AssociatedFiles, self).__init__, kwargs)
        self.description = kwargs['description']
        self.content = kwargs['content']
Exemple #30
0
class AxisMap(RetinotopyMap):
    """Abstract two-dimensional map of responses to stimuli along a single response axis (e.g., altitude) with unit
    """

    __nwbfields__ = ('unit', )

    @docval(
        *get_docval(RetinotopyMap.__init__, 'name', 'data', 'field_of_view'), {
            'name': 'unit',
            'type': str,
            'doc': 'Unit that axis data is stored in (e.g., degrees)'
        }, *get_docval(RetinotopyMap.__init__, 'dimension'))
    def __init__(self, **kwargs):
        unit = popargs('unit', kwargs)
        call_docval_func(super().__init__, kwargs)
        self.unit = unit