Skip to content

Commit

Permalink
Drop support for Python 3.6, add 3.10
Browse files Browse the repository at this point in the history
Python 3.6 is reaching End Of Life this month.

Also:
- Upgrade syntax to Python 3.7 using
  `ack --type=python -f | xargs pyupgrade --py37-plus`
  • Loading branch information
nsoranzo committed Dec 16, 2021
1 parent 183a9e9 commit 1283016
Show file tree
Hide file tree
Showing 21 changed files with 50 additions and 46 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.6', '3.9']
python-version: ['3.7', '3.10']
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
Expand All @@ -23,7 +23,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ['3.6', '3.7', '3.8', '3.9']
python-version: ['3.7', '3.8', '3.9', '3.10']
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/align/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def set_score(self, score):
def __str__(self):
s = "a score=" + str(self.score)
for key in self.attributes:
s += " {}={}".format(key, self.attributes[key])
s += f" {key}={self.attributes[key]}"
s += "\n"
# Components
for c in self.components:
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/align/epo_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def cch(cigar, s, e):
for s, t, q in zip(S, T, Q):
if not (cch(c1, th, th+s) and cch(c2, th, th+s)):
pdb.set_trace()
assert cch(c1, th, th+s) and cch(c2, th, th+s), "{} and {}".format(c1[th:th+s], c2[th:th+s])
assert cch(c1, th, th+s) and cch(c2, th, th+s), f"{c1[th:th+s]} and {c2[th:th+s]}"
if t > q:
cch(c1, th+s, th+s+t) and c1[th+s:th+s+t] == '-'*t
else:
Expand Down
4 changes: 2 additions & 2 deletions lib/bx/align/maf.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ def __init__(self, file, attributes=None):
for key in attributes:
if key == 'version':
continue
self.file.writelines(" {}={}".format(key, attributes[key]))
self.file.writelines(f" {key}={attributes[key]}")
self.file.write("\n")

def write(self, alignment):
self.file.write("a score=" + str(alignment.score))
for key in alignment.attributes:
self.file.write(" {}={}".format(key, alignment.attributes[key]))
self.file.write(f" {key}={alignment.attributes[key]}")
self.file.write("\n")
# Components
rows = []
Expand Down
12 changes: 8 additions & 4 deletions lib/bx/align/score_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,14 @@ def test_align(self):

def test_accumulate(self):
ss = bx.align.score.hox70
self.assert_(allclose(bx.align.score.accumulate_scores(ss, "-----CTTT", "CTTAGTTTA"),
cumsum(array([-430, -30, -30, -30, -30, -31, 91, 91, -123]))))
self.assert_(allclose(bx.align.score.accumulate_scores(ss, "-----CTTT", "CTTAGTTTA", skip_ref_gaps=True),
cumsum(array([-581, 91, 91, -123]))))
self.assertTrue(allclose(
bx.align.score.accumulate_scores(ss, "-----CTTT", "CTTAGTTTA"),
cumsum(array([-430, -30, -30, -30, -30, -31, 91, 91, -123]))
))
self.assertTrue(allclose(
bx.align.score.accumulate_scores(ss, "-----CTTT", "CTTAGTTTA", skip_ref_gaps=True),
cumsum(array([-581, 91, 91, -123]))
))

def test_nonsymm_scoring(self):
ss = nonsymm_scheme
Expand Down
4 changes: 2 additions & 2 deletions lib/bx/bitset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ def bitset_complement(exons):
bits.invert()

# only complement within the range of the list
ex_start = min([a[0] for a in exons])
ex_end = max([a[1] for a in exons])
ex_start = min(a[0] for a in exons)
ex_end = max(a[1] for a in exons)
end = ex_start
len = ex_end
while True:
Expand Down
8 changes: 4 additions & 4 deletions lib/bx/cookbook/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def add_argument(self, action):
invocations.append(get_invocation(subaction))

# update the maximum item length
invocation_length = max([len(s) for s in invocations])
invocation_length = max(len(s) for s in invocations)
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length,
action_length)
Expand Down Expand Up @@ -1151,7 +1151,7 @@ def __call__(self, string):
def __repr__(self):
args = [self._mode, self._bufsize]
args_str = ', '.join([repr(arg) for arg in args if arg is not None])
return '{}({})'.format(type(self).__name__, args_str)
return f'{type(self).__name__}({args_str})'

