local_barrier_model¶
Direct local-barrier rules for KMC event rates.
LocalBarrierModel is the lightweight alternative to fitting a local cluster
expansion. It is useful when the migration barrier can be written directly as a
small set of ordered rules:
use a constant fallback barrier for every hop;
count selected occupation states in an event local environment;
count chemical species after mapping occupation states to species labels;
match a short wildcard occupation pattern; or
match an exact event/local-occupation entry.
The model works with the same compact KMC state used by the simulator. State
values are nonnegative integer indices. For binary models, occupied and
template are aliases for state 0 and vacant and mismatch are
aliases for state 1. Multicomponent rules can use explicit state indices
such as 2 or 3. Rule order is significant: the first matching rule
supplies the selected property, usually barrier in meV. If no rule matches,
default_properties are used when present. compute_probability returns an
event rate in Hz using temperature in K and attempt frequency in Hz.
Minimal setup:
from kmcpy.models import LocalBarrierModel
model = LocalBarrierModel.constant_barrier(300.0)
model.to("model.json")
Rule-based setup:
model = LocalBarrierModel(default_barrier=300.0)
model.add_state_count_rule(
name="crowded",
sites="local_env",
state="occupied",
min_count=3,
barrier=450.0,
)
The saved model.json can be referenced by model_file in a simulation
configuration. BaseModel.from_config dispatches to this class when the model
file carries this class’ Monty metadata.
- class kmcpy.models.local_barrier_model.LocalBarrierModel(rules=None, name='LocalBarrierModel', default_properties=None, default_barrier=None, default_property='barrier', probability_mode='barrier_arrhenius', probability_property='barrier', site_species=None)[source]¶
Choose migration barriers from ordered local-environment rules.
LocalBarrierModelstores a list of simple rule dictionaries and evaluates them against aStateandEvent. Each rule returns a dictionary of numeric properties; by defaultcomputereturns thebarrierproperty.compute_probabilitythen evaluates the Arrhenius rate when the current endpoint states match a mobile-vacancy hop.- Parameters:
rules (
Optional[list[dict[str,Any]]]) – Ordered rule dictionaries. The first matching rule is used.name (
str) – Human-readable model name.default_properties (
Optional[dict[str,float]]) – Property dictionary used when no rule matches.default_barrier (
Optional[float]) – Shortcut fordefault_properties={"barrier": value}.default_property (
str) – Property returned bycomputewhenproperty_nameis not supplied.probability_mode (
str) – Probability calculation mode. Currently only"barrier_arrhenius"is supported.probability_property (
str) – Property used as the barrier incompute_probability.site_species (
Optional[dict[Any,Any]]) – Mapping used byspecies_countrules. The shape is{site_index: {occupation_state: species}}. For example,{10: {0: "P", 1: "Si", 2: "Al"}}means site 10 is counted as P, Si, or Al depending on its current state index.
- Supported rule types:
constantAlways matches and returns its properties. In most cases,
default_barrieris clearer than an explicit constant rule.state_countCounts how many selected sites have the requested state index. Binary aliases such as
occupied/0andvacant/1are accepted for convenience.species_countCounts species labels after applying
site_species.patternMatches selected occupations against a pattern containing nonnegative state indices, binary state aliases, or
"*"wildcards.exactMatches a specific event and exact occupation vector. This is the direct replacement for catalog-style local-environment tables.
- Site selectors:
Rules can use
sites="local_env","mobile_ion","canonical","from","to","all", or an explicit list of active-site indices.canonicalmeansevent.mobile_ion_indicesfollowed byevent.local_env_indiceswith duplicates removed.
Examples
Constant barrier:
model = LocalBarrierModel.constant_barrier(300.0)
At least three occupied local-environment sites:
model = LocalBarrierModel(default_barrier=300.0) model.add_state_count_rule( name="crowded", sites="local_env", state="occupied", min_count=3, barrier=450.0, )
More than three Si sites in the local environment:
model = LocalBarrierModel( default_barrier=300.0, site_species={ 1: {0: "P", 1: "Si"}, 2: {0: "Si", 1: "P"}, 3: {0: "Si", 1: "P"}, 4: {0: "Al", 1: "Si"}, }, ) model.add_species_count_rule( name="si_rich", sites="local_env", species="Si", min_count=4, barrier=420.0, )
Exact event/local-environment match:
model = LocalBarrierModel.from_exact_entries([ { "mobile_ion_indices": [0, 1], "local_env_indices": [1, 2, 3], "occupations": [1, 0, 1, 0], "properties": {"barrier": 250.0}, } ])
- add_exact_rule(mobile_ion_indices, local_env_indices, occupations, barrier=None, properties=None, name=None)[source]¶
Add an event-specific exact occupation rule.
occupationsmust follow canonical site order for the suppliedmobile_ion_indicesandlocal_env_indices. Use this rule type when the barrier is known only for one exact event/environment pattern.- Return type:
str
- add_pattern_rule(pattern, barrier=None, properties=None, name=None, sites='canonical')[source]¶
Add a wildcard occupation pattern rule.
Patterns can contain nonnegative integer state indices, binary state aliases, or
"*"wildcards. The pattern length must match the number of selected sites.- Return type:
str
- add_rule(rule)[source]¶
Add one normalized local barrier rule to the ordered rule list.
- Return type:
None
- add_species_count_rule(species, barrier=None, properties=None, name=None, sites='local_env', count=None, min_count=None, max_count=None)[source]¶
Add a rule based on the number of sites currently carrying a species.
Species labels are looked up from
site_speciesusing each selected site index and current occupation value. This is appropriate for rules such as “use a higher barrier when at least four selected sites are Si”.- Return type:
str
- add_state_count_rule(state, barrier=None, properties=None, name=None, sites='local_env', count=None, min_count=None, max_count=None)[source]¶
Add a rule based on the number of sites in an occupation state.
stateaccepts any nonnegative integer state index. The binary aliases"occupied"/0and"vacant"/1are also accepted. Supply exactly one ofcountor amin_count/max_countrange.- Return type:
str
- apply_event(*, event, simulation_state)¶
Commit an accepted event to optional model-side state.
Stateless models can ignore this hook. Stateful external adapters should update only the changed sites here so their internal state stays aligned with kMCpy’s
State.- Return type:
None
- build(rules=None, default_properties=None, default_barrier=None, default_property=None, probability_mode=None, probability_property=None, site_species=None)[source]¶
Replace this model’s rule table.
- Return type:
None
- compute(simulation_state, event, property_name=None)[source]¶
Compute a barrier/property value by local rule matching.
- Return type:
float
- compute_probability(event, runtime_config, simulation_state)[source]¶
Compute event rate in Hz from a selected meV barrier.
- Return type:
float
- classmethod constant_barrier(barrier, name='ConstantBarrierModel', **kwargs)[source]¶
Construct a model that returns the same barrier for every event.
This is the simplest setup for smoke tests, toy simulations, or models where all event rates share one activation barrier. The returned model has no rules; the barrier is stored in
default_properties.- Return type:
- classmethod entry_from_event_state(event, state, properties, name=None)[source]¶
Build an exact-match rule from a runtime event and state snapshot.
The occupation vector is sampled in canonical event-site order:
mobile_ion_indicesfirst, thenlocal_env_indiceswith duplicate site indices removed. Use this helper when turning a known event/state snapshot into an exact rule without manually constructing the occupation list.- Return type:
dict[str,Any]
- classmethod from_config(config)¶
Load the configured model.
Called on
BaseModel, this dispatches to the concrete model class declared by the model file orconfig.model_type. Called on a concrete subclass, it loads that subclass directly fromconfig.model_file.
- classmethod from_exact_entries(entries, name='LocalBarrierModel', default_properties=None, default_barrier=None, default_property='barrier', probability_mode='barrier_arrhenius', probability_property='barrier', site_species=None)[source]¶
Construct from exact event/local-occupation entries.
Each entry must contain
mobile_ion_indices,local_env_indices,occupations, andproperties. Theoccupationslist is in canonical site order: mobile-ion sites first, then local-environment sites with duplicates removed. Duplicate exact entries are rejected.- Return type:
- classmethod from_file(filename)[source]¶
Load from a model file or direct model payload.
- Return type:
- classmethod get_fitter_class()¶
Return fitter implementation for this model class.
- initialize_state(*, simulation_state, event_lib=None, structure=None, config=None, active_site_order=None)¶
Initialize optional stateful model caches from the KMC state.
Stateless models can ignore this hook. Stateful adapters can use it to build their own occupancy representation once, instead of rebuilding it during every event-rate evaluation.
- Return type:
None
- classmethod load(file_path)¶
Loads a class from a provided json file.
- Parameters:
file_path (os.PathLike) – The json file to load from.
- Returns:
An instance of the class being reloaded.
- Return type:
MSONable
- save(json_path, mkdir=True, json_kwargs=None, pickle_kwargs=None, strict=True)¶
Utility that uses the standard tools of MSONable to convert the class to json format, but also save it to disk. In addition, this method intelligently uses pickle to individually pickle class objects that are not serializable, saving them separately. This maximizes the readability of the saved class information while allowing _any_ class to be at least partially serializable to disk.
For a fully MSONable class, only a class.json file will be saved to the location {save_dir}/class.json. For a partially MSONable class, additional information will be saved to the save directory at {save_dir}. This includes a pickled object for each attribute that e serialized.
- Parameters:
file_path (os.PathLike) – The file to which to save the json object. A pickled object of the same name but different extension might also be saved if the class is not entirely MSONable.
mkdir (bool) – If True, makes the provided directory, including all parent directories.
json_kwargs (dict) – Keyword arguments to pass to the serializer.
pickle_kwargs (dict) – Keyword arguments to pass to pickle.dump.
strict (bool) – If True, will not allow you to overwrite existing files.
- to_json()¶
Returns a json string representation of the MSONable object.
- Return type:
str
- unsafe_hash()¶
Returns an hash of the current object. This uses a generic but low performance method of converting the object to a dictionary, flattening any nested keys, and then performing a hash on the resulting object
- classmethod validate_monty_v1(_MSONable__input_value)¶
Pydantic validator with correct signature for pydantic v1.x
- classmethod validate_monty_v2(_MSONable__input_value, _)¶
Pydantic validator with correct signature for pydantic v2.x