megobin 0.1.0__py3-none-any.whl
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.
- megobin/__init__.py +24 -0
- megobin/_protocol_check.py +59 -0
- megobin/binners/__init__.py +0 -0
- megobin/binners/base.py +31 -0
- megobin/binners/semibin_2.py +347 -0
- megobin/configs/binner/dbscan_ensemble.yaml +8 -0
- megobin/configs/binner/dbscan_ensemble_semibin.yaml +14 -0
- megobin/configs/dataset/example.yaml +10 -0
- megobin/configs/encoder/semibin2.yaml +9 -0
- megobin/configs/encoder/uncertain_gen.yaml +5 -0
- megobin/configs/evaluate.yaml +6 -0
- megobin/configs/evaluator/checkm2.yaml +6 -0
- megobin/configs/experiment/semibin2_longread.yaml +39 -0
- megobin/configs/experiment/uncertain_gen_dbscan.yaml +36 -0
- megobin/configs/features/canonical_kmer.yaml +8 -0
- megobin/configs/features/canonical_kmer_abundance.yaml +10 -0
- megobin/configs/filter/no_op.yaml +1 -0
- megobin/configs/filter/uncertainty.yaml +3 -0
- megobin/configs/logger/mlflow.yaml +10 -0
- megobin/configs/logger/none.yaml +1 -0
- megobin/configs/logger/tensorboard.yaml +7 -0
- megobin/configs/logger/wandb.yaml +13 -0
- megobin/configs/loss/hinge.yaml +2 -0
- megobin/configs/loss/mahalanobis_bce.yaml +4 -0
- megobin/configs/optimizer/adam.yaml +5 -0
- megobin/configs/optimizer/adamw.yaml +5 -0
- megobin/configs/optimizer/sgd.yaml +5 -0
- megobin/configs/pair_sampler/semibin2.yaml +9 -0
- megobin/configs/pair_sampler/uncertain_gen.yaml +3 -0
- megobin/configs/pipeline/bin_raw_features.yaml +19 -0
- megobin/configs/pipeline/embed_and_bin.yaml +37 -0
- megobin/configs/scheduler/constant.yaml +4 -0
- megobin/configs/scheduler/cosine.yaml +4 -0
- megobin/configs/scheduler/step_lr.yaml +4 -0
- megobin/configs/trainer/single_phase.yaml +23 -0
- megobin/configs/trainer/two_phase.yaml +53 -0
- megobin/contracts.py +221 -0
- megobin/data/__init__.py +0 -0
- megobin/data/base.py +31 -0
- megobin/data/semibin2_sampler.py +92 -0
- megobin/data/uncertain_gen_sampler.py +73 -0
- megobin/encoders/__init__.py +0 -0
- megobin/encoders/base.py +66 -0
- megobin/encoders/semibin_2.py +128 -0
- megobin/encoders/uncertaingen.py +140 -0
- megobin/evaluate.py +57 -0
- megobin/evaluators/__init__.py +0 -0
- megobin/evaluators/base.py +11 -0
- megobin/evaluators/checkm2.py +109 -0
- megobin/features/__init__.py +0 -0
- megobin/features/feature_merge.py +446 -0
- megobin/features/generate_abundance.py +295 -0
- megobin/features/generate_kmers.py +58 -0
- megobin/features/run_features.py +82 -0
- megobin/features/views.py +122 -0
- megobin/filters/__init__.py +0 -0
- megobin/filters/base.py +19 -0
- megobin/filters/no_op.py +20 -0
- megobin/filters/uncertainty.py +59 -0
- megobin/losses/__init__.py +0 -0
- megobin/losses/base.py +26 -0
- megobin/losses/hinge_contrastive.py +38 -0
- megobin/losses/mahalanobis_bce.py +49 -0
- megobin/manifest.py +92 -0
- megobin/pipeline.py +261 -0
- megobin/ports.py +123 -0
- megobin/refiners/__init__.py +0 -0
- megobin/refiners/base.py +29 -0
- megobin/refiners/no_op.py +14 -0
- megobin/stages/__init__.py +0 -0
- megobin/stages/binner.py +56 -0
- megobin/stages/embedder.py +165 -0
- megobin/stages/features.py +101 -0
- megobin/stages/filter.py +49 -0
- megobin/stages/refiner.py +35 -0
- megobin/status.py +57 -0
- megobin/testrun.py +237 -0
- megobin/trainers/__init__.py +0 -0
- megobin/trainers/base.py +23 -0
- megobin/trainers/single_phase.py +177 -0
- megobin/trainers/two_phase.py +204 -0
- megobin/utils/SemiBin_utils.py +656 -0
- megobin/utils/__init__.py +0 -0
- megobin/utils/atomicwrite.py +223 -0
- megobin/utils/checkpoints.py +37 -0
- megobin/utils/external.py +133 -0
- megobin/utils/fasta.py +67 -0
- megobin/utils/logger.py +27 -0
- megobin/utils/marker.hmm +105657 -0
- megobin/utils/markers.py +240 -0
- megobin/utils/mlflow_logger.py +84 -0
- megobin/utils/naive_orffinder.py +143 -0
- megobin/utils/no_op_logger.py +30 -0
- megobin/utils/orffinding.py +139 -0
- megobin/utils/provenance.py +76 -0
- megobin/utils/tensorboard_logger.py +101 -0
- megobin/utils/wandb_logger.py +92 -0
- megobin/z.py +70 -0
- megobin-0.1.0.dist-info/METADATA +204 -0
- megobin-0.1.0.dist-info/RECORD +104 -0
- megobin-0.1.0.dist-info/WHEEL +5 -0
- megobin-0.1.0.dist-info/licenses/LICENSE +21 -0
- megobin-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +78 -0
- megobin-0.1.0.dist-info/top_level.txt +1 -0
megobin/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""MegoBin: a modular research pipeline for metagenomic binning."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
_PACKAGE_DIR = Path(__file__).resolve().parent
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _find_config_dir() -> Path:
|
|
9
|
+
"""The folder with the YAML config groups (``experiment/``, ``binner/``, ...).
|
|
10
|
+
|
|
11
|
+
In the repository the folder is ``configs/`` at the top, and
|
|
12
|
+
``megobin/configs`` is a link to it. The link is what puts the YAML files
|
|
13
|
+
inside a built package, so that ``pip install`` from a wheel or from a git
|
|
14
|
+
address gives a MegoBin that finds its configs without the repository.
|
|
15
|
+
A checkout that could not create the link (git on Windows without symlink
|
|
16
|
+
support) still finds the folder one level up.
|
|
17
|
+
"""
|
|
18
|
+
packaged = _PACKAGE_DIR / "configs"
|
|
19
|
+
if packaged.is_dir():
|
|
20
|
+
return packaged.resolve()
|
|
21
|
+
return _PACKAGE_DIR.parent / "configs"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
CONFIG_DIR: Path = _find_config_dir()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Static Protocol-conformance assertions.
|
|
2
|
+
|
|
3
|
+
Each assignment forces mypy to verify, structurally, that the concrete
|
|
4
|
+
class satisfies the Protocol. A class that drops or renames a Protocol
|
|
5
|
+
method fails mypy here — the CI gate catches it instead of a runtime
|
|
6
|
+
``AttributeError`` 20 minutes into training.
|
|
7
|
+
|
|
8
|
+
This module is import-only for the type checker. It is not executed
|
|
9
|
+
in production code paths and has no runtime effect beyond the imports
|
|
10
|
+
themselves.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from megobin.binners.base import Binner
|
|
14
|
+
from megobin.binners.semibin_2 import DBSCANEnsembleBinner
|
|
15
|
+
from megobin.data.base import PairSampler
|
|
16
|
+
from megobin.data.semibin2_sampler import SemiBin2PairSampler
|
|
17
|
+
from megobin.data.uncertain_gen_sampler import UncertainGenPairSampler
|
|
18
|
+
from megobin.encoders.base import Encoder
|
|
19
|
+
from megobin.encoders.semibin_2 import SemiBin2Encoder
|
|
20
|
+
from megobin.encoders.uncertaingen import UncertainGenEncoder
|
|
21
|
+
from megobin.evaluators.base import Evaluator
|
|
22
|
+
from megobin.evaluators.checkm2 import CheckM2Evaluator
|
|
23
|
+
from megobin.filters.base import Filter
|
|
24
|
+
from megobin.filters.no_op import NoOpFilter
|
|
25
|
+
from megobin.filters.uncertainty import UncertaintyFilter
|
|
26
|
+
from megobin.losses.base import ContrastiveLoss
|
|
27
|
+
from megobin.losses.hinge_contrastive import HingeContrastiveLoss
|
|
28
|
+
from megobin.losses.mahalanobis_bce import MahalanobisBCELoss
|
|
29
|
+
from megobin.refiners.base import Refiner
|
|
30
|
+
from megobin.refiners.no_op import IdentityRefiner
|
|
31
|
+
from megobin.trainers.base import Trainer
|
|
32
|
+
from megobin.trainers.single_phase import SinglePhaseTrainer
|
|
33
|
+
from megobin.trainers.two_phase import TwoPhaseTrainer
|
|
34
|
+
from megobin.utils.logger import Logger
|
|
35
|
+
from megobin.utils.mlflow_logger import MLflowLogger
|
|
36
|
+
from megobin.utils.no_op_logger import NoOpLogger
|
|
37
|
+
from megobin.utils.tensorboard_logger import TensorBoardLogger
|
|
38
|
+
from megobin.utils.wandb_logger import WandbLogger
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _encoder_inst() -> Encoder:
|
|
42
|
+
return UncertainGenEncoder(input_dim=1, hidden_dim=1, embedding_dim=1)
|
|
43
|
+
def _encoder_semibin_inst() -> Encoder:
|
|
44
|
+
return SemiBin2Encoder(input_dim=1, kmer_dim=1, hidden_dim=1, output_dim=1)
|
|
45
|
+
_loss_hinge: type[ContrastiveLoss] = HingeContrastiveLoss
|
|
46
|
+
_loss_mahalanobis: type[ContrastiveLoss] = MahalanobisBCELoss
|
|
47
|
+
_binner: type[Binner] = DBSCANEnsembleBinner
|
|
48
|
+
_evaluator: type[Evaluator] = CheckM2Evaluator
|
|
49
|
+
_sampler: type[PairSampler] = UncertainGenPairSampler
|
|
50
|
+
_sampler_semibin: type[PairSampler] = SemiBin2PairSampler
|
|
51
|
+
_filter_noop: type[Filter] = NoOpFilter
|
|
52
|
+
_filter_uncertainty: type[Filter] = UncertaintyFilter
|
|
53
|
+
_trainer_single: type[Trainer] = SinglePhaseTrainer
|
|
54
|
+
_trainer_two: type[Trainer] = TwoPhaseTrainer
|
|
55
|
+
_logger_noop: type[Logger] = NoOpLogger
|
|
56
|
+
_logger_tensorboard: type[Logger] = TensorBoardLogger
|
|
57
|
+
_logger_mlflow: type[Logger] = MLflowLogger
|
|
58
|
+
_logger_wandb: type[Logger] = WandbLogger
|
|
59
|
+
_refiner_identity: type[Refiner] = IdentityRefiner
|
|
File without changes
|
megobin/binners/base.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from typing import Protocol, runtime_checkable
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@runtime_checkable
|
|
8
|
+
class Binner(Protocol):
|
|
9
|
+
@property
|
|
10
|
+
def needs(self) -> Mapping[str, frozenset[str]]:
|
|
11
|
+
"""Inputs by port: ``{"z_kept": {"mu"}, "contigs": {"fasta"}, ...}``."""
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
@property
|
|
15
|
+
def provides(self) -> Mapping[str, frozenset[str]]:
|
|
16
|
+
"""Outputs by port: ``{"bins": {"one_label_per_contig"}}``."""
|
|
17
|
+
...
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def embedding(self) -> tuple[str, str]:
|
|
21
|
+
"""Which array is clustered: ``(port, label)``."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def bindings(self) -> Mapping[str, str]:
|
|
26
|
+
"""Constructor kwargs -> named runtime values handed over by the binner
|
|
27
|
+
stage (``contig_fasta``, ``contig_names``, ``contig_lengths``,
|
|
28
|
+
``markers_dir``, plus any other input port by name)."""
|
|
29
|
+
...
|
|
30
|
+
|
|
31
|
+
def cluster(self, embeddings: np.ndarray) -> np.ndarray: ...
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
# This module has been adapted from SemiBin's DBSCAN ensemble binning flow:
|
|
2
|
+
# https://github.com/BigDataBiology/SemiBin/blob/main/SemiBin/long_read_cluster.py
|
|
3
|
+
# https://github.com/BigDataBiology/SemiBin/blob/main/SemiBin/utils.py
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import warnings
|
|
9
|
+
from collections import defaultdict
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from sklearn.cluster import dbscan
|
|
13
|
+
from sklearn.exceptions import EfficiencyWarning
|
|
14
|
+
from sklearn.neighbors import kneighbors_graph
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class DBSCANEnsembleBinner:
|
|
18
|
+
needs = {
|
|
19
|
+
"z_kept": frozenset({"mu"}),
|
|
20
|
+
"contigs": frozenset({"fasta"}),
|
|
21
|
+
}
|
|
22
|
+
provides = {"bins": frozenset({"one_label_per_contig"})}
|
|
23
|
+
embedding = ("z_kept", "mu")
|
|
24
|
+
bindings = {
|
|
25
|
+
"contig_fasta": "contig_fasta",
|
|
26
|
+
"contig_names": "contig_names",
|
|
27
|
+
"contig_lengths": "contig_lengths",
|
|
28
|
+
"output_dir": "markers_dir",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
eps_values=(
|
|
34
|
+
0.01,
|
|
35
|
+
0.05,
|
|
36
|
+
0.1,
|
|
37
|
+
0.15,
|
|
38
|
+
0.2,
|
|
39
|
+
0.25,
|
|
40
|
+
0.3,
|
|
41
|
+
0.35,
|
|
42
|
+
0.4,
|
|
43
|
+
0.45,
|
|
44
|
+
0.5,
|
|
45
|
+
0.55,
|
|
46
|
+
),
|
|
47
|
+
min_samples: int = 5,
|
|
48
|
+
min_bin_size: int = 1,
|
|
49
|
+
minfasta: int = 0,
|
|
50
|
+
k_neighbours: int = 200,
|
|
51
|
+
n_jobs: int = -1,
|
|
52
|
+
n_total_markers: int = 107,
|
|
53
|
+
contig_fasta=None,
|
|
54
|
+
contig_names=None,
|
|
55
|
+
contig_lengths=None,
|
|
56
|
+
contig_to_marker=None,
|
|
57
|
+
output_dir=None,
|
|
58
|
+
min_contig_len=None,
|
|
59
|
+
num_process: int = 0,
|
|
60
|
+
orf_finder: str = "fast-naive",
|
|
61
|
+
prodigal_output_faa=None,
|
|
62
|
+
):
|
|
63
|
+
self.eps_values = list(eps_values)
|
|
64
|
+
self.min_samples = min_samples
|
|
65
|
+
self.min_bin_size = min_bin_size
|
|
66
|
+
self.minfasta = minfasta
|
|
67
|
+
self.k_neighbours = k_neighbours
|
|
68
|
+
self.n_jobs = n_jobs
|
|
69
|
+
self.n_total_markers = n_total_markers
|
|
70
|
+
|
|
71
|
+
self.contig_fasta = None if contig_fasta is None else os.fspath(contig_fasta)
|
|
72
|
+
self.contig_names = None if contig_names is None else np.asarray(contig_names)
|
|
73
|
+
self.contig_lengths = (
|
|
74
|
+
None if contig_lengths is None else np.asarray(contig_lengths)
|
|
75
|
+
)
|
|
76
|
+
self.contig_to_marker = contig_to_marker
|
|
77
|
+
self.output_dir = None if output_dir is None else os.fspath(output_dir)
|
|
78
|
+
self.min_contig_len = min_contig_len
|
|
79
|
+
self.num_process = num_process
|
|
80
|
+
self.orf_finder = orf_finder
|
|
81
|
+
self.prodigal_output_faa = prodigal_output_faa
|
|
82
|
+
|
|
83
|
+
self._logger = logging.getLogger(__name__)
|
|
84
|
+
self._marker_per_row_cache: list[list[str]] | None = None
|
|
85
|
+
|
|
86
|
+
@staticmethod
|
|
87
|
+
def programs_for(config) -> list[str]:
|
|
88
|
+
"""Outside programs a binner built from *config* will start.
|
|
89
|
+
|
|
90
|
+
Marker genes come from ``hmmsearch`` unless the caller hands over a
|
|
91
|
+
ready ``contig_to_marker`` table.
|
|
92
|
+
"""
|
|
93
|
+
if config.get("contig_to_marker") is not None:
|
|
94
|
+
return []
|
|
95
|
+
programs = ["hmmsearch"]
|
|
96
|
+
if (
|
|
97
|
+
config.get("orf_finder", "fast-naive") == "prodigal"
|
|
98
|
+
and config.get("prodigal_output_faa") is None
|
|
99
|
+
):
|
|
100
|
+
programs.append("prodigal")
|
|
101
|
+
return programs
|
|
102
|
+
|
|
103
|
+
def _workers(self) -> int:
|
|
104
|
+
"""Processes for the marker step. 0 means all CPUs, as in SemiBin."""
|
|
105
|
+
if self.num_process and self.num_process > 0:
|
|
106
|
+
return int(self.num_process)
|
|
107
|
+
return os.cpu_count() or 1
|
|
108
|
+
|
|
109
|
+
def _resolve_markers(self, n_rows: int) -> list[list[str]]:
|
|
110
|
+
"""Return a list of marker-id lists, one per embedding row.
|
|
111
|
+
|
|
112
|
+
Cached on the instance after the first call so the (potentially
|
|
113
|
+
expensive) HMM step runs at most once per binner.
|
|
114
|
+
"""
|
|
115
|
+
if self._marker_per_row_cache is not None:
|
|
116
|
+
return self._marker_per_row_cache
|
|
117
|
+
|
|
118
|
+
if self.contig_to_marker is not None:
|
|
119
|
+
if self.contig_names is None:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
"DBSCANEnsembleBinner: `contig_names` is required when "
|
|
122
|
+
"`contig_to_marker` is supplied so the dict can be "
|
|
123
|
+
"aligned to embedding rows."
|
|
124
|
+
)
|
|
125
|
+
if len(self.contig_names) != n_rows:
|
|
126
|
+
raise ValueError(
|
|
127
|
+
f"DBSCANEnsembleBinner: contig_names length "
|
|
128
|
+
f"({len(self.contig_names)}) does not match the number "
|
|
129
|
+
f"of embedding rows ({n_rows})."
|
|
130
|
+
)
|
|
131
|
+
per_row = [
|
|
132
|
+
list(self.contig_to_marker.get(str(name), []))
|
|
133
|
+
for name in self.contig_names
|
|
134
|
+
]
|
|
135
|
+
elif self.contig_fasta is not None:
|
|
136
|
+
per_row = self._call_markers_from_fasta(n_rows)
|
|
137
|
+
else:
|
|
138
|
+
raise ValueError(
|
|
139
|
+
"DBSCANEnsembleBinner needs either `contig_to_marker` or "
|
|
140
|
+
"`contig_fasta` (with `contig_names`) at construction time."
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
self._marker_per_row_cache = per_row
|
|
144
|
+
return per_row
|
|
145
|
+
|
|
146
|
+
def _call_markers_from_fasta(self, n_rows: int) -> list[list[str]]:
|
|
147
|
+
from megobin.utils.markers import estimate_seeds, get_marker
|
|
148
|
+
from megobin.utils.SemiBin_utils import load_fasta
|
|
149
|
+
|
|
150
|
+
if self.contig_names is None:
|
|
151
|
+
raise ValueError(
|
|
152
|
+
"DBSCANEnsembleBinner: `contig_names` is required alongside "
|
|
153
|
+
"`contig_fasta` to align markers with embedding rows."
|
|
154
|
+
)
|
|
155
|
+
if len(self.contig_names) != n_rows:
|
|
156
|
+
raise ValueError(
|
|
157
|
+
f"DBSCANEnsembleBinner: contig_names length "
|
|
158
|
+
f"({len(self.contig_names)}) does not match the number "
|
|
159
|
+
f"of embedding rows ({n_rows})."
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
if self.min_contig_len is None:
|
|
163
|
+
assert self.contig_fasta is not None
|
|
164
|
+
computed_min, _, _ = load_fasta(self.contig_fasta, ratio=0.05)
|
|
165
|
+
binned_length = computed_min
|
|
166
|
+
else:
|
|
167
|
+
binned_length = self.min_contig_len
|
|
168
|
+
|
|
169
|
+
out = self.output_dir
|
|
170
|
+
if out is not None:
|
|
171
|
+
os.makedirs(out, exist_ok=True)
|
|
172
|
+
|
|
173
|
+
with tempfile.TemporaryDirectory() as tdir:
|
|
174
|
+
target = out if out is not None else tdir
|
|
175
|
+
estimate_seeds(
|
|
176
|
+
self.contig_fasta,
|
|
177
|
+
binned_length,
|
|
178
|
+
self._workers(),
|
|
179
|
+
output=target,
|
|
180
|
+
orf_finder=self.orf_finder,
|
|
181
|
+
prodigal_output_faa=self.prodigal_output_faa,
|
|
182
|
+
)
|
|
183
|
+
c2m = get_marker(
|
|
184
|
+
os.path.join(target, "markers.hmmout"),
|
|
185
|
+
fasta_path=self.contig_fasta,
|
|
186
|
+
min_contig_len=binned_length,
|
|
187
|
+
orf_finder=self.orf_finder,
|
|
188
|
+
contig_to_marker=True,
|
|
189
|
+
)
|
|
190
|
+
# get_marker returns [] (not a dict) when no marker hits were found;
|
|
191
|
+
# treat that as "no markers" so binning degrades gracefully instead
|
|
192
|
+
# of raising AttributeError on the .get() below.
|
|
193
|
+
if not isinstance(c2m, dict):
|
|
194
|
+
c2m = {}
|
|
195
|
+
return [list(c2m.get(str(name), [])) for name in self.contig_names]
|
|
196
|
+
|
|
197
|
+
def _dbscan_sweep(self, embeddings: np.ndarray) -> list[np.ndarray]:
|
|
198
|
+
n = embeddings.shape[0]
|
|
199
|
+
k = min(self.k_neighbours, max(n - 1, 1))
|
|
200
|
+
dist_matrix = kneighbors_graph(
|
|
201
|
+
embeddings,
|
|
202
|
+
n_neighbors=k,
|
|
203
|
+
mode="distance",
|
|
204
|
+
p=2,
|
|
205
|
+
n_jobs=self.n_jobs,
|
|
206
|
+
)
|
|
207
|
+
sample_weight = (
|
|
208
|
+
self.contig_lengths.astype(float)
|
|
209
|
+
if self.contig_lengths is not None
|
|
210
|
+
else None
|
|
211
|
+
)
|
|
212
|
+
results = []
|
|
213
|
+
# `kneighbors_graph` already orders each row's neighbours by distance,
|
|
214
|
+
# but DBSCAN's precomputed path copies the matrix and calls `setdiag`
|
|
215
|
+
# to add self-distances, which undoes the sort. sklearn then sorts
|
|
216
|
+
# again itself (correctly) and warns once per eps value. Sorting here
|
|
217
|
+
# would not help, since `setdiag` runs afterwards, so this one harmless
|
|
218
|
+
# warning is silenced around the sweep.
|
|
219
|
+
with warnings.catch_warnings():
|
|
220
|
+
warnings.filterwarnings(
|
|
221
|
+
"ignore",
|
|
222
|
+
message="Precomputed sparse input was not sorted by row values",
|
|
223
|
+
category=EfficiencyWarning,
|
|
224
|
+
)
|
|
225
|
+
for eps in self.eps_values:
|
|
226
|
+
_, labels = dbscan(
|
|
227
|
+
dist_matrix,
|
|
228
|
+
eps=eps,
|
|
229
|
+
min_samples=self.min_samples,
|
|
230
|
+
n_jobs=self.n_jobs,
|
|
231
|
+
metric="precomputed",
|
|
232
|
+
sample_weight=sample_weight,
|
|
233
|
+
)
|
|
234
|
+
results.append(np.asarray(labels))
|
|
235
|
+
return results
|
|
236
|
+
|
|
237
|
+
def _select_best_bin(
|
|
238
|
+
self,
|
|
239
|
+
results: list[np.ndarray],
|
|
240
|
+
marker_per_row: list[list[str]],
|
|
241
|
+
weights: np.ndarray,
|
|
242
|
+
) -> list[int] | None:
|
|
243
|
+
for max_contamination in (0.1, 0.2, 0.3, 0.4, 0.5, 1.0):
|
|
244
|
+
max_f1 = 0.0
|
|
245
|
+
weight_of_max = float("inf")
|
|
246
|
+
best_bin: list[int] | None = None
|
|
247
|
+
for labels in results:
|
|
248
|
+
clusters: dict[int, list[int]] = defaultdict(list)
|
|
249
|
+
for row, label in enumerate(labels):
|
|
250
|
+
if label != -1:
|
|
251
|
+
clusters[int(label)].append(row)
|
|
252
|
+
for rows in clusters.values():
|
|
253
|
+
if len(rows) < self.min_bin_size:
|
|
254
|
+
continue
|
|
255
|
+
cluster_weight = float(sum(weights[r] for r in rows))
|
|
256
|
+
if self.minfasta > 0 and cluster_weight < self.minfasta:
|
|
257
|
+
continue
|
|
258
|
+
markers: list[str] = []
|
|
259
|
+
for r in rows:
|
|
260
|
+
markers.extend(marker_per_row[r])
|
|
261
|
+
if not markers:
|
|
262
|
+
continue
|
|
263
|
+
unique = set(markers)
|
|
264
|
+
recall = len(unique) / self.n_total_markers
|
|
265
|
+
contamination = (len(markers) - len(unique)) / len(markers)
|
|
266
|
+
if contamination > max_contamination:
|
|
267
|
+
continue
|
|
268
|
+
denom = recall + (1 - contamination)
|
|
269
|
+
if denom <= 0:
|
|
270
|
+
continue
|
|
271
|
+
f1 = 2 * recall * (1 - contamination) / denom
|
|
272
|
+
if f1 > max_f1 or (
|
|
273
|
+
f1 == max_f1 and cluster_weight <= weight_of_max
|
|
274
|
+
):
|
|
275
|
+
max_f1 = f1
|
|
276
|
+
weight_of_max = cluster_weight
|
|
277
|
+
best_bin = list(rows)
|
|
278
|
+
if max_f1 > 0 and best_bin is not None:
|
|
279
|
+
return best_bin
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
def cluster(self, embeddings: np.ndarray) -> np.ndarray:
|
|
283
|
+
embeddings = np.asarray(embeddings)
|
|
284
|
+
n = embeddings.shape[0]
|
|
285
|
+
if n == 0:
|
|
286
|
+
return np.zeros(0, dtype=np.int64)
|
|
287
|
+
if n == 1:
|
|
288
|
+
return np.zeros(1, dtype=np.int64)
|
|
289
|
+
|
|
290
|
+
if self.minfasta > 0 and self.contig_lengths is None:
|
|
291
|
+
raise ValueError(
|
|
292
|
+
"DBSCANEnsembleBinner: minfasta > 0 requires contig_lengths "
|
|
293
|
+
"(base-pair weights) so bins can be sized in bp."
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
marker_per_row = self._resolve_markers(n)
|
|
297
|
+
weights = (
|
|
298
|
+
self.contig_lengths.astype(float)
|
|
299
|
+
if self.contig_lengths is not None
|
|
300
|
+
else np.ones(n, dtype=float)
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
sweep = self._dbscan_sweep(embeddings)
|
|
304
|
+
|
|
305
|
+
active = list(range(n))
|
|
306
|
+
extracted: list[list[int]] = []
|
|
307
|
+
while active:
|
|
308
|
+
if self.minfasta > 0 and sum(weights[r] for r in active) < self.minfasta:
|
|
309
|
+
break
|
|
310
|
+
if len(active) == 1:
|
|
311
|
+
extracted.append(list(active))
|
|
312
|
+
break
|
|
313
|
+
local_marker = [marker_per_row[r] for r in active]
|
|
314
|
+
local_weights = np.array([weights[r] for r in active])
|
|
315
|
+
local_sweep = [
|
|
316
|
+
np.array([sweep_eps[r] for r in active]) for sweep_eps in sweep
|
|
317
|
+
]
|
|
318
|
+
best_local = self._select_best_bin(local_sweep, local_marker, local_weights)
|
|
319
|
+
if best_local is None:
|
|
320
|
+
break
|
|
321
|
+
best_global = [active[i] for i in best_local]
|
|
322
|
+
extracted.append(best_global)
|
|
323
|
+
best_set = set(best_global)
|
|
324
|
+
active = [r for r in active if r not in best_set]
|
|
325
|
+
|
|
326
|
+
labels = np.full(n, -1, dtype=np.int64)
|
|
327
|
+
if self.minfasta > 0:
|
|
328
|
+
# SemiBin-faithful: drop sub-minfasta bins; leftovers stay -1.
|
|
329
|
+
bin_id = 0
|
|
330
|
+
for rows in extracted:
|
|
331
|
+
if sum(weights[r] for r in rows) < self.minfasta:
|
|
332
|
+
continue
|
|
333
|
+
for r in rows:
|
|
334
|
+
labels[r] = bin_id
|
|
335
|
+
bin_id += 1
|
|
336
|
+
return labels
|
|
337
|
+
|
|
338
|
+
# Backward-compatible default: each leftover contig becomes a singleton.
|
|
339
|
+
for bin_id, rows in enumerate(extracted):
|
|
340
|
+
for r in rows:
|
|
341
|
+
labels[r] = bin_id
|
|
342
|
+
next_id = len(extracted)
|
|
343
|
+
for r in range(n):
|
|
344
|
+
if labels[r] == -1:
|
|
345
|
+
labels[r] = next_id
|
|
346
|
+
next_id += 1
|
|
347
|
+
return labels
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
_target_: megobin.binners.semibin_2.DBSCANEnsembleBinner
|
|
2
|
+
eps_values: [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55]
|
|
3
|
+
min_samples: 5
|
|
4
|
+
min_bin_size: 1
|
|
5
|
+
k_neighbours: 200
|
|
6
|
+
n_total_markers: 107
|
|
7
|
+
orf_finder: fast-naive
|
|
8
|
+
num_process: 0 # processes for the marker step; 0: all CPUs (as in SemiBin)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SemiBin-faithful long-read variant of the DBSCAN ensemble binner:
|
|
2
|
+
# minfasta > 0 activates SemiBin's bp-based bin sizing — sub-minfasta
|
|
3
|
+
# clusters are never extracted, the greedy loop stops once the remaining
|
|
4
|
+
# contigs total < minfasta bp, and leftover contigs are labelled -1
|
|
5
|
+
# (dropped by the pipeline, mirroring SemiBin's write_bins(minfasta=...)).
|
|
6
|
+
_target_: megobin.binners.semibin_2.DBSCANEnsembleBinner
|
|
7
|
+
eps_values: [0.01, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55]
|
|
8
|
+
min_samples: 5
|
|
9
|
+
min_bin_size: 1
|
|
10
|
+
minfasta: 200000
|
|
11
|
+
k_neighbours: 200
|
|
12
|
+
n_total_markers: 107
|
|
13
|
+
orf_finder: fast-naive
|
|
14
|
+
num_process: 1 # marker ORF-finding workers; override e.g. binner.num_process=8
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Placeholder dataset config — copy and edit for your own data.
|
|
2
|
+
#
|
|
3
|
+
# `signals` enumerates what's available on disk; feature configs declare
|
|
4
|
+
# what they need (`required_signals`), and pipeline.py fails fast on a
|
|
5
|
+
# mismatch.
|
|
6
|
+
|
|
7
|
+
name: example
|
|
8
|
+
path: data/example/
|
|
9
|
+
signals: [kmers, abundance]
|
|
10
|
+
num_bams: 1
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
_target_: megobin.encoders.semibin_2.SemiBin2Encoder
|
|
2
|
+
# Single-sample long-read defaults. For combined mode (>=5 BAMs) set
|
|
3
|
+
# is_combined: true and input_dim: 136 + n_sample (abundance enters the net).
|
|
4
|
+
input_dim: 136 # network input width (136 single; 136 + n_sample combined)
|
|
5
|
+
kmer_dim: 136 # k-mer block width (split point for the depth concat)
|
|
6
|
+
hidden_dim: 512
|
|
7
|
+
output_dim: 100 # SemiBin embedding dimension
|
|
8
|
+
dropout: 0.2
|
|
9
|
+
is_combined: false
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
_target_: megobin.evaluators.checkm2.CheckM2Evaluator
|
|
2
|
+
threads: 1
|
|
3
|
+
extra_args: []
|
|
4
|
+
# How to start CheckM2. Default: the `checkm2` on PATH. A list runs it through a
|
|
5
|
+
# launcher, e.g. [pixi, run, -e, checkm2, checkm2] (what `pixi run evaluate` sets).
|
|
6
|
+
command: checkm2
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# @package _global_
|
|
2
|
+
#
|
|
3
|
+
# SemiBin2 single-sample long-read path (self-supervised).
|
|
4
|
+
# Shape: features -> embedder (SemiBin2PairSampler + SemiBin2Encoder + hinge
|
|
5
|
+
# loss + single-phase trainer) -> filter (no-op) -> DBSCAN ensemble binner.
|
|
6
|
+
# Scoring is not part of the run: python -m megobin.evaluate bins_dir=<run>/bins
|
|
7
|
+
|
|
8
|
+
defaults:
|
|
9
|
+
- /dataset: example
|
|
10
|
+
- /pipeline: embed_and_bin
|
|
11
|
+
- /features: canonical_kmer_abundance
|
|
12
|
+
- /encoder: semibin2
|
|
13
|
+
- /loss: hinge
|
|
14
|
+
- /pair_sampler: semibin2
|
|
15
|
+
- /trainer: single_phase
|
|
16
|
+
- /filter: no_op
|
|
17
|
+
- /binner: dbscan_ensemble_semibin
|
|
18
|
+
- /logger: tensorboard
|
|
19
|
+
- _self_
|
|
20
|
+
|
|
21
|
+
seed: 42
|
|
22
|
+
# Path to an encoder.pt of an earlier run: skip training and load these
|
|
23
|
+
# weights ("train once, bin many", see docs/05-experiment-tracking/checkpoints.md).
|
|
24
|
+
resume_from: null
|
|
25
|
+
|
|
26
|
+
pipeline:
|
|
27
|
+
name: semibin2_longread
|
|
28
|
+
target: bins
|
|
29
|
+
interventions: []
|
|
30
|
+
|
|
31
|
+
trainer:
|
|
32
|
+
epochs: 15 # SemiBin2 self-supervised long-read default
|
|
33
|
+
drop_last: true # SemiBin2 drops the trailing partial batch
|
|
34
|
+
|
|
35
|
+
encoder:
|
|
36
|
+
input_dim: 136
|
|
37
|
+
kmer_dim: 136
|
|
38
|
+
output_dim: 100
|
|
39
|
+
is_combined: false
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# @package _global_
|
|
2
|
+
#
|
|
3
|
+
# UncertainGen: mean-then-covariance training, DBSCAN ensemble binner.
|
|
4
|
+
# Shape: features -> embedder (UncertainGenPairSampler + UncertainGenEncoder +
|
|
5
|
+
# Mahalanobis BCE + two-phase trainer) -> filter (no-op) -> DBSCAN ensemble.
|
|
6
|
+
# Phase 1 trains `mean` with a loss that needs z.mu only; phase 2 trains `cov`
|
|
7
|
+
# with a loss that needs z.var (see configs/trainer/two_phase.yaml).
|
|
8
|
+
# Scoring is not part of the run: python -m megobin.evaluate bins_dir=<run>/bins
|
|
9
|
+
|
|
10
|
+
defaults:
|
|
11
|
+
- /dataset: example
|
|
12
|
+
- /pipeline: embed_and_bin
|
|
13
|
+
- /features: canonical_kmer_abundance
|
|
14
|
+
- /encoder: uncertain_gen
|
|
15
|
+
- /loss: mahalanobis_bce
|
|
16
|
+
- /pair_sampler: uncertain_gen
|
|
17
|
+
- /trainer: two_phase
|
|
18
|
+
- /filter: no_op
|
|
19
|
+
- /binner: dbscan_ensemble
|
|
20
|
+
- /logger: tensorboard
|
|
21
|
+
- _self_
|
|
22
|
+
|
|
23
|
+
seed: 42
|
|
24
|
+
# Path to an encoder.pt of an earlier run: skip training and load these
|
|
25
|
+
# weights ("train once, bin many", see docs/05-experiment-tracking/checkpoints.md).
|
|
26
|
+
resume_from: null
|
|
27
|
+
use_abundance: true
|
|
28
|
+
|
|
29
|
+
pipeline:
|
|
30
|
+
name: uncertain_gen_dbscan
|
|
31
|
+
target: bins
|
|
32
|
+
interventions: []
|
|
33
|
+
|
|
34
|
+
encoder:
|
|
35
|
+
input_dim: 136
|
|
36
|
+
embedding_dim: 256
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
_target_: megobin.filters.no_op.NoOpFilter
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Optional: needs the package `mlflow` (pixi: the `tracking` environment;
|
|
2
|
+
# pip: pip install -e ".[mlflow]"). See docs/05-experiment-tracking/choosing-a-tracker.md.
|
|
3
|
+
_target_: megobin.utils.mlflow_logger.MLflowLogger
|
|
4
|
+
# Where runs are stored. Default: a file mlflow.db in the folder you start
|
|
5
|
+
# MegoBin from, unless the variable MLFLOW_TRACKING_URI is set. For a tracking
|
|
6
|
+
# server put its address here, e.g. http://my-server:5000.
|
|
7
|
+
tracking_uri: ${oc.env:MLFLOW_TRACKING_URI,sqlite:///mlflow.db}
|
|
8
|
+
experiment: megobin # runs are grouped by experiment in the MLflow UI
|
|
9
|
+
run_name: null # null: MLflow invents a name
|
|
10
|
+
tags: null # e.g. {hypothesis: H1}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
_target_: megobin.utils.no_op_logger.NoOpLogger
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
_target_: megobin.utils.tensorboard_logger.TensorBoardLogger
|
|
2
|
+
# logdir inherits Hydra's per-run output dir so each experiment gets
|
|
3
|
+
# its own event file. Override to point at a shared location for
|
|
4
|
+
# cross-run comparison, e.g. tb_root/{hypothesis_id}/{run_name}.
|
|
5
|
+
logdir: ${hydra:runtime.output_dir}/tb
|
|
6
|
+
name: null # defaults to the logdir's basename
|
|
7
|
+
flush_secs: 30
|