Skip to content

Commit

Permalink
apply pre-commit changes
Browse files Browse the repository at this point in the history
  • Loading branch information
jfennick committed Mar 27, 2023
1 parent bbb2716 commit 8b7c88b
Show file tree
Hide file tree
Showing 18 changed files with 106 additions and 99 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
"[yaml]": {
"editor.suggest.showWords": false
},
"notebook.output.textLineLimit": 100,
"notebook.output.textLineLimit": 100
}
9 changes: 5 additions & 4 deletions atomselect_demo.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
def main(selection_string, input_pdb_path, output_pdb_path):
from workflow_types import *
# NOTE: No other top-level imports supported


def main(selection_string, input_pdb_path, output_pdb_path): # type: ignore[no-untyped-def]
import mdtraj
traj = mdtraj.load(input_pdb_path)
print(traj)
Expand All @@ -8,9 +12,6 @@ def main(selection_string, input_pdb_path, output_pdb_path):
traj.save(output_pdb_path)


from workflow_types import *
# NOTE: No other top-level imports supported

inputs = {'selection_string': string,
'input_pdb_path': pdbfile,
'output_pdb_path': {**string, 'default': 'selection.pdb'}}
Expand Down
17 changes: 5 additions & 12 deletions auth/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@

from pydantic import BaseSettings

"""
Setup logger
"""
# Setup logger
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger("plots.settings")

"""
Load environment variables
"""


# Load environment variables
class Settings(BaseSettings):
"""Settings for the API.
This defines the required inputs for the environment file.
Expand All @@ -29,7 +24,7 @@ class Settings(BaseSettings):
JWKS_ENDPOINT: Optional[str] = None
OFFLINE_USER: Optional[str] = None

class Config: # NOQA:D106
class Config: # NOQA: D106

env_file = ".env"

Expand All @@ -46,7 +41,7 @@ class Config: # NOQA:D106
+ "Make sure to create a .env file and specify a folder for serving data."
)

""" Define static types """
# Define static types
CLASS_TYPES = ["string"]

SUPPORTED_FORMATS = [".feather", ".arrow", ".csv", ".parquet", ".hdf5"]
Expand All @@ -56,7 +51,5 @@ class Config: # NOQA:D106
CACHED_FILES: Dict[str, Dict[str, Any]] = {}


"""
Reusable Constants
"""
# Reusable Constants
DEFAULT_USER: str = "default_user"
5 changes: 3 additions & 2 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# See https://docs.pytest.org/en/7.1.x/example/simple.html
from typing import Any
import pytest


def pytest_addoption(parser) -> None:
def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption('--cwl_runner', type=str, required=False, default='cwltool', choices=['cwltool', 'toil-cwl-runner'],
help='The CWL runner to use for running workflows locally.')


@pytest.fixture
def cwl_runner(request):
def cwl_runner(request: pytest.FixtureRequest) -> Any:
return request.config.getoption("--cwl_runner")
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# we can use more precise edam formats and thus let CWL catch more errors.
# In other words, the cwl scripts are type-safe wrappers around this script.


def main() -> None:
parser = argparse.ArgumentParser()
required_args = parser.add_argument_group('required arguments')
Expand Down
37 changes: 19 additions & 18 deletions cwl_adapters/yank/yank_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ def check_options(options: Dict[str, Any], args: argparse.Namespace) -> None:
args (argparse.Namespace): The command line arguments.
"""
if 'verbose' not in options:
options['verbose'] = True #'yes'
options['verbose'] = True # 'yes'
if 'resume_setup' not in options:
options['resume_setup'] = True #'yes'
options['resume_setup'] = True # 'yes'
if 'resume_simulation' not in options:
options['resume_simulation'] = True #'yes'
options['resume_simulation'] = True # 'yes'

if options.get('start_from_trailblaze_samples', '') == 'yes':
print('Warning: start_from_trailblaze_samples should always be set to no; setting to no')
options['start_from_trailblaze_samples'] = False #'no' # yes generates NaNs!
options['start_from_trailblaze_samples'] = False # 'no' # yes generates NaNs!

