Beispiel #1
0
 def test_from_stimulus_file(self):
     stimulus_file = StimulusFile.from_lims(
         behavior_session_id=self.behavior_session_id, db=self.dbconn)
     timestamps = StimulusTimestamps.from_stimulus_file(
         stimulus_file=stimulus_file)
     rewards = Rewards.from_stimulus_file(stimulus_file=stimulus_file,
                                          stimulus_timestamps=timestamps)
     assert rewards == self.expected
Beispiel #2
0
    def setup_class(cls):
        dir = Path(__file__).parent.resolve()
        test_data_dir = dir / 'test_data'

        stimulus_file = StimulusFile(filepath=test_data_dir /
                                     'behavior_stimulus_file.pkl')
        ts = StimulusTimestamps.from_stimulus_file(stimulus_file=stimulus_file)
        cls.licks = Licks.from_stimulus_file(stimulus_file=stimulus_file,
                                             stimulus_timestamps=ts)
Beispiel #3
0
    def setup_method(self, method):
        self.nwbfile = pynwb.NWBFile(session_description='asession',
                                     identifier='1234',
                                     session_start_time=datetime.now())

        # Need to write stimulus timestamps first
        bsf = StimulusFile(filepath=self.test_data_dir /
                           'behavior_stimulus_file.pkl')
        ts = StimulusTimestamps.from_stimulus_file(stimulus_file=bsf)
        ts.to_nwb(nwbfile=self.nwbfile)
Beispiel #4
0
def test_stimulus_timestamps_from_json(
    monkeypatch, dict_repr, has_pkl, has_sync
):
    mock_stimulus_file = create_autospec(StimulusFile)
    mock_sync_file = create_autospec(SyncFile)

    mock_get_behavior_stimulus_timestamps = create_autospec(
        get_behavior_stimulus_timestamps
    )
    mock_get_ophys_stimulus_timestamps = create_autospec(
        get_ophys_stimulus_timestamps
    )

    with monkeypatch.context() as m:
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps.StimulusFile",
            mock_stimulus_file
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps.SyncFile",
            mock_sync_file
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps"
            ".get_behavior_stimulus_timestamps",
            mock_get_behavior_stimulus_timestamps
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps"
            ".get_ophys_stimulus_timestamps",
            mock_get_ophys_stimulus_timestamps
        )
        mock_stimulus_file_instance = mock_stimulus_file.from_json(dict_repr)
        ts_from_stim = StimulusTimestamps.from_stimulus_file(
            stimulus_file=mock_stimulus_file_instance)

        if has_pkl and has_sync:
            mock_sync_file_instance = mock_sync_file.from_json(dict_repr)
            ts_from_sync = StimulusTimestamps.from_sync_file(
                sync_file=mock_sync_file_instance)

    if has_pkl and has_sync:
        mock_get_ophys_stimulus_timestamps.assert_called_once_with(
            sync_path=mock_sync_file_instance.filepath
        )
        assert ts_from_sync._sync_file == mock_sync_file_instance
    else:
        assert ts_from_stim._stimulus_file == mock_stimulus_file_instance
        mock_get_behavior_stimulus_timestamps.assert_called_once_with(
            stimulus_pkl=mock_stimulus_file_instance.data
        )
Beispiel #5
0
 def test_from_stimulus_file(self):
     stimulus_file = StimulusFile.from_lims(
         behavior_session_id=self.behavior_session_id, db=self.dbconn)
     stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
         stimulus_file=stimulus_file)
     stimuli = Stimuli.from_stimulus_file(
         stimulus_file=stimulus_file,
         stimulus_timestamps=stimulus_timestamps,
         limit_to_images=['im065'])
     assert stimuli.presentations == self.expected_presentations
     assert stimuli.templates == self.expected_templates
Beispiel #6
0
def test_stimulus_timestamps_from_json2():
    dir = Path(__file__).parent.parent.resolve()
    test_data_dir = dir / 'test_data'
    sf_path = test_data_dir / 'stimulus_file.pkl'

    sf = StimulusFile.from_json(
        dict_repr={'behavior_stimulus_file': str(sf_path)})
    stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
        stimulus_file=sf)
    expected = np.array([0.016 * i for i in range(11)])
    assert np.allclose(expected, stimulus_timestamps.value)
