Skip to content

Commit

Permalink
Fix remaining linter complaints
Browse files Browse the repository at this point in the history
  • Loading branch information
padix-key committed Jul 6, 2024
1 parent fd97901 commit 85eaf61
Show file tree
Hide file tree
Showing 31 changed files with 102 additions and 163 deletions.
2 changes: 1 addition & 1 deletion doc/apidoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# information.

__author__ = "Patrick Kunzmann"
__all__ = ["create_api_doc", "skip_non_methods"]
__all__ = ["create_api_doc", "skip_nonrelevant"]

import enum
import json
Expand Down
2 changes: 1 addition & 1 deletion doc/bibliography.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,6 @@ def format_article(self, param):

return Text(*authors, title, journal, volume, pages, date, doi)

except:
except Exception:
warnings.warn(f"Invalid BibTeX entry '{entry.key}'")
return Text(entry.key)
1 change: 0 additions & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,6 @@
# Do not run example scripts with a trailing '_noexec'
"filename_pattern": "^((?!_noexec).)*$",
"ignore_pattern": r"(.*ignore\.py)|(.*pymol\.py)",
"backreferences_dir": None,
"download_all_examples": False,
# Never report run time
"min_reported_time": sys.maxsize,
Expand Down
36 changes: 18 additions & 18 deletions doc/examples/scripts/sequence/misc/local_alignment_statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@


# The probability density function of the extreme value distribution
def pdf(x, l, u):
t = np.exp(-l * (x - u))
return l * t * np.exp(-t)
def pdf(x, lam, u):
t = np.exp(-lam * (x - u))
return lam * t * np.exp(-t)


x = np.linspace(-5, 10, 1000)
Expand Down Expand Up @@ -240,15 +240,15 @@ def pdf(x, l, u):
# respectively.

# Use method of moments to estimate distribution parameters
l = np.pi / np.sqrt(6 * np.var(sample_scores))
u = np.mean(sample_scores) - np.euler_gamma / l
lam = np.pi / np.sqrt(6 * np.var(sample_scores))
u = np.mean(sample_scores) - np.euler_gamma / lam

# Score frequencies for the histogram
freqs = np.bincount(sample_scores) / SAMPLE_SIZE

# Coordinates for the fit
x = np.linspace(0, len(freqs) - 1, 1000)
y = pdf(x, l, u)
y = pdf(x, lam, u)

fig, ax = plt.subplots(figsize=(8.0, 4.0))
ax.scatter(
Expand Down Expand Up @@ -291,7 +291,7 @@ def pdf(x, l, u):
# The sequence lengths to be sampled
length_samples = np.logspace(*np.log10(LENGTH_RANGE), LENGTH_SAMPLE_SIZE).astype(int)
u_series = np.zeros(LENGTH_SAMPLE_SIZE)
l_series = np.zeros(LENGTH_SAMPLE_SIZE)
lam_series = np.zeros(LENGTH_SAMPLE_SIZE)
for i, length in enumerate(length_samples):
# The same procedure from above
random_sequence_code = np.random.choice(
Expand All @@ -311,8 +311,8 @@ def pdf(x, l, u):
)[0]
scores[j] = sample_alignment.score

l_series[i] = np.pi / np.sqrt(6 * np.var(scores))
u_series[i] = np.mean(scores) - np.euler_gamma / l_series[i]
lam_series[i] = np.pi / np.sqrt(6 * np.var(scores))
u_series[i] = np.mean(scores) - np.euler_gamma / lam_series[i]

########################################################################
# Now we use a linear fit of :math:`u` to check if there is a linear
Expand All @@ -325,8 +325,8 @@ def pdf(x, l, u):

slope, intercept, r, _, _ = linregress(ln_mn, u_series)
# More precise parameter estimation from fit
l = 1 / slope
k = np.exp(intercept * l)
lam = 1 / slope
k = np.exp(intercept * lam)

# Coordinates for fit
x_fit = np.linspace(0, 16, 100)
Expand All @@ -347,12 +347,12 @@ def pdf(x, l, u):
)

