136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233 | class Locus:
def __init__(self, name: str = None, seq: Seq | None = Seq(''), genes: dict[str: Gene] = None,
type_label: str = None, phenotypes: list[tuple[set[tuple[str, str]], str]] = None,
index: int | None = 0):
self.name = name or ''
self.seq = seq
self._length = len(self.seq)
self.genes = genes or {}
self.type_label = type_label or ''
self.phenotypes = phenotypes or []
self.index = index
@classmethod
def from_seqrecord(cls, record: SeqRecord, locus_name: str, type_name: str, load_seq: bool = True,
extract_translations: bool = False):
if load_seq:
self = cls(name=locus_name, seq=record.seq)
else:
self = cls(name=locus_name)
self._length = len(record.seq) # We are not loading the sequence, so we need to set the length manually
n = 1
for feature in record.features: # type: SeqFeature
if feature.type == 'CDS':
name = f"{locus_name}_{str(n).zfill(2)}" + (
f"_{gene_name}" if (gene_name := feature.qualifiers.get('gene', [''])[0]) else '')
gene = Gene(
name=name, gene_name=gene_name, dna_seq=feature.extract(record.seq), start=feature.location.start,
end=feature.location.end, strand='+' if feature.location.strand == 1 else '-',
product=feature.qualifiers.get('product', [''])[0]
)
if not len(gene.dna_seq) % 3 == 0: # Check the gene is a multiple of 3 (complete CDS)
# TODO: this is quite strict, but enforces the inclusion of complete CDS in Kaptive databases
raise GeneError(f'DNA sequence of {name} is not a multiple of 3')
if name in self.genes:
raise LocusError(f'Gene {name} already exists in locus {self}')
if extract_translations: # Force translation of the gene
gene.extract_translation()
self.genes[name] = gene
n += 1
self.type_label = type_name if not self.name.startswith('Extra_genes') else None # Extra genes don't have a type
return self
def __hash__(self): # TODO: Check if this is used at all
return hash(self.name) # The name of the locus is unique and immutable
def __repr__(self):
return self.name
def __len__(self):
return self._length or len(self.seq)
def __getitem__(self, item) -> Gene:
if not (result := self.genes.get(item)):
raise LocusError(f'Could not find {item} in locus {self.name}')
return result
def __iter__(self):
return iter(self.genes.values())
def add_phenotype(self, genes: dict[str, str] | None, extra_genes: set[tuple[str, str]] | None, phenotype: str,
strict: bool = False):
if extra_genes:
self.phenotypes = sorted(self.phenotypes + [(extra_genes, phenotype)], key=lambda x: len(x[0]),
reverse=True)
else: # Turn gene names into a set of tuples with the gene name and state
genes = {(g.name, state) for g in self if
(state := genes.get('ALL', genes.get(g.gene_name, genes.get(g.name, None))))}
if genes:
self.phenotypes = sorted(self.phenotypes + [(genes, phenotype)], key=lambda x: len(x[0]), reverse=True)
elif strict: # If strict, raise an error
raise PhenotypeError(f"Phenotype ({phenotype}) based on ({genes}) does not apply to {self}")
def format(self, format_spec):
if format_spec == 'fna':
if len(self.seq) == 0:
warning(f'No DNA sequence for {self}')
return ""
return f'>{self.name}\n{self.seq}\n'
if format_spec in {'ffn', 'faa'}:
return ''.join([gene.format(format_spec) for gene in self])
raise ValueError(f'Invalid format specifier: {format_spec}')
def write(self, fna: str | PathLike | TextIO = None, ffn: str | PathLike | TextIO = None,
faa: str | PathLike | TextIO = None):
"""Write the typing result to files or file handles."""
for f, fmt in [(fna, 'fna'), (ffn, 'ffn'), (faa, 'faa')]:
if f:
if isinstance(f, TextIOBase):
f.write(self.format(fmt))
elif isinstance(f, PathLike) or isinstance(f, str):
with open(path.join(f, f'{self.name.replace("/", "_")}.{fmt}'), 'wt') as handle:
handle.write(self.format(fmt))
|