Beispiel #7
0
    def from_lims(
        cls,
        db: PostgresQueryMixin,
        behavior_session_id: int,
        filtered: bool = True,
        zscore_threshold: float = 10.0,
        stimulus_timestamps: Optional[StimulusTimestamps] = None
    ) -> "RunningSpeed":
        stimulus_file = StimulusFile.from_lims(db, behavior_session_id)
        if stimulus_timestamps is None:
            stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
                stimulus_file=stimulus_file)

        running_speed = cls._get_running_speed_df(stimulus_file,
                                                  stimulus_timestamps,
                                                  filtered, zscore_threshold)
        return cls(running_speed=running_speed,
                   stimulus_file=stimulus_file,
                   stimulus_timestamps=stimulus_timestamps,
                   filtered=filtered)
    def from_lims(
        cls,
        db: PostgresQueryMixin,
        behavior_session_id: int,
        ophys_experiment_id: Optional[int] = None,
    ) -> "RunningAcquisition":

        stimulus_file = StimulusFile.from_lims(db, behavior_session_id)
        stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
            stimulus_file=stimulus_file)
        running_acq_df = get_running_df(
            data=stimulus_file.data,
            time=stimulus_timestamps.value,
        )
        running_acq_df.drop("speed", axis=1, inplace=True)

        return cls(
            running_acquisition=running_acq_df,
            stimulus_file=stimulus_file,
            stimulus_timestamps=stimulus_timestamps,
        )
Beispiel #9
0
def test_stimulus_timestamps_from_json3():
    """
    Test that StimulusTimestamps.from_stimulus_file
    just returns the sum of the intervalsms field in the
    behavior stimulus pickle file, padded with a zero at the
    first timestamp.
    """
    dir = Path(__file__).parent.parent.resolve()
    test_data_dir = dir / 'test_data'
    sf_path = test_data_dir / 'stimulus_file.pkl'

    sf = StimulusFile.from_json(
        dict_repr={'behavior_stimulus_file': str(sf_path)})

    sf._data['items']['behavior']['intervalsms'] = [0.1, 0.2, 0.3, 0.4]

    stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
        stimulus_file=sf)

    expected = np.array([0., 0.0001, 0.0003, 0.0006, 0.001])
    np.testing.assert_array_almost_equal(stimulus_timestamps.value,
                                         expected,
                                         decimal=10)
Beispiel #10
0
 def test_from_stimulus_file(self):
     st = StimulusTimestamps.from_stimulus_file(
         stimulus_file=self.stimulus_file)
     licks = Licks.from_stimulus_file(stimulus_file=self.stimulus_file,
                                      stimulus_timestamps=st)
     assert licks == self.expected
Beispiel #11
0
def test_stimulus_timestamps_from_lims(
    monkeypatch, behavior_session_id, ophys_experiment_id
):
    mock_db_conn = create_autospec(PostgresQueryMixin, instance=True)

    mock_stimulus_file = create_autospec(StimulusFile)
    mock_sync_file = create_autospec(SyncFile)

    mock_get_behavior_stimulus_timestamps = create_autospec(
        get_behavior_stimulus_timestamps
    )
    mock_get_ophys_stimulus_timestamps = create_autospec(
        get_ophys_stimulus_timestamps
    )

    with monkeypatch.context() as m:
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps.StimulusFile",
            mock_stimulus_file
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps.SyncFile",
            mock_sync_file
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps"
            ".get_behavior_stimulus_timestamps",
            mock_get_behavior_stimulus_timestamps
        )
        m.setattr(
            "allensdk.brain_observatory.behavior.data_objects"
            ".timestamps.stimulus_timestamps.stimulus_timestamps"
            ".get_ophys_stimulus_timestamps",
            mock_get_ophys_stimulus_timestamps
        )
        mock_stimulus_file_instance = mock_stimulus_file.from_lims(
            mock_db_conn, behavior_session_id
        )
        ts_from_stim = StimulusTimestamps.from_stimulus_file(
            stimulus_file=mock_stimulus_file_instance)
        assert ts_from_stim._stimulus_file == mock_stimulus_file_instance

        if behavior_session_id is not None and ophys_experiment_id is not None:
            mock_sync_file_instance = mock_sync_file.from_lims(
                mock_db_conn, ophys_experiment_id
            )
            ts_from_sync = StimulusTimestamps.from_sync_file(
                sync_file=mock_sync_file_instance)

    if behavior_session_id is not None and ophys_experiment_id is not None:
        mock_get_ophys_stimulus_timestamps.assert_called_once_with(
            sync_path=mock_sync_file_instance.filepath
        )
        assert ts_from_sync._sync_file == mock_sync_file_instance
    else:
        mock_stimulus_file.from_lims.assert_called_with(
            mock_db_conn, behavior_session_id
        )
        mock_get_behavior_stimulus_timestamps.assert_called_once_with(
            stimulus_pkl=mock_stimulus_file_instance.data
        )
