1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
|
#########################################################################
# MacSyFinder - Detection of macromolecular systems in protein dataset #
# using systems modelling and similarity search. #
# Authors: Sophie Abby, Bertrand Neron #
# Copyright (c) 2014-2024 Institut Pasteur (Paris) and CNRS. #
# See the COPYRIGHT file for details #
# #
# This file is part of MacSyFinder package. #
# #
# MacSyFinder is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# MacSyFinder is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details . #
# #
# You should have received a copy of the GNU General Public License #
# along with MacSyFinder (COPYING). #
# If not, see <https://www.gnu.org/licenses/>. #
#########################################################################
import os
import unittest
import shutil
import tempfile
import sysconfig
import argparse
from macsypy.profile import Profile
from macsypy.gene import CoreGene, ModelGene
from macsypy.model import Model
from macsypy.profile import ProfileFactory
from macsypy.config import Config, MacsyDefaults
from macsypy.registries import ModelLocation
from macsypy.error import MacsypyError
from tests import MacsyTest
class TestProfile(MacsyTest):
def setUp(self):
args = argparse.Namespace()
args.sequence_db = self.find_data("base", "test_1.fasta")
args.db_type = 'gembase'
args.models_dir = self.find_data('models')
args.res_search_dir = tempfile.gettempdir()
args.log_level = 50
self.cfg = Config(MacsyDefaults(), args)
if os.path.exists(self.cfg.working_dir()):
shutil.rmtree(self.cfg.working_dir())
os.makedirs(self.cfg.working_dir())
self.model_name = 'foo'
self.model_location = ModelLocation(path=os.path.join(args.models_dir, self.model_name))
self.profile_factory = ProfileFactory(self.cfg)
def tearDown(self):
try:
shutil.rmtree(self.cfg.working_dir())
except Exception:
pass
def test_len(self):
model = Model("functional/T12SS-simple-exch", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile("abc")
profile = Profile(gene, self.cfg, path)
self.assertEqual(len(profile), 501)
###########################
# test compressed profile #
###########################
model = Model("functional_gzip/T12SS-simple-exch", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
profile = Profile(gene, self.cfg, path)
self.assertEqual(len(profile), 501)
model = Model("foo/compressed_profile", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
for ext in 'bz2', 'zip':
with self.subTest(ext=ext):
path = self.find_data('models', 'foo', 'profiles', f'{ext}.hmm.{ext}')
with self.catch_log(log_name='macsypy'):
with self.assertRaises(MacsypyError) as ctx:
Profile(gene, self.cfg, path)
self.assertEqual(str(ctx.exception),
f"Cannot read profile {path}: MacSyFinder does not support '{ext}' compression "
f"(only gzip).")
###################
# unreadable gzip #
###################
path = self.find_data('models', 'foo', 'profiles', 'bad_ext.hmm.gz')
with self.catch_log(log_name='macsypy'):
with self.assertRaises(MacsypyError) as ctx:
Profile(gene, self.cfg, path)
self.assertEqual(str(ctx.exception),
f"Cannot read profile {path}: Not a gzipped file (b'BZ')"
)
def test_ga_threshold(self):
# No GA threshold
model = Model("foo/T2SS", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
profile = Profile(gene, self.cfg, path)
self.assertFalse(profile.ga_threshold)
model = Model("foo/T2SS", 10)
# GA threshold line ends with ;
gene_name = 'T5aSS_PF03797'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
profile = Profile(gene, self.cfg, path)
self.assertTrue(profile.ga_threshold)
# GA threshold line do NOT ends with ;
gene_name = 'PF05930.13'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
profile = Profile(gene, self.cfg, path)
self.assertTrue(profile.ga_threshold)
# GA threshold invalid format string instead float
gene_name = 'bad_GA'
with self.catch_log(log_name='macsypy'):
# When a CoreGene is created a Profile is automatically instanciated
# So I mute the log to do not polute output
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
with self.catch_log(log_name='macsypy') as log:
profile = Profile(gene, self.cfg, path)
catch_msg = log.get_value().strip()
self.assertFalse(profile.ga_threshold)
self.assertEqual(catch_msg,
"bad_GA GA score is not well formatted expected 2 floats got ''22.00'' ''23.00''.\n"
"GA score will not used for gene 'bad_GA'.")
# GA threshold invalid format only one score
gene_name = 'bad_GA_2'
with self.catch_log(log_name='macsypy'):
# When a CoreGene is created a Profile is automatically instanciated
# So I mute the log to do not polute output
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile(gene_name)
with self.catch_log(log_name='macsypy') as log:
profile = Profile(gene, self.cfg, path)
catch_msg = log.get_value().strip()
self.assertFalse(profile.ga_threshold)
self.assertEqual(catch_msg,
"bad_GA_2 GA score is not well formatted. expected: 'GA float float' got 'GA 22.00'.\n"
"GA score will not used for gene 'bad_GA_2'.")
def test_str(self):
model = Model("foo/T2SS", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile("abc")
profile = Profile(gene, self.cfg, path)
s = "{0} : {1}".format(gene.name, path)
self.assertEqual(str(profile), s)
#@unittest.skipIf(not shutil.which('hmmsearch'), 'hmmsearch not found in PATH')
@unittest.skip("For some reason this fails to find hmmer_results - skipping")
def test_execute_hmm_with_GA(self):
for db_type in ("gembase", "ordered_replicon", "unordered"):
self.cfg._set_db_type(db_type)
model = Model("foo/T2SS", 10)
gene_name = 'T5aSS_PF03797'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
# case GA threshold in profile
profile_path = self.model_location.get_profile("T5aSS_PF03797")
profile = Profile(gene, self.cfg, profile_path)
report = profile.execute()
hmmer_raw_out = profile.hmm_raw_output
with open(hmmer_raw_out, 'r') as hmmer_raw_out_file:
first_l = hmmer_raw_out_file.readline()
# a hmmsearch output file has been produced
self.assertTrue(first_l.startswith("# hmmsearch :: search profile(s) against a sequence database"))
for _ in range(5):
# skip 4 lines
line = hmmer_raw_out_file.readline()
# a hmmsearch used the abc profile line should become with: "# query HMM file: {the path tp hmm profile used}"
self.assertTrue(line.find(profile_path) != -1)
for _ in range(3):
# skip 2 lines
line = hmmer_raw_out_file.readline()
self.assertEqual("# model-specific thresholding: GA cutoffs", line.strip())
# test if profile is executed only once per run
report_bis = profile.execute()
self.assertIs(report, report_bis)
@unittest.skipIf(not shutil.which('hmmsearch'), 'hmmsearch not found in PATH')
def test_execute_hmm_protected_path(self):
# create a hmmdir with space in name
self.cfg.hmmer_dir = lambda: 'hmmer results'
# create sequence_db path with space in path
seq_path = os.path.join(self.cfg.working_dir(), "test test1.fasta")
shutil.copyfile(self.find_data("base", "test_1.fasta"),
seq_path)
self.cfg._set_sequence_db(seq_path)
model = Model("foo/T2SS", 10)
gene_name = 'T5aSS_PF03797'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
# case GA threshold in profile
profile_path = self.model_location.get_profile("T5aSS_PF03797")
profile = Profile(gene, self.cfg, profile_path)
profile.execute()
hmmer_raw_out = profile.hmm_raw_output
with open(hmmer_raw_out, 'r') as hmmer_raw_out_file:
first_l = hmmer_raw_out_file.readline()
# a hmmsearch output file has been produced
self.assertTrue(first_l.startswith("# hmmsearch :: search profile(s) against a sequence database"))
for _ in range(5):
# skip 4 lines
line = hmmer_raw_out_file.readline()
# a hmmsearch used the abc profile line should become with: "# query HMM file: {the path tp hmm profile used}"
self.assertTrue(line.find(profile_path) != -1)
for _ in range(3):
# skip 2 lines
line = hmmer_raw_out_file.readline()
self.assertEqual("# model-specific thresholding: GA cutoffs", line.strip())
@unittest.skipIf(not shutil.which('hmmsearch'), 'hmmsearch not found in PATH')
def test_execute_hmm_w_GA_n_nocutga(self):
# case GA threshold in profile but --no-cut-ga is set
args = argparse.Namespace()
args.sequence_db = self.find_data("base", "test_1.fasta")
args.db_type = 'gembase'
args.models_dir = self.find_data('models')
args.res_search_dir = tempfile.gettempdir()
args.log_level = 0
args.e_value_search = 0.5
args.no_cut_ga = True
cfg = Config(MacsyDefaults(), args)
model = Model("foo/T2SS", 10)
gene_name = 'T5aSS_PF03797'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
profile_path = self.model_location.get_profile("T5aSS_PF03797")
profile = Profile(gene, cfg, profile_path)
profile.execute()
hmmer_raw_out = profile.hmm_raw_output
with open(hmmer_raw_out, 'r') as hmmer_raw_out_file:
for i in range(9):
line = hmmer_raw_out_file.readline()
self.assertEqual("# sequence reporting threshold: E-value <= 0.5", line.strip())
@unittest.skipIf(not shutil.which('hmmsearch'), 'hmmsearch not found in PATH')
def test_execute_hmm_wo_GA(self):
# case cut-ga but no GA threshold in hmmprofile
model = Model("foo/T2SS", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
# case -cut-ga and GA threshold in profile
profile_path = self.model_location.get_profile("abc")
profile = Profile(gene, self.cfg, profile_path)
with self.catch_log():
profile.execute()
hmmer_raw_out = profile.hmm_raw_output
with open(hmmer_raw_out, 'r') as hmmer_raw_out_file:
first_l = hmmer_raw_out_file.readline()
# a hmmsearch output file has been produced
self.assertTrue(first_l.startswith("# hmmsearch :: search profile(s) against a sequence database"))
for _ in range(5):
# skip 4 lines
line = hmmer_raw_out_file.readline()
# a hmmsearch used the abc profile line should become with: "# query HMM file: {the path tp hmm profile used}"
self.assertTrue(line.find(profile_path) != -1)
for _ in range(3):
# skip 2 lines
line = hmmer_raw_out_file.readline()
self.assertEqual('# sequence reporting threshold: E-value <= 0.1', line.strip())
def test_execute_unknown_binary(self):
self.cfg._options['hmmer'] = "Nimportnaoik"
model = Model("foo/T2SS", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile("abc", )
profile = Profile(gene, self.cfg, path)
with self.catch_log():
with self.assertRaises(RuntimeError):
profile.execute()
def test_execute_hmmer_failed(self):
fake_hmmer = os.path.join(tempfile.gettempdir(), 'hmmer_failed')
with open(fake_hmmer, 'w') as hmmer:
hmmer.write("""#! {}
import sys
sys.exit(127)
""".format(sysconfig.sys.executable))
try:
os.chmod(hmmer.name, 0o755)
self.cfg._options['hmmer'] = hmmer.name
model = Model("foo/T2SS", 10)
gene_name = 'abc'
c_gene = CoreGene(self.model_location, gene_name, self.profile_factory)
gene = ModelGene(c_gene, model)
path = self.model_location.get_profile("abc", )
profile = Profile(gene, self.cfg, path)
with self.catch_log():
with self.assertRaisesRegex(RuntimeError,
"an error occurred during Hmmer "
"execution: command = .* : return code = 127 .*"):
profile.execute()
finally:
try:
os.unlink(fake_hmmer)
except Exception:
pass
|