Esempio n. 1
0
def view_test_results(name: Optional[str] = None):
    """
    View the results of a particular test.
    
    :param name:    Name, or `None` to use the currently loaded model.
    """
    if name:
        tdir = TestDirectory(name)
        groot.file_load(tdir.r_model)

    model = groot.current_model()

    groot.print_trees(model.user_graphs["original_graph"],
                      format=groot.EFormat._HTML,
                      file="open")
    groot.print_trees(model.fusion_graph_unclean,
                      format=groot.EFormat._HTML,
                      file="open")
    groot.print_trees(model.fusion_graph_clean,
                      format=groot.EFormat._HTML,
                      file="open")

    for component in model.components:
        groot.print_trees(component.named_tree_unrooted,
                          format=groot.EFormat._HTML,
                          file="open")
        groot.print_trees(component.named_tree,
                          format=groot.EFormat._HTML,
                          file="open")

    report = model.user_reports["test_differences"].html

    with OpeningWriter() as view_report:
        view_report.write(report)
Esempio n. 2
0
 def _refresh_labels( self ):
     # Wizard
     wt = groot.Wizard.get_active()
     
     if wt is not None and wt.is_paused:
         self.ui.FRA_PAUSED.setVisible( True )
         self.ui.LBL_NEXT.setText( wt.get_stage_name() )
     else:
         self.ui.FRA_PAUSED.setVisible( False )
     
     # Others
     m = groot.current_model()
     
     for stage, indicator, label, box, btn in self.map:
         status = m.get_status( stage )
         
         if status.is_hot:
             indicator.setStyleSheet( "background:red;" + self.INDICATOR_SUFFIX )
         elif status.is_complete:
             indicator.setStyleSheet( "background:green;" + self.INDICATOR_SUFFIX )
         elif status.is_partial:
             indicator.setStyleSheet( "background:orange;" + self.INDICATOR_SUFFIX )
         else:
             indicator.setStyleSheet( "background:silver;" + self.INDICATOR_SUFFIX )
         
         box.setText( str( status ) )
Esempio n. 3
0
    def on_BTN_SEQUENCE_clicked(self) -> None:
        """
        Signal handler:
        """
        accession = self.seq_view.get_gene_name(self.seq_view.highlight_row)

        if accession:
            gene: groot.Gene = groot.current_model().genes[accession]
            self.inspect_elsewhere(gene)
Esempio n. 4
0
    def on_BTN_POSITION_clicked(self) -> None:
        """
        Signal handler:
        """
        accession = self.seq_view.get_gene_name(self.seq_view.highlight_row)

        if accession:
            gene: groot.Gene = groot.current_model().genes[accession]
            col = self.seq_view.highlight_col
            domains = list(x for x in gene.iter_userdomains()
                           if x.start <= col <= x.end)
            self.inspect_elsewhere(domains)
Esempio n. 5
0
    def on_BTN_SITE_clicked(self) -> None:
        """
        Signal handler:
        """
        accession = self.seq_view.get_gene_name(self.seq_view.highlight_row)

        if accession:
            gene: groot.Gene = groot.current_model().genes[accession]
            col = self.seq_view.highlight_col
            site = self.seq_view.get_site_text(self.seq_view.highlight_row,
                                               col)
            domains = list(
                x for x in gene.iter_userdomains()
                if x.start <= col <= x.end and x.site_array[col] == site)
            self.inspect_elsewhere(domains)