# ===========================
# Optional and Positional Parsing
Expand Down Expand Up @@ -1911,10 +1911,10 @@ def consume_positionals(start_index):
while start_index <= max_option_string_index:

# consume any Positionals preceding the next option
next_option_string_index = min([
next_option_string_index = min(
index
for index in option_string_indices
if index >= start_index])
if index >= start_index)
if start_index != next_option_string_index:
positionals_end_index = consume_positionals(start_index)

Expand Down
4 changes: 2 additions & 2 deletions lib/bx/gene_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def CDSReader(fh, format='gff'):
# for gene in genelist.values():
for gene in grouplist:
chrom, strand, cds_exons = genelist[gene]
seqlen = sum([a[1]-a[0] for a in cds_exons])
seqlen = sum(a[1]-a[0] for a in cds_exons)
overhang = seqlen % 3
if overhang > 0:
if strand == '+':
Expand Down Expand Up @@ -288,7 +288,7 @@ def FeatureReader(fh, format='gff', alt_introns_subtract="exons", gtf_parse=None
introns = bitset_union(introns)

# assure CDS is a multiple of 3, trim from last exon if necessary
seqlen = sum([a[1]-a[0] for a in cds_exons])
seqlen = sum(a[1]-a[0] for a in cds_exons)
overhang = seqlen % 3
if overhang > 0:
if strand == '+':
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/intervals/intersection_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def test_empty(self):
def test_public_interval(self):

def fn(ival):
return self.assert_(ival.interval)
return self.assertTrue(ival.interval)

self.iv.traverse(fn)

Expand Down
2 changes: 1 addition & 1 deletion lib/bx/intervals/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def binned_bitsets(self, upstream_pad=0, downstream_pad=0, lens=None):
except ValueError as e:
# We will only reach here when constructing this bitset from the lens dict
# since the value of MAX is always safe.
raise Exception("Invalid chrom length {} in 'lens' dictionary. {}".format(str(size), str(e)))
raise Exception(f"Invalid chrom length {str(size)} in 'lens' dictionary. {str(e)}")
bitsets[chrom] = bbs
last_chrom = chrom
last_bitset = bitsets[chrom]
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/intervals/random_intervals.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def throw_random_intervals(lengths, regions, save_interval_func=None, allow_over
region with start and end modified.
"""
# Copy regions
regions = sorted([(x[1]-x[0], x[0], x) for x in regions])
regions = sorted((x[1]-x[0], x[0], x) for x in regions)
# Sort (long regions first)
regions.reverse()
# Throw
Expand Down
6 changes: 3 additions & 3 deletions lib/bx/phylo/newick.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __eq__(self, other):
return self.__dict__ == other.__dict__

def __repr__(self):
return "Tree( {}, {} )".format(repr(self.label), repr(self.edges))
return f"Tree( {repr(self.label)}, {repr(self.edges)} )"


@total_ordering
Expand All @@ -60,7 +60,7 @@ def __init__(self, length, tip):
self.tip = tip

def pretty(self):
return "Edge( {}, \n{}\n)".format(repr(self.length), indent(repr(self.tip)))
return f"Edge( {repr(self.length)}, \n{indent(repr(self.tip))}\n)"

def __lt__(self, other):
return self.__dict__ < other.__dict__
Expand All @@ -69,7 +69,7 @@ def __eq__(self, other):
return self.__dict__ == other.__dict__

def __repr__(self):
return "Edge( {}, {} )".format(repr(self.length), repr(self.tip))
return f"Edge( {repr(self.length)}, {repr(self.tip)} )"


def create_parser():
Expand Down
2 changes: 1 addition & 1 deletion lib/bx/pwm/maf_select_motifs.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def main():
def mafwrite(alignment, kvec=None, jvec=None, file=sys.stdout):
file.write("a score=" + str(alignment.score))
for key in alignment.attributes:
file.write(" {}={}".format(key, alignment.attributes[key]))
file.write(f" {key}={alignment.attributes[key]}")
file.write("\n")
rows = []
if not kvec:
Expand Down
12 changes: 6 additions & 6 deletions lib/bx/pwm/position_weight_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def __init__(self, id, rows, alphabet, background=None, score_correction=True):
# Reference 2: Gertz et al.: Genome Res. 2005 Aug;15(8):1145-52.
def information_content_calculation(self, i, counts):
# Reference 1)
return 2 + sum([self.information_base_content(base, i, counts) for base in self.alphabet])
return 2 + sum(self.information_base_content(base, i, counts) for base in self.alphabet)

# Reference 2)
# return sum( [ self.information_base_content(base,i,counts) for base in self.alphabet ] )
Expand Down Expand Up @@ -522,8 +522,8 @@ def score_quantum_seq(self, seq):
raw = 0
try:
for i, nt in enumerate(subseq):
numer = sum([subseq[i][nt] * self.probs[i][nt] for nt in subseq[i]])
denom = sum([subseq[i][nt] * self.background[nt] for nt in subseq[i]])
numer = sum(subseq[i][nt] * self.probs[i][nt] for nt in subseq[i])
denom = sum(subseq[i][nt] * self.background[nt] for nt in subseq[i])
raw += math.log(numer/denom, 2)
scaled = self.scaled(raw)
except KeyError:
Expand Down Expand Up @@ -559,7 +559,7 @@ def simple_probability(self, freq, base, i):
# ----------------------
# sum(f(base,{A,C,G,T}))

return float(freq[i][base]) / sum([freq[i][nt] for nt in self.alphabet])
return float(freq[i][base]) / sum(freq[i][nt] for nt in self.alphabet)

def corrected_probability_score(self, freq, base, i):
# p(base,i) = f(base,i) + s(base)
Expand Down Expand Up @@ -812,7 +812,7 @@ def sum_of_squares(x, y=None):
xmean = float(sum(x)) / len(x)
ymean = float(sum(y)) / len(y)
assert len(x) == len(y)
return sum([float(xi)*float(yi) for xi, yi in zip(x, y)]) - len(x)*xmean*ymean
return sum(float(xi)*float(yi) for xi, yi in zip(x, y)) - len(x)*xmean*ymean


def consensus_symbol(pattern):
Expand Down Expand Up @@ -857,7 +857,7 @@ def consensus_symbol(pattern):
if tops[1] > 0.5 and tops[1] >= 2 * tops[0]:
return symbols[f.index(tops[1])]
elif tops[0] < 0.5 and sum(tops) >= 0.75:
degen = frozenset([symbols[f.index(v)] for v in tops])
degen = frozenset(symbols[f.index(v)] for v in tops)
for degenSymbol, wobbles in wobblers.items():
# print >>sys.stderr,wobbles
if degen == wobbles:
Expand Down
6 changes: 3 additions & 3 deletions lib/bx/pwm/pwm_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,16 @@ def testReader(self):
wm = wms[0]
dScores = wm.score_seq(dSeq)
assert len(dScores) == 2
assert "{:.4f} {:.4f} {:.4f} {:.4f}".format(dScores[0][0], dScores[0][1], dScores[1][0], dScores[1][1]) == dScoresExpected
assert f"{dScores[0][0]:.4f} {dScores[0][1]:.4f} {dScores[1][0]:.4f} {dScores[1][1]:.4f}" == dScoresExpected

qdSeq = []
for (ix, nt) in enumerate(dSeq):
qdSeq.append(dict())
qdSeq[ix][nt] = 1.0
qScores = wm.score_seq(qdSeq)
assert len(qScores) == 2
assert "{:.4f} {:.4f} {:.4f} {:.4f}".format(qScores[0][0], qScores[0][1], qScores[1][0], qScores[1][1]) == dScoresExpected
assert f"{qScores[0][0]:.4f} {qScores[0][1]:.4f} {qScores[1][0]:.4f} {qScores[1][1]:.4f}" == dScoresExpected

qScores = wm.score_seq(qSeq)
assert len(qScores) == 1
assert "{:.4f} {:.4f}".format(qScores[0][0], qScores[0][1]) == qScoresExpected
assert f"{qScores[0][0]:.4f} {qScores[0][1]:.4f}" == qScoresExpected
2 changes: 1 addition & 1 deletion lib/bx/seq/seq.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def get(self, start, length):
assert length >= 0, "Length must be non-negative (got %d)" % length
assert start >= 0, "Start must be greater than 0 (got %d)" % start
assert start + length <= self.length, \
"Interval beyond end of sequence ({}..{} > {})".format(start, start + length, self.length)
f"Interval beyond end of sequence ({start}..{start + length} > {self.length})"
# Fetch sequence and reverse complement if necesary
if not self.revcomp:
return self.raw_fetch(start, length)
Expand Down
4 changes: 2 additions & 2 deletions lib/bx/seq/seq_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ def test_get_reader(self):
text = "%s" % seq
fields = text.split()
assert (len(fields) == 2), "SeqReader.__str__ returns incorrect sequence string \"%s\" (%d)" % text
assert (fields[0] == valid2_fa[ix][0]), "FastaReader returned the wrong name ({},{})".format(fields[0], valid2_fa[ix][0])
assert (fields[1] == valid2_fa[ix][1]), "FastaReader returned the wrong text ({},{})".format(fields[1], valid2_fa[ix][1])
assert (fields[0] == valid2_fa[ix][0]), f"FastaReader returned the wrong name ({fields[0]},{valid2_fa[ix][0]})"
assert (fields[1] == valid2_fa[ix][1]), f"FastaReader returned the wrong text ({fields[1]},{valid2_fa[ix][1]})"


def check_get(seqfile, valid_seq, start, len):
Expand Down
10 changes: 5 additions & 5 deletions lib/bx_extras/pyparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def __iadd__(self, other):
return self

def __repr__(self):
return "({}, {})".format(repr(self.__toklist), repr(self.__tokdict))
return f"({repr(self.__toklist)}, {repr(self.__tokdict)})"

def __str__(self):
out = "["
Expand Down Expand Up @@ -1665,7 +1665,7 @@ def charsAsStr(s):
return s

if self.initCharsOrig != self.bodyCharsOrig:
self.strRepr = "W:({},{})".format(charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig))
self.strRepr = f"W:({charsAsStr(self.initCharsOrig)},{charsAsStr(self.bodyCharsOrig)})"
else:
self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)

Expand Down Expand Up @@ -2204,7 +2204,7 @@ def __str__(self):
pass

if self.strRepr is None:
self.strRepr = "{}:({})".format(self.__class__.__name__, str(self.exprs))
self.strRepr = f"{self.__class__.__name__}:({str(self.exprs)})"
return self.strRepr

def streamline(self):
Expand Down Expand Up @@ -2599,7 +2599,7 @@ def __str__(self):
pass

if self.strRepr is None and self.expr is not None:
self.strRepr = "{}:({})".format(self.__class__.__name__, str(self.expr))
self.strRepr = f"{self.__class__.__name__}:({str(self.expr)})"
return self.strRepr


Expand Down Expand Up @@ -3410,7 +3410,7 @@ def pa(s, l, tokens):
if attrName not in tokens:
raise ParseException(s, l, "no matching attribute " + attrName)
if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(s, l, "attribute '{}' has value '{}', must be '{}'".format(attrName, tokens[attrName], attrValue))
raise ParseException(s, l, f"attribute '{attrName}' has value '{tokens[attrName]}', must be '{attrValue}'")
return pa


Expand Down
2 changes: 1 addition & 1 deletion lib/bx_extras/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -3829,7 +3829,7 @@ def asign(a):
Returns: array shape of a, with -1 where a<0 and +1 where a>=0
"""
a = N.asarray(a)
if ((isinstance(a, type(1.4))) or (isinstance(a, type(1)))):
if ((isinstance(a, float)) or (isinstance(a, int))):
return a-a-N.less(a, 0)+N.greater(a, 0)
else:
return N.zeros(N.shape(a))-N.less(a, 0)+N.greater(a, 0)
Expand Down
2 changes: 1 addition & 1 deletion scripts/axt_to_fasta.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def main():
# $$$ this should be moved to a bx.align.fasta module

def print_component_as_fasta(c, id=None):
header = ">{}_{}_{}".format(c.src, c.start, c.start + c.size)
header = f">{c.src}_{c.start}_{c.start + c.size}"
if id is not None:
header += " " + id
print(header)
Expand Down
4 changes: 2 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ classifiers =
License :: OSI Approved :: MIT License
Operating System :: POSIX
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Topic :: Scientific/Engineering :: Bio-Informatics
Topic :: Software Development :: Libraries :: Python Modules
name = bx-python
Expand All @@ -33,7 +33,7 @@ package_dir =
=lib
py_modules =
psyco_full
python_requires = >=3.6
python_requires = >=3.7
zip_safe = False

[options.package_data]
Expand Down

0 comments on commit 1283016

Please sign in to comment.