Best Python code snippet using autotest_python
annotate.py
Source:annotate.py  
1import shutil2import sys3from genomad import database, mmseqs2, prodigal, sequence, taxonomy, utils4from genomad._paths import GenomadOutputs5def write_genes_output(genes_output, database_obj, prodigal_obj, mmseqs2_obj):6    marker_annotation_dict = database_obj.get_marker_annotation()7    gene_match_dict = mmseqs2_obj.get_matches()8    taxdb = database_obj.get_taxdb()9    with open(genes_output, "w") as fout:10        fout.write(11            "gene\tstart\tend\tlength\tstrand\tgc_content\tgenetic_code\trbs_motif\t"12            "marker\tevalue\tbitscore\tuscg\tplasmid_hallmark\tvirus_hallmark\ttaxid\t"13            "taxname\tannotation_conjscan\tannotation_accessions\tannotation_description\n"14        )15        for (16            contig,17            gene_num,18            start,19            end,20            strand,21            rbs,22            code,23            gc,24        ) in prodigal_obj.proteins():25            gene = f"{contig}_{gene_num}"26            match, evalue, bitscore, taxid = gene_match_dict.get(27                gene, ("NA", "NA", "NA", 1)28            )29            taxname = taxdb.taxid2name[taxid] if taxid != 1 else "NA"30            (31                uscg,32                plasmid_hallmark,33                virus_hallmark,34                conjscan,35                accession,36                description,37            ) = marker_annotation_dict.get(match, (0, 0, 0, "NA", "NA", "NA"))38            gene_length = end - start + 139            fout.write(40                f"{gene}\t{start}\t{end}\t{gene_length}\t{strand}\t{gc:.3f}\t{code}\t"41                f"{rbs}\t{match}\t{evalue}\t{bitscore}\t{uscg}\t{plasmid_hallmark}\t"42                f"{virus_hallmark}\t{taxid}\t{taxname}\t{conjscan}\t{accession}\t{description}\n"43            )44def main(45    input_path,46    output_path,47    database_path,48    use_minimal_db,49    restart,50    threads,51    verbose,52    sensitivity,53    evalue,54    splits,55    cleanup,56):57    # Create `output_path` if it does not exist58    if not output_path.is_dir():59        output_path.mkdir()60    # Define the prefix and the output files61    prefix = input_path.stem62    if utils.is_compressed(input_path) != utils.Compression.uncompressed:63        prefix = prefix.rsplit(".", 1)[0]64    outputs = GenomadOutputs(prefix, output_path)65    # Create the console66    console = utils.HybridConsole(output_file=outputs.annotate_log, verbose=verbose)67    # Create a dictionary containing the parameters68    parameter_dict = {69        "use_minimal_db": use_minimal_db,70        "sensitivity": sensitivity,71        "evalue": evalue,72    }73    # Display the module header74    utils.display_header(75        console,76        "annotate",77        (78            "This will perform gene calling in the input sequences and "79            "annotate the predicted proteins with geNomad's markers."80        ),81        outputs.annotate_dir,82        [83            outputs.annotate_execution_info,84            outputs.annotate_genes_output,85            outputs.annotate_taxonomy_output,86            outputs.annotate_mmseqs2_output,87            outputs.annotate_proteins_output,88        ],89        [90            "execution parameters",91            "gene annotation data",92            "taxonomic assignment",93            "MMseqs2 output file",94            "protein FASTA file",95        ],96    )97    # Check if the required binaries are in the PATH98    required_executables = ["mmseqs", "prodigal-gv"]99    if missing_executables := utils.check_executables(required_executables):100        console.error(101            "These dependencies are missing and need to be installed: [u]"102            + "[/u], [u]".join(missing_executables)103            + "[/u]. The current execution will be terminated."104        )105        sys.exit(1)106    # Check the input FASTA file107    if not sequence.check_fasta(input_path):108        console.error(109            f"[u]{input_path}[/u] is either empty or contains multiple entries "110            "with the same identifier. Please check your input FASTA file and "111            "execute [cyan]genomad annotate[/cyan] again."112        )113        sys.exit(1)114    # Print initial log115    console.log("Executing [cyan]genomad annotate[/cyan].")116    # Check if steps can be skipped117    skip = False118    if (119        outputs.annotate_execution_info.exists()120        and any(121            [122                outputs.annotate_proteins_output.exists(),123                outputs.annotate_genes_output.exists(),124            ]125        )126        and not restart127    ):128        # Check if the previous execution used the same input file and parameters129        if utils.compare_executions(130            input_path, parameter_dict, outputs.annotate_execution_info131        ):132            skip = True133            console.log(134                "Previous execution detected. Steps will be skipped "135                "unless their outputs are not found. Use the [cyan]"136                "--restart[/cyan] option to force the execution of all "137                "the steps again."138            )139        else:140            console.log(141                "The input file or the parameters changed since the last "142                "execution. Previous outputs will be overwritten."143            )144    # If necessary, create the subdirectory145    if not outputs.annotate_dir.is_dir():146        console.log(f"Creating the [green]{outputs.annotate_dir}[/green] directory.")147        outputs.annotate_dir.mkdir()148    # Write the execution data to `execution_info_output`149    utils.write_execution_info(150        "annotate", input_path, parameter_dict, outputs.annotate_execution_info151    )152    # Initialize the database object153    database_obj = database.Database(database_path)154    # Run prodigal-gv155    prodigal_obj = prodigal.Prodigal(input_path, outputs.annotate_proteins_output)156    if skip and outputs.annotate_proteins_output.exists():157        console.log(158            f"[green]{outputs.annotate_proteins_output.name}[/green] was found. "159            "Skipping gene prediction with prodigal-gv."160        )161    else:162        with console.status("Predicting proteins with prodigal-gv."):163            prodigal_obj.run_parallel_prodigal(threads)164            console.log(165                "Proteins predicted with prodigal-gv were written to "166                f"[green]{outputs.annotate_proteins_output.name}[/green]."167            )168    # Run MMseqs2169    mmseqs2_obj = mmseqs2.MMseqs2(170        outputs.annotate_mmseqs2_output,171        outputs.annotate_mmseqs2_dir,172        outputs.annotate_proteins_output,173        database_obj,174        use_minimal_db=use_minimal_db,175    )176    if skip and outputs.annotate_mmseqs2_output.exists():177        console.log(178            f"[green]{outputs.annotate_mmseqs2_output.name}[/green] was found. "179            "Skipping protein annotation with MMseqs2."180        )181    else:182        with console.status(183            "Annotating proteins with MMseqs2 and geNomad database "184            f"(v{database_obj.version})."185        ):186            mmseqs2_obj.run_mmseqs2(threads, sensitivity, evalue, splits)187            console.log(188                "Proteins annotated with MMseqs2 and geNomad database "189                f"(v{database_obj.version}) were written to "190                f"[green]{outputs.annotate_mmseqs2_output.name}[/green]."191            )192    if cleanup and outputs.annotate_mmseqs2_dir.is_dir():193        console.log(f"Deleting [green]{outputs.annotate_mmseqs2_dir.name}[/green].")194        shutil.rmtree(outputs.annotate_mmseqs2_dir)195    # Write `annotate_genes_output`196    with console.status(197        f"Writing [green]{outputs.annotate_genes_output.name}[/green]."198    ):199        write_genes_output(200            outputs.annotate_genes_output, database_obj, prodigal_obj, mmseqs2_obj201        )202        console.log(203            f"Gene data was written to [green]{outputs.annotate_genes_output.name}[/green]."204        )205    # Write `annotate_taxonomy_output`206    with console.status(207        f"Writing [green]{outputs.annotate_taxonomy_output.name}[/green]."208    ):209        taxonomy.write_taxonomic_assignment(210            outputs.annotate_taxonomy_output,211            outputs.annotate_genes_output,212            database_obj,213        )214        console.log(215            f"Taxonomic assignment data was written to [green]{outputs.annotate_taxonomy_output.name}[/green]."216        )...minesweeper_test.py
Source:minesweeper_test.py  
2from minesweeper import annotate3# Tests adapted from `problem-specifications//canonical-data.json`4class MinesweeperTest(unittest.TestCase):5    def test_no_rows(self):6        self.assertEqual(annotate([]), [])7    def test_no_columns(self):8        self.assertEqual(annotate([""]), [""])9    def test_no_mines(self):10        self.assertEqual(annotate(["   ", "   ", "   "]), ["   ", "   ", "   "])11    def test_minefield_with_only_mines(self):12        self.assertEqual(annotate(["***", "***", "***"]), ["***", "***", "***"])13    def test_mine_surrounded_by_spaces(self):14        self.assertEqual(annotate(["   ", " * ", "   "]), ["111", "1*1", "111"])15    def test_space_surrounded_by_mines(self):16        self.assertEqual(annotate(["***", "* *", "***"]), ["***", "*8*", "***"])17    def test_horizontal_line(self):18        self.assertEqual(annotate([" * * "]), ["1*2*1"])19    def test_horizontal_line_mines_at_edges(self):20        self.assertEqual(annotate(["*   *"]), ["*1 1*"])21    def test_vertical_line(self):22        self.assertEqual(annotate([" ", "*", " ", "*", " "]), ["1", "*", "2", "*", "1"])23    def test_vertical_line_mines_at_edges(self):24        self.assertEqual(annotate(["*", " ", " ", " ", "*"]), ["*", "1", " ", "1", "*"])25    def test_cross(self):26        self.assertEqual(27            annotate(["  *  ", "  *  ", "*****", "  *  ", "  *  "]),28            [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "],29        )30    def test_large_minefield(self):31        self.assertEqual(32            annotate([" *  * ", "  *   ", "    * ", "   * *", " *  * ", "      "]),33            ["1*22*1", "12*322", " 123*2", "112*4*", "1*22*2", "111111"],34        )35    # Additional tests for this track36    def test_annotate_9(self):37        self.assertEqual(38            annotate(["     ", "   * ", "     ", "     ", " *   "]),39            ["  111", "  1*1", "  111", "111  ", "1*1  "],40        )41    def test_different_len(self):42        with self.assertRaisesWithMessage(ValueError):43            annotate([" ", "*  ", "  "])44    def test_invalid_char(self):45        with self.assertRaisesWithMessage(ValueError):46            annotate(["X  * "])47    # Utility functions48    def assertRaisesWithMessage(self, exception):49        return self.assertRaisesRegex(exception, r".+")50if __name__ == "__main__":...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
