Beispiel #1
0
class Summary(HasTraits):
    summary_table = List(Data)
    subject = Instance(Data)

    view = QtView(
        Item(
            'summary_table',
            editor=TableEditor(
                editable=False,
                selected='subject',
                adapter=SummaryAdapter(),
                # operations = [],
                # images     = [ op.abspath('green_ball.png'),
                #             op.abspath('red_ball.png'), ]
            )),
        resizable=True,
        width=0.75,
        height=0.75)
Beispiel #2
0
class EEGSensorApp(t.HasTraits):

    sensor = t.Instance(EEGSensor)
    filters = t.List(t.Instance(TimeDomainFilter))

    sensor_operation_controller = t.Instance(SensorOperationController)

    def _sensor_operation_controller_default(self):
        return SensorOperationController(model=self.sensor)

    sensor_timeseries_controller = t.Instance(SensorTimeseriesController)

    def _sensor_timeseries_controller_default(self):
        return SensorTimeseriesController(model=self.sensor,
                                          filters=self.filters)

    sensor_fft_controller = t.Instance(SensorFFTController)

    def _sensor_fft_controller_default(self):
        return SensorFFTController(model=self.sensor)

    traits_view = QtView(
        HGroup(
            VGroup(Item('sensor_timeseries_controller', style='custom'),
                   show_border=True,
                   show_labels=False),
            VGroup(Item('sensor_fft_controller', style='custom'),
                   Item('sensor_operation_controller', style='custom'),
                   show_border=True,
                   show_labels=False),
        ),
        title="EEG Sensor Console",
        icon=ImageResource('application'),
        # style_sheet_path='dark_style_sheet.qss',
        style_sheet=qdarkstyle.load_stylesheet(pyside=True),
        resizable=True,
        handler=AppHandler(),
    )
