mc — Monte Carlo Placement¶
The Monte Carlo engine behind MC Placement & Chain Growth, also used by bead-spring generation.
Collision detection¶
AutoPoly.mc.collision
¶
Collision Detection Module for Monte Carlo Placement
This module provides efficient 3D collision detection using monomer-level spheres and cell-linked list data structure for O(N) expected complexity.
Key Features: - Hard-sphere collision model at monomer level - Cell-linked list for spatial hashing - Efficient add/remove operations - Configurable tolerance for overlap detection
Created on 2026-01-29 @author: zwu
Classes:
| Name | Description |
|---|---|
MonomerSphere |
Represents a monomer as a single sphere for collision detection. |
CollisionDetector |
Efficient collision detection using cell-linked list spatial hashing. |
Functions:
| Name | Description |
|---|---|
calculate_box_size |
Calculate cubic box size from monomer count and target density. |
MonomerSphere
dataclass
¶
Represents a monomer as a single sphere for collision detection.
Attributes:
| Name | Type | Description |
|---|---|---|
center |
ndarray
|
3D coordinates of the sphere center (monomer geometric center) |
radius |
float
|
Collision radius of the monomer |
monomer_id |
int
|
Unique identifier for this monomer |
Source code in AutoPoly/mc/collision.py
CollisionDetector
¶
Efficient collision detection using cell-linked list spatial hashing.
This class implements a 3D grid-based spatial hashing scheme for fast collision queries. Each cell in the grid contains references to spheres whose centers fall within that cell.
The algorithm achieves O(N) expected time for both insertion and collision queries when the cell size is properly tuned to the sphere sizes.
Attributes:
| Name | Type | Description |
|---|---|---|
box_bounds |
Tuple of ((xmin, xmax), (ymin, ymax), (zmin, zmax)) |
|
cell_size |
Size of each cell in the spatial grid |
|
cells |
Dict[Tuple[int, int, int], Set[int]]
|
Dictionary mapping cell indices to sets of monomer IDs |
spheres |
Dict[int, MonomerSphere]
|
Dictionary mapping monomer IDs to MonomerSphere objects |
Example
detector = CollisionDetector( ... box_bounds=((-50, 50), (-50, 50), (-50, 50)), ... cell_size=5.0 ... ) detector.add_monomer(0, np.array([0, 0, 0]), 2.0) detector.check_collision(np.array([1, 0, 0]), 2.0) True
Methods:
| Name | Description |
|---|---|
estimate_radius |
Estimate collision radius for a monomer from connection atom positions. |
estimate_radius_from_coords |
Estimate collision radius from atom coordinates using bounding sphere. |
add_monomer |
Add a monomer sphere to the collision detector. |
remove_monomer |
Remove a monomer sphere from the collision detector. |
check_collision |
Check if a sphere at the given position would collide with existing spheres. |
check_collision_detailed |
Check collision with detailed information about the colliding sphere. |
check_bounds |
Check if a sphere is within the simulation box bounds. |
get_sphere_count |
Return the total number of spheres in the detector. |
clear |
Remove all spheres from the detector. |
Source code in AutoPoly/mc/collision.py
44 45 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 87 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 136 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 189 190 191 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 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 324 325 326 327 328 329 330 331 332 333 334 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 365 366 367 368 369 370 | |
estimate_radius(left_conn: np.ndarray, right_conn: np.ndarray, buffer: float = 1.5) -> float
staticmethod
¶
Estimate collision radius for a monomer from connection atom positions.
The radius is estimated as half the distance between connection atoms plus a buffer to account for atoms extending beyond the backbone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left_conn
|
ndarray
|
Coordinates of left connection atom |
required |
right_conn
|
ndarray
|
Coordinates of right connection atom |
required |
buffer
|
float
|
Additional padding in Angstroms (default: 1.5) |
1.5
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated collision radius in Angstroms |
Source code in AutoPoly/mc/collision.py
estimate_radius_from_coords(atom_coords: np.ndarray, buffer: float = 0.5) -> float
staticmethod
¶
Estimate collision radius from atom coordinates using bounding sphere.
Computes the center of mass and finds the maximum distance from center to any atom, then adds a buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_coords
|
ndarray
|
Array of shape (N, 3) containing atom coordinates |
required |
buffer
|
float
|
Additional padding in Angstroms (default: 0.5) |
0.5
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated collision radius in Angstroms |
Source code in AutoPoly/mc/collision.py
add_monomer(mon_id: int, center: np.ndarray, radius: float) -> None
¶
Add a monomer sphere to the collision detector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mon_id
|
int
|
Unique identifier for the monomer |
required |
center
|
ndarray
|
3D coordinates of the sphere center |
required |
radius
|
float
|
Collision radius of the sphere |
required |
Source code in AutoPoly/mc/collision.py
remove_monomer(mon_id: int) -> None
¶
Remove a monomer sphere from the collision detector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mon_id
|
int
|
Unique identifier of the monomer to remove |
required |
Source code in AutoPoly/mc/collision.py
check_collision(center: np.ndarray, radius: float, exclude_ids: Optional[Set[int]] = None, tolerance: float = 0.1) -> bool
¶
Check if a sphere at the given position would collide with existing spheres.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center
|
ndarray
|
3D coordinates of the test sphere center |
required |
radius
|
float
|
Radius of the test sphere |
required |
exclude_ids
|
Optional[Set[int]]
|
Set of monomer IDs to exclude from collision check |
None
|
tolerance
|
float
|
Overlap tolerance in Angstroms. Negative values allow slight penetration before reporting collision. (default: 0.1) |
0.1
|
Returns:
| Type | Description |
|---|---|
bool
|
True if collision detected, False otherwise |
Source code in AutoPoly/mc/collision.py
check_collision_detailed(center: np.ndarray, radius: float, exclude_ids: Optional[Set[int]] = None, tolerance: float = 0.1) -> Tuple[bool, Optional[int], Optional[float]]
¶
Check collision with detailed information about the colliding sphere.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center
|
ndarray
|
3D coordinates of the test sphere center |
required |
radius
|
float
|
Radius of the test sphere |
required |
exclude_ids
|
Optional[Set[int]]
|
Set of monomer IDs to exclude from collision check |
None
|
tolerance
|
float
|
Overlap tolerance in Angstroms |
0.1
|
Returns:
| Type | Description |
|---|---|
Tuple[bool, Optional[int], Optional[float]]
|
Tuple of (collision_detected, colliding_monomer_id, overlap_distance) |
Source code in AutoPoly/mc/collision.py
check_bounds(center: np.ndarray, radius: float) -> bool
¶
Check if a sphere is within the simulation box bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
center
|
ndarray
|
3D coordinates of the sphere center |
required |
radius
|
float
|
Radius of the sphere |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the sphere is completely within bounds, False otherwise |
Source code in AutoPoly/mc/collision.py
get_sphere_count() -> int
¶
calculate_box_size(total_monomers: int, monomer_density: float = 0.1) -> float
¶
Calculate cubic box size from monomer count and target density.
A low default density (0.1 monomers/A^3) ensures sufficient space between monomers for successful MC placement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_monomers
|
int
|
Total number of monomers in the system |
required |
monomer_density
|
float
|
Target number density (monomers/A^3), default 0.1 |
0.1
|
Returns:
| Type | Description |
|---|---|
float
|
Box side length (Angstroms) for a cubic box |
Example
calculate_box_size(100, monomer_density=0.1) 21.544... # 100 monomers at density 0.1 -> volume = 1000 A^3 -> box ~ 10 A
Source code in AutoPoly/mc/collision.py
Chain growth¶
AutoPoly.mc.chain_growth
¶
Chain Growth Monte Carlo Module for Self-Avoiding Random Walk
This module implements self-avoiding random walk (SAW) for building polymer chains monomer-by-monomer with collision detection. The chain grows by aligning each new monomer's left connection point to the previous monomer's right connection point.
Key Features: - Parse monomer templates from .lt files - 3D transformation (rotation + translation) for monomer alignment - Self-avoiding random walk with dihedral angle sampling - Generation of moltemplate .rot().move() commands
Connection Point Convention (from .lt files): - First atom in "Data Atoms": Left connection point (C1) - Second atom in "Data Atoms": Right connection point (C2)
Created on 2026-01-29 @author: zwu
Classes:
| Name | Description |
|---|---|
AtomData |
Data for a single atom parsed from .lt file. |
MonomerTemplate |
Template for a monomer parsed from .lt file. |
MonomerPlacement |
Represents a placed monomer with its transformation. |
ChainGrowthMC |
Self-Avoiding Random Walk chain growth using Monte Carlo. |
Functions:
| Name | Description |
|---|---|
parse_lt_file |
Parse a monomer .lt file to extract atom coordinates and connection points. |
rotation_matrix_from_axis_angle |
Create a 3x3 rotation matrix from axis-angle representation. |
rotation_matrix_align_vectors |
Create rotation matrix that aligns vector v1 to vector v2. |
rotation_matrix_to_axis_angle |
Convert a 3x3 rotation matrix to axis-angle representation. |
random_rotation_matrix |
Generate a uniformly distributed random rotation matrix. |
AtomData
dataclass
¶
Data for a single atom parsed from .lt file.
Attributes:
| Name | Type | Description |
|---|---|---|
atom_id |
str
|
Atom identifier (e.g., "C1", "H3") |
element |
str
|
Element symbol (e.g., "C", "H") |
coords |
ndarray
|
3D coordinates as numpy array |
atom_type |
str
|
Force field atom type |
charge |
float
|
Partial charge |
Source code in AutoPoly/mc/chain_growth.py
MonomerTemplate
dataclass
¶
Template for a monomer parsed from .lt file.
Attributes:
| Name | Type | Description |
|---|---|---|
lt_file |
str
|
Path to the .lt file |
monomer_name |
str
|
Name of the monomer (e.g., "monomer_0_1i") |
monomer_type |
str
|
Type of monomer ("first", "middle", "last", or "ring") |
atoms |
List[AtomData]
|
List of all atoms with local coordinates |
left_conn_coords |
Optional[ndarray]
|
Coordinates of left connection atom (first atom, C1) |
right_conn_coords |
Optional[ndarray]
|
Coordinates of right connection atom (second atom, C2) |
left_conn_id |
Optional[str]
|
Atom ID of left connection (e.g., "C1") or None for first monomer |
right_conn_id |
Optional[str]
|
Atom ID of right connection (e.g., "C2") or None for last monomer |
bond_vector |
Optional[ndarray]
|
Vector from left to right connection (for middle monomers) |
Methods:
| Name | Description |
|---|---|
get_center |
Calculate the geometric center of all atoms. |
get_all_coords |
Get array of all atom coordinates. |
Source code in AutoPoly/mc/chain_growth.py
get_center() -> np.ndarray
¶
Calculate the geometric center of all atoms.
MonomerPlacement
dataclass
¶
Represents a placed monomer with its transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
template |
MonomerTemplate
|
The monomer template used |
position |
ndarray
|
Translation vector applied |
rotation_matrix |
ndarray
|
3x3 rotation matrix applied |
rotation_axis_angle |
Tuple[float, float, float, float]
|
(angle_deg, ax, ay, az) for moltemplate .rot() command |
monomer_index |
int
|
Index in the chain |
world_coords |
ndarray
|
Atom coordinates after transformation |
world_left_conn |
Optional[ndarray]
|
Left connection point after transformation |
world_right_conn |
Optional[ndarray]
|
Right connection point after transformation |
Source code in AutoPoly/mc/chain_growth.py
ChainGrowthMC
¶
Self-Avoiding Random Walk chain growth using Monte Carlo.
This class builds polymer chains by placing monomers one at a time, using collision detection to ensure self-avoiding conformations.
The algorithm: 1. Place first monomer at origin with random orientation 2. For each subsequent monomer: a. Align left connection to previous monomer's right connection b. Sample random dihedral angles c. Check for collisions d. Accept if no collision, retry otherwise
Attributes:
| Name | Type | Description |
|---|---|---|
collision_detector |
CollisionDetector for checking overlaps |
|
max_attempts |
Maximum placement attempts per monomer |
|
templates |
Dict[str, MonomerTemplate]
|
Cache of loaded monomer templates |
Methods:
| Name | Description |
|---|---|
load_monomer_template |
Load and cache a monomer template from .lt file. |
align_monomer_to_connection |
Align monomer so its left connection is at target position. |
sample_bond_angle |
Sample a bond angle randomly within the configured range. |
grow_chain |
Build a polymer chain using self-avoiding random walk. |
grow_chain_from_templates |
Build a polymer chain from pre-built monomer templates. |
generate_lt_commands |
Generate moltemplate instantiation commands from placements. |
Source code in AutoPoly/mc/chain_growth.py
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 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 525 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 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 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 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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 | |
load_monomer_template(lt_file: str) -> MonomerTemplate
¶
Load and cache a monomer template from .lt file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lt_file
|
str
|
Path to the .lt file |
required |
Returns:
| Type | Description |
|---|---|
MonomerTemplate
|
MonomerTemplate with parsed data |
Source code in AutoPoly/mc/chain_growth.py
align_monomer_to_connection(template: MonomerTemplate, target_position: np.ndarray, incoming_direction: np.ndarray, dihedral_angle: float = 0.0) -> Tuple[np.ndarray, np.ndarray]
¶
Align monomer so its left connection is at target position.
Note: In the new bond angle implementation, incoming_direction already includes both bond angle bend and dihedral rotation. The dihedral_angle parameter is kept for backward compatibility with legacy mode.
Steps: 1. Translate monomer so left_conn is at origin 2. Rotate to align bond_vector with incoming_direction 3. (Legacy) Apply dihedral rotation around backbone axis 4. Translate so left_conn is at target_position
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
MonomerTemplate
|
MonomerTemplate to align |
required |
target_position
|
ndarray
|
Where left_conn should be placed |
required |
incoming_direction
|
ndarray
|
Direction the backbone is coming from (already includes bond angle and dihedral) |
required |
dihedral_angle
|
float
|
(Deprecated) Dihedral angle in radians |
0.0
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Tuple of (3x3 rotation matrix, translation vector) |
Source code in AutoPoly/mc/chain_growth.py
sample_bond_angle() -> float
¶
Sample a bond angle randomly within the configured range.
Returns:
| Type | Description |
|---|---|
float
|
Bond angle in radians (C-C-C angle between consecutive monomers) |
Source code in AutoPoly/mc/chain_growth.py
grow_chain(monomer_lt_files: List[str], chain_id: int = 0, start_position: Optional[np.ndarray] = None) -> List[MonomerPlacement]
¶
Build a polymer chain using self-avoiding random walk.
Algorithm: 1. Place first monomer at start_position with random 3D orientation 2. For each subsequent monomer: - Get right_conn of previous monomer as target for left_conn - Sample random dihedral angles - Check collision with all placed atoms - Accept if no collision, retry otherwise
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monomer_lt_files
|
List[str]
|
List of .lt file paths for each monomer in sequence |
required |
chain_id
|
int
|
Unique identifier for this chain |
0
|
start_position
|
Optional[ndarray]
|
Starting position (default: origin) |
None
|
Returns:
| Type | Description |
|---|---|
List[MonomerPlacement]
|
List of MonomerPlacement objects for each placed monomer |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If chain growth fails after max_attempts |
Source code in AutoPoly/mc/chain_growth.py
grow_chain_from_templates(templates: List[MonomerTemplate], chain_id: int = 0, start_position: Optional[np.ndarray] = None) -> List[MonomerPlacement]
¶
Build a polymer chain from pre-built monomer templates.
Same algorithm as grow_chain(), but takes MonomerTemplate objects directly instead of parsing them from .lt files. This lets the force-field-agnostic geometry stage grow chains before any typed .lt file exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
templates
|
List[MonomerTemplate]
|
MonomerTemplate for each monomer in sequence |
required |
chain_id
|
int
|
Unique identifier for this chain |
0
|
start_position
|
Optional[ndarray]
|
Starting position (default: origin) |
None
|
Returns:
| Type | Description |
|---|---|
List[MonomerPlacement]
|
List of MonomerPlacement objects for each placed monomer |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If chain growth fails after max_attempts |
Source code in AutoPoly/mc/chain_growth.py
generate_lt_commands(placements: List[MonomerPlacement], use_rotation: bool = True) -> List[str]
¶
Generate moltemplate instantiation commands from placements.
Output format: monomer[0] = new MonomerA.rot(angle,ax,ay,az).move(x,y,z)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
placements
|
List[MonomerPlacement]
|
List of MonomerPlacement from grow_chain() |
required |
use_rotation
|
bool
|
Whether to include .rot() commands |
True
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of moltemplate command strings |
Source code in AutoPoly/mc/chain_growth.py
parse_lt_file(lt_file: str) -> MonomerTemplate
¶
Parse a monomer .lt file to extract atom coordinates and connection points.
The .lt file format has atoms in the "Data Atoms" block with the format: $atom:ID $mol:... @atom:TYPE CHARGE X Y Z
Connection point convention: - First atom (C1): Left connection point - Second atom (C2): Right connection point
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lt_file
|
str
|
Path to the .lt file |
required |
Returns:
| Type | Description |
|---|---|
MonomerTemplate
|
MonomerTemplate with parsed data |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the .lt file doesn't exist |
ValueError
|
If the file format is invalid |
Source code in AutoPoly/mc/chain_growth.py
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 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 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
rotation_matrix_from_axis_angle(axis: np.ndarray, angle_rad: float) -> np.ndarray
¶
Create a 3x3 rotation matrix from axis-angle representation.
Uses Rodrigues' rotation formula.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
ndarray
|
Unit vector defining rotation axis |
required |
angle_rad
|
float
|
Rotation angle in radians |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
3x3 rotation matrix |
Source code in AutoPoly/mc/chain_growth.py
rotation_matrix_align_vectors(v1: np.ndarray, v2: np.ndarray) -> np.ndarray
¶
Create rotation matrix that aligns vector v1 to vector v2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v1
|
ndarray
|
Source vector |
required |
v2
|
ndarray
|
Target vector |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
3x3 rotation matrix R such that R @ v1 is parallel to v2 |
Source code in AutoPoly/mc/chain_growth.py
rotation_matrix_to_axis_angle(R: np.ndarray) -> Tuple[float, float, float, float]
¶
Convert a 3x3 rotation matrix to axis-angle representation.
Returns format suitable for moltemplate: (angle_degrees, ax, ay, az)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
R
|
ndarray
|
3x3 rotation matrix |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float, float, float]
|
Tuple of (angle_degrees, axis_x, axis_y, axis_z) |
Source code in AutoPoly/mc/chain_growth.py
random_rotation_matrix() -> np.ndarray
¶
Generate a uniformly distributed random rotation matrix.
Uses the algorithm from Graphics Gems III for uniform random rotations based on quaternion sampling.
Returns:
| Type | Description |
|---|---|
ndarray
|
3x3 rotation matrix |
Source code in AutoPoly/mc/chain_growth.py
Molecular placement¶
AutoPoly.mc.placement
¶
Molecular Placement Module for Monte Carlo Random Placement
This module provides Monte Carlo random placement of polymers and molecules in a simulation box with collision detection.
Key Features: - Random position generation within box bounds - Uniform random orientation using quaternion sampling - Collision-aware sequential placement - Generation of moltemplate .rot().move() commands
Created on 2026-01-29 @author: zwu
Classes:
| Name | Description |
|---|---|
PolymerPlacement |
Represents a placed polymer chain with its transformation. |
MoleculePlacement |
Represents a placed molecule with its transformation. |
MolecularPlacementMC |
Monte Carlo random placement of polymers and molecules. |
PolymerPlacement
dataclass
¶
Represents a placed polymer chain with its transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
polymer_id |
int
|
Unique identifier for this polymer |
poly_name |
str
|
Name of the polymer (e.g., "poly_1") |
position |
ndarray
|
Translation vector for the entire polymer |
rotation_matrix |
ndarray
|
3x3 rotation matrix for the entire polymer |
rotation_axis_angle |
Tuple[float, float, float, float]
|
(angle_deg, ax, ay, az) for moltemplate |
monomer_placements |
Optional[List[MonomerPlacement]]
|
List of MonomerPlacement for chain growth (optional) |
center |
Optional[ndarray]
|
Center of mass of the polymer |
radius |
float
|
Bounding sphere radius |
Source code in AutoPoly/mc/placement.py
MoleculePlacement
dataclass
¶
Represents a placed molecule with its transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
molecule_id |
int
|
Unique identifier for this molecule |
molecule_name |
str
|
Name of the molecule type (e.g., "water") |
instance_name |
str
|
Instance name in moltemplate (e.g., "molecule_1") |
position |
ndarray
|
Translation vector |
rotation_matrix |
ndarray
|
3x3 rotation matrix |
rotation_axis_angle |
Tuple[float, float, float, float]
|
(angle_deg, ax, ay, az) for moltemplate |
center |
Optional[ndarray]
|
Center of the molecule after placement |
radius |
float
|
Collision radius |
Source code in AutoPoly/mc/placement.py
MolecularPlacementMC
¶
Monte Carlo random placement of polymers and molecules.
This class handles placing multiple polymers and molecules in a simulation box using random positions and orientations while avoiding collisions.
Attributes:
| Name | Type | Description |
|---|---|---|
box_bounds |
Simulation box boundaries |
|
collision_detector |
CollisionDetector for overlap checking |
|
max_attempts |
Maximum placement attempts per molecule |
Methods:
| Name | Description |
|---|---|
random_position |
Generate a uniform random position within the box bounds. |
random_orientation |
Generate a uniform random orientation. |
estimate_polymer_radius |
Estimate bounding sphere for a polymer chain. |
estimate_polymer_radius_from_templates |
Estimate polymer radius from template files and spacing. |
place_polymer |
Place a polymer with random position and orientation. |
place_molecule |
Place a molecule with random position and orientation. |
place_all_polymers |
Place multiple polymers sequentially with collision avoidance. |
place_all_molecules |
Place multiple molecules sequentially with collision avoidance. |
generate_polymer_lt_commands |
Generate moltemplate instantiation commands for polymers. |
generate_molecule_lt_commands |
Generate moltemplate instantiation commands for molecules. |
get_placement_stats |
Get statistics about placed entities. |
clear |
Reset the placement state. |
Source code in AutoPoly/mc/placement.py
83 84 85 86 87 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 136 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 189 190 191 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 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 324 325 326 327 328 329 330 331 332 333 334 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 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 401 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 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 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 | |
random_position(margin: float = 0.0) -> np.ndarray
¶
Generate a uniform random position within the box bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
margin
|
float
|
Minimum distance from box walls |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
3D position as numpy array |
Source code in AutoPoly/mc/placement.py
random_orientation() -> Tuple[np.ndarray, Tuple[float, float, float, float]]
¶
Generate a uniform random orientation.
Uses quaternion sampling for uniform distribution on SO(3).
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, Tuple[float, float, float, float]]
|
Tuple of (3x3 rotation matrix, (angle_deg, ax, ay, az)) |
Source code in AutoPoly/mc/placement.py
estimate_polymer_radius(monomer_placements: List[MonomerPlacement]) -> Tuple[np.ndarray, float]
staticmethod
¶
Estimate bounding sphere for a polymer chain.
Computes the center of mass and maximum distance from center to any atom in the chain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
monomer_placements
|
List[MonomerPlacement]
|
List of MonomerPlacement from chain growth |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, float]
|
Tuple of (center position, bounding sphere radius) |
Source code in AutoPoly/mc/placement.py
estimate_polymer_radius_from_templates(lt_files: List[str], spacing: float = 3.5) -> float
staticmethod
¶
Estimate polymer radius from template files and spacing.
Uses a simple linear model: radius = N * spacing / 2
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lt_files
|
List[str]
|
List of .lt file paths |
required |
spacing
|
float
|
Expected monomer spacing in Angstroms |
3.5
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated radius in Angstroms |
Source code in AutoPoly/mc/placement.py
place_polymer(poly_name: str, radius: float, center: Optional[np.ndarray] = None) -> Optional[PolymerPlacement]
¶
Place a polymer with random position and orientation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poly_name
|
str
|
Name of the polymer (e.g., "poly_1") |
required |
radius
|
float
|
Bounding sphere radius for collision detection |
required |
center
|
Optional[ndarray]
|
Optional center offset within polymer coordinates |
None
|
Returns:
| Type | Description |
|---|---|
Optional[PolymerPlacement]
|
PolymerPlacement if successful, None if failed after max_attempts |
Source code in AutoPoly/mc/placement.py
place_molecule(molecule_name: str, radius: float, instance_name: Optional[str] = None) -> Optional[MoleculePlacement]
¶
Place a molecule with random position and orientation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
molecule_name
|
str
|
Type name of the molecule (e.g., "water") |
required |
radius
|
float
|
Collision radius for the molecule |
required |
instance_name
|
Optional[str]
|
Optional instance name. If None, auto-generated. |
None
|
Returns:
| Type | Description |
|---|---|
Optional[MoleculePlacement]
|
MoleculePlacement if successful, None if failed after max_attempts |
Source code in AutoPoly/mc/placement.py
place_all_polymers(polymer_specs: List[Dict[str, Any]]) -> List[PolymerPlacement]
¶
Place multiple polymers sequentially with collision avoidance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
polymer_specs
|
List[Dict[str, Any]]
|
List of dicts with keys: - poly_name: Name of the polymer (e.g., "poly_1") - radius: Bounding sphere radius - center: Optional center offset (default: origin) |
required |
Returns:
| Type | Description |
|---|---|
List[PolymerPlacement]
|
List of PolymerPlacement objects |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any polymer fails to place |
Source code in AutoPoly/mc/placement.py
place_all_molecules(molecule_specs: List[Dict[str, Any]]) -> List[MoleculePlacement]
¶
Place multiple molecules sequentially with collision avoidance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
molecule_specs
|
List[Dict[str, Any]]
|
List of dicts with keys: - molecule_name: Type name of the molecule - radius: Collision radius - instance_name: Optional instance name |
required |
Returns:
| Type | Description |
|---|---|
List[MoleculePlacement]
|
List of MoleculePlacement objects |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any molecule fails to place |
Source code in AutoPoly/mc/placement.py
generate_polymer_lt_commands(placements: List[PolymerPlacement], use_rotation: bool = True) -> List[str]
¶
Generate moltemplate instantiation commands for polymers.
Output format: polymer_1 = new poly_1.rot(angle,ax,ay,az).move(x,y,z)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
placements
|
List[PolymerPlacement]
|
List of PolymerPlacement |
required |
use_rotation
|
bool
|
Whether to include .rot() commands |
True
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of moltemplate command strings |
Source code in AutoPoly/mc/placement.py
generate_molecule_lt_commands(placements: List[MoleculePlacement], use_rotation: bool = True) -> List[str]
¶
Generate moltemplate instantiation commands for molecules.
Output format: molecule_1 = new water.rot(angle,ax,ay,az).move(x,y,z)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
placements
|
List[MoleculePlacement]
|
List of MoleculePlacement |
required |
use_rotation
|
bool
|
Whether to include .rot() commands |
True
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List of moltemplate command strings |
Source code in AutoPoly/mc/placement.py
get_placement_stats() -> Dict[str, int]
¶
Get statistics about placed entities.
Returns:
| Type | Description |
|---|---|
Dict[str, int]
|
Dict with counts of placed polymers and molecules |