if 'checkpoint_interval' in options and 'switch_phase_interval' in options:
if options['switch_phase_interval'] < 0 or options['checkpoint_interval'] < 0:
Expand Down Expand Up @@ -55,6 +55,7 @@ def check_options(options: Dict[str, Any], args: argparse.Namespace) -> None:
if args.phase in ['setup_only', 'trailblaze', 'equilibration']:
options['default_number_of_iterations'] = 0


def make_molecules_tag(args: argparse.Namespace) -> Dict[str, Any]:
"""Returns the basic tags which describe the molecules in a system.
Expand Down Expand Up @@ -105,7 +106,7 @@ def make_systems_tag_group2(complex_top_filename: str, ligand_top_filename: str,
'phase1_path': [complex_top_filename, args.input_complex_crd_path],
'phase2_path': [ligand_top_filename, args.input_ligand_crd_path],
'ligand_dsl': 'resname MOL',
#'solvent_dsl': 'resname WAT', # optional
# ' solvent_dsl': 'resname WAT', # optional
'solvent': 'spce_50mM_acetate_55',
'gromacs_include_dir': gromacs_include_dir,
}}}
Expand All @@ -130,11 +131,11 @@ def make_experiment_tag(system_name: str = 'system_name') -> Dict[str, Any]:
'temperature': '302.15*kelvin'},
'protocol': 'binding-auto',
}
# Cannot use restraints on 32 bit systems :(
#restraint:
# #type: FlatBottom
# restrained_ligand_atoms: (resname MOL) and (mass > 1.5)
# restrained_receptor_atoms: f'({residue_indices_str}) and (mass > 1.5)'
# Cannot use restraints on 32 bit systems :(
# restraint:
# #type: FlatBottom
# restrained_ligand_atoms: (resname MOL) and (mass > 1.5)
# restrained_receptor_atoms: f'({residue_indices_str}) and (mass > 1.5)'
return exp


Expand All @@ -151,9 +152,9 @@ def unzip_topology_files(zip_path: str) -> str:
with zipfile.ZipFile(zip_path, 'r') as zip_file:
filenames = zip_file.namelist()
# This extracts to a temporary directory which is not writable when using Docker.
#zip_file.extractall(Path(outdir).parent)
# zip_file.extractall(Path(outdir).parent)
# Instead, use unzip which extracts in-place (in the same directory)
cmd = ['unzip', '-n', zip_path] # Use -n to avoid overwriting files.
cmd = ['unzip', '-n', zip_path] # Use -n to avoid overwriting files.
sub.run(cmd, check=True)
top_filenames = [fn for fn in filenames if Path(fn).suffix == '.top']
if len(top_filenames) != 1:
Expand Down Expand Up @@ -216,15 +217,15 @@ def main() -> None:

if group1:
systems_tag = make_systems_tag_group1()
else: # group2
else: # group2
systems_tag = make_systems_tag_group2(complex_top_filename, ligand_top_filename, args)

#yaml_dict['systems'] = {**yaml_dict['systems'], **systems_tag['systems']} # merge?
yaml_dict['systems'] = systems_tag['systems'] # overwrite
# yaml_dict['systems'] = {**yaml_dict['systems'], **systems_tag['systems']} # merge?
yaml_dict['systems'] = systems_tag['systems'] # overwrite

yaml_dict['experiment_name'] = make_experiment_tag()
#yaml_dict['experiments'] = yaml_dict.get('experiments', []).append('experiment_name') # append?
yaml_dict['experiments'] = ['experiment_name'] # overwrite
# yaml_dict['experiments'] = yaml_dict.get('experiments', []).append('experiment_name') # append?
yaml_dict['experiments'] = ['experiment_name'] # overwrite

options: Dict[str, Any] = yaml_dict['options']
check_options(options, args)
Expand All @@ -234,7 +235,7 @@ def main() -> None:
f.write(yaml.dump(yaml_dict))

# Run yank
subcommand = ['script', '-y', yaml_filename] # trailblaze, equilibration, production
subcommand = ['script', '-y', yaml_filename] # trailblaze, equilibration, production
if args.phase == 'setup_only':
subcommand = ['script', '--setup-only', '-y', yaml_filename]
if args.phase == 'analyze':
Expand Down
8 changes: 4 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Dict
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
Expand Down Expand Up @@ -29,8 +30,8 @@
# ones.
extensions = [
'myst_parser',
'sphinx.ext.napoleon', # Support google (and numpy) docstring styles
"sphinx_autodoc_typehints", # Load AFTER napoleon
'sphinx.ext.napoleon', # Support google (and numpy) docstring styles
"sphinx_autodoc_typehints", # Load AFTER napoleon
# See https://github.com/agronholm/sphinx-autodoc-typehints/issues/15
# NOTE: sphinx_autodoc_typehints automatically strips type annotations
# from the function signature and inserts them into the docstring.
Expand Down Expand Up @@ -70,11 +71,10 @@
# can be added to autodoc_type_aliases instead of showing their expansions.
# However, I can't seem to get it to work.
# TODO: Consider removing all type aliases in favor of classes.
from typing import Dict
autodoc_type_aliases: Dict[str, str] = {
}
napoleon_use_param = True
napoleon_type_aliases: Dict[str, str] = {
napoleon_type_aliases: Dict[str, str] = {
}

# Add any paths that contain templates here, relative to this directory.
Expand Down
4 changes: 2 additions & 2 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ipytree
myst-parser
# https://docs.readthedocs.io/en/stable/intro/getting-started-with-sphinx.html
# "We strongly recommend to pin the Sphinx version used for your project to build the docs to avoid potential future incompatibilities."
sphinx==6.1.*
myst-parser
sphinx-autodoc-typehints
ipytree
38 changes: 18 additions & 20 deletions examples/scripts/autodock_vina_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,27 +41,25 @@

# After the initial headers, an autodock vina log file consists of
# 1 or more blocks of the following form:
"""
Performing docking (random seed: -193947260) ...
0% 10 20 30 40 50 60 70 80 90 100%
|----|----|----|----|----|----|----|----|----|----|
***************************************************
mode | affinity | dist from best mode
| (kcal/mol) | rmsd l.b.| rmsd u.b.
-----+------------+----------+----------
1 -5.773 0 0
2 -5.577 4.821 7.207
3 -5.46 4.053 6.446
4 -5.44 1.344 3.349
5 -5.431 3.576 5.58
6 -5.412 3.012 5.868
7 -5.405 1.914 4.145
8 -5.403 3.209 6.271
9 -5.392 2.556 4.714
"""
# Performing docking (random seed: -193947260) ...
# 0% 10 20 30 40 50 60 70 80 90 100%
# |----|----|----|----|----|----|----|----|----|----|
# ***************************************************

# mode | affinity | dist from best mode
# | (kcal/mol) | rmsd l.b.| rmsd u.b.
# -----+------------+----------+----------
# 1 -5.773 0 0
# 2 -5.577 4.821 7.207
# 3 -5.46 4.053 6.446
# 4 -5.44 1.344 3.349
# 5 -5.431 3.576 5.58
# 6 -5.412 3.012 5.868
# 7 -5.405 1.914 4.145
# 8 -5.403 3.209 6.271
# 9 -5.392 2.556 4.714
# If rescoring, the relevant line from each log file is of the form:
"""Estimated Free Energy of Binding : -8.659 (kcal/mol) [=(1)+(2)+(3)-(4)]"""
# Estimated Free Energy of Binding : -8.659 (kcal/mol) [=(1)+(2)+(3)-(4)]

scores: List[float] = []
scores_all: List[List[float]] = []
Expand Down
17 changes: 12 additions & 5 deletions examples/scripts/generate_conformers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
# pylint: disable=import-outside-toplevel,no-member
# type: ignore
import distutils.util
import math
from typing import List

from workflow_types import *


def calculate_dG(Kd):
def calculate_dG(Kd: float) -> float:
""" Calculates binding free energy from Kd
Args:
Kd (float): The binding affinity of the protein-ligand complex
Returns:
float: The binding free energy
"""
# Calculate the binding free energy from Kd so we can make the correlation plots.
# See https://en.wikipedia.org/wiki/Binding_constant
ideal_gas_constant = 8.31446261815324 # J/(Mol*K)
Expand All @@ -26,7 +33,7 @@ def calculate_dG(Kd):
return dG


def main(input_excel_path, query, min_row, max_row, smiles_column,
def main(input_excel_path, query, min_row, max_row, smiles_column, # type: ignore[no-untyped-def]
binding_data_column, convert_Kd_dG, output_txt_path):
import pandas
import rdkit
Expand Down Expand Up @@ -119,8 +126,8 @@ def main(input_excel_path, query, min_row, max_row, smiles_column,

inputs = {'input_excel_path': xlsxfile,
'query': string,
'min_row': {**integer, 'default': 1},
'max_row': {**integer, 'default': -1},
'min_row': {'type': 'int', 'format': 'edam:format_2330', 'default': 1},
'max_row': {'type': 'int', 'format': 'edam:format_2330', 'default': -1},
'smiles_column': string,
'binding_data_column': string,
'convert_Kd_dG': string,
Expand Down
4 changes: 1 addition & 3 deletions examples/scripts/generate_pdbbind_complex.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# pylint: disable=import-outside-toplevel,no-member
# type: ignore
from collections import defaultdict
import distutils.util
import math
Expand Down Expand Up @@ -88,7 +87,7 @@ def read_index_file(index_file_path: str) -> pd.DataFrame:
standard_type = re.split(r"=[-+]?(?:\d*\.\d+|\d+)", words[4])[0]
kd = float(re.findall(r"[-+]?(?:\d*\.\d+|\d+)", words[4])[0])
data['Kd_Ki'].append(standard_type)
data['value'].append(kd * unit_conv[unit])
data['value'].append(str(kd * unit_conv[unit]))
data['ligand_name'].append(re.findall(r'\((.*?)\)', words[7])[0])

return pd.DataFrame.from_dict(data)
Expand Down Expand Up @@ -124,7 +123,6 @@ def load_data(index_file_name: str, base_dir: str, query: str, output_txt_path:
# Calculate dG
df = df[['PDB_code', 'value', 'Kd_Ki']]
binding_data: List[str] = []
convert_Kd_dG = distutils.util.strtobool(convert_Kd_dG)
microMolar = 0.000001 # uM
for _, row in enumerate(df.values):

Expand Down
2 changes: 1 addition & 1 deletion examples/scripts/nmr4md.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from workflow_types import *


def main(input_tpr_path, input_trr_path, output_png_path):
def main(input_tpr_path, input_trr_path, output_png_path): # type: ignore[no-untyped-def]
import MDAnalysis as mda
import nmrformd
from matplotlib import pyplot as plt
Expand Down
6 changes: 5 additions & 1 deletion examples/scripts/python_cwl_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,11 @@ def import_python_file(python_module_name: str, python_file_path: Path) -> Modul
if spec:
module_ = importlib.util.module_from_spec(spec)
sys.modules[python_module_name] = module_
spec.loader.exec_module(module_) # type: ignore
if spec.loader:
spec.loader.exec_module(module_) # guard behind if to satisfy mypy
else:
print(f'Error! Cannot load {spec}')
sys.exit(1)
# Note that now (after calling exec_module) we can call import_module without error
# module_ = importlib.import_module(python_module_name)
else:
Expand Down
Empty file modified examples/scripts/remove_terminal_residue_name_prefixes.py
100755 → 100644
Empty file.
Empty file modified examples/scripts/rename_residues_MOL.py
100755 → 100644
Empty file.
Loading

0 comments on commit 8b7c88b

Please sign in to comment.