ax2 = ax.twinx()
ax2.scatter(ln_mn, l_series, color=biotite.colors["lightgreen"], s=8)
ax2.axhline(l, color=biotite.colors["darkgreen"], linestyle=":")
ax2.scatter(ln_mn, lam_series, color=biotite.colors["lightgreen"], s=8)
ax2.axhline(lam, color=biotite.colors["darkgreen"], linestyle=":")
x_annot = 2
ax2.annotate(
f"λ = {l:.3f}",
xy=(x_annot, l),
f"λ = {lam:.3f}",
xy=(x_annot, lam),
xytext=(0, -50),
textcoords="offset pixels",
arrowprops=arrowprops,
Expand Down Expand Up @@ -438,11 +438,11 @@ def pdf(x, l, u):
DATABASE_SIZE = 1_000_000


def e_value(score, length1, length2, k, l):
return k * length1 * length2 * np.exp(-l * score)
def e_value(score, length1, length2, k, lam):
return k * length1 * length2 * np.exp(-lam * score)


e = e_value(alignment.score, len(query_seq), len(hit_seq) * DATABASE_SIZE, k, l)
e = e_value(alignment.score, len(query_seq), len(hit_seq) * DATABASE_SIZE, k, lam)
print(f"E-value = {e:.2e}")

########################################################################
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import matplotlib.pyplot as plt
import numpy as np
from pylab import polyfit
import biotite
import biotite.structure as struct
import biotite.structure.io.gro as gro
Expand Down Expand Up @@ -83,12 +84,9 @@ def cum_water_in_pore(traj, cutoff=6, key_residues=(507, 511)):


# Linear fitting
from pylab import polyfit

open_fit = polyfit(time, counts[0], 1)
closed_fit = polyfit(time, counts[1], 1)


fig, ax = plt.subplots(figsize=(8.0, 4.0))
ax.plot(time, counts[0], label="open pore", color=biotite.colors["dimgreen"])
ax.plot(
Expand Down
83 changes: 3 additions & 80 deletions doc/examples/scripts/structure/protein/peptide_assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,84 +40,7 @@

# Reference peptide bond atom coordinates taken from 1l2y:
# CA, C, N, O, H
peptide_coord = np.array(
[
[-8.608, 3.135, -1.618],
[-7.117, 2.964, -1.897],
[-6.379, 4.031, -2.228],
[-6.634, 1.849, -1.758],
[-6.821, 4.923, -2.394],
]
)


def create_raw_backbone_coord(number_of_res):
"""
Create coordinates for straight peptide chain in z-plane.
The peptide bonds are in trans configuration.
"""
coord = np.zeros((number_of_res * 3, 3))
for i, angle, angle_direction, length in zip(
range(len(coord)),
itertools.cycle([CA_C_N_ANGLE, C_N_CA_ANGLE, N_CA_C_ANGLE]),
itertools.cycle([1, -1]),
itertools.cycle([C_N_LENGTH, N_CA_LENGTH, CA_C_LENGTH]),
):
if i == 0:
coord[i] = [0, 0, 0]
elif i == 1:
coord[i] = [0, length, 0]
else:
# Rotate about z-axis -> backbone lies in z-plane
rot_axis = [0, 0, angle_direction]
# Calculate the coordinates of a new atoms by rotating the previous
# bond by the given angle
new_coord = struc.rotate_about_axis(
coord[i - 2],
axis=rot_axis,
angle=np.deg2rad(angle),
support=coord[i - 1],
)
# Scale bond to correct bond length
bond_vector = new_coord - coord[i - 1]
coord[i] = coord[i - 1] + bond_vector * length / norm(bond_vector)
return coord


def append_residue(chain, residue):
"""
Append a residue to an existing chain.
Modify annotation arrays and remove atoms as necessary.
The atom coordinates are not altered.
"""
if chain.array_length() == 0:
# Chain is empty
residue.res_id[:] = 1
return residue

last_res_id = chain.res_id[-1]

# Remove atoms removed by peptide bond
chain = chain[
(chain.res_id != last_res_id) | ~np.isin(chain.atom_name, ["OXT", "HXT"])
]
residue = residue[~np.isin(residue.atom_name, ["H2", "H3"])]

# Increment residue ID for attached residue
residue.res_id[:] = last_res_id + 1


C_N_LENGTH = 1.34
N_CA_LENGTH = 1.46
CA_C_LENGTH = 1.54

CA_C_N_ANGLE = 114
C_N_CA_ANGLE = 123
N_CA_C_ANGLE = 110

# Reference peptide bond atom coordinates taken from 1l2y:
# CA, C, N, O, H
peptide_coord = np.array(
PEPTIDE_COORD = np.array(
[
[-8.608, 3.135, -1.618],
[-7.117, 2.964, -1.897],
Expand Down Expand Up @@ -221,9 +144,9 @@ def assemble_peptide(sequence):
for atom_name in ["N", "H"]
]
_, transformation = struc.superimpose(
chain.coord[[ca_i, c_i, n_i]], peptide_coord[:3]
chain.coord[[ca_i, c_i, n_i]], PEPTIDE_COORD[:3]
)
chain.coord[[o_i, h_i]] = transformation.apply(peptide_coord[3:])
chain.coord[[o_i, h_i]] = transformation.apply(PEPTIDE_COORD[3:])
return chain


Expand Down
4 changes: 2 additions & 2 deletions doc/scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def pymol_scraper(block, block_vars, gallery_conf):
)

try:
import ammolite
import pymol
import ammolite # noqa: F401
import pymol # noqa: F401
except ImportError:
# If Ammolite is not installed, fall back to the image file,
# if already existing
Expand Down
2 changes: 1 addition & 1 deletion doc/switcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# information.

__author__ = "Patrick Kunzmann"
__all__ = ["create_api_doc", "skip_non_methods"]
__all__ = ["create_switcher_json"]

import json
import re
Expand Down
19 changes: 8 additions & 11 deletions setup_ccd.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import logging
from dataclasses import dataclass
from io import StringIO
from pathlib import Path
import numpy as np
import requests
from biotite.structure.io.pdbx import *


class ComponentException(Exception):
class ComponentError(Exception):
pass


Expand Down Expand Up @@ -303,14 +304,14 @@ def check_presence(pdbx_file, category_name, column_names):
is_present = column_names[0] in category
for name in column_names:
if (name in category) != is_present:
raise ComponentException("Only some column names are missing")
raise ComponentError("Only some column names are missing")
if not is_present:
return

is_unmasked = category[column_names[0]].mask is None
for name in column_names:
if (category[name].mask is None) != is_unmasked:
raise ComponentException("Only some column names are masked")
raise ComponentError("Only some column names are masked")


def concatenate_blocks_into_category(pdbx_file, category_name, column_infos):
Expand All @@ -337,7 +338,7 @@ def concatenate_blocks_into_category(pdbx_file, category_name, column_infos):
for comp_id, block in pdbx_file.items():
try:
if category_name not in block:
raise ComponentException(f"Block has no category '{category_name}'")
raise ComponentError(f"Block has no category '{category_name}'")
chunk = {}
category = block[category_name]
for col_name, info in column_infos.items():
Expand All @@ -348,17 +349,15 @@ def concatenate_blocks_into_category(pdbx_file, category_name, column_infos):
if info.alternative is not None:
col = category[info.alternative]
if col.mask is not None:
raise ComponentException(
raise ComponentError(
f"Missing values in alternative "
f"'{info.alternative}'"
)
else:
raise ComponentException(
f"Missing values in column '{col_name}'"
)
raise ComponentError(f"Missing values in column '{col_name}'")
data_array = col.as_array(info.dtype, info.fill_value)
chunk[col_name] = data_array
except ComponentException as e:
except ComponentError as e:
logging.warning(f"Skipping '{comp_id}': {e}")
# Append all columns in the chunk after the try-except block
# to avoid appending incomplete chunks
Expand Down Expand Up @@ -472,6 +471,4 @@ def setup_ccd(target_diriectory):
compressed_file.write(target_diriectory / "components.bcif")


from pathlib import Path

setup_ccd(Path(__file__).parent / "src" / "biotite" / "structure" / "info" / "ccd")
2 changes: 1 addition & 1 deletion src/biotite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@

from .copyable import *
from .file import *
from .version import __version__, __version_tuple__
from .version import __version__, __version_tuple__ # noqa: F401
from .visualize import *
3 changes: 2 additions & 1 deletion src/biotite/application/muscle/app3.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import re
import subprocess
import warnings
from collections.abc import Sequence
from tempfile import NamedTemporaryFile
from biotite.application.application import AppState, VersionError, requires_state
from biotite.application.localapp import cleanup_tempfile
Expand Down Expand Up @@ -136,7 +137,7 @@ def set_gap_penalty(self, gap_penalty):
raise ValueError("Gap penalty must be negative")
self._gap_open = gap_penalty
self._gap_ext = gap_penalty
elif type(gap_penalty) == tuple:
elif isinstance(gap_penalty, Sequence):
if gap_penalty[0] > 0 or gap_penalty[1] > 0:
raise ValueError("Gap penalty must be negative")
self._gap_open = gap_penalty[0]
Expand Down
5 changes: 3 additions & 2 deletions src/biotite/sequence/align/alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import numbers
import textwrap
from collections.abc import Sequence
import numpy as np
from biotite.sequence.alphabet import LetterAlphabet

Expand Down Expand Up @@ -519,10 +520,10 @@ def score(alignment, matrix, gap_penalty=-10, terminal_penalty=True):
score += matrix[code_i, code_j]

# Sum gap penalties
if type(gap_penalty) == int:
if isinstance(gap_penalty, numbers.Real):
gap_open = gap_penalty
gap_ext = gap_penalty
elif type(gap_penalty) == tuple:
elif isinstance(gap_penalty, Sequence):
gap_open = gap_penalty[0]
gap_ext = gap_penalty[1]
else:
Expand Down
4 changes: 2 additions & 2 deletions src/biotite/sequence/codon.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,11 @@ def load(table_name):
for line in lines:
if not line:
table_found = False
if type(table_name) == int and line.startswith("id"):
if isinstance(table_name, Integral) and line.startswith("id"):
# remove identifier 'id'
if table_name == int(line[2:]):
table_found = True
elif type(table_name) == str and line.startswith("name"):
elif isinstance(table_name, str) and line.startswith("name"):
# Get list of table names from lines
# (separated with ';')
# remove identifier 'name'
Expand Down
Loading

0 comments on commit 85eaf61

Please sign in to comment.