Beispiel #12
0
    def from_lims(cls, behavior_session_id: int,
                  lims_db: Optional[PostgresQueryMixin] = None,
                  stimulus_timestamps: Optional[StimulusTimestamps] = None,
                  monitor_delay: Optional[float] = None,
                  date_of_acquisition: Optional[DateOfAcquisition] = None) \
            -> "BehaviorSession":
        """

        Parameters
        ----------
        behavior_session_id
            Behavior session id
        lims_db
            Database connection. If not provided will create a new one.
        stimulus_timestamps
            Stimulus timestamps. If not provided, will calculate stimulus
            timestamps from stimulus file.
        monitor_delay
            Monitor delay. If not provided, will use an estimate.
            To provide this value, see for example
            allensdk.brain_observatory.behavior.data_objects.stimuli.util.
            calculate_monitor_delay
        date_of_acquisition
            Date of acquisition. If not provided, will read from
            behavior_sessions table.
        Returns
        -------
        `BehaviorSession` instance
        """
        if lims_db is None:
            lims_db = db_connection_creator(
                fallback_credentials=LIMS_DB_CREDENTIAL_MAP)

        behavior_session_id = BehaviorSessionId(behavior_session_id)
        stimulus_file = StimulusFile.from_lims(
            db=lims_db, behavior_session_id=behavior_session_id.value)
        if stimulus_timestamps is None:
            stimulus_timestamps = StimulusTimestamps.from_stimulus_file(
                stimulus_file=stimulus_file)
        running_acquisition = RunningAcquisition.from_lims(
            lims_db, behavior_session_id.value)
        raw_running_speed = RunningSpeed.from_lims(
            lims_db,
            behavior_session_id.value,
            filtered=False,
            stimulus_timestamps=stimulus_timestamps)
        running_speed = RunningSpeed.from_lims(
            lims_db,
            behavior_session_id.value,
            stimulus_timestamps=stimulus_timestamps)
        behavior_metadata = BehaviorMetadata.from_lims(
            behavior_session_id=behavior_session_id, lims_db=lims_db)

        if monitor_delay is None:
            monitor_delay = cls._get_monitor_delay()

        licks, rewards, stimuli, task_parameters, trials = \
            cls._read_data_from_stimulus_file(
                stimulus_file=stimulus_file,
                stimulus_timestamps=stimulus_timestamps,
                trial_monitor_delay=monitor_delay
            )
        if date_of_acquisition is None:
            date_of_acquisition = DateOfAcquisition.from_lims(
                behavior_session_id=behavior_session_id.value, lims_db=lims_db)
        date_of_acquisition = date_of_acquisition.validate(
            stimulus_file=stimulus_file,
            behavior_session_id=behavior_session_id.value)

        return BehaviorSession(behavior_session_id=behavior_session_id,
                               stimulus_timestamps=stimulus_timestamps,
                               running_acquisition=running_acquisition,
                               raw_running_speed=raw_running_speed,
                               running_speed=running_speed,
                               metadata=behavior_metadata,
                               licks=licks,
                               rewards=rewards,
                               stimuli=stimuli,
                               task_parameters=task_parameters,
                               trials=trials,
                               date_of_acquisition=date_of_acquisition)