alg-painter 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.3
2
+ Name: alg-painter
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Author: DLBPointon
6
+ Author-email: DLBPointon <damonlbp@hotmail.co.uk>
7
+ Requires-Dist: argparse>=1.4.0
8
+ Requires-Dist: logging>=0.4.9.6
9
+ Requires-Dist: matplotlib>=3.10.8
10
+ Requires-Dist: pandas>=3.0.2
11
+ Requires-Dist: pathlib>=1.0.1
12
+ Requires-Dist: requests>=2.33.1
13
+ Requires-Python: >=3.12
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ALG_painter
17
+
18
+ This replaces the original sanger-tol/busco_painter scripts.
19
+
20
+ A Python package for the plotting and painting of ALG units to busco results resulting in a ALG assignment plot.
21
+
22
+ Currently, this is rather specific to the Merian Units assigned by Charlotte Wright based on odb10 output.
23
+
24
+ This package contains 3 subcommands:
25
+ - painter - A re-write of the original script (by Charlotte Wright), by Karen van Neikerk, for the paining of ALG's onto busco full table.tsv files. This can optionally call the NCBI API
26
+ - plotter - A python re-write of the original R script written by Charlotte Wright.
27
+ - plotter_2 - A re-write originally intended for GenomeNote production, so includes specific colour palettes and other logic.
28
+
29
+ ## Installation
30
+
31
+ ```
32
+ git clone github.com/sanger-tol/alg_painter.git
33
+
34
+ cd alg_painter/
35
+
36
+ uv pip install ./
37
+
38
+ alg -h
39
+ ```
40
+
41
+ ![ALG_painter_v2 plot](src/tests/data/alg_plotter_v2.png)
@@ -0,0 +1,26 @@
1
+ # ALG_painter
2
+
3
+ This replaces the original sanger-tol/busco_painter scripts.
4
+
5
+ A Python package for the plotting and painting of ALG units to busco results resulting in a ALG assignment plot.
6
+
7
+ Currently, this is rather specific to the Merian Units assigned by Charlotte Wright based on odb10 output.
8
+
9
+ This package contains 3 subcommands:
10
+ - painter - A re-write of the original script (by Charlotte Wright), by Karen van Neikerk, for the paining of ALG's onto busco full table.tsv files. This can optionally call the NCBI API
11
+ - plotter - A python re-write of the original R script written by Charlotte Wright.
12
+ - plotter_2 - A re-write originally intended for GenomeNote production, so includes specific colour palettes and other logic.
13
+
14
+ ## Installation
15
+
16
+ ```
17
+ git clone github.com/sanger-tol/alg_painter.git
18
+
19
+ cd alg_painter/
20
+
21
+ uv pip install ./
22
+
23
+ alg -h
24
+ ```
25
+
26
+ ![ALG_painter_v2 plot](src/tests/data/alg_plotter_v2.png)
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "alg-painter"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "DLBPointon", email = "damonlbp@hotmail.co.uk" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "argparse>=1.4.0",
12
+ "logging>=0.4.9.6",
13
+ "matplotlib>=3.10.8",
14
+ "pandas>=3.0.2",
15
+ "pathlib>=1.0.1",
16
+ "requests>=2.33.1",
17
+ ]
18
+
19
+ [project.scripts]
20
+ alg = "alg_painter.cli:main"
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.10.7,<0.11.0"]
24
+ build-backend = "uv_build"
@@ -0,0 +1,3 @@
1
+ from alg_painter.cli import main
2
+
3
+ __all__ = ["main"]
@@ -0,0 +1,137 @@
1
+ import csv
2
+ import logging
3
+ from collections import Counter
4
+ from pathlib import Path
5
+
6
+ from alg_painter.generics import write_tsv
7
+ from alg_painter.ncbi_api import (
8
+ chrom_lengths_with_unloc,
9
+ fetch_sequence_report,
10
+ )
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def parse_reference_map(ref_path: Path) -> dict[str, str]:
16
+ """
17
+ Return {BUSCO-ID → ALG element} from the reference full_table.
18
+ """
19
+
20
+ # IF LEPIDOPTERAN... SHOULD THIS SIMPLY BE ALG_Z, ALG_1
21
+ alg_set = {"MZ"} | {f"M{i}" for i in range(1, 32)}
22
+ ref_map: dict[str, str] = {}
23
+ with ref_path.open(newline="") as reference_file:
24
+ reader = csv.reader(reference_file, delimiter="\t")
25
+ for row in reader:
26
+ if (
27
+ not row
28
+ or len(row) < 3
29
+ or row[0].startswith("#")
30
+ or row[0].lower().startswith("busco")
31
+ ):
32
+ continue
33
+ alg_unit = row[2].upper().strip()
34
+ if alg_unit in alg_set:
35
+ ref_map[row[0]] = alg_unit
36
+ return ref_map
37
+
38
+
39
+ def parse_busco_table(path: Path) -> tuple[list[tuple], list[str]]:
40
+ """
41
+ Return list of (busco_id, chr, start, stop) tuples and sorted unique chr list.
42
+ This does not filter out any duplicates
43
+ """
44
+ tbl: list[tuple] = []
45
+ chroms: set[str] = set()
46
+ keep_status = {"Complete", "Duplicated"}
47
+
48
+ with path.open(newline="") as fh:
49
+ reader = csv.reader(fh, delimiter="\t")
50
+ for row in reader:
51
+ if not row or row[0].startswith("#") or len(row) < 5:
52
+ continue
53
+ bid, status, chrom, start, stop = row[:5]
54
+ if status not in keep_status:
55
+ continue
56
+ try:
57
+ start_coord, end_coord = int(start), int(stop)
58
+ except ValueError:
59
+ continue
60
+ tbl.append((bid, chrom, start_coord, end_coord))
61
+ chroms.add(chrom)
62
+ return tbl, sorted(chroms)
63
+
64
+
65
+ def build_location_rows(
66
+ reference_map: dict[str, str], query_table: list[tuple]
67
+ ) -> list[str]:
68
+ rows = ["buscoID\tquery_chr\tposition\tassigned_chr\tstatus"]
69
+ for busco_id, query_chromosome, start, end in query_table:
70
+ position = (start + end) / 2
71
+ assigned = reference_map.get(busco_id, "NA")
72
+ rows.append(
73
+ f"{busco_id}\t{query_chromosome}\t{position}\t{assigned}\t{assigned}"
74
+ )
75
+ return rows
76
+
77
+
78
+ def painting_main(arguments):
79
+ logger.info(f"Running PAINTER with: {arguments}")
80
+
81
+ prefix_location = Path(arguments.prefix)
82
+ logging.info(f"Making sure output dir exists at: {prefix_location}")
83
+ prefix_location.mkdir(parents=True, exist_ok=True)
84
+
85
+ output_file_dict = {
86
+ "all_locs": Path(
87
+ f"{prefix_location}/{arguments.prefix}_all_locations.tsv"
88
+ ),
89
+ "chrom_lengths": Path(
90
+ f"{prefix_location}/{arguments.prefix}_chrom_lengths.tsv"
91
+ ),
92
+ "summary": Path(f"{prefix_location}/{arguments.prefix}_summary.tsv"),
93
+ }
94
+
95
+ # Parse the BUSCO tables into the needed formats
96
+ reference_map = parse_reference_map(arguments.alg_table)
97
+
98
+ query_table, query_chromosomes = parse_busco_table(arguments.query_table)
99
+
100
+ # Build the rows of ALL buscos
101
+ all_busco_data = build_location_rows(reference_map, query_table)
102
+
103
+ # If ACCESSION is given then call the NCBI API to get chromosome lenths
104
+ if arguments.accession:
105
+ logger.info(
106
+ f"[Painter] Fetching sequence report for accession: {arguments.accession}"
107
+ )
108
+ seq_report = fetch_sequence_report(arguments.accession)
109
+ pairs = chrom_lengths_with_unloc(seq_report)
110
+ length_lines = ["Chrom\tLength_Mb"] + [
111
+ f"{chromosome}\t{basepairs / 1e6:.3f}"
112
+ for chromosome, basepairs in pairs
113
+ ]
114
+ write_tsv(length_lines, output_file_dict["chrom_lengths"])
115
+ chrom_order = [c for c, _ in pairs]
116
+ else:
117
+ chrom_order = query_chromosomes.copy()
118
+
119
+ query_chroms_set = {chrom for _, chrom, _, _ in query_table}
120
+ missing = [c for c in chrom_order if c not in query_chroms_set]
121
+ for c in missing:
122
+ all_busco_data.append(f"NA\t{c}\tNA\tNA\tNA")
123
+
124
+ logger.info(f"[Painter] Writing tsv to: {output_file_dict['all_locs']}")
125
+ write_tsv(all_busco_data, output_file_dict["all_locs"])
126
+
127
+ # Optional summary generation
128
+ if arguments.write_summary:
129
+ logger.info(
130
+ f"[Painter] Writing summary to: {output_file_dict['summary']}"
131
+ )
132
+ counts = Counter(chrom for _, chrom, _, _ in query_table)
133
+ counts.update({c: 0 for c in missing})
134
+ sum_lines = ["query_chr\tbusco_hits"] + [
135
+ f"{c}\t{counts[c]}" for c in chrom_order
136
+ ]
137
+ write_tsv(sum_lines, output_file_dict["summary"])