AdsorPy 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- adsorpy/VdW_Radii.csv +93 -0
- adsorpy/__init__.py +0 -0
- adsorpy/config.json +56 -0
- adsorpy/molecule_colour.json +111 -0
- adsorpy/molecule_lib.py +657 -0
- adsorpy/randomsequentialadsorption.py +1609 -0
- adsorpy/rsa_calculator.py +340 -0
- adsorpy/rsa_config.py +87 -0
- adsorpy/run_simulation.py +551 -0
- adsorpy-1.0.2.dist-info/METADATA +84 -0
- adsorpy-1.0.2.dist-info/RECORD +13 -0
- adsorpy-1.0.2.dist-info/WHEEL +4 -0
- adsorpy-1.0.2.dist-info/licenses/LICENSE.md +21 -0
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
"""Runs the simulation.
|
|
2
|
+
|
|
3
|
+
run_simulation() should provide the user with customisability.
|
|
4
|
+
Molecules can be generated from .xyz using molecule_lib.
|
|
5
|
+
The config.json can be found in the adsorpy folder as well.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from sys import version_info
|
|
11
|
+
|
|
12
|
+
if version_info >= (3, 11):
|
|
13
|
+
from datetime import UTC, datetime # For datetime stamping and seed generation.
|
|
14
|
+
else:
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
|
|
17
|
+
import time # For timing of the script.
|
|
18
|
+
from itertools import count # A simple counter, iterates with next(...).
|
|
19
|
+
from pathlib import Path # For path handling in Python.
|
|
20
|
+
from typing import Literal, ParamSpec, TypeVar, cast # For type hinting.
|
|
21
|
+
|
|
22
|
+
import molecule_lib as mol # Homebrew lib of molecules and molecule footprint generation.
|
|
23
|
+
import numpy as np # For vectorised computations (performed in C).
|
|
24
|
+
from numpy.random import PCG64DXSM, Generator # New random generator.
|
|
25
|
+
from numpy.typing import NDArray
|
|
26
|
+
from randomsequentialadsorption import MoleculeGroup, Simulator, Surface
|
|
27
|
+
from rsa_config import RsaConfig # Config of the simulation.
|
|
28
|
+
from shapely import Polygon # Shapely creates and manipulates polygons.
|
|
29
|
+
from shapely.prepared import PreparedGeometry
|
|
30
|
+
|
|
31
|
+
P = ParamSpec("P") # Helps with static type checkers.
|
|
32
|
+
T1 = TypeVar("T1")
|
|
33
|
+
T2 = TypeVar("T2", bound=np.generic | Polygon) # type: ignore[explicit-any]
|
|
34
|
+
TargetType = np.generic | Polygon
|
|
35
|
+
Tn = TypeVar("Tn", bound=np.ndarray[tuple[int], np.dtype[np.generic | Polygon]]) # type: ignore[explicit-any]
|
|
36
|
+
|
|
37
|
+
# mypy: plugins = numpy.typing.mypy_plugin
|
|
38
|
+
# Definition of some frequently-used types. Not used by the compiler, just for the user and mypy. Hello user!
|
|
39
|
+
|
|
40
|
+
IdxArray = np.ndarray[tuple[int], np.dtype[np.int_]] # Flat index aray of integers.
|
|
41
|
+
BoolArray = np.ndarray[tuple[int], np.dtype[np.bool_]] # Flat Boolean array.
|
|
42
|
+
CoordPair = np.ndarray[tuple[Literal[2], Literal[1]], np.dtype[np.float64]] # 2x1 array of coordinates
|
|
43
|
+
CoordsArray = np.ndarray[tuple[Literal[2], int], np.dtype[np.float64]] # 2xN array of coords.
|
|
44
|
+
Bools2D = np.ndarray[tuple[int, int], np.dtype[np.bool_]]
|
|
45
|
+
GeoArray = np.ndarray[tuple[int], np.dtype[Polygon]]
|
|
46
|
+
PrepGeoArray = np.ndarray[tuple[int], np.dtype[PreparedGeometry]]
|
|
47
|
+
FloatArray = NDArray[np.float64]
|
|
48
|
+
DistArray = np.ndarray[tuple[int], np.dtype[np.float64]]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def run_simulation( # noqa: PLR0913
|
|
52
|
+
rsa_config: RsaConfig | None = None,
|
|
53
|
+
molecules_list: Polygon | list[Polygon] | GeoArray | None = None,
|
|
54
|
+
rotation_symmetries: int | list[int] | IdxArray | None = None,
|
|
55
|
+
reflection_symmetries: bool | list[bool] | BoolArray | None = None,
|
|
56
|
+
rotation_counts: int | list[int] | IdxArray | None = None,
|
|
57
|
+
lattice_type: str = "triangular",
|
|
58
|
+
site_count: int | None = None,
|
|
59
|
+
lattice_a: float | None = None,
|
|
60
|
+
boundary_condition: str | None = None,
|
|
61
|
+
simulation_type: str = "sequential",
|
|
62
|
+
dosing_distribution: list[float] | None = None,
|
|
63
|
+
include_rejected_flux: bool = False,
|
|
64
|
+
calculate_gap_size: bool = False,
|
|
65
|
+
print_output_flag: bool = False,
|
|
66
|
+
plot_output_flag: bool = False,
|
|
67
|
+
seed: int | None = None,
|
|
68
|
+
timestep_limit: int = 1000000,
|
|
69
|
+
site_x_coords: DistArray | None = None,
|
|
70
|
+
site_y_coords: DistArray | None = None,
|
|
71
|
+
bounding_x_coord: float | None = None,
|
|
72
|
+
bounding_y_coord: float | None = None,
|
|
73
|
+
sticking_probability: float | list[float] = 1.,
|
|
74
|
+
) -> tuple[list[int], DistArray, int, IdxArray, IdxArray]:
|
|
75
|
+
"""Run the RSA simulation.
|
|
76
|
+
|
|
77
|
+
If no molecule is provided, defaults to a circular molecule of radius 0.55 Angstrom.
|
|
78
|
+
Ensure that all lists are of equal length. If only one molecule is provided, adding it to a list is not needed.
|
|
79
|
+
If the simulation_type is "codosing", the dosing_distribution parameter is used, otherwise it is ignored.
|
|
80
|
+
|
|
81
|
+
:param rsa_config: Input parameters defined in the config.
|
|
82
|
+
:param molecules_list: List of molecules. Ensure this list is equal in length to the next three entries.
|
|
83
|
+
:param rotation_symmetries: Rotation symmetries. 0 for circle, 1 for no symmetry, 2 twofold, 3 threefold, etc.
|
|
84
|
+
:param reflection_symmetries: Mirror symmetries. True means mirror symmetry, False means no mirror symmetry.
|
|
85
|
+
:param rotation_counts: Number of rotations to be considered. Preferably numbers that divide 360.
|
|
86
|
+
:param lattice_type: The lattice type. "triangular", "honeycomb", or "square".
|
|
87
|
+
:param site_count: The site count along one axis. Optional. If None, defaults to the value in config.json.
|
|
88
|
+
:param lattice_a: The lattice spacing in Angstrom. If None, defaults to the value in config.json.
|
|
89
|
+
:param boundary_condition: The boundary condition. Optional, can be soft/hard/periodic. If None, defaults to config.
|
|
90
|
+
:param simulation_type: Type of simulation. Valid types are "sequential", "codosing", and "cascade".
|
|
91
|
+
:param dosing_distribution: The distribution of the adsorption attempts in case of "codosing". Uniform if None.
|
|
92
|
+
:param include_rejected_flux: Whether to include rejected flux in the simulation. If True, sites can be reattempted.
|
|
93
|
+
:param calculate_gap_size: Whether to calculate the gap size of the simulation.
|
|
94
|
+
:param print_output_flag: Toggle printing output of simulation.
|
|
95
|
+
:param plot_output_flag: Toggle plotting output of simulation.
|
|
96
|
+
:param seed: The seed for the simulation. If None, takes the datetime in microseconds: YYYMMDDhhmmssuuuuuu.
|
|
97
|
+
:param timestep_limit: The maximum number of timesteps to simulate for when the flux is taken into account.
|
|
98
|
+
:param site_x_coords: x coordinates of the sites. If this and the next four arguments are provided, generate custom.
|
|
99
|
+
:param site_y_coords: y coordinates of the sites. Custom surface overrides site_count and lattice_a.
|
|
100
|
+
:param bounding_x_coord: The bounding box x coordinate value. Only use for custom surface. Leave None otherwise.
|
|
101
|
+
:param bounding_y_coord: The bounding box y coordinate value. Ensure the previous three arguments are provided.
|
|
102
|
+
:param sticking_probability: The sticking probability. Default is 1.0 from config. Per molecule or for all.
|
|
103
|
+
:return:
|
|
104
|
+
0. The molecule count on the surface per molecule group.
|
|
105
|
+
1. The gap size distribution.
|
|
106
|
+
2. The RNG seed.
|
|
107
|
+
3. The fluxes/doses as a list of counts per stepcount of adsorption event.
|
|
108
|
+
4. The available surface function (ASF).
|
|
109
|
+
:raises TypeError: If the sticking probability is an invalid type.
|
|
110
|
+
"""
|
|
111
|
+
rsa_config = RsaConfig(str(Path(__file__).parent / "config.json")) if rsa_config is None else rsa_config
|
|
112
|
+
|
|
113
|
+
molecules_list, rotation_symmetries, reflection_symmetries, rotation_counts = _initialise_run_parameters(
|
|
114
|
+
molecules_list,
|
|
115
|
+
rotation_symmetries,
|
|
116
|
+
reflection_symmetries,
|
|
117
|
+
rotation_counts,
|
|
118
|
+
simulation_type,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
custom_grid_flg: bool = _error_checker(
|
|
122
|
+
molecules_list,
|
|
123
|
+
rotation_symmetries,
|
|
124
|
+
reflection_symmetries,
|
|
125
|
+
rotation_counts,
|
|
126
|
+
simulation_type,
|
|
127
|
+
dosing_distribution,
|
|
128
|
+
boundary_condition,
|
|
129
|
+
site_x_coords,
|
|
130
|
+
site_y_coords,
|
|
131
|
+
bounding_x_coord,
|
|
132
|
+
bounding_y_coord,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# The seed is defined as the datetime in microseconds. The seed is stored so simulations can be verified.
|
|
136
|
+
how_late = datetime.now(UTC) if version_info >= (3, 11) else datetime.utcnow()
|
|
137
|
+
seed = int(how_late.strftime("%Y%m%d%H%M%S%f")) if seed is None else seed
|
|
138
|
+
# As long as the new safer PCG64DXSM generator is not the default, override the generator.
|
|
139
|
+
rng = Generator(PCG64DXSM(seed)) if isinstance(seed, int | np.int_) else seed
|
|
140
|
+
# Output files of the script are datetime stamped.
|
|
141
|
+
timestr = how_late.strftime("%Y%m%dT%H%M%S")
|
|
142
|
+
results_folder = Path.cwd() / "Output" / f"{timestr}_RSA"
|
|
143
|
+
|
|
144
|
+
time_count: count[int] = count()
|
|
145
|
+
|
|
146
|
+
temp_results_folder = results_folder
|
|
147
|
+
attempt_count: int = 0
|
|
148
|
+
# while os.path.isdir(temp_results_folder):
|
|
149
|
+
while temp_results_folder.is_dir():
|
|
150
|
+
temp_results_folder = results_folder.parent / (results_folder.name + f"_{attempt_count}")
|
|
151
|
+
# Add a counter to the end of the folder name.
|
|
152
|
+
attempt_count += 1
|
|
153
|
+
|
|
154
|
+
results_folder = temp_results_folder
|
|
155
|
+
|
|
156
|
+
surf = Surface(rsa_config, lattice_type=lattice_type, lattice_a=lattice_a, site_count=site_count)
|
|
157
|
+
if custom_grid_flg:
|
|
158
|
+
surf.generate_custom_surface(site_x_coords, site_y_coords, bounding_x_coord, bounding_y_coord)
|
|
159
|
+
else:
|
|
160
|
+
surf.generate_grid(rng)
|
|
161
|
+
|
|
162
|
+
molecules = [] # Initially, there are none.
|
|
163
|
+
rot_syms = rotation_symmetries # Rotation symmetry
|
|
164
|
+
mirror_syms = reflection_symmetries # Mirror symmetry
|
|
165
|
+
rot_cnts = rotation_counts
|
|
166
|
+
mgc: count[int] = count()
|
|
167
|
+
if isinstance(sticking_probability, float):
|
|
168
|
+
sticking_probability = [sticking_probability] * len(molecules_list)
|
|
169
|
+
elif not isinstance(sticking_probability, list | np.ndarray):
|
|
170
|
+
errmsg = "sticking_probability must be a float, list, or np.ndarray"
|
|
171
|
+
raise TypeError(errmsg)
|
|
172
|
+
|
|
173
|
+
pp: Polygon
|
|
174
|
+
for idx, (pp, stick) in enumerate(zip(molecules_list, sticking_probability, strict=False)):
|
|
175
|
+
molecules.append(
|
|
176
|
+
MoleculeGroup(
|
|
177
|
+
rsa_config,
|
|
178
|
+
pp,
|
|
179
|
+
rot_syms[idx],
|
|
180
|
+
mirror_syms[idx],
|
|
181
|
+
surf.all_site_count,
|
|
182
|
+
mgc,
|
|
183
|
+
rot_cnts[idx],
|
|
184
|
+
sticking_probability=stick,
|
|
185
|
+
),
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
dbl_max_rad: float = 2.0 * max(cule.max_radius for cule in molecules)
|
|
189
|
+
surf.bp.biggest_radius = dbl_max_rad
|
|
190
|
+
|
|
191
|
+
surf.bp.generate_boundary_conditions(surf) # Generate the boundary conditions.
|
|
192
|
+
for molec in molecules: # Generate the BC and molecules.
|
|
193
|
+
molec.bp.biggest_radius = dbl_max_rad
|
|
194
|
+
molec.bp.generate_boundary_conditions(surf, molec)
|
|
195
|
+
molec.generate_rotated_molecules(molec.bp, molecules)
|
|
196
|
+
sim = Simulator(
|
|
197
|
+
rsa_config,
|
|
198
|
+
include_rejected_flux=include_rejected_flux,
|
|
199
|
+
surf=surf,
|
|
200
|
+
mol_groups=molecules,
|
|
201
|
+
rng=rng,
|
|
202
|
+
boundary_type=boundary_condition,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
all_flux, phi = _select_and_run(
|
|
206
|
+
sim,
|
|
207
|
+
surf,
|
|
208
|
+
molecules,
|
|
209
|
+
simulation_type,
|
|
210
|
+
include_rejected_flux,
|
|
211
|
+
time_count,
|
|
212
|
+
timestep_limit,
|
|
213
|
+
dosing_distribution,
|
|
214
|
+
)
|
|
215
|
+
gaps = _postprocessing(
|
|
216
|
+
sim,
|
|
217
|
+
surf,
|
|
218
|
+
molecules,
|
|
219
|
+
print_output_flag,
|
|
220
|
+
plot_output_flag,
|
|
221
|
+
calculate_gap_size,
|
|
222
|
+
results_folder,
|
|
223
|
+
timestr,
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
return [mgr.molecule_counter for mgr in sim.molgroups], gaps, seed, all_flux, phi
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _run_sequential(
|
|
230
|
+
sim: Simulator,
|
|
231
|
+
surf: Surface,
|
|
232
|
+
molecules: list[MoleculeGroup],
|
|
233
|
+
time_count: count[int],
|
|
234
|
+
timestep_limit: int,
|
|
235
|
+
) -> None:
|
|
236
|
+
for moldx, molgr in enumerate(sim.molgroups):
|
|
237
|
+
while molgr.vacancy_count and next(time_count) < timestep_limit:
|
|
238
|
+
sim.attempt_place_molecule(surf, molecules[moldx])
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _run_codosing(
|
|
242
|
+
sim: Simulator,
|
|
243
|
+
surf: Surface,
|
|
244
|
+
molecules: list[MoleculeGroup],
|
|
245
|
+
time_count: count[int],
|
|
246
|
+
timestep_limit: int,
|
|
247
|
+
dosing_distribution: list[float] | None = None,
|
|
248
|
+
) -> None:
|
|
249
|
+
for moldx, molgr in enumerate(sim.molgroups):
|
|
250
|
+
while molgr.vacancy_count and next(time_count) < timestep_limit:
|
|
251
|
+
sim.attempt_random_placement(surf, *molecules[moldx:], weights=dosing_distribution)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _run_cascade(
|
|
255
|
+
sim: Simulator,
|
|
256
|
+
surf: Surface,
|
|
257
|
+
molecules: list[MoleculeGroup],
|
|
258
|
+
time_count: count[int],
|
|
259
|
+
timestep_limit: int,
|
|
260
|
+
) -> None:
|
|
261
|
+
for moldx, molgr in enumerate(sim.molgroups):
|
|
262
|
+
while molgr.vacancy_count and next(time_count) < timestep_limit:
|
|
263
|
+
sim.attempt_cascading_placement(surf, *molecules[moldx:])
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _run_flux(
|
|
267
|
+
sim: Simulator,
|
|
268
|
+
surf: Surface,
|
|
269
|
+
molecules: list[MoleculeGroup],
|
|
270
|
+
timestep_limit: int,
|
|
271
|
+
) -> tuple[IdxArray, IdxArray]:
|
|
272
|
+
"""Adsorb while taking steps into account.
|
|
273
|
+
|
|
274
|
+
:param sim: Simulator.
|
|
275
|
+
:param surf: Surface.
|
|
276
|
+
:param molecules: MoleculeGroups list, the molecules that will be added to the surface.
|
|
277
|
+
:param timestep_limit: int, number of timesteps to simulate.
|
|
278
|
+
:return: list of indices during which adsorption takes place.
|
|
279
|
+
"""
|
|
280
|
+
all_flux: tuple[IdxArray, ...] = ()
|
|
281
|
+
all_phis: list[int] = []
|
|
282
|
+
for mdx, molgr in enumerate(sim.molgroups):
|
|
283
|
+
mol_flux: list[int] = []
|
|
284
|
+
for step in range(timestep_limit):
|
|
285
|
+
if not molgr.vacancy_count:
|
|
286
|
+
break # Done when nothing is available.
|
|
287
|
+
flag, *_, phis = sim.attempt_cascading_placement(surf, *molecules[mdx:])
|
|
288
|
+
if flag:
|
|
289
|
+
mol_flux.append(step)
|
|
290
|
+
all_phis.append(np.max(phis))
|
|
291
|
+
|
|
292
|
+
all_flux += cast("tuple[IdxArray, ...]", (np.asarray(mol_flux, dtype=np.int_),))
|
|
293
|
+
|
|
294
|
+
return all_flux[0], np.array(all_phis, dtype=np.int_) # FIXME: Fix the [0] later.
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _run_flux_fixedrotation(
|
|
298
|
+
sim: Simulator,
|
|
299
|
+
surf: Surface,
|
|
300
|
+
molecules: list[MoleculeGroup],
|
|
301
|
+
timestep_limit: int,
|
|
302
|
+
distribution: list[float] | None = None,
|
|
303
|
+
) -> tuple[IdxArray, IdxArray]:
|
|
304
|
+
"""Adsorb while taking steps into account. Rotation is fixed and sites are varied instead.
|
|
305
|
+
|
|
306
|
+
:param sim: Simulator.
|
|
307
|
+
:param surf: Surface.
|
|
308
|
+
:param molecules: MoleculeGroups list, the molecules that will be added to the surface.
|
|
309
|
+
:param timestep_limit: int, number of timesteps to simulate.
|
|
310
|
+
:param distribution: list of floats indicating the distribution of the molecules. Empty for uniform distribution.
|
|
311
|
+
:return: list of indices during which adsorption takes place.
|
|
312
|
+
"""
|
|
313
|
+
mol_flux: list[int] = []
|
|
314
|
+
all_phis: list[int] = []
|
|
315
|
+
for step in range(timestep_limit):
|
|
316
|
+
if not np.any([molgroup.vacancy_count for molgroup in molecules]):
|
|
317
|
+
break # If nothing is available, terminate.
|
|
318
|
+
|
|
319
|
+
randmol: MoleculeGroup = sim.rng.choice(molecules, p=distribution)
|
|
320
|
+
if not randmol.vacancy_count:
|
|
321
|
+
continue
|
|
322
|
+
flag, *_, phi = sim.attempt_place_molecule(surf, randmol)
|
|
323
|
+
if flag:
|
|
324
|
+
mol_flux.append(step)
|
|
325
|
+
all_phis.append(np.max(phi))
|
|
326
|
+
|
|
327
|
+
return np.array(mol_flux, dtype=np.int_), np.array(all_phis, dtype=np.int_)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _initialise_run_parameters(
|
|
331
|
+
molecules_list: Polygon | list[Polygon] | np.ndarray[tuple[int], np.dtype[Polygon]] | None = None,
|
|
332
|
+
rotation_symmetries: int | list[int] | np.ndarray[tuple[int], np.dtype[np.int_]] | None = None,
|
|
333
|
+
reflection_symmetries: bool | list[bool] | np.ndarray[tuple[int], np.dtype[np.bool_]] | None = None,
|
|
334
|
+
rotation_counts: int | list[int] | np.ndarray[tuple[int], np.dtype[np.int_]] | None = None,
|
|
335
|
+
simulation_type: str = "sequential",
|
|
336
|
+
) -> tuple[GeoArray, IdxArray, BoolArray, IdxArray]:
|
|
337
|
+
"""Initialise run parameters.
|
|
338
|
+
|
|
339
|
+
:param molecules_list: 2D Molecule footprints.
|
|
340
|
+
:param rotation_symmetries: Rotation symmetries of the molecules.
|
|
341
|
+
:param reflection_symmetries: Reflection symmetries of the molecules.
|
|
342
|
+
:param rotation_counts: Number of rotations.
|
|
343
|
+
:param simulation_type: Type of dosing scheme.
|
|
344
|
+
:return: List of molecules, rotation symmetries, reflection symmetries, rotation counts.
|
|
345
|
+
:raises ValueError: If the requested `simulation_type` does not exist.
|
|
346
|
+
"""
|
|
347
|
+
molecules_list = [mol.circulium(0.55)] if molecules_list is None else molecules_list
|
|
348
|
+
rotation_symmetries = [0] if rotation_symmetries is None else rotation_symmetries
|
|
349
|
+
reflection_symmetries = [True] if reflection_symmetries is None else reflection_symmetries
|
|
350
|
+
rotation_counts = [360] if rotation_counts is None else rotation_counts
|
|
351
|
+
if simulation_type not in {"sequential", "codosing", "cascade"}:
|
|
352
|
+
errmsg = "The simulation type must be either 'sequential', 'codosing', or 'cascade'."
|
|
353
|
+
raise ValueError(errmsg)
|
|
354
|
+
|
|
355
|
+
molecules_list = _turn_into_list(molecules_list, Polygon)
|
|
356
|
+
rotation_symmetries = _turn_into_list(rotation_symmetries, int)
|
|
357
|
+
reflection_symmetries = _turn_into_list(reflection_symmetries, bool)
|
|
358
|
+
rotation_counts = _turn_into_list(rotation_counts, int)
|
|
359
|
+
|
|
360
|
+
mol_list_size = molecules_list.size
|
|
361
|
+
rot_syms = _repeater(rotation_symmetries, mol_list_size)
|
|
362
|
+
refl_syms = _repeater(reflection_symmetries, mol_list_size)
|
|
363
|
+
rot_cnts = _repeater(rotation_counts, mol_list_size)
|
|
364
|
+
|
|
365
|
+
return molecules_list, rot_syms, refl_syms, rot_cnts
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _turn_into_list(val_or_list: T1 | list[T1], compare_to: type[T1]) -> np.ndarray[tuple[int], np.dtype[T2]]: # type: ignore[explicit-any]
|
|
369
|
+
"""Turn a variable or a list into an array.
|
|
370
|
+
|
|
371
|
+
:param val_or_list: value or list.
|
|
372
|
+
:param compare_to: comparison type. Should be either the type of the value or the type in the list.
|
|
373
|
+
:return: the 1D array of the original variable or list.
|
|
374
|
+
"""
|
|
375
|
+
return np.asarray([val_or_list] if isinstance(val_or_list, compare_to) else val_or_list)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _repeater(orig_array: Tn, comparison_len: int) -> Tn: # type: ignore[explicit-any]
|
|
379
|
+
"""Take the array and repeat it if it has a length of 1.
|
|
380
|
+
|
|
381
|
+
:param orig_array: original array.
|
|
382
|
+
:param comparison_len: length of the repetition.
|
|
383
|
+
:return: the array repeated to the proper length.
|
|
384
|
+
"""
|
|
385
|
+
return np.repeat(orig_array, comparison_len) if orig_array.size == 1 else orig_array # type: ignore[return-value]
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _error_checker(
|
|
389
|
+
molecules_list: GeoArray,
|
|
390
|
+
rotation_symmetries: IdxArray,
|
|
391
|
+
reflection_symmetries: BoolArray,
|
|
392
|
+
rotation_counts: IdxArray,
|
|
393
|
+
simulation_type: str,
|
|
394
|
+
dosing_distribution: list[float] | None = None,
|
|
395
|
+
boundary_condition: str | None = None,
|
|
396
|
+
site_x_coords: DistArray | None = None,
|
|
397
|
+
site_y_coords: DistArray | None = None,
|
|
398
|
+
bounding_x_coord: float | None = None,
|
|
399
|
+
bounding_y_coord: float | None = None,
|
|
400
|
+
) -> bool:
|
|
401
|
+
"""Check the errors. Returns bool denoting custom grid (False if grid is not custom).
|
|
402
|
+
|
|
403
|
+
:param molecules_list: list of molecules.
|
|
404
|
+
:param rotation_symmetries: rotation symmetries.
|
|
405
|
+
:param reflection_symmetries: reflection symmetries.
|
|
406
|
+
:param rotation_counts: rotation counts.
|
|
407
|
+
:param simulation_type: simulation type.
|
|
408
|
+
:param dosing_distribution: dosing distribution.
|
|
409
|
+
:param boundary_condition: boundary condition.
|
|
410
|
+
:param site_x_coords: site x coordinates.
|
|
411
|
+
:param site_y_coords: site y coordinates.
|
|
412
|
+
:param bounding_x_coord: boundary x coordinate.
|
|
413
|
+
:param bounding_y_coord: boundary y coordinate.
|
|
414
|
+
:return: the custom grid flag.
|
|
415
|
+
:raises ValueError:
|
|
416
|
+
1) if the length of the molecules, symmetries, reflections, and rotations are unequal,
|
|
417
|
+
2) if the dosing distribution is not the same length as the molecule list,
|
|
418
|
+
3) if the provided boundary condition is not supported,
|
|
419
|
+
4) if the custom grid x/y coordinates/boundaries are not all empty or not all provided.
|
|
420
|
+
"""
|
|
421
|
+
if not len(molecules_list) == len(rotation_symmetries) == len(reflection_symmetries) == len(rotation_counts):
|
|
422
|
+
errmsg = "Number of molecules, symmetries, and/or rotation counts do not match."
|
|
423
|
+
raise ValueError(errmsg)
|
|
424
|
+
|
|
425
|
+
if (
|
|
426
|
+
simulation_type == "codosing"
|
|
427
|
+
and dosing_distribution is not None
|
|
428
|
+
and len(molecules_list) != len(dosing_distribution)
|
|
429
|
+
):
|
|
430
|
+
errmsg = "Dosing distribution must be the same length as the molecule list."
|
|
431
|
+
raise ValueError(errmsg)
|
|
432
|
+
|
|
433
|
+
if boundary_condition is not None and boundary_condition not in {"soft", "hard", "periodic"}:
|
|
434
|
+
errmsg = "Boundary condition must be either 'soft', 'hard', 'periodic', or None."
|
|
435
|
+
raise ValueError(errmsg)
|
|
436
|
+
|
|
437
|
+
custom_any_all: list[bool] = [False, True]
|
|
438
|
+
for comparison in [site_x_coords, site_y_coords, bounding_x_coord, bounding_y_coord]:
|
|
439
|
+
temp_result: bool = comparison is not None
|
|
440
|
+
custom_any_all[0] |= temp_result
|
|
441
|
+
custom_any_all[1] &= temp_result
|
|
442
|
+
|
|
443
|
+
if custom_any_all[0] != custom_any_all[1]: # If not all are None or not None:
|
|
444
|
+
errmsg = """A custom grid will only be generated if 'site_x_coords', 'site_y_coords',
|
|
445
|
+
'bounding_x_coord' and 'bounding_y_coord' are specified. Otherwise, leave all None."""
|
|
446
|
+
raise ValueError(errmsg)
|
|
447
|
+
return custom_any_all[1]
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _postprocessing(
|
|
451
|
+
sim: Simulator,
|
|
452
|
+
surf: Surface,
|
|
453
|
+
molecules: list[MoleculeGroup],
|
|
454
|
+
print_output_flag: bool,
|
|
455
|
+
plot_output_flag: bool,
|
|
456
|
+
calculate_gap_size: bool,
|
|
457
|
+
results_folder: str | Path,
|
|
458
|
+
timestr: str,
|
|
459
|
+
) -> DistArray:
|
|
460
|
+
"""Perform post-processing of the data.
|
|
461
|
+
|
|
462
|
+
:param sim: simulator.
|
|
463
|
+
:param surf: surface.
|
|
464
|
+
:param molecules: list of molecules.
|
|
465
|
+
:param print_output_flag: True if output such as coverages and fraction of covered area should be printed.
|
|
466
|
+
:param plot_output_flag: True if plots are to be shown.
|
|
467
|
+
:param calculate_gap_size: True if gap size should be calculated. Can be computationally intensive.
|
|
468
|
+
:param results_folder: results folder.
|
|
469
|
+
:param timestr: timestr to use.
|
|
470
|
+
:return: the gap size distribution. Empty array if calculate_gap_size is False.
|
|
471
|
+
"""
|
|
472
|
+
if print_output_flag:
|
|
473
|
+
for mdx, molecul in enumerate(sim.molgroups):
|
|
474
|
+
print(f"Mol {mdx}, {molecul.molecule_counter}")
|
|
475
|
+
print(f"Mol dens {mdx}, {100 * molecul.molecule_counter / surf.area}")
|
|
476
|
+
print(f"areamol {mdx}: {molecul.area}")
|
|
477
|
+
|
|
478
|
+
if plot_output_flag:
|
|
479
|
+
Path(results_folder).mkdir(parents=True)
|
|
480
|
+
sim.plot_covered_grid(
|
|
481
|
+
surf,
|
|
482
|
+
molecules,
|
|
483
|
+
save_flag=True,
|
|
484
|
+
plt_flag=True,
|
|
485
|
+
timestr=f"{timestr}",
|
|
486
|
+
results_folder=results_folder,
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
return sim.analyse_gap_size(surf) if calculate_gap_size else np.empty(0)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _select_and_run(
|
|
493
|
+
sim: Simulator,
|
|
494
|
+
surf: Surface,
|
|
495
|
+
molecules: list[MoleculeGroup],
|
|
496
|
+
simulation_type: str,
|
|
497
|
+
include_rejected_flux: bool,
|
|
498
|
+
time_count: count[int],
|
|
499
|
+
timestep_limit: int,
|
|
500
|
+
dosing_distribution: list[float] | None = None,
|
|
501
|
+
) -> tuple[IdxArray, IdxArray]:
|
|
502
|
+
"""Select and run. A collection of the simulations. Putting them in one function helps streamline adjusting them.
|
|
503
|
+
|
|
504
|
+
:param sim: simulator.
|
|
505
|
+
:param surf: surface.
|
|
506
|
+
:param molecules: list of molecules.
|
|
507
|
+
:param simulation_type: simulation type.
|
|
508
|
+
:param include_rejected_flux: True if rejected flux should be included.
|
|
509
|
+
:param timestep_limit: number of time steps.
|
|
510
|
+
:param dosing_distribution: dosing distribution. Leave empty if not needed or uniform.
|
|
511
|
+
:return: Fluxes per molecule if selected.
|
|
512
|
+
:raises ValueError: if the `simulation_type` (dosing scheme) and flux flag combination are not supported.
|
|
513
|
+
"""
|
|
514
|
+
all_flux: IdxArray = np.empty(0, dtype=np.int_)
|
|
515
|
+
phis: IdxArray = np.empty(0, dtype=np.int_)
|
|
516
|
+
|
|
517
|
+
match (simulation_type, include_rejected_flux):
|
|
518
|
+
case ("sequential", False):
|
|
519
|
+
_run_sequential(sim, surf, molecules, time_count, timestep_limit)
|
|
520
|
+
case ("codosing", False):
|
|
521
|
+
_run_codosing(sim, surf, molecules, time_count, timestep_limit, dosing_distribution)
|
|
522
|
+
case ("cascade", False):
|
|
523
|
+
_run_cascade(sim, surf, molecules, time_count, timestep_limit)
|
|
524
|
+
case ("sequential", True):
|
|
525
|
+
all_flux, phis = _run_flux(sim, surf, molecules, timestep_limit)
|
|
526
|
+
case ("codosing", True):
|
|
527
|
+
all_flux, phis = _run_flux_fixedrotation(sim, surf, molecules, timestep_limit)
|
|
528
|
+
case (_, _):
|
|
529
|
+
errmsg = f"Simulation type {simulation_type} with rejected_flux = {include_rejected_flux} is not supported."
|
|
530
|
+
raise ValueError(errmsg)
|
|
531
|
+
return all_flux, phis
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def main() -> Literal[0]:
|
|
535
|
+
"""Run the RSA script, for demonstration purposes.
|
|
536
|
+
|
|
537
|
+
:return: 0 on success.
|
|
538
|
+
"""
|
|
539
|
+
config_path = Path(__file__).parent / "config.json"
|
|
540
|
+
rsa_config = RsaConfig(str(config_path))
|
|
541
|
+
start = time.perf_counter()
|
|
542
|
+
run_simulation(rsa_config, plot_output_flag=True, include_rejected_flux=False)
|
|
543
|
+
end = time.perf_counter()
|
|
544
|
+
totaltime = f"{(end - start):.0f} seconds elapsed since start."
|
|
545
|
+
print(totaltime)
|
|
546
|
+
|
|
547
|
+
return 0
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
if __name__ == "__main__": # Best practice.
|
|
551
|
+
main()
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: AdsorPy
|
|
3
|
+
Version: 1.0.2
|
|
4
|
+
Summary: Random sequential adsorption (RSA) simulation, 2D lattice-based.
|
|
5
|
+
Project-URL: Repository, https://github.com/JoostFWMaas/AdsorPy
|
|
6
|
+
Project-URL: Documentation, https://joostfwmaas.github.io/AdsorPy
|
|
7
|
+
Project-URL: Changelog, https://github.com/JoostFWMaas/AdsorPy/blob/main/CHANGELOG.md
|
|
8
|
+
Author-email: "J.F.W. Maas" <j.f.w.maas@tue.nl>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE.md
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: matplotlib
|
|
21
|
+
Requires-Dist: numba
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: rtree
|
|
24
|
+
Requires-Dist: shapely
|
|
25
|
+
Provides-Extra: testing
|
|
26
|
+
Requires-Dist: hypothesis; extra == 'testing'
|
|
27
|
+
Requires-Dist: mypy; extra == 'testing'
|
|
28
|
+
Requires-Dist: pytest; extra == 'testing'
|
|
29
|
+
Requires-Dist: pytest-cov; extra == 'testing'
|
|
30
|
+
Requires-Dist: ruff; extra == 'testing'
|
|
31
|
+
Requires-Dist: scipy==1.15.3; (python_version <= '3.10') and extra == 'testing'
|
|
32
|
+
Requires-Dist: scipy==1.16.3; (python_version > '3.10') and extra == 'testing'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# AdsorPy
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+

|
|
40
|
+
[](https://codecov.io/github/JoostFWMaas/AdsorPy)
|
|
41
|
+
|
|
42
|
+
Lattice-based random sequential adsorption (RSA) Python 3.10+ script.
|
|
43
|
+
|
|
44
|
+
In RSA, molecules arrive one by one at a surface. Adsorption takes place if the molecule does not overlap with molecules
|
|
45
|
+
already on the surface.
|
|
46
|
+
The list of available orientations for the molecule is traversed in random order until the first orientation that fits
|
|
47
|
+
is found, or until the list is exhausted.
|
|
48
|
+
All available sites are checked, and various metrics can be extracted afterwards such as the coverage, covered area, and
|
|
49
|
+
gap size distribution.
|
|
50
|
+
|
|
51
|
+
## How to use
|
|
52
|
+
|
|
53
|
+
Run the `adsorpy.main` in order to run a simple single run using the standard disk-shaped molecule on hexagonal aluminium oxide.
|
|
54
|
+
New molecules can be created by running the `adsorpy.molecule_lib` or by calling the `adsorpy.molecule_lib.first_time_loader()` function. Molecules can be generated from `.xyz` files. It is
|
|
55
|
+
recommended to run `adsorpy.molecule_lib` directly from command line to define the molecule orientation, then store the new
|
|
56
|
+
molecule string for repeated use.
|
|
57
|
+
|
|
58
|
+
Run the `adsorpy.run_simulation.run_simulation()` function with the molecule footprints generated in the previous step. Output can be printed to stdout, plotted, and saved.
|
|
59
|
+
|
|
60
|
+
User friendliness will be updated at a later stage, allowing the user to define simulation modes, surfaces, and
|
|
61
|
+
molecules more easily.
|
|
62
|
+
|
|
63
|
+
Documentation (generated with `Sphinx`): https://joostfwmaas.github.io/AdsorPy/
|
|
64
|
+
|
|
65
|
+
## Future additions
|
|
66
|
+
|
|
67
|
+
In a future update, the code will be expanded with diffusion, desorption, and species conversion (changing from one molecule on the surface to another).
|
|
68
|
+
|
|
69
|
+
## Design philosophy
|
|
70
|
+
|
|
71
|
+
Because AdsorPy has been made with scientific rigour in mind, the package is tested in multiple ways:
|
|
72
|
+
- Unit tests (`Pytest`) of the code ensure correct behaviour for expected input.
|
|
73
|
+
- Property tests (`Hypothesis`) of the most critical code components ensure correct behaviour for unexpected input as well.
|
|
74
|
+
- `Mypy` (in `--strict` mode) ensures that the package is correctly-typed, as if it were static. The `py.typed` file--a promise that the code is type-hinted properly--is added because the code passes this test.
|
|
75
|
+
- `Ruff` is used as a linter with almost all rules enabled (see the pyproject.toml for the list of exclusions and reasons).
|
|
76
|
+
- `Tox` is used to run all of the aforementioned tests in parallel for multiple Python versions to ensure correct behaviour.
|
|
77
|
+
- CI is used for automated testing.
|
|
78
|
+
|
|
79
|
+
The package also makes use of an optional config file that falls back on standard behaviour, because configs are often used in scientific software (set-and-forget).
|
|
80
|
+
|
|
81
|
+
# Openness and academic collaboration
|
|
82
|
+
|
|
83
|
+
The script was made public for the sake of openness and academic collaboration. Please let me know if you have questions about the script, or if you have discovered any issues/bugs.
|
|
84
|
+
At the end of this file, I will place a list of papers that make use of this work. Feel free to contact me if you want your work to be added to the list as well.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
adsorpy/VdW_Radii.csv,sha256=O89xkkJ_N0QBgrQxh3ciF0W5FWlcnacnnq_5_xxc7ao,721
|
|
2
|
+
adsorpy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
adsorpy/config.json,sha256=lj0ZeJlmjGmpF1W1yB7aGrzrFN58R5AiTFDqTykUsv4,1472
|
|
4
|
+
adsorpy/molecule_colour.json,sha256=yNWHq1ADV6Oybq7-v0B10-wFR5hh_jahLsl0WM7RlRs,2058
|
|
5
|
+
adsorpy/molecule_lib.py,sha256=fl73tux4Tlgg85zxqdm8jog77M0buyaY0hxO_W6bJg8,22137
|
|
6
|
+
adsorpy/randomsequentialadsorption.py,sha256=3f_25BzmalQhM1lgA9NoITNHsGeVNH7Q5OqDJbNZwKc,70331
|
|
7
|
+
adsorpy/rsa_calculator.py,sha256=7-DCNTvz0xY0d53O888bzSkpplAt89bwMXDY65jd9s8,16167
|
|
8
|
+
adsorpy/rsa_config.py,sha256=__p1PunGh1eNs8UzWLRohG1cYKDPFiVfnIH2T1vxsWI,3077
|
|
9
|
+
adsorpy/run_simulation.py,sha256=-bdojo3N3hQG30m3b1qTx_TC8cb28l9KxzLuw0Yn36U,23825
|
|
10
|
+
adsorpy-1.0.2.dist-info/METADATA,sha256=ReUe7vsSwOgPmngnIXImI9ljeP2nzpdtPmGgJDJMi9o,4728
|
|
11
|
+
adsorpy-1.0.2.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
12
|
+
adsorpy-1.0.2.dist-info/licenses/LICENSE.md,sha256=oOf0GHAe5rjSYijPCbUvS4C_8uY1YTD9VTEbZDdRyyM,1070
|
|
13
|
+
adsorpy-1.0.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 J.F.W. Maas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|