Core¶
The core module provides the fundamental data structures and building blocks for MolPy.
Atomistic¶
Atom ¶
Bases: Entity
Atom entity (expects optional keys like {"type": "C", "xyz": [...]})
Atomistic ¶
Atomistic(**props)
Bases: Struct, MembershipMixin, SpatialMixin, ConnectivityMixin
Source code in src/molpy/core/atomistic.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
xyz
property
¶
xyz
Get atomic positions as numpy array.
Returns:
| Type | Description |
|---|---|
|
Nx3 array of atomic coordinates, or list of lists if numpy not available |
add_angle ¶
add_angle(angle)
Add an existing Angle object to the structure.
Source code in src/molpy/core/atomistic.py
337 338 339 340 | |
add_angles ¶
add_angles(angles)
Add multiple existing Angle objects to the structure.
Source code in src/molpy/core/atomistic.py
425 426 427 428 429 | |
add_atom ¶
add_atom(atom)
Add an existing Atom object to the structure.
Source code in src/molpy/core/atomistic.py
327 328 329 330 | |
add_atoms ¶
add_atoms(atoms)
Add multiple existing Atom objects to the structure.
Source code in src/molpy/core/atomistic.py
413 414 415 416 417 | |
add_bond ¶
add_bond(bond)
Add an existing Bond object to the structure.
Source code in src/molpy/core/atomistic.py
332 333 334 335 | |
add_bonds ¶
add_bonds(bonds)
Add multiple existing Bond objects to the structure.
Source code in src/molpy/core/atomistic.py
419 420 421 422 423 | |
add_dihedral ¶
add_dihedral(dihedral)
Add an existing Dihedral object to the structure.
Source code in src/molpy/core/atomistic.py
342 343 344 345 | |
add_dihedrals ¶
add_dihedrals(dihedrals)
Add multiple existing Dihedral objects to the structure.
Source code in src/molpy/core/atomistic.py
431 432 433 434 435 | |
align ¶
align(a, b, *, a_dir=None, b_dir=None, flip=False, entity_type=Atom)
Align entities. Returns self for chaining.
Source code in src/molpy/core/atomistic.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | |
def_angle ¶
def_angle(a, b, c, /, **attrs)
Create a new Angle between three atoms and add it to the structure.
Source code in src/molpy/core/atomistic.py
228 229 230 231 232 | |
def_angles ¶
def_angles(angles_data)
Create multiple Angles from a list of (itom, jtom, ktom) or (itom, jtom, ktom, attrs) tuples.
Source code in src/molpy/core/atomistic.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | |
def_atom ¶
def_atom(**attrs)
Create a new Atom and add it to the structure.
If 'xyz' is provided, it will be converted to separate x, y, z fields.
Source code in src/molpy/core/atomistic.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | |
def_atoms ¶
def_atoms(atoms_data)
Create multiple Atoms from a list of attribute dictionaries.
Source code in src/molpy/core/atomistic.py
349 350 351 352 353 354 355 | |
def_bond ¶
def_bond(a, b, /, **attrs)
Create a new Bond between two atoms and add it to the structure.
Source code in src/molpy/core/atomistic.py
222 223 224 225 226 | |
def_bonds ¶
def_bonds(bonds_data)
Create multiple Bonds from a list of (itom, jtom) or (itom, jtom, attrs) tuples.
Source code in src/molpy/core/atomistic.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
def_dihedral ¶
def_dihedral(a, b, c, d, /, **attrs)
Create a new Dihedral between four atoms and add it to the structure.
Source code in src/molpy/core/atomistic.py
234 235 236 237 238 239 240 | |
def_dihedrals ¶
def_dihedrals(dihedrals_data)
Create multiple Dihedrals from a list of (itom, jtom, ktom, ltom) or (itom, jtom, ktom, ltom, attrs) tuples.
Source code in src/molpy/core/atomistic.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
extract_subgraph ¶
extract_subgraph(center_entities, radius, entity_type=Atom, link_type=Bond)
Extract subgraph preserving all topology (bonds, angles, dihedrals).
Overrides ConnectivityMixin.extract_subgraph to ensure all topology types (bonds, angles, dihedrals) are preserved in the extracted subgraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center_entities
|
Iterable[Atom]
|
Center atoms for extraction |
required |
radius
|
int
|
Topological radius |
required |
entity_type
|
type[Atom]
|
Entity type (should be Atom) |
Atom
|
link_type
|
type[Link]
|
Link type for topology calculation (should be Bond) |
Bond
|
Returns:
| Type | Description |
|---|---|
tuple[Atomistic, list[Atom]]
|
Tuple of (subgraph Atomistic, edge atoms) |
Source code in src/molpy/core/atomistic.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
get_topo ¶
get_topo(entity_type=Atom, link_type=Bond, gen_angle=False, gen_dihe=False, clear_existing=False)
Generate topology (angles and dihedrals) from bonds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_type
|
type[Entity]
|
Entity type to include in topology (default: Atom) |
Atom
|
link_type
|
type[Link]
|
Link type to use for connections (default: Bond) |
Bond
|
gen_angle
|
bool
|
Whether to generate angles |
False
|
gen_dihe
|
bool
|
Whether to generate dihedrals |
False
|
clear_existing
|
bool
|
If True, clear existing angles/dihedrals before generating new ones. If False, only add angles/dihedrals that don't already exist. |
False
|
Returns:
| Type | Description |
|---|---|
|
Topology object |
Source code in src/molpy/core/atomistic.py
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
move ¶
move(delta, *, entity_type=Atom)
Move all entities by delta. Returns self for chaining.
Source code in src/molpy/core/atomistic.py
439 440 441 442 443 444 | |
replicate ¶
replicate(n, transform=None)
Create n copies and merge them into a new system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of copies to create |
required |
transform
|
Optional callable(copy, index) -> None to transform each copy |
None
|
Example
Create 10 waters in a line¶
waters = Water().replicate(10, lambda mol, i: mol.move([i*5, 0, 0]))
Create 3x3 grid¶
grid = Methane().replicate(9, lambda mol, i: mol.move([i%35, i//35, 0]))
Source code in src/molpy/core/atomistic.py
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | |
rotate ¶
rotate(axis, angle, about=None, *, entity_type=Atom)
Rotate entities around axis. Returns self for chaining.
Source code in src/molpy/core/atomistic.py
446 447 448 449 450 451 452 453 454 455 456 | |
scale ¶
scale(factor, about=None, *, entity_type=Atom)
Scale entities by factor. Returns self for chaining.
Source code in src/molpy/core/atomistic.py
458 459 460 461 462 463 464 465 466 467 | |
to_frame ¶
to_frame(atom_fields=None)
Convert to LAMMPS data Frame format.
Converts this Atomistic structure into a Frame suitable for writing as a LAMMPS data file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_fields
|
list[str] | None
|
List of atom fields to extract. If None, extracts all fields. |
None
|
bond_fields
|
List of bond fields to extract. If None, extracts all fields. |
required | |
angle_fields
|
List of angle fields to extract. If None, extracts all fields. |
required | |
dihedral_fields
|
List of dihedral fields to extract. If None, extracts all fields. |
required |
Returns:
| Type | Description |
|---|---|
Frame
|
Frame with atoms, bonds, angles, and dihedrals |
Example
butane = CH3() + CH2() + CH3()
Extract all fields¶
frame = butane.to_frame()
Extract specific fields only¶
frame = butane.to_frame( ... atom_fields=['xyz', 'charge', 'element', 'type'], ... bond_fields=['itom', 'jtom', 'type'], ... ) writer = LammpsDataWriter("system.data") writer.write(frame)
Source code in src/molpy/core/atomistic.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 | |
Dihedral ¶
Dihedral(a, b, c, d, /, **attrs)
Bases: Link
Dihedral (torsion) angle between four atoms
Source code in src/molpy/core/atomistic.py
73 74 75 76 77 78 | |
Box¶
Box ¶
Box(matrix=None, pbc=np.ones(3, dtype=bool), origin=np.zeros(3))
Bases: PeriodicBoundary
Initialize a Box object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | None
|
A 3x3 matrix representing the box dimensions. If None or all elements are zero, a zero matrix is used. If a 1D array of shape (3,) is provided, it is converted to a diagonal matrix. Defaults to None. |
None
|
pbc
|
ndarray
|
A 1D boolean array of shape (3,) indicating periodic boundary conditions along each axis. Defaults to an array of ones (True for all axes). |
ones(3, dtype=bool)
|
origin
|
ndarray
|
A 1D array of shape (3,) representing the origin of the box. Defaults to an array of zeros. |
zeros(3)
|
Source code in src/molpy/core/box.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
bounds
property
¶
bounds
Get the bounds of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 2D array with shape (3, 2) representing the bounds of the box. |
is_periodic
property
¶
is_periodic
Check if the box has periodic boundary conditions in all directions.
l
property
¶
l
Get the lengths of the box along each axis.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 1D array containing the lengths of the box along |
ndarray
|
the x, y, and z axes. |
lx
property
writable
¶
lx
Get the length of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the x-direction, derived from the |
float
|
first element of the matrix representing the box dimensions. |
ly
property
writable
¶
ly
Get the length of the simulation box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the y-direction. |
lz
property
writable
¶
lz
Get the length of the simulation box along the z-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The length of the box in the z-direction. |
matrix
property
¶
matrix
Get the matrix representation of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A 3x3 matrix representing the box dimensions. |
pbc
property
¶
pbc
Get the periodic boundary conditions of the box.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: A boolean array indicating periodicity along each axis. |
style
property
¶
style
Determine the style of the box based on its matrix.
Returns:
| Name | Type | Description |
|---|---|---|
Style |
Style
|
The style of the box (FREE, ORTHOGONAL, or TRICLINIC). |
volume
property
¶
volume
Calculate the volume of the box.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The volume of the box. |
xhi
property
¶
xhi
Calculate the upper boundary of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The x-coordinate of the upper boundary of the box, |
float
|
calculated as the difference between the first element of |
|
float
|
the matrix's first row and the x-coordinate of the origin. |
xlo
property
¶
xlo
Calculate the lower bound of the box along the x-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The x-coordinate of the lower bound, calculated as the |
float
|
negative of the x-component of the origin. |
xy
property
writable
¶
xy
Retrieve the xy component of the matrix.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The value at the (0, 1) position in the matrix. |
yhi
property
¶
yhi
Calculate the upper boundary of the box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The upper boundary value of the box in the y-dimension, |
float
|
calculated as the difference between the y-component of the |
|
float
|
matrix and the y-component of the origin. |
ylo
property
¶
ylo
Get the lower boundary of the box along the y-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The negative value of the y-coordinate of the origin. |
zhi
property
¶
zhi
Calculate the z-component of the box's upper boundary.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The z-coordinate of the upper boundary, calculated as the |
float
|
difference between the z-component of the matrix and the z-component |
|
float
|
of the origin. |
zlo
property
¶
zlo
Calculate the lower boundary of the box along the z-axis.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The z-coordinate of the lower boundary, calculated as the |
float
|
negative value of the third component of the origin vector. |
calc_lengths_angles_from_matrix
staticmethod
¶
calc_lengths_angles_from_matrix(matrix)
Calculate the lengths of the box edges and angles from its matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix representing the box. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[np.ndarray, np.ndarray]: lengths and angles |
Source code in src/molpy/core/box.py
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | |
calc_matrix_from_lengths_angles
staticmethod
¶
calc_matrix_from_lengths_angles(abc, angles)
Compute restricted triclinic box matrix from lengths and angles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
abc
|
ndarray
|
[a, b, c] lattice vector lengths |
required |
angles
|
ndarray
|
[alpha, beta, gamma] in degrees (angles between (b,c), (a,c), (a,b)) |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: 3x3 box matrix with lattice vectors as columns: [a | b | c] |
Source code in src/molpy/core/box.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | |
calc_matrix_from_size_tilts
staticmethod
¶
calc_matrix_from_size_tilts(sizes, tilts)
Get restricted triclinic box matrix from sizes and tilts
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sizes
|
ndarray
|
sizes of box edges |
required |
tilts
|
ndarray
|
tilts between box edges |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: restricted triclinic box matrix |
Source code in src/molpy/core/box.py
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
calc_style_from_matrix
staticmethod
¶
calc_style_from_matrix(matrix)
Determine the style of the box based on its matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix representing the box. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Style |
Style
|
The style of the box (FREE, ORTHOGONAL, or TRICLINIC). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the matrix does not correspond to a valid style. |
Source code in src/molpy/core/box.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
check_matrix
staticmethod
¶
check_matrix(matrix)
Validate the box matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
A 3x3 matrix to validate. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The validated matrix. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the matrix is not valid. |
Source code in src/molpy/core/box.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | |
diff ¶
diff(r1, r2)
Calculate the difference between two points considering periodic boundary conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first point. |
required |
r2
|
ndarray
|
The second point. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The difference vector. |
Source code in src/molpy/core/box.py
798 799 800 801 802 803 804 805 806 807 808 809 | |
diff_all ¶
diff_all(r1, r2)
Calculate the difference between all pairs of points in two sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first set of points. |
required |
r2
|
ndarray
|
The second set of points. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The difference vectors for all pairs. |
Source code in src/molpy/core/box.py
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 | |
diff_dr ¶
diff_dr(dr)
Calculate the difference vector considering periodic boundary conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dr
|
ndarray
|
The difference vector. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The adjusted difference vector. |
Source code in src/molpy/core/box.py
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 | |
dist ¶
dist(r1, r2)
Calculate the distance between two points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first point. |
required |
r2
|
ndarray
|
The second point. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The distance between the points. |
Source code in src/molpy/core/box.py
829 830 831 832 833 834 835 836 837 838 839 840 841 | |
dist_all ¶
dist_all(r1, r2)
Calculate the distances between all pairs of points in two sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r1
|
ndarray
|
The first set of points. |
required |
r2
|
ndarray
|
The second set of points. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The distances for all pairs. |
Source code in src/molpy/core/box.py
843 844 845 846 847 848 849 850 851 852 853 854 855 | |
from_box
classmethod
¶
from_box(box)
Create a new box from an existing box.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box
|
Box
|
The existing box. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Box |
Box
|
A new box with the same properties as the existing box. |
Source code in src/molpy/core/box.py
121 122 123 124 125 126 127 128 129 130 131 132 | |
from_lengths_angles
classmethod
¶
from_lengths_angles(lengths, angles)
Get box matrix from lengths and angles
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lengths
|
ndarray
|
lengths of box edges |
required |
angles
|
ndarray
|
angles between box edges in degree |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: box matrix |
Source code in src/molpy/core/box.py
639 640 641 642 643 644 645 646 647 648 649 650 651 | |
general2restrict
staticmethod
¶
general2restrict(matrix)
Convert general triclinc box matrix to restricted triclinic box matrix
Ref
https://docs.lammps.org/Howto_triclinic.html#transformation-from-general-to-restricted-triclinic-boxes
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
(3, 3) general triclinc box matrix |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: (3, 3) restricted triclinc box matrix |
Source code in src/molpy/core/box.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
get_images ¶
get_images(xyz)
Get the image flags of particles, accounting for box origin and triclinic shape.
Source code in src/molpy/core/box.py
763 764 765 766 767 768 769 | |
get_inv ¶
get_inv()
Get the inverse of the box matrix.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The inverse of the box matrix. |
Source code in src/molpy/core/box.py
771 772 773 774 775 776 777 778 | |
isin ¶
isin(xyz)
Check if point(s) xyz are inside the box. Args: xyz (np.ndarray): shape (..., 3) Returns: np.ndarray: boolean array, True if inside
Source code in src/molpy/core/box.py
881 882 883 884 885 886 887 888 889 890 891 | |
make_absolute ¶
make_absolute(xyz)
Convert fractional coordinates to absolute coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The fractional coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The absolute coordinates. |
Source code in src/molpy/core/box.py
869 870 871 872 873 874 875 876 877 878 879 | |
make_fractional ¶
make_fractional(xyz)
Convert absolute coordinates to fractional coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The absolute coordinates. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The fractional coordinates. |
Source code in src/molpy/core/box.py
857 858 859 860 861 862 863 864 865 866 867 | |
merge ¶
merge(other)
Merge two boxes to find their common space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Box
|
The other box to merge with. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Box |
Box
|
A new box representing the common space. |
Source code in src/molpy/core/box.py
893 894 895 896 897 898 899 900 901 902 903 | |
plot ¶
plot()
Plot the box representation. This method is a placeholder and should be implemented to visualize the box in 3D space.
Source code in src/molpy/core/box.py
77 78 79 80 81 82 | |
to_dict ¶
to_dict()
Convert the box to a dictionary representation.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing the box properties. |
Source code in src/molpy/core/box.py
920 921 922 923 924 925 926 927 928 929 930 931 | |
to_lengths_angles ¶
to_lengths_angles()
Get lengths and angles from box matrix
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
tuple[np.ndarray, np.ndarray]: lengths and angles |
Source code in src/molpy/core/box.py
653 654 655 656 657 658 659 660 | |
transform ¶
transform(transformation_matrix)
Transform the box using a transformation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transformation_matrix
|
ndarray
|
3x3 transformation matrix. |
required |
Returns:
| Type | Description |
|---|---|
Box
|
New Box with transformed dimensions. |
Source code in src/molpy/core/box.py
905 906 907 908 909 910 911 912 913 914 915 916 917 918 | |
unwrap ¶
unwrap(xyz, image)
Unwrap the coordinates of a particle based on its image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates of the particle. |
required |
image
|
ndarray
|
The image of the particle. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The unwrapped coordinates. |
Source code in src/molpy/core/box.py
750 751 752 753 754 755 756 757 758 759 760 761 | |
wrap_free ¶
wrap_free(xyz)
Wrap coordinates for a free box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
Source code in src/molpy/core/box.py
710 711 712 713 714 715 716 717 718 719 720 | |
wrap_orthogonal ¶
wrap_orthogonal(xyz)
Wrap coordinates for an orthogonal box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
Source code in src/molpy/core/box.py
722 723 724 725 726 727 728 729 730 731 732 733 | |
wrap_triclinic ¶
wrap_triclinic(xyz)
Wrap coordinates for a triclinic box style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xyz
|
ndarray
|
The coordinates to wrap. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: The wrapped coordinates. |
Source code in src/molpy/core/box.py
735 736 737 738 739 740 741 742 743 744 745 746 747 748 | |
Forcefield¶
AngleStyle ¶
AngleStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(itom, jtom, ktom, name='', **kwargs)
Define angle type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Central atom type |
required |
ktom
|
AtomType
|
Third atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom) |
''
|
**kwargs
|
Any
|
Angle parameters (e.g. k, theta0, etc.) |
{}
|
Source code in src/molpy/core/forcefield.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | |
to_potential ¶
to_potential()
Create corresponding Potential instance from AngleStyle.
Returns:
| Type | Description |
|---|---|
|
Potential instance that accepts string type labels (from Frame). |
|
|
The potential internally uses TypeIndexedArray to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
Source code in src/molpy/core/forcefield.py
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
AngleType ¶
AngleType(name, itom, jtom, ktom, **kwargs)
Bases: Type
Angle type defined by three atom types
Source code in src/molpy/core/forcefield.py
381 382 383 384 385 386 387 388 389 390 391 392 | |
matches ¶
matches(at1, at2, at3)
Check if matches given atom type triple (supports wildcards and reverse order)
Source code in src/molpy/core/forcefield.py
394 395 396 397 398 399 400 | |
AtomStyle ¶
AtomStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(name, **kwargs)
Define atom type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_
|
Specific type identifier (e.g. opls_135) |
required | |
class_
|
Class identifier (e.g. CT) |
required | |
**kwargs
|
Any
|
Other parameters (element, mass, etc.) |
{}
|
Returns:
| Type | Description |
|---|---|
AtomType
|
Created AtomType instance |
Source code in src/molpy/core/forcefield.py
513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
BondStyle ¶
BondStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(itom, jtom, name='', **kwargs)
Define bond type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom) |
''
|
**kwargs
|
Any
|
Bond parameters (e.g. k, r0, etc.) |
{}
|
Source code in src/molpy/core/forcefield.py
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
to_potential ¶
to_potential()
Create corresponding Potential instance from BondStyle.
Returns:
| Type | Description |
|---|---|
|
Potential instance that accepts string type labels (from Frame). |
|
|
The potential internally uses dictionaries to map type names to parameters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
Source code in src/molpy/core/forcefield.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
BondType ¶
BondType(name, itom, jtom, **kwargs)
Bases: Type
Bond type defined by two atom types
Source code in src/molpy/core/forcefield.py
363 364 365 366 | |
matches ¶
matches(at1, at2)
Check if matches given atom type pair (supports wildcards and order-independent)
Source code in src/molpy/core/forcefield.py
368 369 370 371 372 | |
DihedralStyle ¶
DihedralStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(itom, jtom, ktom, ltom, name='', **kwargs)
Define dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Dihedral parameters |
{}
|
Source code in src/molpy/core/forcefield.py
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 | |
DihedralType ¶
DihedralType(name, itom, jtom, ktom, ltom, **kwargs)
Bases: Type
Dihedral type defined by four atom types
Source code in src/molpy/core/forcefield.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
matches ¶
matches(at1, at2, at3, at4)
Check if matches given atom type quadruple (supports wildcards and reverse order)
Source code in src/molpy/core/forcefield.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
ForceField ¶
ForceField(name='', units='real')
Source code in src/molpy/core/forcefield.py
248 249 250 251 | |
def_style ¶
def_style(style)
Register a Style instance with the force field.
The API no longer accepts Style classes. Callers must pass an instantiated
Style (e.g. ff.def_style(AtomStyle("full"))). If a style with the
same runtime class and name already exists it will be returned instead of
registering a duplicate.
Source code in src/molpy/core/forcefield.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
get_style_by_name ¶
get_style_by_name(name, style_class=Style)
Get a style by name from the force field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the style to find |
required |
style_class
|
type[S]
|
Class of the style to search for (defaults to Style) |
Style
|
Returns:
| Type | Description |
|---|---|
S | None
|
The first matching Style instance, or None if not found |
Source code in src/molpy/core/forcefield.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 | |
to_potentials ¶
to_potentials()
Create Potential instances from all styles in ForceField.
Returns:
| Type | Description |
|---|---|
|
Potentials collection containing all created potential instances |
Note
Only Styles that support to_potential() method will be converted (e.g. BondStyle, AngleStyle, PairStyle)
Source code in src/molpy/core/forcefield.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
ImproperStyle ¶
ImproperStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(itom, jtom, ktom, ltom, name='', **kwargs)
Define improper dihedral type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType
|
Second atom type (usually central atom) |
required |
ktom
|
AtomType
|
Third atom type |
required |
ltom
|
AtomType
|
Fourth atom type |
required |
name
|
str
|
Optional name (defaults to itom-jtom-ktom-ltom) |
''
|
**kwargs
|
Any
|
Improper dihedral parameters |
{}
|
Source code in src/molpy/core/forcefield.py
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | |
ImproperType ¶
ImproperType(name, itom, jtom, ktom, ltom, **kwargs)
Bases: Type
Improper dihedral type defined by four atom types
Source code in src/molpy/core/forcefield.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
matches ¶
matches(at1, at2, at3, at4)
Check if matches given atom type quadruple (supports wildcards)
Source code in src/molpy/core/forcefield.py
466 467 468 469 470 471 472 473 474 475 476 477 | |
PairStyle ¶
PairStyle(name, *args, **kwargs)
Bases: Style
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
def_type ¶
def_type(itom, jtom=None, name='', **kwargs)
Define non-bonded interaction type
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
itom
|
AtomType
|
First atom type |
required |
jtom
|
AtomType | None
|
Second atom type (optional, defaults to same as itom for self-interaction) |
None
|
name
|
str
|
Optional name |
''
|
**kwargs
|
Any
|
Non-bonded parameters (e.g. sigma, epsilon, charge, etc.) |
{}
|
Source code in src/molpy/core/forcefield.py
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 | |
to_potential ¶
to_potential()
Create corresponding Potential instance from PairStyle.
Returns:
| Type | Description |
|---|---|
|
Potential instance containing all PairType parameters |
Raises:
| Type | Description |
|---|---|
ValueError
|
If corresponding Potential class not found or missing required parameters |
Source code in src/molpy/core/forcefield.py
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 | |
PairType ¶
PairType(name, *atom_types, **kwargs)
Bases: Type
Non-bonded interaction type defined by one or two atom types
Source code in src/molpy/core/forcefield.py
486 487 488 489 490 491 492 493 494 495 | |
matches ¶
matches(at1, at2=None)
Check if matches given atom type pair (supports wildcards and order-independent)
Source code in src/molpy/core/forcefield.py
497 498 499 500 501 502 503 504 | |
Style ¶
Style(name, *args, **kwargs)
Source code in src/molpy/core/forcefield.py
160 161 162 163 | |
copy ¶
copy()
Create a copy of this style with the same name and parameters (but not types).
Returns:
| Type | Description |
|---|---|
Style
|
A new Style instance with copied name and parameters |
Source code in src/molpy/core/forcefield.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
get_type_by_name ¶
get_type_by_name(name, type_class=Type)
Get a type by name from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the type to find |
required |
type_class
|
type[Ty]
|
Class of the type to search for (defaults to Type) |
Type
|
Returns:
| Type | Description |
|---|---|
Ty | None
|
The first matching Type instance, or None if not found |
Source code in src/molpy/core/forcefield.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
get_types ¶
get_types(type_class)
Get all types of the specified class from this style.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_class
|
type[Ty]
|
Class of the types to retrieve (e.g., AtomType, BondType) |
required |
Returns:
| Type | Description |
|---|---|
list[Ty]
|
List of types of the specified class |
Source code in src/molpy/core/forcefield.py
212 213 214 215 216 217 218 219 220 221 | |
Type ¶
Type(name, *args, **kwargs)
Source code in src/molpy/core/forcefield.py
62 63 64 | |
copy ¶
copy()
Create a copy of this type with the same name and parameters.
Returns:
| Type | Description |
|---|---|
Type
|
A new Type instance with copied parameters |
Source code in src/molpy/core/forcefield.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
Frame¶
Block ¶
Block(vars_=None)
Bases: MutableMapping[str, ndarray]
Lightweight container that maps variable names -> NumPy arrays.
• Behaves like a dict but auto-casts any assigned value to ndarray.
• All built-in dict/MutableMapping helpers work out of the box.
• Supports advanced indexing: by key, by index/slice, by mask, by list of keys.
Parameters¶
vars_ : dict[str, ArrayLike] or None, optional Initial data to populate the Block. Keys are variable names, values are array-like data that will be converted to numpy arrays.
Examples¶
Create and access basic data:
blk = Block() blk["x"] = [0.0, 1.0, 2.0] blk["y"] = [0.0, 0.0, 0.0] "x" in blk True len(blk) 2 blk["x"].dtype dtype('float64')
Multiple indexing methods:
blk = Block({"id": [1, 2, 3], "x": [10.0, 20.0, 30.0]}) blk[0] # Access single row, returns dict {'id': 1, 'x': 10.0} blk[0:2] # Slice access {'id': array([1, 2]), 'x': array([10., 20.])} blk[["id", "x"]] # Multi-column access, returns 2D array (requires same dtype) Traceback (most recent call last): ... ValueError: Arrays must have the same dtype...
Using boolean masks for filtering:
blk = Block({"id": [1, 2, 3, 4, 5], "mol": [1, 1, 2, 2, 3]}) mask = blk["mol"] < 3 sub_blk = blk[mask] sub_blk["id"] array([1, 2, 3, 4]) sub_blk.nrows 4
Sorting:
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) sorted_blk = blk.sort("x") # Returns new Block sorted_blk["x"] array([1, 2, 3]) _ = blk.sort_("x") # In-place sort, returns self blk["x"] array([1, 2, 3])
Source code in src/molpy/core/frame.py
79 80 81 82 83 84 85 86 87 88 89 90 | |
copy ¶
copy()
Shallow copy (arrays are not copied).
Source code in src/molpy/core/frame.py
293 294 295 | |
from_csv
classmethod
¶
from_csv(filepath, *, delimiter=',', encoding='utf-8', header=None, **kwargs)
Create a Block from a CSV file or StringIO.
Parameters¶
filepath : str, Path, or StringIO Path to the CSV file or StringIO object delimiter : str, default="," CSV delimiter character encoding : str, default="utf-8" File encoding (ignored for StringIO) header : list[str] or None, default=None Column names. If None, first row is used as headers. If provided, CSV is assumed to have no header row. **kwargs Additional arguments passed to csv.reader
Returns¶
Block A new Block instance with data from the CSV file
Examples¶
Read from StringIO:
from io import StringIO csv_data = StringIO("x,y,z\n0,1,2\n3,4,5") block = Block.from_csv(csv_data) block["x"] array([0, 3]) block.nrows 2
CSV without header:
csv_no_header = StringIO("0,1,2\n3,4,5") block = Block.from_csv(csv_no_header, header=["x", "y", "z"]) list(block.keys()) ['x', 'y', 'z'] block.nrows 2
Source code in src/molpy/core/frame.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
from_dict
classmethod
¶
from_dict(data)
Inverse of :meth:to_dict.
Source code in src/molpy/core/frame.py
187 188 189 190 | |
iterrows ¶
iterrows(n=None)
Iterate over rows of the block.
Returns¶
Iterator[tuple[int, dict[str, Any]]] An iterator yielding (index, row_data) pairs where: - index: int, the row index - row_data: dict, mapping variable names to their values for this row
Examples¶
blk = Block({ ... "id": [1, 2, 3], ... "type": ["C", "O", "N"], ... "x": [0.0, 1.0, 2.0], ... "y": [0.0, 0.0, 1.0], ... "z": [0.0, 0.0, 0.0] ... }) for index, row in blk.iterrows(): # doctest: +SKIP ... print(f"Row {index}: {row}") Row 0: {'id': 1, 'type': 'C', 'x': 0.0, 'y': 0.0, 'z': 0.0} Row 1: {'id': 2, 'type': 'O', 'x': 1.0, 'y': 0.0, 'z': 0.0} Row 2: {'id': 3, 'type': 'N', 'x': 2.0, 'y': 1.0, 'z': 0.0}
Notes¶
This method is similar to pandas DataFrame.iterrows() but returns a dictionary for each row instead of a pandas Series.
Source code in src/molpy/core/frame.py
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 | |
itertuples ¶
itertuples(index=True, name='Row')
Iterate over rows of the block as named tuples.
Parameters¶
index : bool, default=True If True, include the row index as the first element name : str, default="Row" The name of the named tuple class
Returns¶
Iterator[Any] An iterator yielding named tuples for each row
Examples¶
blk = Block({ ... "id": [1, 2, 3], ... "type": ["C", "O", "N"], ... "x": [0.0, 1.0, 2.0] ... }) for row in blk.itertuples(): ... print(f"Index: {row.Index}, ID: {row.id}, Type: {row.type}") Index: 0, ID: 1, Type: C Index: 1, ID: 2, Type: O Index: 2, ID: 3, Type: N
Notes¶
This method is similar to pandas DataFrame.itertuples().
Source code in src/molpy/core/frame.py
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |
sort ¶
sort(key, *, reverse=False)
Sort the block by a specific variable and return a new sorted Block.
This method creates a new Block instance with sorted data, leaving the original Block unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Block
|
A new Block with sorted data. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
Example
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) sorted_blk = blk.sort("x") sorted_blk["x"] array([1, 2, 3]) sorted_blk["y"] array([10, 20, 30])
Original block is unchanged¶
blk["x"] array([3, 1, 2])
Source code in src/molpy/core/frame.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | |
sort_ ¶
sort_(key, *, reverse=False)
Sort the block in-place by a specific variable.
This method modifies the current Block instance by sorting all variables according to the specified key. The original data is overwritten.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The variable name to sort by. |
required |
reverse
|
bool
|
If True, sort in descending order. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Self
|
Self (for method chaining). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the key variable doesn't exist in the block. |
ValueError
|
If any variable has different length than the key variable. |
Example
blk = Block({"x": [3, 1, 2], "y": [30, 10, 20]}) _ = blk.sort_("x") # Returns self for chaining blk["x"] array([1, 2, 3]) blk["y"] array([10, 20, 30])
Original data is now sorted¶
Source code in src/molpy/core/frame.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
to_dict ¶
to_dict()
Return a JSON-serialisable copy (arrays -> Python lists).
Source code in src/molpy/core/frame.py
183 184 185 | |
Frame ¶
Frame(blocks=None, **props)
Hierarchical numerical data container with named blocks.
Frame stores multiple Block objects under string keys (e.g., "atoms", "bonds") and allows arbitrary metadata to be attached. It's designed for molecular simulation data where different entity types need separate tabular storage.
Structure
Frame ├─ blocks: dict[str, Block] # Named data blocks └─ metadata: dict[str, Any] # Arbitrary metadata (box, timestep, etc.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
dict[str, Block | dict] | None
|
Initial blocks. If a dict value is not a Block, it will be converted. |
None
|
**props
|
Any
|
Arbitrary keyword arguments stored in metadata. |
{}
|
Examples:
Create Frame and add data blocks:
>>> frame = Frame()
>>> frame["atoms"] = Block({"x": [0.0, 1.0], "y": [0.0, 0.0], "z": [0.0, 0.0]})
>>> frame["atoms"]["x"]
array([0., 1.])
>>> frame["atoms"].nrows
2
Initialize with nested dictionaries:
>>> frame = Frame(blocks={
... "atoms": {"id": [1, 2, 3], "type": ["C", "H", "H"]},
... "bonds": {"i": [0, 0], "j": [1, 2]}
... })
>>> list(frame._blocks)
['atoms', 'bonds']
>>> frame["atoms"]["id"]
array([1, 2, 3])
Add metadata:
>>> frame = Frame()
>>> frame.metadata["timestep"] = 0
>>> frame.metadata["description"] = "Test system"
>>> frame.metadata["timestep"]
0
>>> frame.metadata["description"]
'Test system'
Chained access:
>>> frame = Frame(blocks={"atoms": {"x": [1, 2, 3], "y": [4, 5, 6]}})
>>> atoms = frame["atoms"]
>>> xyz_combined = atoms[["x", "y"]]
>>> xyz_combined.shape
(3, 2)
Iterate over all blocks and variables:
>>> frame = Frame(blocks={
... "atoms": {"id": [1, 2], "mass": [12.0, 1.0]},
... "bonds": {"i": [0], "j": [1]}
... })
>>> for block_name in frame._blocks:
... print(f"{block_name}: {list(frame[block_name].keys())}")
atoms: ['id', 'mass']
bonds: ['i', 'j']
Initialize a Frame with optional blocks and metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
blocks
|
dict[str, Block | BlockLike] | None
|
Initial blocks. If a dict value is not a Block, it will be converted to a Block. Defaults to None. |
None
|
**props
|
Any
|
Arbitrary keyword arguments stored in metadata. |
{}
|
Source code in src/molpy/core/frame.py
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 | |
blocks
property
¶
blocks
Iterate over stored Block objects.
Returns:
| Type | Description |
|---|---|
Iterator[Block]
|
Iterator[Block]: Iterator over Block values stored in this Frame. |
Note
To iterate over block names use for name in frame._blocks or
frame._blocks.keys().
Examples:
>>> frame = Frame(blocks={"atoms": {"x": [1]}, "bonds": {"i": [0]}})
>>> [b for b in frame.blocks]
[Block(x: shape=(1,), i: shape=(1,))]
copy ¶
copy()
Create a shallow copy of the Frame.
Blocks are copied (shallow), but the underlying numpy arrays are not.
Returns:
| Name | Type | Description |
|---|---|---|
Frame |
Frame
|
A new Frame instance with copied blocks and metadata. |
Examples:
>>> frame = Frame(blocks={"atoms": {"x": [1, 2, 3]}}, timestep=0)
>>> frame_copy = frame.copy()
>>> frame_copy.metadata["timestep"] = 1
>>> frame.metadata["timestep"] # Original unchanged
0
Source code in src/molpy/core/frame.py
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 | |
from_dict
classmethod
¶
from_dict(data)
Create a Frame from a dictionary representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary containing "blocks" and optionally "metadata" keys. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Frame |
Frame
|
A new Frame instance reconstructed from the dictionary. |
Examples:
>>> data = {
... "blocks": {"atoms": {"x": [1, 2, 3]}},
... "metadata": {"timestep": 0}
... }
>>> frame = Frame.from_dict(data)
>>> frame["atoms"]["x"]
array([1, 2, 3])
>>> frame.metadata["timestep"]
0
Source code in src/molpy/core/frame.py
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 | |
to_dict ¶
to_dict()
Convert Frame to a dictionary representation.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary containing "blocks" and "metadata" keys. Blocks are converted to dictionaries via Block.to_dict(). |
Examples:
>>> frame = Frame(blocks={"atoms": {"x": [1, 2]}}, timestep=0)
>>> data = frame.to_dict()
>>> "blocks" in data
True
>>> "metadata" in data
True
Source code in src/molpy/core/frame.py
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 | |
Script¶
Script - Editable script management with filesystem and URL support.
This module provides a Script class for managing script content that can be stored locally or loaded from URLs. It supports editing, formatting, and filesystem operations without any execution logic.
Script
dataclass
¶
Script(name, language='bash', description=None, _lines=list(), path=None, url=None, tags=set())
Represents an editable script with filesystem and URL support.
This class manages script content, metadata, and filesystem operations. It does NOT provide execution logic - only content management.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Logical name of the script |
language |
ScriptLanguage
|
Script language type |
description |
str | None
|
Optional human-readable description |
_lines |
list[str]
|
Internal storage for multi-line content |
path |
Path | None
|
Local file path if stored on disk |
url |
str | None
|
URL the script was loaded from (if any) |
tags |
set[str]
|
Optional lightweight tag system |
lines
property
¶
lines
Get a copy of all script lines.
Returns:
| Type | Description |
|---|---|
list[str]
|
Copy of internal lines list |
text
property
¶
text
Get the full script as a single string.
Returns:
| Type | Description |
|---|---|
str
|
Script content with lines joined by newlines, with exactly one trailing newline |
append ¶
append(line='')
Append a single line to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
line
|
str
|
Line content to append |
''
|
Source code in src/molpy/core/script.py
238 239 240 241 242 243 244 245 | |
append_block ¶
append_block(block)
Append a multi-line block to the script.
The block is dedented, trailing newlines are stripped, and then split into lines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
str
|
Multi-line string block to append |
required |
Source code in src/molpy/core/script.py
256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
clear ¶
clear()
Remove all lines from the script.
Source code in src/molpy/core/script.py
234 235 236 | |
delete ¶
delete(index)
Delete the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to delete |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
Source code in src/molpy/core/script.py
299 300 301 302 303 304 305 306 307 308 309 310 311 | |
delete_file ¶
delete_file()
Delete the script file from the filesystem.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
OSError
|
If the file cannot be deleted |
Source code in src/molpy/core/script.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | |
extend ¶
extend(lines)
Append multiple lines in order to the end of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
Iterable of lines to append |
required |
Source code in src/molpy/core/script.py
247 248 249 250 251 252 253 254 | |
format ¶
format(**kwargs)
Apply string formatting to all lines and return a new Script.
Uses Python's str.format(**kwargs) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Format arguments |
{}
|
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
Source code in src/molpy/core/script.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | |
format_with_mapping ¶
format_with_mapping(mapping)
Apply string formatting to all lines using a mapping and return a new Script.
Uses Python's str.format_map(mapping) on each line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, Any]
|
Format mapping |
required |
Returns:
| Type | Description |
|---|---|
Script
|
New Script instance with formatted lines |
Source code in src/molpy/core/script.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
from_path
classmethod
¶
from_path(path, *, language=None, description=None)
Create a Script from a local file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the script file |
required |
language
|
ScriptLanguage | None
|
Optional language override. If None, guessed from extension |
None
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from file |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
Source code in src/molpy/core/script.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
from_text
classmethod
¶
from_text(name, text, *, language='bash', description=None, path=None, url=None)
Create a Script from text content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logical name of the script |
required |
text
|
str
|
Multi-line text content |
required |
language
|
ScriptLanguage
|
Script language type |
'bash'
|
description
|
str | None
|
Optional description |
None
|
path
|
str | Path | None
|
Optional local file path |
None
|
url
|
str | None
|
Optional URL source |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance with normalized content |
Source code in src/molpy/core/script.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
from_url
classmethod
¶
from_url(url, *, name=None, language='other', description=None)
Create a Script from a URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to fetch the script from |
required |
name
|
str | None
|
Optional name. If None, derived from URL |
None
|
language
|
ScriptLanguage
|
Script language type |
'other'
|
description
|
str | None
|
Optional description |
None
|
Returns:
| Type | Description |
|---|---|
Script
|
Script instance loaded from URL |
Raises:
| Type | Description |
|---|---|
URLError
|
If the URL cannot be fetched |
Source code in src/molpy/core/script.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | |
insert ¶
insert(index, line)
Insert a single line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index where to insert |
required |
line
|
str
|
Line content to insert |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
Source code in src/molpy/core/script.py
271 272 273 274 275 276 277 278 279 280 281 282 | |
move ¶
move(new_path)
Move the script file to a new location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_path
|
str | Path
|
New file path |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was moved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be moved |
Source code in src/molpy/core/script.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | |
preview ¶
preview(max_lines=20, *, with_line_numbers=True)
Generate a preview of the script.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_lines
|
int
|
Maximum number of lines to show |
20
|
with_line_numbers
|
bool
|
Whether to include line numbers |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Preview string |
Source code in src/molpy/core/script.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
reload ¶
reload()
Reload the script content from its associated path.
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the file does not exist |
IOError
|
If the file cannot be read |
Source code in src/molpy/core/script.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
rename ¶
rename(new_name)
Rename the script file (keeping the same directory).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_name
|
str
|
New file name (with or without extension) |
required |
Returns:
| Type | Description |
|---|---|
Path
|
New path where the script was renamed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If script has no associated path |
FileNotFoundError
|
If the original file does not exist |
OSError
|
If the file cannot be renamed |
Source code in src/molpy/core/script.py
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | |
replace ¶
replace(index, line)
Replace the line at the given index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
0-based index of line to replace |
required |
line
|
str
|
New line content |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range |
Source code in src/molpy/core/script.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
save ¶
save(path=None)
Save the script to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
Optional path to save to. If None, uses self.path |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path where the script was saved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no path is provided and self.path is None |
IOError
|
If the file cannot be written |
Source code in src/molpy/core/script.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
Topology¶
Molecular topology graph using igraph.
Provides graph-based representation of molecular connectivity with automated detection of angles, dihedrals, and impropers.
Topology ¶
Topology(*args, entity_to_idx=None, idx_to_entity=None, **kwargs)
Bases: Graph
Topology graph with bidirectional entity-to-index mapping.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_to_idx |
dict[Any, int]
|
Dictionary mapping Entity objects to their vertex indices |
idx_to_entity |
list[Any]
|
List mapping vertex indices to Entity objects |
Initialize Topology graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Arguments passed to igraph.Graph.init |
()
|
|
entity_to_idx
|
dict[Any, int] | None
|
Optional dictionary mapping entities to indices |
None
|
idx_to_entity
|
list[Any] | None
|
Optional list mapping indices to entities |
None
|
**kwargs
|
Keyword arguments passed to igraph.Graph.init |
{}
|
Source code in src/molpy/core/topology.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
add_angle ¶
add_angle(idx_i, idx_j, idx_k, **props)
Add angle by ensuring bonds i-j and j-k exist.
Source code in src/molpy/core/topology.py
141 142 143 144 145 146 | |
add_angles ¶
add_angles(angle_idx)
Add multiple angles from array of triplets.
Source code in src/molpy/core/topology.py
148 149 150 151 152 | |
add_atom ¶
add_atom(name, **props)
Add a single atom vertex.
Source code in src/molpy/core/topology.py
116 117 118 | |
add_atoms ¶
add_atoms(n_atoms, **props)
Add multiple atom vertices.
Source code in src/molpy/core/topology.py
120 121 122 | |
add_bond ¶
add_bond(idx_i, idx_j, **props)
Add bond between atoms i and j if not already connected.
Source code in src/molpy/core/topology.py
128 129 130 131 | |
add_bonds ¶
add_bonds(bond_idx, **props)
Add multiple bonds from array of pairs.
Source code in src/molpy/core/topology.py
137 138 139 | |
delete_atom ¶
delete_atom(index)
Delete atom(s) by index.
Source code in src/molpy/core/topology.py
124 125 126 | |
delete_bond ¶
delete_bond(index)
Delete bond(s) by index.
Source code in src/molpy/core/topology.py
133 134 135 | |
union ¶
union(other)
Merge another topology into this one.
Source code in src/molpy/core/topology.py
154 155 156 157 | |