Esempio n. 6
0
def run_test(name: str) -> groot.EChanges:
    """
    Runs a test case and saves the results to the global results folder. 
    
    :param name:       A name or path to the test case.
                       If no full path is provided the "samples" folder will be assumed.
                       The test case folder must contain:
                        
                            * The data (BLAST, FASTA)
                            * A `tree.csv` file describing the expected results (in edge-list format)
                            * A `groot.ini` file describing the parameters to use.
                             
    :return:           Nothing is returned, the results are saved to the global results folder. 
    """

    # Load sample file
    tdir = TestDirectory(name)

    # Define outputs
    file_helper.create_directory(tdir.r_folder, overwrite=True)

    # Check the requisite files exist
    if not os.path.isdir(tdir.t_folder):
        raise ValueError(
            "This is not a test case (it is not even a folder, «{}»).".format(
                tdir.t_folder))

    if not os.path.isfile(tdir.t_tree):
        raise ValueError(
            "This is not a test case (it is missing the edge list file, «{}»)."
            .format(tdir.t_tree))

    if not os.path.isfile(tdir.t_ini):
        raise ValueError(
            "This is not a test case (it is missing the INI file, «{}»).".
            format(tdir.t_ini))

    # Read the test specs
    specs = io_helper.load_ini(tdir.t_ini)

    if "groot_test" not in specs:
        raise ValueError(
            "This is not a test case (it is missing the `groot_test` section from the INI file, «{}»)."
            .format(tdir.t_ini))

    if not "groot_wizard" in specs:
        raise ValueError(
            "This is not a test case (it is missing the «wizard» section from the INI «{}»)."
            .format(tdir.t_ini))

    wizard_params = specs["groot_wizard"]

    try:
        wiz_tol = int(wizard_params["tolerance"])
        wiz_og = wizard_params["outgroups"].split(",")
    except KeyError as ex:
        raise ValueError(
            "This is not a test case (it is missing the «{}» setting from the «wizard» section of the INI «{}»)."
            .format(ex, tdir.t_ini))

    # Copy the test files to the output folder
    for file in file_helper.list_dir(tdir.t_folder):
        shutil.copy(
            file, file_helper.format_path(file,
                                          tdir.r_folder + "/input_{N}{E}"))

    # Create settings
    walkthrough = groot.Wizard(
        new=True,
        name=tdir.r_model,
        imports=groot.sample_data.get_sample_contents(tdir.t_folder),
        pauses=set(),
        tolerance=wiz_tol,
        outgroups=wiz_og,
        alignment="",
        tree="maximum_likelihood",  # "neighbor_joining",
        view=False,
        save=False,
        supertree="clann")

    try:
        # Execute the wizard (no pauses are set so this only requires 1 `step`)
        walkthrough.make_active()
        walkthrough.step()

        if not walkthrough.is_completed:
            raise ValueError("Expected wizard to complete but it did not.")

        # Add the original graph to the Groot `Model` in case we debug
        test_tree_file_data = groot.UserGraph(mgraph.importing.import_edgelist(
            file_helper.read_all_text(tdir.t_tree), delimiter="\t"),
                                              name="original_graph")
        groot.rectify_nodes(test_tree_file_data.graph, groot.current_model())
        groot.current_model().user_graphs.append(
            groot.FixedUserGraph(test_tree_file_data.graph, "original_graph"))
    finally:
        # Save the final model regardless of whether the test succeeded
        groot.file_save(tdir.r_model)

    # Perform the comparison
    model = groot.current_model()
    differences = groot.compare_graphs(model.fusion_graph_clean,
                                       test_tree_file_data)
    q = differences.raw_data["quartets"]["match_quartets"]
    print("match_quartets: " + q)

    # Write the results---

    # ---Summary
    io_helper.save_ini(tdir.r_summary, differences.raw_data)

    # ---Alignments
    groot.print_alignments(file=tdir.r_alignments)

    # ---Differences
    file_helper.write_all_text(tdir.r_comparison,
                               differences.html,
                               newline=True)
    differences.name = "test_differences"
    groot.current_model().user_reports.append(differences)

    # ---Model
    groot.file_save(tdir.r_model)

    # Done
    intermake.pr.printx(
        "<verbose>The test has completed, see «{}».</verbose>".format(
            tdir.r_comparison))
    return groot.EChanges.MODEL_OBJECT
Esempio n. 7
0
 def get_model(self) -> groot.Model:
     return groot.current_model()
Esempio n. 8
0
    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle("Genes")

        self.queue = []

        root_layout = qt.QVBoxLayout()
        self.setLayout(root_layout)

        toolbar = qt.QFrame()
        root_layout.addWidget(toolbar)

        self.tool_layout = qt.QHBoxLayout()
        self.tool_layout.setContentsMargins(qt.QMargins(0, 0, 0, 0))
        toolbar.setLayout(self.tool_layout)
        self.add_select_button(toolbar)

        self.add_toolbar_item("Import\nnames", resources.rename.icon(),
                              self.on_mnu_rename)

        qt.toolbar_helper.add_spacer(toolbar)
        self.add_toolbar_item("Refresh", resources.refresh.icon(),
                              self.refresh_data)
        self.add_toolbar_item("Help", resources.help.icon(), self.on_mnu_help)

        self.scroll_area = qt.QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setSizePolicy(qt.QSizePolicy.MinimumExpanding,
                                       qt.QSizePolicy.Expanding)
        self.scroll_area.setHorizontalScrollBarPolicy(qt.Qt.ScrollBarAlwaysOff)
        self.scroll_area.setMinimumWidth(1024)
        root_layout.addWidget(self.scroll_area)

        frame = qt.QWidget()
        self.scroll_area.setWidget(frame)

        self.layout = qt.QGridLayout()
        self.layout.setContentsMargins(qt.QMargins(0, 0, 0, 0))
        frame.setLayout(self.layout)

        self.model = groot.current_model()

        self.setStyleSheet("""
        QAbstractButton[style="custom"]
        {
            background: white;
            border: 2px solid white;
            border-radius: 4px;
        }
        
        QAbstractButton[style="custom"]:hover
        {
            border: 2px solid black;
        }
        
        QAbstractButton[style="custom"]:pressed
        {
            border: 2px solid silver;
        }
        
        QAbstractButton[style="custom"]:checked
        {
            background: #03A9F4;
        }
        """)

        self.lut: Dict[groot.Gene,
                       Tuple[qt.QLineEdit, qt.QAbstractButton,
                             qt.QAbstractButton, qt.QAbstractButton]] = {}
        self.refresh_data()

        btn_box = qt.QDialogButtonBox()
        btn_box.setStandardButtons(qt.QDialogButtonBox.Apply
                                   | qt.QDialogButtonBox.Ok
                                   | qt.QDialogButtonBox.Cancel)
        btn_box.button(qt.QDialogButtonBox.Apply).clicked.connect(
            self.on_apply)
        btn_box.button(qt.QDialogButtonBox.Ok).clicked.connect(self.on_ok)
        btn_box.button(qt.QDialogButtonBox.Cancel).clicked.connect(
            self.on_cancel)
        root_layout.addWidget(btn_box)
Esempio n. 9
0
    def _on_gene(self, name: str):
        if name == "none":
            return

        gene = groot.current_model().genes[name]
        self.inspect_elsewhere(gene)