class ProjectInfoUI(cmp.project.ProjectInfo):
    """Class that extends the :class:`ProjectInfo` with graphical components.

    It supports graphically the setting of all processing properties / attributes
    of an :class:`ProjectInfo` instance.

    Attributes
    -----------
    creation_mode : traits.Enum
        Mode for loading the dataset. Valid values are
        'Load BIDS dataset', 'Install Datalad BIDS dataset'

    install_datalad_dataset_via_ssh : traits.Bool
        If set to True install the datalad dataset from a remote server
        via ssh.(True by default)

    ssh_user : traits.Str
        Remote server username.
        (Required if ``install_datalad_dataset_via_ssh`` is True)

    ssh_pwd <traits.Password>
        Remote server password.
        (Required if ``install_datalad_dataset_via_ssh`` is True)

    ssh_remote : traits.Str
        Remote server IP or URL.
        (Required if ``install_datalad_dataset_via_ssh`` is True)

    datalad_dataset_path : traits.Directory
        Path to the datalad dataset on the remote server.
        (Required if ``install_datalad_dataset_via_ssh`` is True)

    summary_view_button : traits.ui.Button
        Button that shows the pipeline processing summary table

    pipeline_processing_summary_view : traits.ui.VGroup
        TraitsUI VGroup that contains ``Item('pipeline_processing_summary')``

    dataset_view : traits.ui.View
        TraitsUI View that shows a summary of project settings and
        modality available for a given subject

    traits_view : QtView
        TraitsUI QtView that includes the View 'dataset_view'

    create_view : traits.ui.View
        Dialog view to create a BIDS Dataset

    subject_view : traits.ui.View
        Dialog view to select of subject

    subject_session_view : traits.ui.View
        Dialog view to select the subject session

    dmri_bids_acq_view : traits.ui.View
        Dialog view to select the diffusion acquisition model

    anat_warning_view : traits.ui.View
        View that displays a warning message regarding
        the anatomical T1w data

    anat_config_error_view : traits.ui.View
        Error view that displays an error message regarding
        the configuration of the anatomical pipeline

    dmri_warning_view : traits.ui.View
        View that displays a warning message regarding
        the diffusion MRI data

    dmri_config_error_view : traits.ui.View
        View that displays an error message regarding
        the configuration of the diffusion pipeline

    fmri_warning_view : traits.ui.View
        View that displays a warning message regarding
        the functional MRI data

    fmri_config_error_view : traits.ui.View
        View that displays an error message regarding
        the configuration of the fMRI pipeline

    open_view : traits.ui.View
        Dialog view to load a BIDS Dataset

    anat_select_config_to_load : traits.ui.View
        Dialog view to load the configuration file of the anatomical pipeline

    diffusion_imaging_model_select_view : traits.ui.View
        Dialog view to select the diffusion acquisition model

    dmri_select_config_to_load : traits.ui.View
        Dialog view to load the configuration file of the diffusion MRI pipeline

    fmri_select_config_to_load : traits.ui.View
        Dialog view to load the configuration file of the fMRI pipeline
    """

    creation_mode = Enum("Load BIDS dataset", "Install Datalad BIDS dataset")
    install_datalad_dataset_via_ssh = Bool(True)
    ssh_user = String("remote_username")
    ssh_pwd = Password("")
    ssh_remote = String("IP address/ Machine name")
    datalad_dataset_path = Directory(
        "/shared/path/to/existing/datalad/dataset")

    anat_runs = List()
    anat_run = Enum(values="anat_runs")

    dmri_runs = List()
    dmri_run = Enum(values="dmri_runs")

    fmri_runs = List()
    fmri_run = Enum(values="fmri_runs")

    summary_view_button = Button("Pipeline processing summary")

    pipeline_processing_summary_view = VGroup(
        Item("pipeline_processing_summary"))

    dataset_view = VGroup(
        VGroup(
            HGroup(
                Item(
                    "base_directory",
                    width=-0.3,
                    style="readonly",
                    label="",
                    resizable=True,
                ),
                Item(
                    "number_of_subjects",
                    width=-0.3,
                    style="readonly",
                    label="Number of participants",
                    resizable=True,
                ),
                "summary_view_button",
            ),
            label="BIDS Dataset",
        ),
        spring,
        HGroup(
            Group(
                Item("subject",
                     style="simple",
                     show_label=True,
                     resizable=True)),
            Group(
                Item("subject_session",
                     style="simple",
                     label="Session",
                     resizable=True),
                visible_when='subject_session!=""',
            ),
            springy=True,
        ),
        spring,
        Group(
            Item("t1_available", style="readonly", label="T1", resizable=True),
            HGroup(
                Item(
                    "dmri_available",
                    style="readonly",
                    label="Diffusion",
                    resizable=True,
                ),
                Item(
                    "diffusion_imaging_model",
                    label="Model",
                    resizable=True,
                    enabled_when="dmri_available",
                ),
            ),
            Item("fmri_available",
                 style="readonly",
                 label="BOLD",
                 resizable=True),
            label="Modalities",
        ),
        spring,
        Group(
            Item(
                "anat_last_date_processed",
                label="Anatomical pipeline",
                style="readonly",
                resizable=True,
                enabled_when="t1_available",
            ),
            Item(
                "dmri_last_date_processed",
                label="Diffusion pipeline",
                style="readonly",
                resizable=True,
                enabled_when="dmri_available",
            ),
            Item(
                "fmri_last_date_processed",
                label="fMRI pipeline",
                style="readonly",
                resizable=True,
                enabled_when="fmri_available",
            ),
            label="Last date processed",
        ),
        spring,
        Group(Item("number_of_cores", resizable=True),
              label="Processing configuration"),
        "550",
        spring,
        springy=True,
    )

    traits_view = QtView(Include("dataset_view"))

    create_view = View(
        Item("creation_mode", style="custom"),
        Group(
            Group(
                Item("base_directory", label="BIDS Dataset"),
                visible_when='creation_mode=="Load BIDS dataset"',
            ),
            Group(
                Item("install_datalad_dataset_via_ssh"),
                visible_when='creation_mode=="Install Datalad/BIDS dataset"',
            ),
            Group(
                Item(
                    "ssh_remote",
                    label="Remote ssh server",
                    visible_when="install_datalad_dataset_via_ssh",
                ),
                Item(
                    "ssh_user",
                    label="Remote username",
                    visible_when="install_datalad_dataset_via_ssh",
                ),
                Item(
                    "ssh_pwd",
                    label="Remote password",
                    visible_when="install_datalad_dataset_via_ssh",
                ),
                Item(
                    "datalad_dataset_path",
                    label="Datalad/BIDS Dataset Path/URL to be installed",
                ),
                Item("base_directory", label="Installation directory"),
                visible_when='creation_mode=="Install Datalad/BIDS dataset"',
            ),
        ),
        kind="livemodal",
        title="Data creation: BIDS dataset selection",
        # style_sheet=style_sheet,
        width=modal_width,
        buttons=["OK", "Cancel"],
    )

    subject_view = View(
        Group(Item("subject", label="Selected Subject")),
        kind="modal",
        title="Subject and session selection",
        # style_sheet=style_sheet,
        width=modal_width,
        buttons=["OK", "Cancel"],
    )

    subject_session_view = View(
        Group(
            Item("subject", style="readonly", label="Selected Subject"),
            Item("subject_session", label="Selected Session"),
        ),
        kind="modal",
        title="Session selection",
        # style_sheet=style_sheet,
        width=modal_width,
        buttons=["OK", "Cancel"],
    )

    dmri_bids_acq_view = View(
        Group(Item("dmri_bids_acq", label="Selected model"), ),
        kind="modal",
        title="Selection of diffusion acquisition model",
        # style_sheet=style_sheet,
        width=modal_width,
        buttons=["OK", "Cancel"],
    )

    anat_warning_view = View(
        Group(Item("anat_warning_msg", style="readonly", show_label=False), ),
        title="Warning : Anatomical T1w data",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    anat_config_error_view = View(
        Group(
            Item("anat_config_error_msg", style="readonly",
                 show_label=False), ),
        title="Error",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    dmri_warning_view = View(
        Group(Item("dmri_warning_msg", style="readonly", show_label=False), ),
        title="Warning : Diffusion MRI data",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    dmri_config_error_view = View(
        Group(
            Item("dmri_config_error_msg", style="readonly",
                 show_label=False), ),
        title="Error",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    fmri_warning_view = View(
        Group(Item("fmri_warning_msg", style="readonly", show_label=False), ),
        title="Warning : fMRI data",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    fmri_config_error_view = View(
        Group(
            Item("fmri_config_error_msg", style="readonly",
                 show_label=False), ),
        title="Error",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    open_view = View(
        Item("creation_mode", label="Mode"),
        Group(
            Item("install_datalad_dataset_via_ssh"),
            Item(
                "ssh_remote",
                label="Remote ssh server",
                visible_when="install_datalad_dataset_via_ssh",
            ),
            Item(
                "ssh_user",
                label="Remote username",
                visible_when="install_datalad_dataset_via_ssh",
            ),
            Item(
                "ssh_pwd",
                label="Remote password",
                visible_when="install_datalad_dataset_via_ssh",
            ),
            Item(
                "datalad_dataset_path",
                label="Datalad/BIDS Dataset Path/URL to be installed",
            ),
            Item("base_directory", label="Installation directory"),
            visible_when='creation_mode=="Install Datalad BIDS dataset"',
        ),
        Group(
            Item("base_directory", label="BIDS Dataset"),
            visible_when='creation_mode=="Load BIDS dataset"',
        ),
        kind="livemodal",
        title="BIDS Dataset Creation/Loading",
        # style_sheet=style_sheet,
        width=600,
        height=250,
        buttons=["OK", "Cancel"],
    )

    anat_select_config_to_load = View(
        Group(
            Item("anat_config_to_load_msg", style="readonly",
                 show_label=False),
            Item(
                "anat_config_to_load",
                style="custom",
                editor=EnumEditor(name="anat_available_config"),
                show_label=False,
            ),
        ),
        title="Select configuration for anatomical pipeline",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    anat_custom_map_view = View(
        Group(
            Item(
                "anat_custom_last_stage",
                editor=EnumEditor(name="anat_stage_names"),
                style="custom",
                show_label=False,
            ), ),
        title="Select until which stage to process the anatomical pipeline.",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    diffusion_imaging_model_select_view = View(
        Group(Item("diffusion_imaging_model",
                   label="Diffusion MRI modality"), ),
        title="Please select diffusion MRI modality",
        kind="modal",
        width=modal_width,
        buttons=["OK", "Cancel"],
    )

    dmri_select_config_to_load = View(
        Group(
            Item("dmri_config_to_load_msg", style="readonly",
                 show_label=False), ),
        Item(
            "dmri_config_to_load",
            style="custom",
            editor=EnumEditor(name="dmri_available_config"),
            show_label=False,
        ),
        title="Select configuration for diffusion pipeline",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    dmri_custom_map_view = View(
        Group(
            Item(
                "dmri_custom_last_stage",
                editor=EnumEditor(name="dmri_stage_names"),
                style="custom",
                show_label=False,
            ), ),
        title="Select until which stage to process the diffusion pipeline.",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    fmri_select_config_to_load = View(
        Group(
            Item("fmri_config_to_load_msg", style="readonly",
                 show_label=False), ),
        Item(
            "fmri_config_to_load",
            style="custom",
            editor=EnumEditor(name="fmri_available_config"),
            show_label=False,
        ),
        title="Select configuration for fMRI pipeline",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    fmri_custom_map_view = View(
        Group(
            Item(
                "fmri_custom_last_stage",
                editor=EnumEditor(name="fmri_stage_names"),
                style="custom",
                show_label=False,
            ), ),
        title="Select until which stage to process the fMRI pipeline.",
        kind="modal",
        width=modal_width,
        # style_sheet=style_sheet,
        buttons=["OK", "Cancel"],
    )

    def _summary_view_button_fired(self):
        self.configure_traits(view="pipeline_processing_summary_view")
Beispiel #4
0
class QualityInspectorWindow(HasTraits):
    """Class that defines the Quality Inspector Window.

    Attributes
    ----------
    project_info : cmp.project.ProjectInfo
        Instance of :class:`CMP_Project_Info` that represents the processing project

    anat_pipeline : Instance(HasTraits)
        Instance of anatomical MRI pipeline

    dmri_pipeline : Instance(HasTraits)
        Instance of diffusion MRI pipeline

    fmri_pipeline : Instance(HasTraits)
        Instance of functional MRI pipeline

    anat_inputs_checked : traits.Bool
        Indicates if inputs of anatomical pipeline are available
        (Default: False)

    dmri_inputs_checked : traits.Bool
        Indicates if inputs of diffusion pipeline are available
        (Default: False)

    fmri_inputs_checked : traits.Bool
        Indicates if inputs of functional pipeline are available
        (Default: False)

    output_anat_available : traits.Bool
        Indicates if outputs of anatomical pipeline are available
        (Default: False)

    output_dmri_available : traits.Bool
        Indicates if outputs of diffusion pipeline are available
        (Default: False)

    output_fmri_available : traits.Bool
        Indicates if outputs of functional pipeline are available
        (Default: False)

    traits_view : QtView
        TraitsUI QtView that describes the content of the window
    """
    project_info = Instance(cmp.project.ProjectInfo)

    anat_pipeline = Instance(HasTraits)
    dmri_pipeline = Instance(HasTraits)
    fmri_pipeline = Instance(HasTraits)

    anat_inputs_checked = Bool(False)
    dmri_inputs_checked = Bool(False)
    fmri_inputs_checked = Bool(False)

    output_anat_available = Bool(False)
    output_dmri_available = Bool(False)
    output_fmri_available = Bool(False)

    traits_view = QtView(
        Group(
            # Group(
            #     # Include('dataset_view'),label='Data manager',springy=True
            #     Item('project_info',style='custom',show_label=False),label='Data manager',springy=True, dock='tab'
            # ),
            Group(
                Item("anat_pipeline", style="custom", show_label=False),
                visible_when="output_anat_available",
                label="Anatomical pipeline",
                dock="tab",
            ),
            Group(
                Item(
                    "dmri_pipeline",
                    style="custom",
                    show_label=False,
                    visible_when="output_dmri_available",
                ),
                label="Diffusion pipeline",
                dock="tab",
            ),
            Group(
                Item(
                    "fmri_pipeline",
                    style="custom",
                    show_label=False,
                    visible_when="output_fmri_available",
                ),
                label="fMRI pipeline",
                dock="tab",
            ),
            orientation="horizontal",
            layout="tabbed",
            springy=True,
            enabled_when="output_anat_available",
        ),
        title="Connectome Mapper 3 Inspector",
        menubar=MenuBar(
            Menu(
                ActionGroup(Action(name="Quit", action="_on_close"), ),
                name="File",
            ), ),
        handler=cmp.bidsappmanager.gui.handlers.ConfigQualityWindowHandler(),
        style_sheet=style_sheet,
        width=0.5,
        height=0.8,
        resizable=True,  # scrollable=True,
        # icon=get_icon("qualitycontrol.png")
    )

    error_msg = Str("")
    error_view = View(
        Group(Item("error_msg", style="readonly", show_label=False), ),
        title="Error",
        kind="modal",
        # style_sheet=style_sheet,
        buttons=["OK"],
    )

    def __init__(
        self,
        project_info=None,
        anat_inputs_checked=False,
        dmri_inputs_checked=False,
        fmri_inputs_checked=False,
    ):
        """Constructor of an :class:``PipelineConfiguratorWindow`` instance.

        Parameters
        ----------
        project_info : cmp.project.ProjectInfo
            :class:`CMP_Project_Info` object (Default: None)

        anat_inputs_checked : traits.Bool
            Boolean that indicates if anatomical pipeline inputs are available
            (Default: False)

        dmri_inputs_checked = : traits.Bool
            Boolean that indicates if diffusion pipeline inputs are available
            (Default: False)

        fmri_inputs_checked : traits.Bool
            Boolean that indicates if functional pipeline inputs are available
            (Default: False)
        """
        print("> Initialize window...")
        self.project_info = project_info

        self.anat_inputs_checked = anat_inputs_checked
        self.dmri_inputs_checked = dmri_inputs_checked
        self.fmri_inputs_checked = fmri_inputs_checked

        aborded = self.select_subject()

        if aborded:
            raise Exception(
                BColors.FAIL +
                " .. ABORDED: The quality control window will not be displayed."
                +
                "Selection of subject/session was cancelled at initialization."
                + BColors.ENDC)

    def select_subject(self):
        """Function to select the subject and session for which to inspect outputs."""
        print(
            "> Selection of subject (and session) for which to inspect outputs"
        )
        valid_selected_subject = False
        select = True
        aborded = False

        while not valid_selected_subject and not aborded:

            # Select subject from BIDS dataset
            np_res = self.project_info.configure_traits(view="subject_view")

            if not np_res:
                aborded = True
                break

            print("  .. INFO: Selected subject: {}".format(
                self.project_info.subject))

            # Select session if any
            bids_layout = BIDSLayout(self.project_info.base_directory)
            subject = self.project_info.subject.split("-")[1]

            sessions = bids_layout.get(target="session",
                                       return_type="id",
                                       subject=subject)

            if len(sessions) > 0:
                print("  .. INFO: Input dataset has sessions")
                print(sessions)

                self.project_info.subject_sessions = []

                for ses in sessions:
                    self.project_info.subject_sessions.append("ses-" +
                                                              str(ses))

                np_res = self.project_info.configure_traits(
                    view="subject_session_view")

                if not np_res:
                    aborded = True
                    break

                self.project_info.anat_config_file = os.path.join(
                    self.project_info.base_directory,
                    "derivatives",
                    __cmp_directory__,
                    "{}".format(self.project_info.subject),
                    "{}".format(self.project_info.subject_session),
                    "{}_{}_anatomical_config.json".format(
                        self.project_info.subject,
                        self.project_info.subject_session),
                )
                if os.access(self.project_info.anat_config_file, os.F_OK):
                    print("> Initialize anatomical pipeline")
                    self.anat_pipeline = project.init_anat_project(
                        self.project_info, False)
                else:
                    self.anat_pipeline = None

                if self.dmri_inputs_checked:
                    self.project_info.dmri_config_file = os.path.join(
                        self.project_info.base_directory,
                        "derivatives",
                        __cmp_directory__,
                        "{}".format(self.project_info.subject),
                        "{}".format(self.project_info.subject_session),
                        "{}_{}_diffusion_config.json".format(
                            self.project_info.subject,
                            self.project_info.subject_session),
                    )
                    if os.access(self.project_info.dmri_config_file, os.F_OK):
                        print("> Initialize diffusion pipeline")
                        (
                            dmri_valid_inputs,
                            self.dmri_pipeline,
                        ) = project.init_dmri_project(self.project_info,
                                                      bids_layout, False)
                    else:
                        self.dmri_pipeline = None

                    # self.dmri_pipeline.subject = self.project_info.subject
                    # self.dmri_pipeline.global_conf.subject = self.project_info.subject

                if self.fmri_inputs_checked:
                    self.project_info.fmri_config_file = os.path.join(
                        self.project_info.base_directory,
                        "derivatives",
                        __cmp_directory__,
                        "{}".format(self.project_info.subject),
                        "{}".format(self.project_info.subject_session),
                        "{}_{}_fMRI_config.json".format(
                            self.project_info.subject,
                            self.project_info.subject_session),
                    )
                    if os.access(self.project_info.fmri_config_file, os.F_OK):
                        print("> Initialize fMRI pipeline")
                        (
                            fmri_valid_inputs,
                            self.fmri_pipeline,
                        ) = project.init_fmri_project(self.project_info,
                                                      bids_layout, False)
                    else:
                        self.fmri_pipeline = None

                    # self.fmri_pipeline.subject = self.project_info.subject
                    # self.fmri_pipeline.global_conf.subject = self.project_info.subject

                # self.anat_pipeline.global_conf.subject_session = self.project_info.subject_session

                # if self.dmri_pipeline is not None:
                #     self.dmri_pipeline.global_conf.subject_session = self.project_info.subject_session
                #
                # if self.fmri_pipeline is not None:
                #     self.fmri_pipeline.global_conf.subject_session = self.project_info.subject_session

                print("  .. INFO: Selected session %s" %
                      self.project_info.subject_session)
                if self.anat_pipeline is not None:
                    self.anat_pipeline.stages[
                        "Segmentation"].config.freesurfer_subject_id = os.path.join(
                            self.project_info.base_directory,
                            "derivatives",
                            __freesurfer_directory__,
                            "{}_{}".format(self.project_info.subject,
                                           self.project_info.subject_session),
                        )
            else:
                print("  .. INFO: No session detected")
                self.project_info.anat_config_file = os.path.join(
                    self.project_info.base_directory,
                    "derivatives",
                    __cmp_directory__,
                    "{}".format(self.project_info.subject),
                    "{}_anatomical_config.json".format(
                        self.project_info.subject),
                )
                if os.access(self.project_info.anat_config_file, os.F_OK):
                    self.anat_pipeline = project.init_anat_project(
                        self.project_info, False)
                else:
                    self.anat_pipeline = None

                if self.dmri_inputs_checked:
                    self.project_info.dmri_config_file = os.path.join(
                        self.project_info.base_directory,
                        "derivatives",
                        __cmp_directory__,
                        "{}".format(self.project_info.subject),
                        "{}_diffusion_config.json".format(
                            self.project_info.subject),
                    )
                    if os.access(self.project_info.dmri_config_file, os.F_OK):
                        (
                            dmri_valid_inputs,
                            self.dmri_pipeline,
                        ) = project.init_dmri_project(self.project_info,
                                                      bids_layout, False)
                    else:
                        self.dmri_pipeline = None

                    # self.dmri_pipeline.subject = self.project_info.subject
                    # self.dmri_pipeline.global_conf.subject = self.project_info.subject

                if self.fmri_inputs_checked:
                    self.project_info.fmri_config_file = os.path.join(
                        self.project_info.base_directory,
                        "derivatives",
                        __cmp_directory__,
                        "{}".format(self.project_info.subject),
                        "{}_fMRI_config.json".format(
                            self.project_info.subject),
                    )
                    if os.access(self.project_info.fmri_config_file, os.F_OK):
                        (
                            fmri_valid_inputs,
                            self.fmri_pipeline,
                        ) = project.init_fmri_project(self.project_info,
                                                      bids_layout, False)
                    else:
                        self.fmri_pipeline = None

                    # self.fmri_pipeline.subject = self.project_info.subject
                    # self.fmri_pipeline.global_conf.subject = self.project_info.subject

                # self.anat_pipeline.global_conf.subject_session = ''
                if self.anat_pipeline is not None:
                    self.anat_pipeline.stages[
                        "Segmentation"].config.freesurfer_subjects_dir = os.path.join(
                            self.project_info.base_directory,
                            "derivatives",
                            __freesurfer_directory__,
                            "{}".format(self.project_info.subject),
                        )

            if self.anat_pipeline is not None:
                print("> Anatomical pipeline output inspection")
                self.anat_pipeline.view_mode = "inspect_outputs_view"
                for stage in list(self.anat_pipeline.stages.values()):
                    print("  ... Inspect stage {}".format(stage))
                    stage.define_inspect_outputs()
                    # print('Stage {}: {}'.format(stage.stage_dir, stage.inspect_outputs))
                    if (len(stage.inspect_outputs) >
                            0) and (stage.inspect_outputs[0] !=
                                    "Outputs not available"):
                        self.output_anat_available = True

            if self.dmri_pipeline is not None:
                print("> Diffusion pipeline output inspection")
                self.dmri_pipeline.view_mode = "inspect_outputs_view"
                for stage in list(self.dmri_pipeline.stages.values()):
                    print("  ... Inspect stage {}".format(stage))
                    stage.define_inspect_outputs()
                    # print('Stage {}: {}'.format(stage.stage_dir, stage.inspect_outputs))
                    if (len(stage.inspect_outputs) >
                            0) and (stage.inspect_outputs[0] !=
                                    "Outputs not available"):
                        self.output_dmri_available = True

            if self.fmri_pipeline is not None:
                print("> fMRI pipeline output inspection")
                self.fmri_pipeline.view_mode = "inspect_outputs_view"
                for stage in list(self.fmri_pipeline.stages.values()):
                    print("  ... Inspect stage {}".format(stage))
                    stage.define_inspect_outputs()
                    # print('Stage {}: {}'.format(stage.stage_dir, stage.inspect_outputs))
                    if (len(stage.inspect_outputs) >
                            0) and (stage.inspect_outputs[0] !=
                                    "Outputs not available"):
                        self.output_fmri_available = True

            print_blue("  .. Anatomical output(s) available : %s" %
                       self.output_anat_available)
            print_blue("  .. Diffusion output(s) available : %s" %
                       self.output_dmri_available)
            print_blue("  .. fMRI output(s) available : %s" %
                       self.output_fmri_available)

            if (self.output_anat_available or self.output_dmri_available
                    or self.output_fmri_available):
                valid_selected_subject = True
            else:
                self.error_msg = (
                    "  .. ERROR: No output available! " +
                    "Please select another subject (and session if any)!")
                print_error(self.error_msg)
                select = error(message=self.error_msg,
                               title="Error",
                               buttons=["OK", "Cancel"])
                aborded = not select

        return aborded

    def update_diffusion_imaging_model(self, new):
        """Function called when ``diffusion_imaging_model`` is updated."""
        self.dmri_pipeline.diffusion_imaging_model = new
Beispiel #5
0
class DiffusionPipelineUI(DiffusionPipeline):
    """Class that extends the :class:`~cmp.pipelines.diffusion.diffusion.DiffusionPipeline` with graphical components.

    Attributes
    ----------
    preprocessing : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the preprocessing stage depending on the ``view_mode``

    registration : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the registration stage depending on the ``view_mode``

    diffusion : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the diffusion reconstruction and tractography stage depending 
        on the ``view_mode``

    connectome : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the connectome stage depending on the ``view_mode``

    view_mode : ['config_view', 'inspect_outputs_view']
        Variable used to control the display of either (1) the configuration
        or (2) the quality inspection of stage of the pipeline

    pipeline_group : traitsUI panel
        Panel defining the layout of the buttons of the stages with corresponding images

    traits_view : QtView
        QtView that includes the ``pipeline_group`` panel

    See also
    ---------
    cmp.pipelines.diffusion.diffusion.DiffusionPipeline
    """

    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    preprocessing = Button('Preprocessing')
    # preprocessing.setIcon(QIcon(QPixmap("preprocessing.png")))

    diffusion = Button('Diffusion')
    # diffusion.setIcon(QIcon(QPixmap("diffusion.png")))

    registration = Button('Registration')
    # registration.setIcon(QIcon(QPixmap("registration.png")))

    connectome = Button('Connectome')
    # connectome.setIcon(QIcon(QPixmap("connectome.png")))

    pipeline_group = VGroup(
        HGroup(spring,
               UItem('preprocessing',
                     style='custom',
                     width=222,
                     height=129,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('preprocessing').absolute_path)),
               spring,
               show_labels=False,
               label="",
               padding=0),
        HGroup(spring,
               UItem('registration',
                     style='custom',
                     width=222,
                     height=129,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('registration').absolute_path)),
               spring,
               show_labels=False,
               label="",
               padding=0),
        HGroup(spring,
               UItem('diffusion',
                     style='custom',
                     width=222,
                     height=244,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('diffusion').absolute_path)),
               spring,
               show_labels=False,
               label="",
               padding=0),
        HGroup(spring,
               UItem('connectome',
                     style='custom',
                     width=222,
                     height=129,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('connectome').absolute_path)),
               spring,
               show_labels=False,
               label="",
               padding=0),
        padding=0,
        # layout='split',
        # springy=True
    )

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):
        """Constructor of the DiffusionPipelineUI class.

        Parameters
        -----------
        project_info : cmp.project.CMP_Project_Info
            CMP_Project_Info object that stores general information
            such as the BIDS root and output directories (see
            :class_`cmp.project.CMP_Project_Info` for more details)

        See Also
        ---------
        cmp.pipelines.diffusion.DiffusionPipeline.__init__
        """
        DiffusionPipeline.__init__(self, project_info)

        self.stages = {
            'Preprocessing':
            PreprocessingStageUI(bids_dir=project_info.base_directory,
                                 output_dir=project_info.output_directory),
            'Registration':
            RegistrationStageUI(
                pipeline_mode="Diffusion",
                fs_subjects_dir=project_info.freesurfer_subjects_dir,
                fs_subject_id=os.path.basename(
                    project_info.freesurfer_subject_id),
                bids_dir=project_info.base_directory,
                output_dir=self.output_directory),
            'Diffusion':
            DiffusionStageUI(bids_dir=project_info.base_directory,
                             output_dir=project_info.output_directory),
            'Connectome':
            ConnectomeStageUI(bids_dir=project_info.base_directory,
                              output_dir=project_info.output_directory)
        }

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    project_info.subject_session, self.pipeline_name,
                    self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    self.pipeline_name, self.stages[stage].name)

    def _preprocessing_fired(self, info):
        """Method that displays the window for the preprocessing stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The preprocessing button object
        """
        self.stages['Preprocessing'].configure_traits(view=self.view_mode)

    def _diffusion_fired(self, info):
        """Method that displays the window for the diffusion stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The diffusion button object
        """
        self.stages['Diffusion'].configure_traits(view=self.view_mode)

    def _registration_fired(self, info):
        """Method that displays the window for the registration stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The registration button object
        """
        self.stages['Registration'].configure_traits(view=self.view_mode)

    def _connectome_fired(self, info):
        """Method that displays the window for the connectome stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The connectome button object
        """
        self.stages['Connectome'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        """Method that checks if inputs of the diffusion pipeline are available in the datasets.

        Parameters
        -----------
        layout : bids.BIDSLayout
            BIDSLayout object used to query

        gui : bool
            If True, display message in GUI

        Returns
        -------
        valid_inputs : bool
            True in all inputs of the anatomical pipeline are available
        """
        print('**** Check Inputs  ****')
        diffusion_available = False
        bvecs_available = False
        bvals_available = False
        valid_inputs = False

        if self.global_conf.subject_session == '':
            subject = self.subject
        else:
            subject = "_".join(
                (self.subject, self.global_conf.subject_session))

        dwi_file = os.path.join(self.subject_directory, 'dwi',
                                subject + '_dwi.nii.gz')
        bval_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bval')
        bvec_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bvec')

        subjid = self.subject.split("-")[1]

        try:
            layout = BIDSLayout(self.base_directory)
            print("Valid BIDS dataset with %s subjects" %
                  len(layout.get_subjects()))
            for subj in layout.get_subjects():
                self.global_conf.subjects.append('sub-' + str(subj))
            # self.global_conf.subjects = ['sub-'+str(subj) for subj in layout.get_subjects()]
            # self.global_conf.modalities = [
            #     str(mod) for mod in layout.get_modalities()]
            # mods = layout.get_modalities()
            types = layout.get_modalities()
            # print "Available modalities :"
            # for mod in mods:
            #     print "-%s" % mod

            if self.global_conf.subject_session == '':

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.nii.gz')
                if len(files) > 0:
                    dwi_file = os.path.join(files[0].dirname,
                                            files[0].filename)
                    print(dwi_file)
                else:
                    error(message="Diffusion image not found for subject %s." %
                          subjid,
                          title="Error",
                          buttons=['OK', 'Cancel'],
                          parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bval')
                if len(files) > 0:
                    bval_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bval_file)
                else:
                    error(
                        message="Diffusion bval image not found for subject %s."
                        % subjid,
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bvec')
                if len(files) > 0:
                    bvec_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bvec_file)
                else:
                    error(
                        message="Diffusion bvec image not found for subject %s."
                        % subjid,
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return
            else:
                sessid = self.global_conf.subject_session.split("-")[1]

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.nii.gz',
                                   session=sessid)
                if len(files) > 0:
                    dwi_file = os.path.join(files[0].dirname,
                                            files[0].filename)
                    print(dwi_file)
                else:
                    error(
                        message=
                        "Diffusion image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bval',
                                   session=sessid)
                if len(files) > 0:
                    bval_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bval_file)
                else:
                    error(
                        message=
                        "Diffusion bval image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bvec',
                                   session=sessid)
                if len(files) > 0:
                    bvec_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bvec_file)
                else:
                    error(
                        message=
                        "Diffusion bvec image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

            print("Looking for....")
            print("dwi_file : %s" % dwi_file)
            print("bvecs_file : %s" % bvec_file)
            print("bvals_file : %s" % bval_file)

            if os.path.isfile(dwi_file):
                print("DWI available")
                diffusion_available = True

        except Exception:
            error(
                message=
                "Invalid BIDS dataset. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)
            return

        if os.path.isfile(bval_file):
            bvals_available = True

        if os.path.isfile(bvec_file):
            bvecs_available = True

        if diffusion_available:
            if bvals_available and bvecs_available:
                self.stages[
                    'Diffusion'].config.diffusion_imaging_model_choices = self.diffusion_imaging_model

                # Copy diffusion data to derivatives / cmp  / subject / dwi
                if self.global_conf.subject_session == '':
                    out_dwi_file = os.path.join(self.derivatives_directory,
                                                'cmp', self.subject, 'dwi',
                                                subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bval')
                    out_bvec_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bvec')
                else:
                    out_dwi_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bval')
                    out_bvec_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bvec')

                if not os.path.isfile(out_dwi_file):
                    shutil.copy(src=dwi_file, dst=out_dwi_file)
                if not os.path.isfile(out_bvec_file):
                    shutil.copy(src=bvec_file, dst=out_bvec_file)
                if not os.path.isfile(out_bval_file):
                    shutil.copy(src=bval_file, dst=out_bval_file)

                valid_inputs = True
                input_message = 'Inputs check finished successfully.\nDiffusion and morphological data available.'
            else:
                input_message = 'Error during inputs check.\nDiffusion bvec or bval files not available.'
        else:
            if self.global_conf.subject_session == '':
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject, 'dwi') + '!'
            else:
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject,
                    self.global_conf.subject_session, 'dwi') + '!'

        if gui:
            # input_notification = Check_Input_Notification(message=input_message,
            #                                               diffusion_imaging_model_options=diffusion_imaging_model,
            #                                               diffusion_imaging_model=diffusion_imaging_model)
            # input_notification.configure_traits()
            print(input_message)
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model
        else:
            print(input_message)
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model

        if diffusion_available:
            valid_inputs = True
        else:
            print("Missing required inputs.")
            error(
                message=
                "Missing diffusion inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        # for stage in self.stages.values():
        #     if stage.enabled:
        #         print stage.name
        #         print stage.stage_dir

        # self.fill_stages_outputs()

        return valid_inputs
Beispiel #6
0
class fMRIPipelineUI(fMRIPipeline):
    """Class that extends the :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline` with graphical components.

    Attributes
    ----------
    preprocessing : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the preprocessing stage depending on the ``view_mode``

    registration : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the registration stage depending on the ``view_mode``

    functionalMRI : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the extra preprocessing stage stage depending on the ``view_mode``

    connectome : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the connectome stage depending on the ``view_mode``

    view_mode : ['config_view', 'inspect_outputs_view']
        Variable used to control the display of either (1) the configuration
        or (2) the quality inspection of stage of the pipeline

    pipeline_group : traitsUI panel
        Panel defining the layout of the buttons of the stages with corresponding images

    traits_view : QtView
        QtView that includes the ``pipeline_group`` panel

    See also
    ---------
    cmp.pipelines.functional.fMRI.fMRIPipeline
    """

    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    preprocessing = Button('Preprocessing')
    functionalMRI = Button('FunctionalMRI')
    registration = Button('Registration')
    connectome = Button('Connectome')

    pipeline_group = VGroup(
        HGroup(spring, UItem('preprocessing', style='custom', width=222, height=129, resizable=False,
                             style_sheet=return_button_style_sheet(ImageResource('preprocessing').absolute_path)), spring,
               show_labels=False, label=""),
        HGroup(spring, UItem('registration', style='custom', width=222, height=129, resizable=False,
                             style_sheet=return_button_style_sheet(ImageResource('registration').absolute_path)), spring,
               show_labels=False, label=""),
        HGroup(spring, UItem('functionalMRI', style='custom', width=222, height=168, resizable=False,
                             style_sheet=return_button_style_sheet(ImageResource('functionalMRI').absolute_path)), spring,
               show_labels=False, label=""),
        HGroup(spring, UItem('connectome', style='custom', width=222, height=129, resizable=False,
                             style_sheet=return_button_style_sheet(ImageResource('connectome').absolute_path)), spring,
               show_labels=False, label=""),
        spring,
        springy=True
    )

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):
        """Constructor of the fMRIPipelineUI class.

        Parameters
        -----------
        project_info : cmp.project.CMP_Project_Info
            CMP_Project_Info object that stores general information
            such as the BIDS root and output directories (see
            :class_`cmp.project.CMP_Project_Info` for more details)

        See also
        ---------
        cmp.pipelines.functional.fMRIPipeline.__init__
        """
        fMRIPipeline.__init__(self, project_info)

        self.stages = {'Preprocessing': PreprocessingStageUI(bids_dir=project_info.base_directory,
                                                             output_dir=project_info.output_directory),
                       'Registration': RegistrationStageUI(pipeline_mode="fMRI",
                                                           fs_subjects_dir=project_info.freesurfer_subjects_dir,
                                                           fs_subject_id=os.path.basename(project_info.freesurfer_subject_id),
                                                           bids_dir=project_info.base_directory,
                                                           output_dir=self.output_directory),
                       'FunctionalMRI': FunctionalMRIStageUI(bids_dir=project_info.base_directory,
                                                             output_dir=project_info.output_directory),
                       'Connectome': ConnectomeStageUI(bids_dir=project_info.base_directory,
                                                       output_dir=project_info.output_directory)
                       }

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(self.base_directory, "derivatives", 'nipype', self.subject,
                                                            project_info.subject_session, self.pipeline_name,
                                                            self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(self.base_directory, "derivatives", 'nipype', self.subject,
                                                            self.pipeline_name, self.stages[stage].name)

    def _preprocessing_fired(self, info):
        """Method that displays the window for the preprocessing stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The preprocessing button object
        """
        self.stages['Preprocessing'].configure_traits(view=self.view_mode)

    def _functionalMRI_fired(self, info):
        """Method that displays the window for the extra preprocessing stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The extra preprocessing button object
        """
        self.stages['FunctionalMRI'].configure_traits(view=self.view_mode)

    def _registration_fired(self, info):
        """Method that displays the window for the registration stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The registration button object
        """
        if self.view_mode == 'config_view':
            self.stages['Registration'].configure_traits(
                view='config_view_fmri')
        else:
            self.stages['Registration'].configure_traits(view=self.view_mode)

    def _connectome_fired(self, info):
        """Method that displays the window for the connectome stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The connectome button object
        """
        self.stages['Connectome'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        """Method that checks if inputs of the fMRI pipeline are available in the datasets.

        Parameters
        -----------
        layout : bids.BIDSLayout
            BIDSLayout object used to query

        gui : bool
            If True, display message in GUI

        Returns
        -------
        valid_inputs : bool
            True in all inputs of the fMRI pipeline are available
        """
        print('**** Check Inputs ****')
        fMRI_available = False
        fMRI_json_available = False
        t1_available = False
        t2_available = False
        valid_inputs = False

        if self.global_conf.subject_session == '':
            subject = self.subject
        else:
            subject = "_".join(
                (self.subject, self.global_conf.subject_session))

        fmri_file = os.path.join(
            self.subject_directory, 'func', subject + '_task-rest_bold.nii.gz')
        json_file = os.path.join(
            self.subject_directory, 'func', subject + '_task-rest_bold.json')
        t1_file = os.path.join(self.subject_directory,
                               'anat', subject + '_T1w.nii.gz')
        t2_file = os.path.join(self.subject_directory,
                               'anat', subject + '_T2w.nii.gz')

        subjid = self.subject.split("-")[1]

        print("Looking for....")

        if self.global_conf.subject_session == '':

            files = layout.get(subject=subjid, suffix='bold',
                               extensions='.nii.gz')
            if len(files) > 0:
                fmri_file = os.path.join(files[0].dirname, files[0].filename)
                print(fmri_file)
            else:
                error(message="BOLD image not found for subject %s." % subjid, title="Error",
                      buttons=['OK', 'Cancel'], parent=None)
                return

            files = layout.get(
                subject=subjid, suffix='bold', extensions='.json')
            if len(files) > 0:
                json_file = os.path.join(files[0].dirname, files[0].filename)
                print(json_file)
            else:
                error(message="BOLD json sidecar not found for subject %s." % subjid, title="Warning",
                      buttons=['OK', 'Cancel'], parent=None)

            files = layout.get(subject=subjid, suffix='T1w',
                               extensions='.nii.gz')
            if len(files) > 0:
                t1_file = os.path.join(files[0].dirname, files[0].filename)
                print(t1_file)
            else:
                error(message="T1w image not found for subject %s." % subjid, title="Error", buttons=['OK', 'Cancel'],
                      parent=None)
                return

            files = layout.get(subject=subjid, suffix='T2w',
                               extensions='.nii.gz')
            if len(files) > 0:
                t2_file = os.path.join(files[0].dirname, files[0].filename)
                print(t2_file)
            else:
                error(message="T2w image not found for subject %s." % subjid, title="Warning",
                      buttons=['OK', 'Cancel'], parent=None)

        else:
            sessid = self.global_conf.subject_session.split("-")[1]

            files = layout.get(subject=subjid, suffix='bold',
                               extensions='.nii.gz', session=sessid)
            if len(files) > 0:
                fmri_file = os.path.join(files[0].dirname, files[0].filename)
                print(fmri_file)
            else:
                error(message="BOLD image not found for subject %s, session %s." % (
                    subjid, self.global_conf.subject_session), title="Error", buttons=['OK', 'Cancel'], parent=None)
                return

            files = layout.get(subject=subjid, suffix='bold',
                               extensions='.json', session=sessid)
            if len(files) > 0:
                json_file = os.path.join(files[0].dirname, files[0].filename)
                print(json_file)
            else:
                error(message="BOLD json sidecar not found for subject %s, session %s." % (
                    subjid, self.global_conf.subject_session), title="Warning", buttons=['OK', 'Cancel'], parent=None)

            files = layout.get(subject=subjid, suffix='T1w',
                               extensions='.nii.gz', session=sessid)
            if len(files) > 0:
                t1_file = os.path.join(files[0].dirname, files[0].filename)
                print(t1_file)
            else:
                error(message="T1w image not found for subject %s, session %s." % (
                    subjid, self.global_conf.subject_session), title="Error", buttons=['OK', 'Cancel'], parent=None)
                return

            files = layout.get(subject=subjid, suffix='T2w',
                               extensions='.nii.gz', session=sessid)
            if len(files) > 0:
                t2_file = os.path.join(files[0].dirname, files[0].filename)
                print(t2_file)
            else:
                error(message="T2w image not found for subject %s, session %s." % (
                    subjid, self.global_conf.subject_session), title="Warning", buttons=['OK', 'Cancel'], parent=None)

        print("fmri_file : %s" % fmri_file)
        print("json_file : %s" % json_file)
        print("t1_file : %s" % t1_file)
        print("t2_file : %s" % t2_file)

        if os.path.isfile(t1_file):
            # print("%s available" % typ)
            t1_available = True
        if os.path.isfile(t2_file):
            # print("%s available" % typ)
            t2_available = True
        if os.path.isfile(fmri_file):
            # print("%s available" % typ)
            fMRI_available = True
        if os.path.isfile(json_file):
            # print("%s available" % typ)
            fMRI_json_available = True

        if fMRI_available:
            if self.global_conf.subject_session == '':
                out_dir = os.path.join(
                    self.output_directory, 'cmp', self.subject)
            else:
                out_dir = os.path.join(
                    self.output_directory, 'cmp', self.subject, self.global_conf.subject_session)

            out_fmri_file = os.path.join(
                out_dir, 'func', subject + '_task-rest_desc-cmp_bold.nii.gz')
            shutil.copy(src=fmri_file, dst=out_fmri_file)

            valid_inputs = True
            input_message = 'Inputs check finished successfully.\nfMRI data available.'

            if t2_available:
                out_t2_file = os.path.join(
                    out_dir, 'anat', subject + '_T2w.nii.gz')
                shutil.copy(src=t2_file, dst=out_t2_file)
                # swap_and_reorient(src_file=os.path.join(self.base_directory,'NIFTI','T2_orig.nii.gz'),
                #                   ref_file=os.path.join(self.base_directory,'NIFTI','fMRI.nii.gz'),
                #                   out_file=os.path.join(self.base_directory,'NIFTI','T2.nii.gz'))

            if fMRI_json_available:
                out_json_file = os.path.join(
                    out_dir, 'func', subject + '_task-rest_desc-cmp_bold.json')
                shutil.copy(src=json_file, dst=out_json_file)

        else:
            input_message = 'Error during inputs check. \nfMRI data not available (fMRI).'

        print(input_message)

        # if gui:
        #     # input_notification = Check_Input_Notification(message=input_message, imaging_model='fMRI')
        #     # input_notification.configure_traits()
        #     self.global_conf.imaging_model = input_notification.imaging_model
        #     self.stages['Registration'].config.imaging_model = input_notification.imaging_model
        # else:
        #     self.global_conf.imaging_model = 'fMRI'
        #     self.stages['Registration'].config.imaging_model = 'fMRI'

        self.global_conf.imaging_model = 'fMRI'
        self.stages['Registration'].config.imaging_model = 'fMRI'

        if t2_available:
            self.stages['Registration'].config.registration_mode_trait = [
                'FSL (Linear)', 'BBregister (FS)']
        else:
            self.stages['Registration'].config.registration_mode_trait = [
                'FSL (Linear)']

        # self.fill_stages_outputs()

        return valid_inputs
class MainWindow(HasTraits):
    """Class that defines the Main window of the Connectome Mapper 3 GUI.

    Attributes
    ----------
    project_info : cmp.bidsappmanager.project.ProjectInfoUI
        Instance of :class:`CMP_Project_InfoUI` that represents the processing project

    anat_pipeline : Instance(HasTraits)
        Instance of anatomical MRI pipeline UI

    dmri_pipeline : Instance(HasTraits)
        Instance of diffusion MRI pipeline UI

    fmri_pipeline : Instance(HasTraits)
        Instance of functional MRI pipeline UI

    configurator_ui : `PipelineConfiguratorWindow`
        Instance of :class:`PipelineConfiguratorWindow`

    bidsapp_ui : `BIDSAppInterfaceWindow`
        Instance of :class:`BIDSAppInterfaceWindow`

    quality_control_ui : `QualityInspectorWindow`
        Instance of :class:`QualityInspectorWindow`

    load_dataset : traits.ui.Action
        TraitsUI Action to load a BIDS dataset

    bidsapp : traits.ui.Button
        Button that displays the BIDS App Interface window

    configurator : traits.ui.Button
        Button thats displays the pipeline Configurator window

    quality_control : traits.ui.Button
        Button that displays the pipeline Quality Control / Inspector window

    manager_group : traits.ui.View
        TraitsUI View that describes the content of the main window

    traits_view : QtView
        TraitsUI QtView that includes ``manager_group`` and parameterize
        the window with menu
    """
    project_info = Instance(cmp.project.ProjectInfo)

    anat_pipeline = Instance(HasTraits)
    dmri_pipeline = Instance(HasTraits)
    fmri_pipeline = Instance(HasTraits)

    configurator_ui = Instance(
        cmp.bidsappmanager.gui.config.PipelineConfiguratorWindow)
    bidsapp_ui = Instance(
        cmp.bidsappmanager.gui.bidsapp.BIDSAppInterfaceWindow)
    quality_control_ui = Instance(
        cmp.bidsappmanager.gui.qc.QualityInspectorWindow)

    load_dataset = Action(name="Load BIDS Dataset...", action="load_dataset")

    project_info.style_sheet = style_sheet

    configurator = Button("")
    bidsapp = Button("")
    quality_control = Button("")

    view_mode = 1

    manager_group = VGroup(
        spring,
        HGroup(
            spring,
            HGroup(
                Item(
                    "configurator",
                    style="custom",
                    width=200,
                    height=200,
                    resizable=False,
                    label="",
                    show_label=False,
                    style_sheet=return_button_style_sheet(
                        ImageResource(
                            pkg_resources.resource_filename(
                                "cmp",
                                os.path.join("bidsappmanager/images",
                                             "configurator_200x200.png"),
                            )).absolute_path),
                ),
                show_labels=False,
                label="",
            ),
            spring,
            HGroup(
                Item(
                    "bidsapp",
                    style="custom",
                    width=200,
                    height=200,
                    resizable=False,
                    style_sheet=return_button_style_sheet(
                        ImageResource(
                            pkg_resources.resource_filename(
                                "cmp",
                                os.path.join("bidsappmanager/images",
                                             "bidsapp_200x200.png"),
                            )).absolute_path),
                ),
                show_labels=False,
                label="",
            ),
            spring,
            HGroup(
                Item(
                    "quality_control",
                    style="custom",
                    width=200,
                    height=200,
                    resizable=False,
                    style_sheet=return_button_style_sheet(
                        ImageResource(
                            pkg_resources.resource_filename(
                                "cmp",
                                os.path.join(
                                    "bidsappmanager/images",
                                    "qualitycontrol_200x200.png",
                                ),
                            )).absolute_path),
                ),
                show_labels=False,
                label="",
            ),
            spring,
            springy=True,
            visible_when="handler.project_loaded==True",
        ),
        spring,
        springy=True,
    )

    traits_view = QtView(
        HGroup(Include("manager_group"), ),
        title="Connectome Mapper {} - BIDS App Manager".format(__version__),
        menubar=MenuBar(
            Menu(
                ActionGroup(load_dataset, ),
                ActionGroup(Action(name="Quit", action="_on_close"), ),
                name="File",
            ), ),
        handler=cmp.bidsappmanager.gui.handlers.MainWindowHandler(),
        style_sheet=style_sheet,
        width=0.5,
        height=0.8,
        resizable=True,  # , scrollable=True , resizable=True
        # icon=get_icon("cmp.png")
    )

    def _bidsapp_fired(self):
        """ Callback of the "bidsapp" button. This displays the BIDS App Interface window."""
        print_blue("[Open BIDS App Window]")
        bids_layout = BIDSLayout(self.project_info.base_directory)
        subjects = bids_layout.get_subjects()

        anat_config = os.path.join(self.project_info.base_directory, "code/",
                                   "ref_anatomical_config.json")
        dmri_config = os.path.join(self.project_info.base_directory, "code/",
                                   "ref_diffusion_config.json")
        fmri_config = os.path.join(self.project_info.base_directory, "code/",
                                   "ref_fMRI_config.json")

        self.bidsapp_ui = cmp.bidsappmanager.gui.bidsapp.BIDSAppInterfaceWindow(
            project_info=self.project_info,
            bids_root=self.project_info.base_directory,
            subjects=sorted(subjects),
            anat_config=anat_config,
            dmri_config=dmri_config,
            fmri_config=fmri_config,
        )
        self.bidsapp_ui.configure_traits()

    def _configurator_fired(self):
        """Callback of the "configurator" button. This displays the Configurator Window."""
        print_blue("[Open Pipeline Configurator Window]")
        if self.project_info.t1_available:
            if os.path.isfile(self.project_info.anat_config_file):
                print("  .. Anatomical config file : %s" %
                      self.project_info.anat_config_file)

        if self.project_info.dmri_available:
            if os.path.isfile(self.project_info.dmri_config_file):
                print("  .. Diffusion config file : %s" %
                      self.project_info.dmri_config_file)

        if self.project_info.fmri_available:
            if os.path.isfile(self.project_info.fmri_config_file):
                print("  .. fMRI config file : %s" %
                      self.project_info.fmri_config_file)

        self.configurator_ui = cmp.bidsappmanager.gui.config.PipelineConfiguratorWindow(
            project_info=self.project_info,
            anat_pipeline=self.anat_pipeline,
            dmri_pipeline=self.dmri_pipeline,
            fmri_pipeline=self.fmri_pipeline,
            anat_inputs_checked=self.project_info.t1_available,
            dmri_inputs_checked=self.project_info.dmri_available,
            fmri_inputs_checked=self.project_info.fmri_available,
        )

        self.configurator_ui.configure_traits()

    def _quality_control_fired(self):
        """Callback of the "Inspector" button. This displays the Quality Control (Inspector) Window."""
        print_blue("[Open Quality Inspector Window]")
        if self.project_info.t1_available:
            if os.path.isfile(self.project_info.anat_config_file):
                print("  .. Anatomical config file : %s" %
                      self.project_info.anat_config_file)

        if self.project_info.dmri_available:
            if os.path.isfile(self.project_info.dmri_config_file):
                print("  .. Diffusion config file : %s" %
                      self.project_info.dmri_config_file)

        if self.project_info.fmri_available:
            if os.path.isfile(self.project_info.fmri_config_file):
                print("  .. fMRI config file : %s" %
                      self.project_info.fmri_config_file)

        try:
            self.quality_control_ui = cmp.bidsappmanager.gui.qc.QualityInspectorWindow(
                project_info=self.project_info,
                anat_inputs_checked=self.project_info.t1_available,
                dmri_inputs_checked=self.project_info.dmri_available,
                fmri_inputs_checked=self.project_info.fmri_available,
            )
            self.quality_control_ui.configure_traits()
        except Exception as e:
            print(e)
Beispiel #8
0
class fMRIPipelineUI(fMRIPipeline):
    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    preprocessing = Button('Preprocessing')
    functionalMRI = Button('FunctionalMRI')
    registration = Button('Registration')
    connectome = Button('Connectome')

    pipeline_group = VGroup(HGroup(spring,
                                   UItem('preprocessing',
                                         style='custom',
                                         width=450,
                                         height=130,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('preprocessing'),
                                             'label':
                                             ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('registration',
                                         style='custom',
                                         width=500,
                                         height=110,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('registration'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('functionalMRI',
                                         style='custom',
                                         width=450,
                                         height=240,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('functionalMRI'),
                                             'label':
                                             ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('connectome',
                                         style='custom',
                                         width=450,
                                         height=130,
                                         resizable=True,
                                         editor_args={
                                             'image':
                                             ImageResource('connectome'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            spring,
                            springy=True)

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):

        fMRIPipeline.__init__(self, project_info)

        self.stages = {
            'Preprocessing':
            PreprocessingStageUI(bids_dir=project_info.base_directory,
                                 output_dir=project_info.output_directory),
            'Registration':
            RegistrationStageUI(
                pipeline_mode="fMRI",
                fs_subjects_dir=project_info.freesurfer_subjects_dir,
                fs_subject_id=os.path.basename(
                    project_info.freesurfer_subject_id),
                bids_dir=project_info.base_directory,
                output_dir=self.output_directory),
            'FunctionalMRI':
            FunctionalMRIStageUI(bids_dir=project_info.base_directory,
                                 output_dir=project_info.output_directory),
            'Connectome':
            ConnectomeStageUI(bids_dir=project_info.base_directory,
                              output_dir=project_info.output_directory)
        }

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    project_info.subject_session, self.pipeline_name,
                    self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    self.pipeline_name, self.stages[stage].name)

    def _preprocessing_fired(self, info):
        # print("preproc fired")
        self.stages['Preprocessing'].configure_traits(view=self.view_mode)

    def _functionalMRI_fired(self, info):
        # print("func fired")
        self.stages['FunctionalMRI'].configure_traits(view=self.view_mode)

    def _registration_fired(self, info):
        if self.view_mode == 'config_view':
            self.stages['Registration'].configure_traits(
                view='config_view_fmri')
        else:
            self.stages['Registration'].configure_traits(view=self.view_mode)

    def _connectome_fired(self, info):
        self.stages['Connectome'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        print('**** Check Inputs ****')
        fMRI_available = False
        fMRI_json_available = False
        t1_available = False
        t2_available = False
        valid_inputs = False

        if self.global_conf.subject_session == '':
            subject = self.subject
        else:
            subject = "_".join(
                (self.subject, self.global_conf.subject_session))

        fmri_file = os.path.join(self.subject_directory, 'func',
                                 subject + '_task-rest_bold.nii.gz')
        json_file = os.path.join(self.subject_directory, 'func',
                                 subject + '_task-rest_bold.json')
        t1_file = os.path.join(self.subject_directory, 'anat',
                               subject + '_T1w.nii.gz')
        t2_file = os.path.join(self.subject_directory, 'anat',
                               subject + '_T2w.nii.gz')

        subjid = self.subject.split("-")[1]

        print("Looking for....")

        if self.global_conf.subject_session == '':

            files = layout.get(subject=subjid,
                               suffix='bold',
                               extensions='.nii.gz')
            if len(files) > 0:
                fmri_file = os.path.join(files[0].dirname, files[0].filename)
                print(fmri_file)
            else:
                error(message="BOLD image not found for subject %s." %
                      (subjid),
                      title="Error",
                      buttons=['OK', 'Cancel'],
                      parent=None)
                return

            files = layout.get(subject=subjid,
                               suffix='bold',
                               extensions='.json')
            if len(files) > 0:
                json_file = os.path.join(files[0].dirname, files[0].filename)
                print(json_file)
            else:
                error(message="BOLD json sidecar not found for subject %s." %
                      (subjid),
                      title="Warning",
                      buttons=['OK', 'Cancel'],
                      parent=None)

            files = layout.get(subject=subjid,
                               suffix='T1w',
                               extensions='.nii.gz')
            if len(files) > 0:
                t1_file = os.path.join(files[0].dirname, files[0].filename)
                print(t1_file)
            else:
                error(message="T1w image not found for subject %s." % (subjid),
                      title="Error",
                      buttons=['OK', 'Cancel'],
                      parent=None)
                return

            files = layout.get(subject=subjid,
                               suffix='T2w',
                               extensions='.nii.gz')
            if len(files) > 0:
                t2_file = os.path.join(files[0].dirname, files[0].filename)
                print(t2_file)
            else:
                error(message="T2w image not found for subject %s." % (subjid),
                      title="Warning",
                      buttons=['OK', 'Cancel'],
                      parent=None)

        else:
            sessid = self.global_conf.subject_session.split("-")[1]

            files = layout.get(subject=subjid,
                               suffix='bold',
                               extensions='.nii.gz',
                               session=sessid)
            if len(files) > 0:
                fmri_file = os.path.join(files[0].dirname, files[0].filename)
                print(fmri_file)
            else:
                error(
                    message="BOLD image not found for subject %s, session %s."
                    % (subjid, self.global_conf.subject_session),
                    title="Error",
                    buttons=['OK', 'Cancel'],
                    parent=None)
                return

            files = layout.get(subject=subjid,
                               suffix='bold',
                               extensions='.json',
                               session=sessid)
            if len(files) > 0:
                json_file = os.path.join(files[0].dirname, files[0].filename)
                print(json_file)
            else:
                error(
                    message=
                    "BOLD json sidecar not found for subject %s, session %s." %
                    (subjid, self.global_conf.subject_session),
                    title="Warning",
                    buttons=['OK', 'Cancel'],
                    parent=None)

            files = layout.get(subject=subjid,
                               suffix='T1w',
                               extensions='.nii.gz',
                               session=sessid)
            if len(files) > 0:
                t1_file = os.path.join(files[0].dirname, files[0].filename)
                print(t1_file)
            else:
                error(
                    message="T1w image not found for subject %s, session %s." %
                    (subjid, self.global_conf.subject_session),
                    title="Error",
                    buttons=['OK', 'Cancel'],
                    parent=None)
                return

            files = layout.get(subject=subjid,
                               suffix='T2w',
                               extensions='.nii.gz',
                               session=sessid)
            if len(files) > 0:
                t2_file = os.path.join(files[0].dirname, files[0].filename)
                print(t2_file)
            else:
                error(
                    message="T2w image not found for subject %s, session %s." %
                    (subjid, self.global_conf.subject_session),
                    title="Warning",
                    buttons=['OK', 'Cancel'],
                    parent=None)

        print("fmri_file : %s" % fmri_file)
        print("json_file : %s" % json_file)
        print("t1_file : %s" % t1_file)
        print("t2_file : %s" % t2_file)

        if os.path.isfile(t1_file):
            # print("%s available" % typ)
            t1_available = True
        if os.path.isfile(t2_file):
            # print("%s available" % typ)
            t2_available = True
        if os.path.isfile(fmri_file):
            # print("%s available" % typ)
            fMRI_available = True
        if os.path.isfile(json_file):
            # print("%s available" % typ)
            fMRI_json_available = True

        # print('fMRI :',fMRI_available)
        # print('t1 :',t1_available)
        # print('t2 :',t2_available)

        if fMRI_available:
            if self.global_conf.subject_session == '':
                out_dir = os.path.join(self.output_directory, 'cmp',
                                       self.subject)
            else:
                out_dir = os.path.join(self.output_directory, 'cmp',
                                       self.subject,
                                       self.global_conf.subject_session)

            out_fmri_file = os.path.join(
                out_dir, 'func', subject + '_task-rest_desc-cmp_bold.nii.gz')
            shutil.copy(src=fmri_file, dst=out_fmri_file)

            valid_inputs = True
            input_message = 'Inputs check finished successfully.\nfMRI data available.'

            if t2_available:
                out_t2_file = os.path.join(out_dir, 'anat',
                                           subject + '_T2w.nii.gz')
                shutil.copy(src=t2_file, dst=out_t2_file)
                # swap_and_reorient(src_file=os.path.join(self.base_directory,'NIFTI','T2_orig.nii.gz'),
                #                   ref_file=os.path.join(self.base_directory,'NIFTI','fMRI.nii.gz'),
                #                   out_file=os.path.join(self.base_directory,'NIFTI','T2.nii.gz'))

            if fMRI_json_available:
                out_json_file = os.path.join(
                    out_dir, 'func', subject + '_task-rest_desc-cmp_bold.json')
                shutil.copy(src=json_file, dst=out_json_file)

        else:
            input_message = 'Error during inputs check. \nfMRI data not available (fMRI).'

        print(input_message)

        # if gui:
        #     # input_notification = Check_Input_Notification(message=input_message, imaging_model='fMRI')
        #     # input_notification.configure_traits()
        #     self.global_conf.imaging_model = input_notification.imaging_model
        #     self.stages['Registration'].config.imaging_model = input_notification.imaging_model
        # else:
        #     self.global_conf.imaging_model = 'fMRI'
        #     self.stages['Registration'].config.imaging_model = 'fMRI'

        self.global_conf.imaging_model = 'fMRI'
        self.stages['Registration'].config.imaging_model = 'fMRI'

        if t2_available:
            self.stages['Registration'].config.registration_mode_trait = [
                'FSL (Linear)', 'BBregister (FS)'
            ]
        else:
            self.stages['Registration'].config.registration_mode_trait = [
                'FSL (Linear)'
            ]

        # self.fill_stages_outputs()

        return valid_inputs
Beispiel #9
0
class DiffusionPipelineUI(DiffusionPipeline):
    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    preprocessing = Button('Preprocessing')
    # preprocessing.setIcon(QIcon(QPixmap("preprocessing.png")))

    diffusion = Button('Diffusion')
    # diffusion.setIcon(QIcon(QPixmap("diffusion.png")))

    registration = Button('Registration')
    # registration.setIcon(QIcon(QPixmap("registration.png")))

    connectome = Button('Connectome')
    # connectome.setIcon(QIcon(QPixmap("connectome.png")))

    pipeline_group = VGroup(HGroup(spring,
                                   UItem('preprocessing',
                                         style='custom',
                                         width=444,
                                         height=196,
                                         editor_args={
                                             'image':
                                             ImageResource('preprocessing'),
                                             'label':
                                             ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('registration',
                                         style='custom',
                                         width=444,
                                         height=196,
                                         editor_args={
                                             'image':
                                             ImageResource('registration'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('diffusion',
                                         style='custom',
                                         width=460,
                                         height=374,
                                         editor_args={
                                             'image':
                                             ImageResource('diffusion'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            HGroup(spring,
                                   UItem('connectome',
                                         style='custom',
                                         width=444,
                                         height=184,
                                         editor_args={
                                             'image':
                                             ImageResource('connectome'),
                                             'label': ""
                                         }),
                                   spring,
                                   show_labels=False,
                                   label=""),
                            springy=True)

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):

        DiffusionPipeline.__init__(self, project_info)

        self.stages = {
            'Preprocessing':
            PreprocessingStageUI(bids_dir=project_info.base_directory,
                                 output_dir=project_info.output_directory),
            'Registration':
            RegistrationStageUI(
                pipeline_mode="Diffusion",
                fs_subjects_dir=project_info.freesurfer_subjects_dir,
                fs_subject_id=os.path.basename(
                    project_info.freesurfer_subject_id),
                bids_dir=project_info.base_directory,
                output_dir=self.output_directory),
            'Diffusion':
            DiffusionStageUI(bids_dir=project_info.base_directory,
                             output_dir=project_info.output_directory),
            'Connectome':
            ConnectomeStageUI(bids_dir=project_info.base_directory,
                              output_dir=project_info.output_directory)
        }

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    project_info.subject_session, self.pipeline_name,
                    self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    self.pipeline_name, self.stages[stage].name)

    def _preprocessing_fired(self, info):
        self.stages['Preprocessing'].configure_traits(view=self.view_mode)

    def _diffusion_fired(self, info):
        self.stages['Diffusion'].configure_traits(view=self.view_mode)

    def _registration_fired(self, info):
        self.stages['Registration'].configure_traits(view=self.view_mode)

    def _connectome_fired(self, info):
        # self.stages['MRTrixConnectome'].configure_traits()
        self.stages['Connectome'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        print('**** Check Inputs  ****')
        diffusion_available = False
        bvecs_available = False
        bvals_available = False
        valid_inputs = False

        if self.global_conf.subject_session == '':
            subject = self.subject
        else:
            subject = "_".join(
                (self.subject, self.global_conf.subject_session))

        dwi_file = os.path.join(self.subject_directory, 'dwi',
                                subject + '_dwi.nii.gz')
        bval_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bval')
        bvec_file = os.path.join(self.subject_directory, 'dwi',
                                 subject + '_dwi.bvec')

        subjid = self.subject.split("-")[1]

        try:
            layout = BIDSLayout(self.base_directory)
            print("Valid BIDS dataset with %s subjects" %
                  len(layout.get_subjects()))
            for subj in layout.get_subjects():
                self.global_conf.subjects.append('sub-' + str(subj))
            # self.global_conf.subjects = ['sub-'+str(subj) for subj in layout.get_subjects()]
            self.global_conf.modalities = [
                str(mod) for mod in layout.get_modalities()
            ]
            # mods = layout.get_modalities()
            types = layout.get_modalities()
            # print "Available modalities :"
            # for mod in mods:
            #     print "-%s" % mod

            if self.global_conf.subject_session == '':

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.nii.gz')
                if len(files) > 0:
                    dwi_file = os.path.join(files[0].dirname,
                                            files[0].filename)
                    print(dwi_file)
                else:
                    error(message="Diffusion image not found for subject %s." %
                          (subjid),
                          title="Error",
                          buttons=['OK', 'Cancel'],
                          parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bval')
                if len(files) > 0:
                    bval_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bval_file)
                else:
                    error(
                        message="Diffusion bval image not found for subject %s."
                        % (subjid),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bvec')
                if len(files) > 0:
                    bvec_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bvec_file)
                else:
                    error(
                        message="Diffusion bvec image not found for subject %s."
                        % (subjid),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return
            else:
                sessid = self.global_conf.subject_session.split("-")[1]

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.nii.gz',
                                   session=sessid)
                if len(files) > 0:
                    dwi_file = os.path.join(files[0].dirname,
                                            files[0].filename)
                    print(dwi_file)
                else:
                    error(
                        message=
                        "Diffusion image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bval',
                                   session=sessid)
                if len(files) > 0:
                    bval_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bval_file)
                else:
                    error(
                        message=
                        "Diffusion bval image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

                files = layout.get(subject=subjid,
                                   suffix='dwi',
                                   extensions='.bvec',
                                   session=sessid)
                if len(files) > 0:
                    bvec_file = os.path.join(files[0].dirname,
                                             files[0].filename)
                    print(bvec_file)
                else:
                    error(
                        message=
                        "Diffusion bvec image not found for subject %s, session %s."
                        % (subjid, self.global_conf.subject_session),
                        title="Error",
                        buttons=['OK', 'Cancel'],
                        parent=None)
                    return

            print("Looking for....")
            print("dwi_file : %s" % dwi_file)
            print("bvecs_file : %s" % bvec_file)
            print("bvals_file : %s" % bval_file)

            if os.path.isfile(dwi_file):
                print("DWI available")
                diffusion_available = True

        except Exception:
            error(
                message=
                "Invalid BIDS dataset. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)
            return

        if os.path.isfile(bval_file):
            bvals_available = True

        if os.path.isfile(bvec_file):
            bvecs_available = True

        if diffusion_available:
            if bvals_available and bvecs_available:
                self.stages[
                    'Diffusion'].config.diffusion_imaging_model_choices = self.diffusion_imaging_model

                # Copy diffusion data to derivatives / cmp  / subject / dwi
                if self.global_conf.subject_session == '':
                    out_dwi_file = os.path.join(self.derivatives_directory,
                                                'cmp', self.subject, 'dwi',
                                                subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bval')
                    out_bvec_file = os.path.join(self.derivatives_directory,
                                                 'cmp', self.subject, 'dwi',
                                                 subject + '_dwi.bvec')
                else:
                    out_dwi_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.nii.gz')
                    out_bval_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bval')
                    out_bvec_file = os.path.join(
                        self.derivatives_directory, 'cmp', self.subject,
                        self.global_conf.subject_session, 'dwi',
                        subject + '_dwi.bvec')

                if not os.path.isfile(out_dwi_file):
                    shutil.copy(src=dwi_file, dst=out_dwi_file)
                if not os.path.isfile(out_bvec_file):
                    shutil.copy(src=bvec_file, dst=out_bvec_file)
                if not os.path.isfile(out_bval_file):
                    shutil.copy(src=bval_file, dst=out_bval_file)

                valid_inputs = True
                input_message = 'Inputs check finished successfully.\nDiffusion and morphological data available.'
            else:
                input_message = 'Error during inputs check.\nDiffusion bvec or bval files not available.'
        else:
            if self.global_conf.subject_session == '':
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject, 'dwi') + '!'
            else:
                input_message = 'Error during inputs check. No diffusion data available in folder ' + os.path.join(
                    self.base_directory, self.subject,
                    self.global_conf.subject_session, 'dwi') + '!'
        # diffusion_imaging_model = diffusion_imaging_model[0]

        if gui:
            # input_notification = Check_Input_Notification(message=input_message, diffusion_imaging_model_options=diffusion_imaging_model,diffusion_imaging_model=diffusion_imaging_model)
            # input_notification.configure_traits()
            print(input_message)
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model

            # if diffusion_available:
            #     n_vol = nib.load(dwi_file).shape[3]
            #     if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #         self.stages['Preprocessing'].config.end_vol = n_vol-1
            #     self.stages['Preprocessing'].config.max_vol = n_vol-1

            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model
        else:
            print(input_message)
            self.global_conf.diffusion_imaging_model = self.diffusion_imaging_model

            # if diffusion_available:
            #     n_vol = nib.load(dwi_file).shape[3]
            #     if self.stages['Preprocessing'].config.end_vol == 0 or self.stages['Preprocessing'].config.end_vol == self.stages['Preprocessing'].config.max_vol or self.stages['Preprocessing'].config.end_vol >= n_vol-1:
            #         self.stages['Preprocessing'].config.end_vol = n_vol-1
            #     self.stages['Preprocessing'].config.max_vol = n_vol-1

            self.stages[
                'Registration'].config.diffusion_imaging_model = self.diffusion_imaging_model
            self.stages[
                'Diffusion'].config.diffusion_imaging_model = self.diffusion_imaging_model

        if (diffusion_available):
            valid_inputs = True
        else:
            print("Missing required inputs.")
            error(
                message=
                "Missing diffusion inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        # for stage in self.stages.values():
        #     if stage.enabled:
        #         print stage.name
        #         print stage.stage_dir

        # self.fill_stages_outputs()

        return valid_inputs
Beispiel #10
0
class AnatomicalPipelineUI(AnatomicalPipeline):
    segmentation = Button()
    # segmentation.setIcon(QIcon(QPixmap("segmentation.png")))

    parcellation = Button()

    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    # parcellation.setIcon(QIcon(QPixmap("parcellation.png")))

    # custom_run = Button('Custom...')
    # run = Button('Run...')

    pipeline_group = VGroup(
        HGroup(spring,
               UItem('segmentation',
                     style='custom',
                     width=450,
                     height=170,
                     resizable=True,
                     editor_args={
                         'image': ImageResource('segmentation'),
                         'label': ""
                     }),
               spring,
               show_labels=False,
               label=""),
        # Item('parcellation',editor=CustomEditor(image=ImageResource('parcellation'))),show_labels=False),
        HGroup(spring,
               UItem('parcellation',
                     style='custom',
                     width=450,
                     height=200,
                     resizable=True,
                     editor_args={
                         'image': ImageResource('parcellation'),
                         'label': ""
                     }),
               spring,
               show_labels=False,
               label=""),
        spring,
        springy=True)

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):

        AnatomicalPipeline.__init__(self, project_info)

        self.stages = {
            'Segmentation':
            SegmentationStageUI(bids_dir=project_info.base_directory,
                                output_dir=project_info.output_directory),
            'Parcellation':
            ParcellationStageUI(pipeline_mode="Diffusion",
                                bids_dir=project_info.base_directory,
                                output_dir=project_info.output_directory)
        }

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    project_info.subject_session, self.pipeline_name,
                    self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    self.pipeline_name, self.stages[stage].name)

    def _segmentation_fired(self, info):
        self.stages['Segmentation'].configure_traits(view=self.view_mode)

    def _parcellation_fired(self, info):
        self.stages['Parcellation'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        print('**** Check Inputs  ****')
        t1_available = False
        valid_inputs = False

        types = layout.get_modalities()

        if self.global_conf.subject_session == '':
            T1_file = os.path.join(self.subject_directory, 'anat',
                                   self.subject + '_T1w.nii.gz')
        else:
            subjid = self.subject.split("-")[1]
            sessid = self.global_conf.subject_session.split("-")[1]
            files = layout.get(subject=subjid,
                               suffix='T1w',
                               extensions='.nii.gz',
                               session=sessid)
            if len(files) > 0:
                T1_file = files[0].filename
                print(T1_file)
            else:
                error(
                    message="T1w image not found for subject %s, session %s." %
                    (subjid, self.global_conf.subject_session),
                    title="Error",
                    buttons=['OK', 'Cancel'],
                    parent=None)
                return

        print("Looking in %s for...." % self.base_directory)
        print("T1_file : %s" % T1_file)

        for typ in types:
            if typ == 'T1w' and os.path.isfile(T1_file):
                print("%s available" % typ)
                t1_available = True

        if t1_available:
            # Copy diffusion data to derivatives / cmp  / subject / dwi
            if self.global_conf.subject_session == '':
                out_T1_file = os.path.join(self.derivatives_directory, 'cmp',
                                           self.subject, 'anat',
                                           self.subject + '_T1w.nii.gz')
            else:
                out_T1_file = os.path.join(
                    self.derivatives_directory, 'cmp', self.subject,
                    self.global_conf.subject_session, 'anat', self.subject +
                    '_' + self.global_conf.subject_session + '_T1w.nii.gz')

            if not os.path.isfile(out_T1_file):
                shutil.copy(src=T1_file, dst=out_T1_file)

            valid_inputs = True
            input_message = 'Inputs check finished successfully. \nOnly anatomical data (T1) available.'
        else:
            input_message = 'Error during inputs check. No anatomical data available in folder ' + os.path.join(
                self.base_directory, self.subject) + '/anat/!'

        # diffusion_imaging_model = diffusion_imaging_model[0]

        if gui:
            # input_notification = Check_Input_Notification(message=input_message, diffusion_imaging_model_options=diffusion_imaging_model,diffusion_imaging_model=diffusion_imaging_model)
            # input_notification.configure_traits()
            print(input_message)

        else:
            print(input_message)

        if (t1_available):
            valid_inputs = True
        else:
            print("Missing required inputs.")
            error(
                message=
                "Missing required inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        for stage in list(self.stages.values()):
            if stage.enabled:
                print(stage.name)
                print(stage.stage_dir)

        # self.fill_stages_outputs()

        return valid_inputs

    def check_output(self):
        t1_available = False
        brain_available = False
        brainmask_available = False
        wm_available = False
        roivs_available = False
        valid_output = False

        subject = self.subject

        if self.global_conf.subject_session == '':
            anat_deriv_subject_directory = os.path.join(
                self.base_directory, "derivatives", "cmp", self.subject,
                'anat')
        else:
            if self.global_conf.subject_session not in subject:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", "cmp", subject,
                    self.global_conf.subject_session, 'anat')
                subject = "_".join((subject, self.global_conf.subject_session))
            else:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", "cmp",
                    subject.split("_")[0], self.global_conf.subject_session,
                    'anat')

        T1_file = os.path.join(anat_deriv_subject_directory,
                               subject + '_T1w_head.nii.gz')
        brain_file = os.path.join(anat_deriv_subject_directory,
                                  subject + '_T1w_brain.nii.gz')
        brainmask_file = os.path.join(anat_deriv_subject_directory,
                                      subject + '_T1w_brainmask.nii.gz')
        wm_mask_file = os.path.join(anat_deriv_subject_directory,
                                    subject + '_T1w_class-WM.nii.gz')
        roiv_files = glob.glob(anat_deriv_subject_directory + "/" + subject +
                               "_T1w_parc_scale*.nii.gz")

        error_message = ''

        if os.path.isfile(T1_file):
            t1_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % T1_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(brain_file):
            brain_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % brain_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(brainmask_file):
            brainmask_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % brainmask_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(wm_mask_file):
            wm_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % wm_mask_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        cnt1 = 0
        cnt2 = 0
        for roiv_file in roiv_files:
            cnt1 = cnt1 + 1
            if os.path.isfile(roiv_file):
                cnt2 = cnt2 + 1
        if cnt1 == cnt2:
            roivs_available = True
        else:
            error_message = "Missing %g/%g anatomical parcellation output files. Please re-run the anatomical pipeline" % (
                cnt1 - cnt2, cnt1)
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if t1_available is True and brain_available is True and brainmask_available is True and wm_available is True and roivs_available is True:
            print("valid deriv/anat output")
            valid_output = True

        return valid_output, error_message
Beispiel #11
0
class AnatomicalPipelineUI(AnatomicalPipeline):
    """Class that extends the :class:`~cmp.pipelines.anatomical.anatomical.AnatomicalPipeline` with graphical components.

    Attributes
    ----------
    segmentation : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the segmentation stage depending on the ``view_mode``

    parcellation : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the segmentation stage depending on the ``view_mode``

    view_mode : ['config_view', 'inspect_outputs_view']
        Variable used to control the display of either (1) the configuration
        or (2) the quality inspection of stage of the pipeline

    pipeline_group : traitsUI panel
        Panel defining the layout of the buttons of the stages with corresponding images

    traits_view : QtView
        QtView that includes the ``pipeline_group`` panel

    See also
    ---------
    cmp.pipelines.anatomical.anatomical.AnatomicalPipeline
    """

    segmentation = Button()

    parcellation = Button()

    view_mode = Enum("config_view", ["config_view", "inspect_outputs_view"])

    pipeline_group = VGroup(
        HGroup(
            spring,
            UItem(
                "segmentation",
                style="custom",
                width=222,
                height=129,
                resizable=False,
                style_sheet=return_button_style_sheet(
                    ImageResource("segmentation").absolute_path
                ),
            ),
            spring,
            show_labels=False,
            label="",
        ),
        # Item('parcellation',editor=CustomEditor(image=ImageResource('parcellation'))),show_labels=False),
        HGroup(
            spring,
            UItem(
                "parcellation",
                style="custom",
                width=222,
                height=129,
                resizable=False,
                style_sheet=return_button_style_sheet(
                    ImageResource("parcellation").absolute_path
                ),
            ),
            spring,
            show_labels=False,
            label="",
        ),
        spring,
        springy=True,
    )

    traits_view = QtView(Include("pipeline_group"))

    def __init__(self, project_info):
        """Constructor of the AnatomicalPipelineUI class.

        Parameters
        -----------
        project_info : cmp.project.ProjectInfo
            CMP_Project_Info object that stores general information
            such as the BIDS root and output directories (see
            :class_`cmp.project.CMP_Project_Info` for more details)

        See also
        ---------
        cmp.pipelines.anatomical.AnatomicalPipeline.__init__
        """
        AnatomicalPipeline.__init__(self, project_info)

        if len(project_info.subject_sessions) > 0:
            subject_id = "_".join((self.subject, self.global_conf.subject_session))
            subject_session = self.global_conf.subject_session
        else:
            subject_id = self.subject
            subject_session = ""

        self.stages = {
            "Segmentation": SegmentationStageUI(
                subject=self.subject,
                session=subject_session,
                bids_dir=project_info.base_directory,
                output_dir=project_info.output_directory,
            ),
            "Parcellation": ParcellationStageUI(
                pipeline_mode="Diffusion",
                subject=self.subject,
                session=subject_session,
                bids_dir=project_info.base_directory,
                output_dir=project_info.output_directory,
            ),
        }

        self.stages["Segmentation"].config.freesurfer_subjects_dir = os.path.join(
            self.output_directory, __freesurfer_directory__
        )
        self.stages["Segmentation"].config.freesurfer_subject_id = os.path.join(
            self.output_directory, __freesurfer_directory__, subject_id
        )

        print(
            "Freesurfer subjects directory: "
            + self.stages["Segmentation"].config.freesurfer_subjects_dir
        )

        for stage in list(self.stages.keys()):
            if project_info.subject_session != "":
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory,
                    "derivatives",
                    __nipype_directory__,
                    self.subject,
                    project_info.subject_session,
                    self.pipeline_name,
                    self.stages[stage].name,
                )
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory,
                    "derivatives",
                    __nipype_directory__,
                    self.subject,
                    self.pipeline_name,
                    self.stages[stage].name,
                )

            self.stages["Segmentation"].config.on_trait_change(
                self._update_parcellation, "seg_tool"
            )
            self.stages["Parcellation"].config.on_trait_change(
                self._update_segmentation, "parcellation_scheme"
            )


    def _update_parcellation(self):
        """Update self.stages['Parcellation'].config.parcellation_scheme when ``seg_tool`` is updated."""
        if self.stages["Segmentation"].config.seg_tool == "Custom segmentation":
            self.stages["Parcellation"].config.parcellation_scheme = "Custom"
            self.stages["Parcellation"].config.parcellation_scheme_editor = ["Custom"]
        else:
            self.stages["Parcellation"].config.parcellation_scheme = "Lausanne2018"
            self.stages["Parcellation"].config.parcellation_scheme_editor = [
                "NativeFreesurfer", "Lausanne2018", "Custom"
            ]

    def _update_segmentation(self):
        """Update self.stages['Segmentation'].config.seg_tool when ``parcellation_scheme`` is updated."""
        if self.stages["Parcellation"].config.parcellation_scheme == "Custom":
            self.stages["Segmentation"].config.seg_tool = "Custom segmentation"
        else:
            self.stages["Segmentation"].config.seg_tool = "Freesurfer"

    def _segmentation_fired(self, info):
        """Method that displays the window for the segmentation stage.

        The window changed accordingly to the value of ``view_mode`` to be
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The segmentation button object
        """
        self.stages["Segmentation"].configure_traits(view=self.view_mode)

    def _parcellation_fired(self, info):
        """Method that displays the window for the parcellation stage.

        The window changed accordingly to the value of ``view_mode`` to be
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The parcellation button object
        """
        self.stages["Parcellation"].configure_traits(view=self.view_mode)

    def check_input(self, layout):
        """Method that checks if inputs of the anatomical pipeline are available in the datasets.

        Parameters
        -----------
        layout : bids.BIDSLayout
            BIDSLayout object used to query

        Returns
        -------
        valid_inputs : bool
            True in all inputs of the anatomical pipeline are available
        """
        print("**** Check Inputs  ****")
        t1_available = False
        valid_inputs = False

        types = layout.get_modalities()

        subjid = self.subject.split("-")[1]

        if self.global_conf.subject_session != "":
            sessid = self.global_conf.subject_session.split("-")[1]

        files = layout.get(
            subject=subjid,
            session=None if (self.global_conf.subject_session == "") else sessid,
            suffix="T1w",
            extension="nii.gz",
        )
        if len(files) > 0:
            T1_file = files[0].filename
            print(T1_file)
        else:
            error(
                message="T1w image not found for subject %s, session %s."
                % (subjid, self.global_conf.subject_session),
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )
            return False

        for typ in types:
            if typ == "T1w" and os.path.isfile(T1_file):
                print("T1_file found: %s" % T1_file)
                t1_available = True

        if t1_available:
            # Copy diffusion data to derivatives / cmp  / subject / dwi
            if self.global_conf.subject_session == "":
                out_T1_file = os.path.join(
                    self.derivatives_directory, __cmp_directory__,
                    self.subject, "anat",
                    self.subject + "_T1w.nii.gz",
                )
            else:
                out_T1_file = os.path.join(
                    self.derivatives_directory, __cmp_directory__,
                    self.subject, self.global_conf.subject_session, "anat",
                    f'{self.subject}_{self.global_conf.subject_session}_T1w.nii.gz',
                )

            if not os.path.isfile(out_T1_file):
                shutil.copy(src=T1_file, dst=out_T1_file)

            msg = "Inputs check finished successfully. \nAnatomical data (T1w) available."
            print(f'\tINFO: {msg}')
            valid_inputs = True
        else:
            msg = (
                "  * No anatomical data (T1w) available in folder "
                + os.path.join(self.base_directory, self.subject, 'anat')
                + "!\n"
            )
            print(f'\tERROR: Missing required inputs: {msg}')
            error(
                message=f"Missing required inputs:\n{msg} Please see documentation for more details.",
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        if self.stages["Parcellation"].config.parcellation_scheme == "Custom":
            msg = ""

            custom_parc_nii_available = True
            custom_parc_tsv_available = True
            custom_brainmask_available = True
            custom_gm_mask_available = True
            custom_wm_mask_available = True
            custom_csf_mask_available = True
            custom_aparcaseg_available = True
            
            # Add custom BIDS derivatives directories to the BIDSLayout
            custom_derivatives_dirnames = [
                self.stages["Parcellation"].config.custom_parcellation.get_toolbox_derivatives_dir(),
                self.stages["Segmentation"].config.custom_brainmask.get_toolbox_derivatives_dir(),
                self.stages["Segmentation"].config.custom_gm_mask.get_toolbox_derivatives_dir(),
                self.stages["Segmentation"].config.custom_wm_mask.get_toolbox_derivatives_dir(),
                self.stages["Segmentation"].config.custom_csf_mask.get_toolbox_derivatives_dir(),
                self.stages["Segmentation"].config.custom_aparcaseg.get_toolbox_derivatives_dir()
            ]
            # Keep only unique custom derivatives to make the BIDSLayout happy
            custom_derivatives_dirnames = list(set(custom_derivatives_dirnames))
            for custom_derivatives_dirname in  custom_derivatives_dirnames:
                if custom_derivatives_dirname not in layout.derivatives:
                    print(f"    * Add custom_derivatives_dirname: {custom_derivatives_dirname}")
                    layout.add_derivatives(os.path.join(self.base_directory, 'derivatives', custom_derivatives_dirname))

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Parcellation"].config.custom_parcellation.suffix,
                atlas=self.stages["Parcellation"].config.custom_parcellation.atlas,
                resolution=self.stages["Parcellation"].config.custom_parcellation.resolution,
                extension="nii.gz",
            )
            if len(files) > 0:
                custom_parc_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_parc_file = "NotFound"
                custom_parc_nii_available = False
            print("... custom_parc_file : %s" % custom_parc_file)

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Parcellation"].config.custom_parcellation.suffix,
                extension="tsv",
                atlas=self.stages["Parcellation"].config.custom_parcellation.atlas,
                resolution=self.stages["Parcellation"].config.custom_parcellation.resolution,
            )
            if len(files) > 0:
                custom_parc_tsv_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_parc_tsv_file = "NotFound"
                msg += f'  * Custom parcellation ({self.stages["Parcellation"].config.custom_parcellation}) not found\n'
                custom_parc_tsv_available = False
            print("... custom_parc_tsv_file : %s" % custom_parc_tsv_file)

            if not custom_parc_nii_available and not custom_parc_tsv_available:
                valid_inputs = False

            files = layout.get(
                    subject=subjid,
                    session=(None
                             if self.global_conf.subject_session == ""
                             else self.global_conf.subject_session.split("-")[1]),
                    suffix=self.stages["Segmentation"].config.custom_brainmask.suffix,
                    extension="nii.gz",
                    desc=self.stages["Segmentation"].config.custom_brainmask.desc,
            )
            if len(files) > 0:
                custom_brainmask_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_brainmask_file = "NotFound"
                msg += f'  * Custom brain mask ({self.stages["Segmentation"].config.custom_brainmask}) not found\n'
                custom_brainmask_available = False
            print("... custom_brainmask_file : %s" % custom_brainmask_file)

            if not custom_brainmask_available:
                valid_inputs = False

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Segmentation"].config.custom_gm_mask.suffix,
                extension="nii.gz",
                label=self.stages["Segmentation"].config.custom_gm_mask.label,
            )
            if len(files) > 0:
                custom_gm_mask_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_gm_mask_file = "NotFound"
                msg += f'  * Custom gray matter mask ({self.stages["Segmentation"].config.custom_gm_mask}) not found\n'
                custom_gm_mask_available = False
            print("... custom_gm_mask_file : %s" % custom_gm_mask_file)

            if not custom_gm_mask_available:
                valid_inputs = False

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Segmentation"].config.custom_wm_mask.suffix,
                extension="nii.gz",
                label=self.stages["Segmentation"].config.custom_wm_mask.label,
            )
            if len(files) > 0:
                custom_wm_mask_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_wm_mask_file = "NotFound"
                msg += f'  * Custom white matter mask ({self.stages["Segmentation"].config.custom_wm_mask}) not found\n'
                custom_wm_mask_available = False
            print("... custom_wm_mask_file : %s" % custom_wm_mask_file)

            if not custom_wm_mask_available:
                valid_inputs = False

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Segmentation"].config.custom_csf_mask.suffix,
                extension="nii.gz",
                label=self.stages["Segmentation"].config.custom_csf_mask.label,
            )
            if len(files) > 0:
                custom_csf_mask_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_csf_mask_file = "NotFound"
                msg += f'  * Custom CSF mask ({self.stages["Segmentation"].config.custom_csf_mask}) not found\n'
                custom_csf_mask_available = False
            print("... custom_csf_mask_file : %s" % custom_csf_mask_file)

            if not custom_csf_mask_available:
                valid_inputs = False

            files = layout.get(
                subject=subjid,
                session=(None
                         if self.global_conf.subject_session == ""
                         else self.global_conf.subject_session.split("-")[1]),
                suffix=self.stages["Segmentation"].config.custom_aparcaseg.suffix,
                extension="nii.gz",
                desc=self.stages["Segmentation"].config.custom_aparcaseg.desc,
            )
            if len(files) > 0:
                custom_aparcaseg_file = os.path.join(files[0].dirname, files[0].filename)
            else:
                custom_aparcaseg_file = "NotFound"
                msg += f'  * Custom Freesurfer\'s aparc+aseg ({self.stages["Segmentation"].config.custom_gm_mask}) not found\n'
                custom_aparcaseg_available = False
            print("... custom_aparcaseg_file : %s" % custom_aparcaseg_file)

            if not custom_aparcaseg_available:
                valid_inputs = False

            if not valid_inputs:
                error(
                    message=f"Missing required custom inputs:\n{msg} Please see documentation for more details.",
                    title="Error",
                    buttons=["OK", "Cancel"],
                    parent=None,
                )

        return valid_inputs

    def check_output(self):
        """Method that checks if outputs of the anatomical pipeline are available.

        Returns
        --------
        valid_output : bool
            True is all outputs are found

        error_message : string
            Message in case there is an error
        """
        t1_available = False
        brain_available = False
        brainmask_available = False
        wm_available = False
        roivs_available = False
        valid_output = False

        subject = self.subject

        if self.global_conf.subject_session == "":
            anat_deriv_subject_directory = os.path.join(
                self.base_directory, "derivatives", __cmp_directory__, self.subject, "anat"
            )
        else:
            if self.global_conf.subject_session not in subject:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", __cmp_directory__,
                    subject, self.global_conf.subject_session, "anat",
                )
                subject = "_".join((subject, self.global_conf.subject_session))
            else:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", __cmp_directory__,
                    subject.split("_")[0], self.global_conf.subject_session, "anat",
                )

        T1_file = os.path.join(
            anat_deriv_subject_directory, subject + "_T1w_head.nii.gz"
        )
        brain_file = os.path.join(
            anat_deriv_subject_directory, subject + "_T1w_brain.nii.gz"
        )
        brainmask_file = os.path.join(
            anat_deriv_subject_directory, subject + "_T1w_brainmask.nii.gz"
        )
        wm_mask_file = os.path.join(
            anat_deriv_subject_directory, subject + "_T1w_class-WM.nii.gz"
        )
        roiv_files = glob.glob(
            anat_deriv_subject_directory + "/" + subject + "_T1w_parc_scale*.nii.gz"
        )

        error_message = ""

        if os.path.isfile(T1_file):
            t1_available = True
        else:
            error_message = (
                "Missing anatomical output file %s . Please re-run the anatomical pipeline"
                % T1_file
            )
            print(error_message)
            error(
                message=error_message,
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        if os.path.isfile(brain_file):
            brain_available = True
        else:
            error_message = (
                "Missing anatomical output file %s . Please re-run the anatomical pipeline"
                % brain_file
            )
            print(error_message)
            error(
                message=error_message,
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        if os.path.isfile(brainmask_file):
            brainmask_available = True
        else:
            error_message = (
                "Missing anatomical output file %s . Please re-run the anatomical pipeline"
                % brainmask_file
            )
            print(error_message)
            error(
                message=error_message,
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        if os.path.isfile(wm_mask_file):
            wm_available = True
        else:
            error_message = (
                "Missing anatomical output file %s . Please re-run the anatomical pipeline"
                % wm_mask_file
            )
            print(error_message)
            error(
                message=error_message,
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        cnt1 = 0
        cnt2 = 0
        for roiv_file in roiv_files:
            cnt1 = cnt1 + 1
            if os.path.isfile(roiv_file):
                cnt2 = cnt2 + 1
        if cnt1 == cnt2:
            roivs_available = True
        else:
            error_message = (
                "Missing %g/%g anatomical parcellation output files. Please re-run the anatomical pipeline"
                % (cnt1 - cnt2, cnt1)
            )
            print(error_message)
            error(
                message=error_message,
                title="Error",
                buttons=["OK", "Cancel"],
                parent=None,
            )

        if (
            t1_available is True
            and brain_available is True
            and brainmask_available is True
            and wm_available is True
            and roivs_available is True
        ):
            print("valid deriv/anat output")
            valid_output = True

        return valid_output, error_message
Beispiel #12
0
class AnatomicalPipelineUI(AnatomicalPipeline):
    """Class that extends the :class:`~cmp.pipelines.anatomical.anatomical.AnatomicalPipeline` with graphical components.

    Attributes
    ----------
    segmentation : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the segmentation stage depending on the ``view_mode``

    parcellation : traits.ui.Button
        Button to open the window for configuration or quality inspection
        of the segmentation stage depending on the ``view_mode``

    view_mode : ['config_view', 'inspect_outputs_view']
        Variable used to control the display of either (1) the configuration
        or (2) the quality inspection of stage of the pipeline

    pipeline_group : traitsUI panel
        Panel defining the layout of the buttons of the stages with corresponding images

    traits_view : QtView
        QtView that includes the ``pipeline_group`` panel

    See also
    ---------
    cmp.pipelines.anatomical.anatomical.AnatomicalPipeline
    """

    segmentation = Button()

    parcellation = Button()

    view_mode = Enum('config_view', ['config_view', 'inspect_outputs_view'])

    pipeline_group = VGroup(
        HGroup(spring,
               UItem('segmentation',
                     style='custom',
                     width=222,
                     height=129,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('segmentation').absolute_path)),
               spring,
               show_labels=False,
               label=""),
        # Item('parcellation',editor=CustomEditor(image=ImageResource('parcellation'))),show_labels=False),
        HGroup(spring,
               UItem('parcellation',
                     style='custom',
                     width=222,
                     height=129,
                     resizable=False,
                     style_sheet=return_button_style_sheet(
                         ImageResource('parcellation').absolute_path)),
               spring,
               show_labels=False,
               label=""),
        spring,
        springy=True)

    traits_view = QtView(Include('pipeline_group'))

    def __init__(self, project_info):
        """Constructor of the AnatomicalPipelineUI class.

        Parameters
        -----------
        project_info : cmp.project.CMP_Project_Info
            CMP_Project_Info object that stores general information
            such as the BIDS root and output directories (see
            :class_`cmp.project.CMP_Project_Info` for more details)

        See also
        ---------
        cmp.pipelines.anatomical.AnatomicalPipeline.__init__
        """
        AnatomicalPipeline.__init__(self, project_info)

        self.stages = {
            'Segmentation':
            SegmentationStageUI(bids_dir=project_info.base_directory,
                                output_dir=project_info.output_directory),
            'Parcellation':
            ParcellationStageUI(pipeline_mode="Diffusion",
                                bids_dir=project_info.base_directory,
                                output_dir=project_info.output_directory)
        }

        if len(project_info.subject_sessions) > 0:
            subject_id = "_".join(
                (self.subject, self.global_conf.subject_session))
        else:
            subject_id = self.subject

        self.stages[
            'Segmentation'].config.freesurfer_subjects_dir = os.path.join(
                self.output_directory, 'freesurfer')
        self.stages[
            'Segmentation'].config.freesurfer_subject_id = os.path.join(
                self.output_directory, 'freesurfer', subject_id)

        print('Freesurfer subjects directory: ' +
              self.stages['Segmentation'].config.freesurfer_subjects_dir)

        for stage in list(self.stages.keys()):
            if project_info.subject_session != '':
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    project_info.subject_session, self.pipeline_name,
                    self.stages[stage].name)
            else:
                self.stages[stage].stage_dir = os.path.join(
                    self.base_directory, "derivatives", 'nipype', self.subject,
                    self.pipeline_name, self.stages[stage].name)

    def _segmentation_fired(self, info):
        """Method that displays the window for the segmentation stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The segmentation button object
        """
        self.stages['Segmentation'].configure_traits(view=self.view_mode)

    def _parcellation_fired(self, info):
        """Method that displays the window for the parcellation stage.

        The window changed accordingly to the value of ``view_mode`` to be 
        in configuration or quality inspection mode.

        Parameters
        -----------
        info : traits.ui.Button
            The parcellation button object
        """
        self.stages['Parcellation'].configure_traits(view=self.view_mode)

    def check_input(self, layout, gui=True):
        """Method that checks if inputs of the anatomical pipeline are available in the datasets.

        Parameters
        -----------
        layout : bids.BIDSLayout
            BIDSLayout object used to query

        gui : Boolean
            If `True` display messages and errors in graphical window

        Returns
        -------
        valid_inputs : bool
            True in all inputs of the anatomical pipeline are available
        """
        print('**** Check Inputs  ****')
        t1_available = False
        valid_inputs = False

        types = layout.get_modalities()

        if self.global_conf.subject_session == '':
            T1_file = os.path.join(self.subject_directory, 'anat',
                                   self.subject + '_T1w.nii.gz')
        else:
            subjid = self.subject.split("-")[1]
            sessid = self.global_conf.subject_session.split("-")[1]
            files = layout.get(subject=subjid,
                               suffix='T1w',
                               extensions='.nii.gz',
                               session=sessid)
            if len(files) > 0:
                T1_file = files[0].filename
                print(T1_file)
            else:
                error(
                    message="T1w image not found for subject %s, session %s." %
                    (subjid, self.global_conf.subject_session),
                    title="Error",
                    buttons=['OK', 'Cancel'],
                    parent=None)
                return

        print("Looking in %s for...." % self.base_directory)
        print("T1_file : %s" % T1_file)

        for typ in types:
            if typ == 'T1w' and os.path.isfile(T1_file):
                print("%s available" % typ)
                t1_available = True

        if t1_available:
            # Copy diffusion data to derivatives / cmp  / subject / dwi
            if self.global_conf.subject_session == '':
                out_T1_file = os.path.join(self.derivatives_directory, 'cmp',
                                           self.subject, 'anat',
                                           self.subject + '_T1w.nii.gz')
            else:
                out_T1_file = os.path.join(
                    self.derivatives_directory, 'cmp', self.subject,
                    self.global_conf.subject_session, 'anat', self.subject +
                    '_' + self.global_conf.subject_session + '_T1w.nii.gz')

            if not os.path.isfile(out_T1_file):
                shutil.copy(src=T1_file, dst=out_T1_file)

            valid_inputs = True
            input_message = 'Inputs check finished successfully. \nOnly anatomical data (T1) available.'
        else:
            input_message = 'Error during inputs check. No anatomical data available in folder ' + os.path.join(
                self.base_directory, self.subject) + '/anat/!'

        # diffusion_imaging_model = diffusion_imaging_model[0]

        if gui:
            # input_notification = Check_Input_Notification(message=input_message,
            #                                               diffusion_imaging_model_options=diffusion_imaging_model,
            #                                               diffusion_imaging_model=diffusion_imaging_model)
            # input_notification.configure_traits()
            print(input_message)

        else:
            print(input_message)

        if t1_available:
            valid_inputs = True
        else:
            print("Missing required inputs.")
            error(
                message=
                "Missing required inputs. Please see documentation for more details.",
                title="Error",
                buttons=['OK', 'Cancel'],
                parent=None)

        for stage in list(self.stages.values()):
            if stage.enabled:
                print(stage.name)
                print(stage.stage_dir)

        # self.fill_stages_outputs()

        return valid_inputs

    def check_output(self):
        """Method that checks if outputs of the anatomical pipeline are available.

        Returns
        --------
        valid_output : bool
            True is all outputs are found

        error_message : string
            Message in case there is an error
        """
        t1_available = False
        brain_available = False
        brainmask_available = False
        wm_available = False
        roivs_available = False
        valid_output = False

        subject = self.subject

        if self.global_conf.subject_session == '':
            anat_deriv_subject_directory = os.path.join(
                self.base_directory, "derivatives", "cmp", self.subject,
                'anat')
        else:
            if self.global_conf.subject_session not in subject:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", "cmp", subject,
                    self.global_conf.subject_session, 'anat')
                subject = "_".join((subject, self.global_conf.subject_session))
            else:
                anat_deriv_subject_directory = os.path.join(
                    self.base_directory, "derivatives", "cmp",
                    subject.split("_")[0], self.global_conf.subject_session,
                    'anat')

        T1_file = os.path.join(anat_deriv_subject_directory,
                               subject + '_T1w_head.nii.gz')
        brain_file = os.path.join(anat_deriv_subject_directory,
                                  subject + '_T1w_brain.nii.gz')
        brainmask_file = os.path.join(anat_deriv_subject_directory,
                                      subject + '_T1w_brainmask.nii.gz')
        wm_mask_file = os.path.join(anat_deriv_subject_directory,
                                    subject + '_T1w_class-WM.nii.gz')
        roiv_files = glob.glob(anat_deriv_subject_directory + "/" + subject +
                               "_T1w_parc_scale*.nii.gz")

        error_message = ''

        if os.path.isfile(T1_file):
            t1_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % T1_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(brain_file):
            brain_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % brain_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(brainmask_file):
            brainmask_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % brainmask_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if os.path.isfile(wm_mask_file):
            wm_available = True
        else:
            error_message = "Missing anatomical output file %s . Please re-run the anatomical pipeline" % wm_mask_file
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        cnt1 = 0
        cnt2 = 0
        for roiv_file in roiv_files:
            cnt1 = cnt1 + 1
            if os.path.isfile(roiv_file):
                cnt2 = cnt2 + 1
        if cnt1 == cnt2:
            roivs_available = True
        else:
            error_message = "Missing %g/%g anatomical parcellation output files. Please re-run the anatomical pipeline" % (
                cnt1 - cnt2, cnt1)
            print(error_message)
            error(message=error_message,
                  title="Error",
                  buttons=['OK', 'Cancel'],
                  parent=None)

        if t1_available is True and brain_available is True and brainmask_available is True and wm_available is True and roivs_available is True:
            print("valid deriv/anat output")
            valid_output = True

        return valid_output, error_message