Exemplo n.º 1
0
def write_behavior_nwb(session_data, nwb_filepath):

    nwb_filepath_inprogress = nwb_filepath + '.inprogress'
    nwb_filepath_error = nwb_filepath + '.error'

    # Clean out files from previous runs:
    for filename in [
            nwb_filepath_inprogress, nwb_filepath_error, nwb_filepath
    ]:
        if os.path.exists(filename):
            os.remove(filename)

    try:
        json_session = BehaviorSession.from_json(session_data)

        behavior_session_id = session_data['behavior_session_id']
        lims_session = BehaviorSession.from_lims(behavior_session_id)

        logging.info("Comparing a BehaviorSession created from JSON "
                     "with a BehaviorSession created from LIMS")
        assert sessions_are_equal(json_session, lims_session, reraise=True)

        nwbfile = lims_session.to_nwb()
        with NWBHDF5IO(nwb_filepath_inprogress, 'w') as nwb_file_writer:
            nwb_file_writer.write(nwbfile)

        logging.info("Comparing a BehaviorSession created from JSON "
                     "with a BehaviorSession created from NWB")
        nwb_session = BehaviorSession.from_nwb_path(nwb_filepath_inprogress)
        assert sessions_are_equal(json_session, nwb_session, reraise=True)

        os.rename(nwb_filepath_inprogress, nwb_filepath)
        return {'output_path': nwb_filepath}
    except Exception as e:
        if os.path.isfile(nwb_filepath_inprogress):
            os.rename(nwb_filepath_inprogress, nwb_filepath_error)
        raise e
    def from_json(cls,
                  session_data: dict,
                  eye_tracking_z_threshold: float = 3.0,
                  eye_tracking_dilation_frames: int = 2,
                  events_filter_scale: float = 2.0,
                  events_filter_n_time_steps: int = 20,
                  exclude_invalid_rois=True,
                  skip_eye_tracking=False) -> \
            "BehaviorOphysExperiment":
        """

        Parameters
        ----------
        session_data
        eye_tracking_z_threshold
            See `BehaviorOphysExperiment.from_nwb`
        eye_tracking_dilation_frames
            See `BehaviorOphysExperiment.from_nwb`
        events_filter_scale
            See `BehaviorOphysExperiment.from_nwb`
        events_filter_n_time_steps
            See `BehaviorOphysExperiment.from_nwb`
        exclude_invalid_rois
            Whether to exclude invalid rois
        skip_eye_tracking
            Used to skip returning eye tracking data

        """
        def _is_multi_plane_session():
            imaging_plane_group_meta = ImagingPlaneGroup.from_json(
                dict_repr=session_data)
            return cls._is_multi_plane_session(
                imaging_plane_group_meta=imaging_plane_group_meta)

        def _get_motion_correction():
            rigid_motion_transform_file = RigidMotionTransformFile.from_json(
                dict_repr=session_data)
            return MotionCorrection.from_data_file(
                rigid_motion_transform_file=rigid_motion_transform_file)

        def _get_eye_tracking_table(sync_file: SyncFile):
            eye_tracking_file = EyeTrackingFile.from_json(
                dict_repr=session_data)
            eye_tracking_table = EyeTrackingTable.from_data_file(
                data_file=eye_tracking_file,
                sync_file=sync_file,
                z_threshold=eye_tracking_z_threshold,
                dilation_frames=eye_tracking_dilation_frames)
            return eye_tracking_table

        sync_file = SyncFile.from_json(dict_repr=session_data)
        is_multiplane_session = _is_multi_plane_session()
        meta = BehaviorOphysMetadata.from_json(
            dict_repr=session_data, is_multiplane=is_multiplane_session)
        monitor_delay = calculate_monitor_delay(
            sync_file=sync_file, equipment=meta.behavior_metadata.equipment)
        behavior_session = BehaviorSession.from_json(
            session_data=session_data, monitor_delay=monitor_delay)

        if is_multiplane_session:
            ophys_timestamps = OphysTimestampsMultiplane.from_sync_file(
                sync_file=sync_file,
                group_count=meta.ophys_metadata.imaging_plane_group_count,
                plane_group=meta.ophys_metadata.imaging_plane_group)
        else:
            ophys_timestamps = OphysTimestamps.from_sync_file(
                sync_file=sync_file)

        projections = Projections.from_json(dict_repr=session_data)
        cell_specimens = CellSpecimens.from_json(
            dict_repr=session_data,
            ophys_timestamps=ophys_timestamps,
            segmentation_mask_image_spacing=projections.max_projection.spacing,
            events_params=EventsParams(
                filter_scale=events_filter_scale,
                filter_n_time_steps=events_filter_n_time_steps),
            exclude_invalid_rois=exclude_invalid_rois)
        motion_correction = _get_motion_correction()
        if skip_eye_tracking:
            eye_tracking_table = None
            eye_tracking_rig_geometry = None
        else:
            eye_tracking_table = _get_eye_tracking_table(sync_file=sync_file)
            eye_tracking_rig_geometry = EyeTrackingRigGeometry.from_json(
                dict_repr=session_data)

        return BehaviorOphysExperiment(
            behavior_session=behavior_session,
            cell_specimens=cell_specimens,
            ophys_timestamps=ophys_timestamps,
            metadata=meta,
            projections=projections,
            motion_correction=motion_correction,
            eye_tracking_table=eye_tracking_table,
            eye_tracking_rig_geometry=eye_tracking_rig_geometry,
            date_of_acquisition=behavior_session._date_of_acquisition)