Binary perceptron and random K-SAT
A binary perceptron that must store random patterns.
- Class:
PerceptronSatisfiabilitySystem - Import:
from skcomplex.systems.computer_science.neural_networks import PerceptronSatisfiabilitySystem - Field:
computer_science/neural_networks - Topics:
perceptron,satisfiability,disorder,critical load - References:
- Bertin 2021
- Krauth and Mezard 1989
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.computer_science.neural_networks import PerceptronSatisfiabilitySystem
trajectory = PerceptronSatisfiabilitySystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_weights |
21 |
load |
1.5 |
random_state |
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 | none |
| Laws | update |
| Randomness | deterministic |
| Domains | boolean |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class PerceptronSatisfiabilitySystem(BaseSystem):
"""A binary perceptron that must store random patterns.
The patterns are revealed one per step, as cardinality constraints. A pattern `xi` of output `sigma` holds when
`sigma sum_i w_i xi_i > 0`, so with an odd number `N` of weights `w_i = +-1`, when at least `(N + 1) / 2` of the
literals `w_i = sigma xi_i` hold. The patterns are satisfiable up to the critical load `p / N` of about 0.83 in the
limit of many weights (Bertin 2021 §6.3.3, Ex. 6.4). The patterns are drawn from `random_state`, so a disorder
average sweeps it with `sweep`. The system has the group `weights` and the reports `decide.satisfiable` and
`decide.revealed`.
Args:
n_weights:
The number of weights, which is odd.
load:
The number of patterns over the number of weights.
random_state:
The seed or generator of the patterns.
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:
ValidationError:
The number of weights is even, so a pattern can tie.
Examples:
>>> from skcomplex.systems.computer_science.neural_networks import PerceptronSatisfiabilitySystem
>>> PerceptronSatisfiabilitySystem(3, load=1.0).prepare().system_.interactions[0].constraints[0].bound
2
"""
field = 'computer_science/neural_networks'
topics = ('perceptron', 'satisfiability', 'disorder', 'critical load')
references = ('Bertin 2021', 'Krauth and Mezard 1989')
until = 31
def __init__(
self,
n_weights: int = 21,
*,
load: float = 1.5,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_weights = n_weights
self.load = load
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the components of the system built from its model parameters."""
super()._prepare(context)
if self.n_weights % 2 == 0:
error_msg = (
f'perceptron_satisfiability has n_weights={self.n_weights!r}. Use an odd number, so no pattern ties.'
)
raise ValidationError(error_msg)
rng = np.random.default_rng(self.random_state)
n_patterns = round(self.load * self.n_weights)
patterns = rng.choice([-1, 1], size=(n_patterns, self.n_weights)) * rng.choice([-1, 1], size=(n_patterns, 1))
indices = np.arange(1, self.n_weights + 1)
constraints = [
CardinalitySpec(tuple((indices * pattern).tolist()), (self.n_weights + 1) // 2, 'at-least')
for pattern in patterns
]
weights = BinaryWeightElement('weights', size=self.n_weights)
decide = SatisfiabilityInteraction('decide', target='weights', state='active', constraints=constraints)
self.system_ = System(self.label, elements=[weights], interactions=[decide])
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
BinaryWeightElement, fromElement
Interactions:
SatisfiabilityInteraction, fromInteraction
class BinaryWeightElement(Element):
"""Weight of a binary perceptron.
The state 1 stands for `+1` and the state 0 for `-1`.
Args:
label:
The label of the weight or the group.
active:
Whether the weight is `+1`.
size:
The number of weights, or `None` for one.
Examples:
>>> from skcomplex.systems.computer_science.neural_networks import BinaryWeightElement
>>> BinaryWeightElement('weight', active=1.0).active
1.0
"""
def __init__(
self,
label: str,
active: Annotated[object, FiniteEnumeratedSet([0, 1])] = 0.0,
size: int | None = None,
) -> None:
super().__init__(label, size=size)
self.active = active
class SatisfiabilityInteraction(Interaction):
"""Reveal constraints on the Boolean states of a group and decide them.
The constraints come step by step, and one incremental solver decides them. Every step adds the next `reveal`
constraints to one PySAT solver, which keeps what it learned, and sets the states of the members to a satisfying
assignment when one exists. The interaction reports `satisfiable`, 1 or 0, and `revealed`, the number of active
constraints, every step. Its role accepts Boolean states only, so a real state raises `RoleElementError`.
Args:
label:
The label of the interaction.
target:
The path of the group.
state:
The name of the Boolean state of the members.
constraints:
The constraints, in the order they are revealed.
reveal:
The number of constraints revealed per step.
solver:
The name of the PySAT solver.
phase:
The name of the phase of the step the rule runs in, or `None` for the default phase.
Raises:
ValidationError:
A constraint is not a spec or the number revealed per step is not positive, raised by `prepare`.
Examples:
>>> from skcomplex.systems.computer_science.neural_networks import SatisfiabilityInteraction
>>> from skcomplex.systems.computer_science.neural_networks import ClauseSpec
>>> constraints = [ClauseSpec((1, -2))]
>>> interaction = SatisfiabilityInteraction('sat', target='bits', state='active', constraints=constraints)
>>> interaction.reveal
1
"""
reports: ClassVar[tuple[str, ...]] = ('satisfiable', 'revealed')
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def __init__(
self,
label: str,
*,
target: Annotated[Role, 'boolean'],
state: str,
constraints: Sequence[ClauseSpec | CardinalitySpec],
reveal: int = 1,
solver: str = 'cadical153',
phase: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.constraints = constraints
self.reveal = reveal
self.solver = solver
self.phase = phase
def _check_arguments(self) -> None:
"""Raise an error for a constraint not a spec, or a bad number revealed per step.
Raises:
ValidationError:
A constraint is not a spec or the number revealed per step is not positive.
"""
super()._check_arguments()
if self.reveal < 1:
error_msg = f'The satisfiability {self.label!r} has reveal={self.reveal!r}. Reveal at least 1 per step.'
raise ValidationError(error_msg)
for constraint in self.constraints:
if not isinstance(constraint, ClauseSpec | CardinalitySpec):
error_msg = f'The constraint {constraint!r} of {self.label!r} is no ClauseSpec or CardinalitySpec.'
raise ValidationError(error_msg)
constraint._check()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the laws of a binding.
Args:
context:
The namespace of the elements a binding of the roles names.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self._decide, phase=self.phase)]
def _add(self, constraint: ClauseSpec | CardinalitySpec, solver: Solver, pool: IDPool) -> None:
"""Add one constraint to the solver.
A cardinality constraint is encoded with variables of the shared pool.
"""
if isinstance(constraint, ClauseSpec):
solver.add_clause(list(constraint.literals))
return
encode = CardEnc.atleast if constraint.sense == 'at-least' else CardEnc.atmost
for clause in encode(lits=list(constraint.literals), bound=constraint.bound, vpool=pool).clauses:
solver.add_clause(clause)
def _decide(self, system: SystemViewProtocol) -> None:
"""Reveal the next constraints, decide them, and set the members to a solution.
The solution is a satisfying assignment, set when one exists.
"""
agents = system.get_agents(self.target)
if 'solver' not in system.storage:
system.storage.update(
solver=Solver(name=self.solver),
pool=IDPool(start_from=len(agents) + 1),
revealed=0,
)
solver = cast(Solver, system.storage['solver'])
pool = cast(IDPool, system.storage['pool'])
revealed = cast(int, system.storage['revealed'])
following = min(revealed + self.reveal, len(self.constraints))
for constraint in self.constraints[revealed:following]:
self._add(constraint, solver, pool)
system.storage['revealed'] = following
satisfiable = solver.solve()
if satisfiable:
holding = {literal for literal in solver.get_model() if literal > 0}
for index, agent in enumerate(agents, start=1):
setattr(agent, self.state, float(index in holding))
system.report('satisfiable', float(satisfiable))
system.report('revealed', float(following))
Equations
The equations are those that symbolic returns for the system with its default parameters.