Skip to content

Commit

Permalink
various linting and typing changes
Browse files Browse the repository at this point in the history
  • Loading branch information
cgevans committed Oct 30, 2024
1 parent df96149 commit 69ad5c3
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 49 deletions.
2 changes: 2 additions & 0 deletions src/stickydesign/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# ruff: noqa: F401, F403

from .version import __version__

from .endclasses import *
Expand Down
6 changes: 4 additions & 2 deletions src/stickydesign/endclasses.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import numpy as np
from typing_extensions import TypeAlias
from typing import Union, Literal, List, cast, Dict, Any
from collections.abc import Sequence
from typing import Union, Literal, List, cast, Dict, Any, TYPE_CHECKING
from abc import ABC, abstractmethod

if TYPE_CHECKING:
from collections.abc import Sequence

__all__ = [
'Energetics',
'EndTypes',
Expand Down
11 changes: 6 additions & 5 deletions src/stickydesign/multimodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def endchooser(all_energetics,
"""
if templates:
templates = iter(templates)
rng = np.random.default_rng()

def endchooser(currentends, availends, energetics):
nonlocal target_vals, templates
Expand All @@ -45,7 +46,7 @@ def endchooser(currentends, availends, energetics):
[en.matching_uniform(availends) for en in all_energetics],
axis=0)
choices = np.argsort(dev)
choice = choices[np.random.randint(
choice = choices[rng.integers(
0, max(1, ceil(init_wigglefraction * len(availends))))]
return availends[choice]
else:
Expand All @@ -68,25 +69,25 @@ def endchooser(currentends, availends, energetics):
np.sum(
np.array([
en.matching_uniform(availfiltered) - target_val
for en, target_val in zip(all_energetics, target_vals)
for en, target_val in zip(all_energetics, target_vals, strict=True)
])**2,
axis=0))
elif devmethod == 'max':
dev = np.max(np.abs(
np.array([
en.matching_uniform(availfiltered) - target_val
for en, target_val in zip(all_energetics, target_vals)
for en, target_val in zip(all_energetics, target_vals, strict=True)
])), axis=0)
choices = np.argsort(dev)
choice = choices[np.random.randint(
choice = choices[rng.integers(
0, max(1, ceil(len(choices) * next_wigglefraction)))]
LOGGER.debug("Chose {}: {} from {}: {} / {}".format(
availfiltered[choice:choice+1].tolist(),
np.nonzero(choices == choice),
len(availfiltered),
dev[choice],
np.concatenate([en.matching_uniform(availfiltered[choice:choice+1]) for en,
tv in zip(all_energetics, target_vals)])))
tv in zip(all_energetics, target_vals, strict=True)])))

return availfiltered[choice]

Expand Down
10 changes: 5 additions & 5 deletions src/stickydesign/plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
from .stickydesign import energy_array_uniform

def _import_pyplot():
global plt
global plt # noqa: PLW0603
try:
from matplotlib import pyplot as plt
except ImportError:
raise ImportError("matplotlib is required for plotting functions")
except ImportError as e:
raise ImportError("matplotlib is required for plotting functions") from e

def hist_multi(all_ends,
all_energetics,
Expand Down Expand Up @@ -125,8 +125,8 @@ def _multi_data_pandas(ends, all_energetics, energetics_names=None):
"""
try:
import pandas as pd
except ImportError:
raise ImportError("pandas is required for _multi_data_pandas")
except ImportError as e:
raise ImportError("pandas is required for _multi_data_pandas") from e
match = np.array([np.concatenate(
[e.matching_uniform(x) for x in ends]) for e in all_energetics]).T
match = pd.DataFrame(match, columns=energetics_names)
Expand Down
69 changes: 32 additions & 37 deletions src/stickydesign/stickydesign.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import numpy as np
import itertools
import logging
from typing import Optional, List, Union, cast
from typing import Dict, Iterator, Optional, List, Tuple, Union, cast
from typing_extensions import TypeAlias
from collections.abc import Callable
from collections.abc import Sequence
Expand All @@ -23,7 +23,7 @@
'endchooser_standard', 'endchooser_random'
]

def values_chunked(items, endtype, chunk_dim=10):
def values_chunked(items: Sequence[Sequence[int]], endtype: str, chunk_dim: int = 10) -> Iterator[EndArray]:
"""
Given a list of lists of acceptable numbers for each position in a row of
an array, create every possible row, and return an iterator that returns
Expand Down Expand Up @@ -67,7 +67,7 @@ def get_accept_set(endtype: EndTypes,
fdev,
maxendspurious,
spacefilter=None,
adjacents=['n', 'n'],
adjacents=('n', 'n'),
alphabet='n',
energetics=None):
if not energetics:
Expand All @@ -94,16 +94,14 @@ def get_accept_set(endtype: EndTypes,

# Use spacefilter to filter chunks down to usable sequences
matcharrays = []
chunknum = 0
totchunks = None
totends = np.prod([len(x) for x in template])
LOGGER.debug(
"Have {} ends in total before any filtering.".format(totends))
for chunk in endchunk:
for chunknum, chunk in enumerate(endchunk, 1):
matcharrays.append(spacefilter(chunk, energetics))
if not totchunks:
totchunks = totends // len(chunk)
chunknum += 1
LOGGER.debug("Found {} filtered ends in chunk {} of {}.".format(
len(matcharrays[-1]), chunknum, totchunks))
LOGGER.debug("Done with spacefiltering.")
Expand All @@ -114,16 +112,16 @@ def get_accept_set(endtype: EndTypes,

def _make_avail(endtype: EndTypes,
length: int,
spacefilter,
endfilter,
endchooser,
energetics,
adjacents=('n', 'n'),
num=0,
numtries=1,
oldendfilter=None,
oldends=[],
alphabet='n'):
spacefilter: SpaceFilterType,
endfilter: EndFilterType,
endchooser: EndChooserType,
energetics: Energetics,
adjacents: Sequence[str] = ('n', 'n'),
num: int=0,
numtries: int=1,
oldendfilter: Union[EndFilterType, None] = None,
oldends: Union[EndArray, Sequence[str], None] = None,
alphabet: str ='n') -> EndArray:
# Generate the template.
if endtype == 'DT':
template = [lton[adjacents[0]]] + [lton[alphabet.lower()]] \
Expand All @@ -143,16 +141,14 @@ def _make_avail(endtype: EndTypes,

# Use spacefilter to filter chunks down to usable sequences
matcharrays = []
chunknum = 0
totchunks = None
totchunks = -1
totends = np.prod([len(x) for x in template])
LOGGER.debug(
"Have {} ends in total before any filtering.".format(totends))
for chunk in endchunk:
for chunknum, chunk in enumerate(endchunk, 1):
matcharrays.append(spacefilter(chunk, energetics))
if not totchunks:
totchunks = totends // len(chunk)
chunknum += 1
LOGGER.debug("Found {} filtered ends in chunk {} of {}.".format(
len(matcharrays[-1]), chunknum, totchunks))
LOGGER.debug("Done with spacefiltering.")
Expand All @@ -161,7 +157,7 @@ def _make_avail(endtype: EndTypes,

# Use endfilter to filter available sequences taking into account old
# sequences.
if len(oldends) > 0:
if oldends is not None and len(oldends) > 0:
if oldendfilter:
availends = oldendfilter(oldends, None, availends, energetics)
else:
Expand Down Expand Up @@ -333,12 +329,12 @@ def find_end_set_uniform(endtype: EndTypes,

def enhist(endtype: EndTypes,
length: int,
adjacents=('n', 'n'),
alphabet='n',
bins=None,
energetics=None,
plot=False,
color='b'):
adjacents: Sequence[str] = ('n', 'n'),
alphabet: str ='n',
bins: Optional[np.ndarray] = None,
energetics: Optional[Energetics] = None,
plot: bool = False,
color: str ='b') -> Tuple[np.ndarray, np.ndarray, Dict[str, float]]:
if endtype == 'DT':
template = [lton[adjacents[0]]] +\
[lton[alphabet.lower()]] * length + [lton[wc[adjacents[1]]]]
Expand Down Expand Up @@ -557,16 +553,14 @@ def easy_space(endtype: EndTypes,

# Use spacefilter to filter chunks down to usable sequences
matcharrays = []
chunknum = 0
totchunks = None
totends = np.prod([len(x) for x in template])
LOGGER.info(
"Have {} ends in total before any filtering.".format(totends))
for chunk in endchunk:
for chunknum, chunk in enumerate(endchunk, 1):
matcharrays.append(spacefilter(chunk, energetics))
if not totchunks:
totchunks = totends // len(chunk)
chunknum += 1
LOGGER.debug("Found {0} filtered ends in chunk {1} of {2}.".format(
len(matcharrays[-1]), chunknum, totchunks))
LOGGER.debug("Done with spacefiltering.")
Expand Down Expand Up @@ -622,7 +616,7 @@ def endfilter_standard(maxspurious: float) -> EndFilterType:
comp-end, comp-comp) interactions with new ends above maxspurious.
"""

def endfilter(newends: EndArray, currentends: EndArray, availends: EndArray, energetics: Energetics):
def endfilter(newends: EndArray, currentends: EndArray, availends: EndArray, energetics: Energetics) -> EndArray:
endendspurious = energetics.uniform(
np.repeat(newends.ends, len(availends), 0),
np.tile(availends.ends, (len(newends), 1))).reshape(
Expand Down Expand Up @@ -655,7 +649,7 @@ def endfilter_standard_advanced(maxcompspurious: float, maxendspurious: float) -
above maxendspurious.
"""

def endfilter(newends: EndArray, currentends: EndArray, availends: EndArray, energetics: Energetics):
def endfilter(newends: EndArray, currentends: EndArray, availends: EndArray, energetics: Energetics) -> EndArray:
endendspurious = energetics.uniform(
np.repeat(newends.ends, len(availends), 0),
np.tile(availends.ends, (len(newends), 1))).reshape(
Expand Down Expand Up @@ -693,24 +687,25 @@ def energy_array_uniform(seqs: EndArray, energetics: Energetics) -> np.ndarray:

def endchooser_standard(desint: float, wiggle: float = 0.0) -> EndChooserType:
"""Return a random end with end-comp energy closest to desint, subject to some wiggle."""
rng = np.random.default_rng()

def endchooser(currentends: EndArray, availends: EndArray, energetics: Energetics):
def endchooser(currentends: EndArray, availends: EndArray, energetics: Energetics) -> EndArray:
ddiff = np.abs(energetics.matching_uniform(availends) - desint)
choices = np.flatnonzero(ddiff <= np.amin(ddiff)+wiggle)
newend = availends[choices[np.random.randint(0, len(choices))]]
newend = availends[choices[rng.integers(0, len(choices))]]
return newend

return endchooser


def endchooser_random() -> EndChooserType:
"""Return a random end with end-comp energy closest to desint."""
rng = np.random.default_rng()

def endchooser(currentends: EndArray, availends: EndArray, energetics: Energetics):
newend = availends[np.random.randint(0, len(availends))]
def endchooser(currentends: EndArray, availends: EndArray, energetics: Energetics) -> EndArray:
newend = availends[rng.integers(0, len(availends))]
return newend

return endchooser



0 comments on commit 69ad5c3

Please sign in to comment.