Fuzzy oil drop system of protein structure
The fuzzy oil drop of a protein.
- Class:
FuzzyOilDropSystem - Import:
from skcomplex.systems.biology.systems_biology import FuzzyOilDropSystem - Field:
biology/systems_biology - Topics:
protein,hydrophobicity,divergence entropy,structures,monte carlo - References:
- Konieczny et al. 2023
- Levitt 1976
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.biology.systems_biology import FuzzyOilDropSystem
trajectory = FuzzyOilDropSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
entry |
'1L2Y' |
dynamics |
'replay' |
proposals |
1 |
width |
60.0 |
temperature |
0.0 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | lattice |
| Laws | update |
| Randomness | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class FuzzyOilDropSystem(BaseSystem):
"""The fuzzy oil drop of a protein.
It is an ensemble replayed one member per frame or a chain folded by moves.
The default replays the systems of an entry, which sets the effective atoms of the chain, the mean atom of each
residue, to one system per unit of time. With `dynamics='folding'`, the chain starts extended, with all `phi =
-120°` and `psi = 130°`, and each unit of time proposes moves of its dihedral angles, accepted by the row score `RD`
plus one for every pair of effective atoms closer than 3 Å and at least two residues apart. The observables `RD` and
`K` follow Konieczny et al. (2023 §1.3.1) through `fuzzy_oil_drop_measures`. The book gives no folding dynamics, so
the extended start, the clash rule, the rotation width of 60°, and the temperature are choices of this system. The
system has the lattice `chain` of the state `x` or `angle`.
Args:
entry:
The bundled entry, `'1L2Y'`, `'1UBQ'`, or `'5PTI'`.
dynamics:
`'replay'` or `'folding'`.
proposals:
The number of dihedral moves per unit of time of the folding.
width:
The largest rotation of a dihedral move, in degrees.
temperature:
The temperature of the folding, one over the intensity of its sampling, where 0 accepts only moves that do
not raise the score.
label:
The label of the system, which names it when it is nested in another one.
solver:
The solver of the problem, or `'auto'` for the one the system chooses.
backend:
The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.
Raises:
MissingExtraError:
The extra `structures` is not installed.
ValidationError:
The dynamics are unknown.
Examples:
>>> from skcomplex.systems.biology.systems_biology import FuzzyOilDropSystem
>>> FuzzyOilDropSystem().prepare().system_.elements[0].space.shape
(20, 3)
"""
field = 'biology/systems_biology'
topics = ('protein', 'hydrophobicity', 'divergence entropy', 'structures', 'monte carlo')
references = ('Konieczny et al. 2023', 'Levitt 1976')
until = 37
@staticmethod
@lru_cache(maxsize=4)
def _read_chain(entry: str) -> tuple[StructureSpec, BackboneGeometry]:
"""Return a bundled entry and its chain.
The chain rebuilds from angles.
"""
structure = read_structure(entry)
return structure, BackboneGeometry(structure).prepare()
@staticmethod
def _read_value(structure: StructureSpec, kind: str, positions: Array) -> float:
"""Return a value of the fuzzy oil drop of the effective atoms of a chain."""
values = fuzzy_oil_drop_measures(positions[None], structure=structure, kind=kind).values
if values is None:
error_msg = f'The fuzzy oil drop of the kind {kind!r} has no value per frame.'
raise AnalysisError(error_msg)
return float(values[0])
@staticmethod
def _read_observed_value(kind: str, entry: str, state: str, t: float, values: Mapping[str, object]) -> float:
"""Return a value of the fuzzy oil drop of a frame.
The frame holds the coordinates or the angles.
"""
del t
structure, geometry = FuzzyOilDropSystem._read_chain(entry)
numbers = np.asarray(values[state], dtype=float).ravel()
positions = numbers.reshape(-1, COORDINATES) if state == COORDINATE_STATE else None
if positions is None:
positions = geometry.run(numbers).read_effective_atoms()
return FuzzyOilDropSystem._read_value(structure, kind, positions)
def __init__(
self,
entry: str = ENTRY,
*,
dynamics: str = 'replay',
proposals: int = 1,
width: float = 60.0,
temperature: float = 0.0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.entry = entry
self.dynamics = dynamics
self.proposals = proposals
self.width = width
self.temperature = temperature
def _get_observables(self) -> tuple[Observable, ...]:
"""Return the relative distance and the environment factor of the chain."""
state = ANGLE_STATE if self.dynamics == 'folding' else COORDINATE_STATE
return (
Observable(
'RD',
function=partial(FuzzyOilDropSystem._read_observed_value, 'relative-distance', self.entry, state),
),
Observable(
'K',
function=partial(FuzzyOilDropSystem._read_observed_value, 'environment-factor', self.entry, state),
),
)
@staticmethod
def _rotate_dihedral(width: float, row: Array, rng: np.random.Generator) -> Array:
"""Return a row of angles with one random angle rotated by up to a width.
The rotated angle is wrapped to `[-180, 180)`.
"""
site = rng.integers(row.size)
row[site] = (row[site] + rng.uniform(-width, width) + 180.0) % 360.0 - 180.0
return row
@staticmethod
def _read_clashes(positions: Array) -> int:
"""Return the number of clashes of effective atoms.
A clash is a pair of atoms apart along the chain and closer than the clash distance.
"""
rows, columns = np.triu_indices(len(positions), NEAREST_SEPARATED_RESIDUES)
return int(np.sum(np.linalg.norm(positions[rows] - positions[columns], axis=1) < CLASH_DISTANCE))
def _score_angles(self, entry: str, row: Array) -> float:
"""Return the relative distance of a chain rebuilt from a row of angles.
It adds one for every clash.
"""
structure, geometry = FuzzyOilDropSystem._read_chain(entry)
positions = geometry.run(row).read_effective_atoms()
return FuzzyOilDropSystem._read_value(structure, 'relative-distance', positions) + self._read_clashes(positions)
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the fuzzy oil drop of a protein.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
import_extra('Bio.PDB', 'fuzzy_oil_drop', 'structures')
if self.dynamics not in DYNAMICS:
error_msg = f'Unknown dynamics {self.dynamics!r}. Use one of {", ".join(DYNAMICS)}.'
raise ValidationError(error_msg)
self.observables_ = self._get_observables()
structure = read_structure(self.entry)
if self.dynamics == 'replay':
ensemble = structure.effective_atoms
self.system_ = System(
self.label,
elements=[
ChainCoordinateElement(
'chain',
x=ensemble[0],
space=LatticeSpace((ensemble.shape[1], COORDINATES), boundary='fixed'),
),
],
interactions=[EnsembleReplayInteraction('replay', target='chain', state='x', ensemble=ensemble)],
)
return
angles = np.full(BackboneGeometry(structure).prepare().angles_.size, EXTENDED_PHI)
angles[angles.size // 2 :] = EXTENDED_PSI
self.system_ = System(
self.label,
elements=[
DihedralAngleElement(
'chain',
angle=angles[None],
structure=structure,
space=LatticeSpace((1, angles.size), boundary='fixed'),
),
],
interactions=[
SequenceSamplingInteraction(
'folding',
target='chain',
state='angle',
objective=RowScoreSpec(partial(self._score_angles, self.entry), proposals=self.proposals),
move=partial(self._rotate_dihedral, self.width),
intensity=float('inf') if self.temperature == 0 else 1 / self.temperature,
),
],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
ChainCoordinateElement, fromElement
Interactions:
EnsembleReplayInteraction, fromInteraction
class ChainCoordinateElement(Element):
"""Coordinate of an effective atom of a protein chain.
Args:
label:
The label of the element.
x:
The coordinate in ångström.
space:
The lattice of the atoms and their coordinates, or `None` for one coordinate.
Examples:
>>> from skcomplex.systems.biology.systems_biology import ChainCoordinateElement
>>> ChainCoordinateElement('site').x
0.0
"""
visual = VisualSpec(BackboneVisual, {'position': 'x'})
def __init__(self, label: str, x: float | Array = 0.0, space: BaseSpace | None = None) -> None:
super().__init__(label, space=space)
self.x = x
class EnsembleReplayInteraction(Interaction):
"""Drive that sets a lattice state to one member of an ensemble per unit of time.
It holds the last member after the end.
Args:
label:
The label of the interaction.
target:
The path of the lattice group.
state:
The name of the state.
ensemble:
The members, members by the lattice shape.
Examples:
>>> import numpy as np
>>> from skcomplex.systems.biology.systems_biology import EnsembleReplayInteraction
>>> EnsembleReplayInteraction('replay', target='chain', state='x', ensemble=np.zeros((2, 3))).state
'x'
"""
law_classes = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Role,
state: str,
ensemble: Array,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.ensemble = ensemble
def _read_member(self, values: Array, *, time: float, **kwargs: object) -> Array:
"""Return the member of the time at the end of a step."""
return self.ensemble[min(int(time) + 1, len(self.ensemble) - 1)].reshape(values.shape)
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the drive of the state.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: Sequence[BaseLaw] = [UpdateLaw(getattr(context.target, self.state), self._read_member, arrays=True)]