Skip to content

Bead-Spring

AutoPoly.models.bead_spring

Bead-Spring Polymer Model Module

This module provides the BeadSpringPolymer class for generating coarse-grained bead-spring polymer models for molecular dynamics simulations in LAMMPS.

Features: - Multiple bead types (block copolymers) - Per-triplet angle stiffness - FENE bond support - Linear and ring topologies - Monte Carlo pre-equilibration for initial configurations

Classes:

Name Description
BeadType

LJ parameters for a bead type.

AngleType

Angle parameters for a bead triplet.

SAWConfig

Configuration for Self-Avoiding Random Walk generation.

MCConfig

Monte Carlo equilibration configuration.

BeadSpringPolymer

Bead-spring polymer model generator for LAMMPS simulations.

Functions:

Name Description
calculate_box_size

Calculate cubic box size from number of beads and target density.

compute_lj_energy

Compute total LJ energy for non-bonded pairs.

compute_lj_energy_vectorized

Vectorized LJ energy using numpy broadcasting.

compute_local_lj_energy

Compute LJ energy contribution from one bead to all others - O(N).

compute_local_bond_energy

Compute bond energy for bonds involving a specific bead - O(degree).

compute_bond_energy

Compute harmonic bond energy.

compute_bond_energy_vectorized

Vectorized bond energy calculation.

compute_total_energy

Compute total system energy for Metropolis criterion.

build_exclusion_structures

Build exclusion data structures for efficient energy calculations.

metropolis_accept

Metropolis acceptance criterion.

mc_single_bead_displacement

Displace a single bead by random vector.

mc_crankshaft_move

Rotate beads between i and j around the i-j axis.

mc_pivot_move

Rotate arm (pivot_idx+1 to chain_end) around pivot bead.

mc_reptation_move

Remove bead from one end (tail) and attach at other end (head).

mc_tree_pivot_move

Rotate a subtree of beads around a random axis through the pivot bead.

mc_segment_crankshaft_move

Crankshaft move along an explicit bead path (segment).

build_chain_graph

Build per-chain graph metadata for branched MC moves.

place_chains_in_box

Place multiple chains randomly in periodic box.

mc_chain_translation

Translate entire chain by random displacement with PBC.

mc_chain_rotation

Rotate entire chain around its center of mass.

saw_grow_chain

Grow a single polymer chain using Self-Avoiding Random Walk with backtracking.

saw_generate_multi_chain

Generate multiple polymer chains using SAW.

saw_grow_graph

Grow a single chain of arbitrary architecture using SAW with backtracking.

saw_generate_graphs

Generate multiple chains of (possibly different) architectures using SAW.

mc_equilibrate

Pre-equilibrate polymer configuration using MC moves.

canonical_bead_triplet

Return canonical triplet (smaller endpoint first alphabetically).

lb_pair_coeffs

Lorentz-Berthelot mixing for all bead type pairs.

resolve_angle_params

Return (k, theta0) for a canonical triplet, using defaults if unset.

build_angle_type_map

Map canonical triplets to LAMMPS angle type IDs across all chains.

write_lammps_input_script

Write the LAMMPS input script (in.polymer) for a bead-spring system.

BeadType dataclass

LJ parameters for a bead type.

Source code in AutoPoly/models/bead_spring.py
@dataclass
class BeadType:
    """LJ parameters for a bead type."""
    name: str
    mass: float = 1.0
    epsilon: float = 1.0
    sigma: float = 1.0

AngleType dataclass

Angle parameters for a bead triplet.

Source code in AutoPoly/models/bead_spring.py
@dataclass
class AngleType:
    """Angle parameters for a bead triplet."""
    triplet: Tuple[str, str, str]
    k: float = 10.0
    theta0: float = 180.0

SAWConfig dataclass

Configuration for Self-Avoiding Random Walk generation.

Source code in AutoPoly/models/bead_spring.py
@dataclass
class SAWConfig:
    """Configuration for Self-Avoiding Random Walk generation."""
    collision_sigma: float = 1.0          # Bead diameter for collision
    collision_tolerance: float = 0.1      # Overlap tolerance
    n_trials: int = 50                    # Trial positions per bead
    max_backtrack_depth: int = 10         # Max beads to remove when stuck
    max_total_backtracks: int = 1000      # Total backtrack budget per chain
    bond_angle_min: float = 60.0          # Min bond angle (degrees)
    bond_angle_max: float = 180.0         # Max bond angle
    ring_closure_trials: int = 100        # Extra trials for ring closure
    ring_closure_tolerance: float = 0.2   # Distance tolerance for ring closure
    system_retries: int = 3               # Whole-system retries when a chain fails

MCConfig dataclass

Monte Carlo equilibration configuration.

Source code in AutoPoly/models/bead_spring.py
@dataclass
class MCConfig:
    """Monte Carlo equilibration configuration."""
    # Box sizing
    density: float = 0.85           # Bead density (beads per sigma^3)

    # MC move parameters
    max_displacement: float = 0.5   # Max single bead displacement
    max_angle: float = 0.3          # Max rotation angle (radians)
    temperature: float = 1.0        # Reduced temperature for Metropolis

    # Energy parameters
    lj_epsilon: float = 1.0         # LJ energy
    lj_sigma: float = 1.0           # LJ length
    lj_cutoff: float = 2.5          # LJ cutoff in sigma units
    bond_k: float = 100.0           # Bond spring constant
    bond_tolerance: float = 0.3     # Acceptable bond stretch

    # Equilibration settings
    n_steps: int = 10000            # Number of MC steps
    move_weights: Optional[Dict[str, float]] = None  # Move type probabilities

BeadSpringPolymer

Bead-spring polymer model generator for LAMMPS simulations.

Supports multiple bead types for block copolymers, per-triplet angle stiffness, and both harmonic and FENE bond styles.

Methods:

Name Description
equilibrate

Pre-equilibrate the polymer configuration using Monte Carlo moves.

saw_generate

Generate configuration using Self-Avoiding Random Walk.

generate

Generate LAMMPS input files using the configured output backend.

generate_data_file

Generate LAMMPS data file for bead-spring polymer (direct backend).

generate_moltemplate

Generate moltemplate .lt files (and optionally run moltemplate) for

get_system_info

Get comprehensive information about the bead-spring polymer system.

kremer_grest

Create a Kremer-Grest bead-spring polymer with standard parameters.

Attributes:

Name Type Description
n_beads int

Number of beads per chain (derived from sequence).

Source code in AutoPoly/models/bead_spring.py
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
class BeadSpringPolymer:
    """
    Bead-spring polymer model generator for LAMMPS simulations.

    Supports multiple bead types for block copolymers, per-triplet angle
    stiffness, and both harmonic and FENE bond styles.
    """

    VALID_TOPOLOGIES = ["linear", "ring"]
    VALID_BOND_STYLES = ["harmonic", "fene"]
    VALID_PAIR_STYLES = ["lj", "wca"]
    VALID_GENERATION_METHODS = ["geometric", "saw", "mc"]
    VALID_BACKENDS = ["moltemplate", "direct"]

    def __init__(
        self,
        name: str,
        system: object,
        n_chains: int,
        bead_types: List[BeadType],
        sequence: Optional[Union[List[str], List[Tuple[str, int]], str]] = None,
        topology: str = "linear",
        # Architecture (alternative to sequence/topology)
        architecture: Optional[BeadArchitecture] = None,
        # Bond parameters
        bond_length: float = 1.0,
        bond_style: str = "harmonic",
        k_bond: float = 30.0,
        fene_r0: float = 1.5,
        # Pair style parameters
        pair_style: str = "lj",  # "lj" (full LJ 2.5) or "wca" (WCA 2^(1/6))
        # Angle parameters
        use_angles: bool = False,
        default_k_angle: float = 10.0,
        default_theta0: float = 180.0,
        angle_types: Optional[List[AngleType]] = None,
        include_branch_angles: bool = True,
        # Box sizing
        density: Optional[float] = None,
        box_size: Optional[float] = None,
        # Generation method
        generation_method: str = "saw",  # "geometric", "saw", or "mc"
        saw_config: Optional[SAWConfig] = None,
        # Output backend
        backend: str = "moltemplate",  # "moltemplate" (default) or "direct"
        # MC equilibration (legacy, use generation_method="mc" instead)
        equilibrate: bool = False,
        mc_config: Optional[MCConfig] = None,
    ) -> None:
        """
        Initialize bead-spring polymer generator.

        Args:
            name: Name for output files.
            system: System object containing path information.
            n_chains: Number of polymer chains.
            bead_types: List of BeadType objects defining bead parameters.
            sequence: Chain structure as block pattern, explicit list, or string.
                Mutually exclusive with ``architecture``.
            topology: "linear" or "ring" (only used with ``sequence``).
            architecture: BeadArchitecture describing an arbitrary chain
                graph (star, comb, graft, tadpole, dendrimer, custom...).
                Mutually exclusive with ``sequence``/``topology``. Build one
                with the factories in ``AutoPoly.models.architectures``
                (``linear``, ``ring``, ``star``, ``comb``, ``graft``,
                ``tadpole``, ``dendrimer``, ``custom``).
            bond_length: Equilibrium bond length.
            bond_style: "harmonic" or "fene".
            k_bond: Bond force constant.
            fene_r0: FENE maximum extension (only used if bond_style="fene").
            pair_style: Pair interaction style - "lj" for full LJ (cutoff 2.5) or
                "wca" for WCA purely repulsive (cutoff 2^(1/6)*sigma ≈ 1.12246).
                For Kremer-Grest melts at P=0, use "wca" (recommended).
            use_angles: Whether to include angle potentials.
            default_k_angle: Default angle force constant for unspecified triplets.
            default_theta0: Default equilibrium angle for unspecified triplets.
            angle_types: List of AngleType objects for specific triplet parameters.
            include_branch_angles: Whether to include angle triplets centered
                on branch points (beads with degree > 2, e.g. comb graft
                points and star centers). Their stiffness is configured like
                any other triplet via ``angle_types``/``default_k_angle``.
                Only relevant for branched architectures.
            density: Target bead density (beads/sigma^3). If set, box size is calculated.
            box_size: Explicit box size. Overrides density if both are set.
            generation_method: Method for generating initial configurations:
                - "geometric": Simple geometric placement (fast, may have overlaps)
                - "saw": Self-Avoiding Random Walk (fast, overlap-free)
                - "mc": Monte Carlo equilibration (slow, equilibrated)
            saw_config: SAW configuration. Uses defaults if None.
            backend: Output backend used by :meth:`generate`:
                - "moltemplate" (default): emit .lt files and run the bundled
                  moltemplate -> moltemplate/system.data + system.in.*
                  (standard AutoPoly output layout; mixable with other
                  moltemplate objects).
                - "direct": write polymer.data + in.polymer directly
                  (lightweight; better for very large melts).
            equilibrate: Whether to run MC equilibration (legacy, use generation_method="mc").
            mc_config: Monte Carlo configuration. Uses defaults if None.

        Raises:
            ValueError: If parameters are invalid.

        Note on FENE Bonds:
            The FENE potential has NO explicit r0 (equilibrium bond length) parameter.
            The equilibrium distance of ~0.97 for Kremer-Grest polymers EMERGES from
            the balance of FENE (attractive, wants r→0) + WCA (repulsive, prevents r<~1.0).
            LAMMPS FENE syntax: bond_coeff * K R0 epsilon sigma
        """
        if architecture is None and topology not in self.VALID_TOPOLOGIES:
            raise ValueError(f"Topology must be one of: {self.VALID_TOPOLOGIES}")
        if architecture is not None and (sequence is not None or topology != "linear"):
            raise ValueError(
                "Pass either 'architecture' or 'sequence'/'topology', not both"
            )
        if architecture is None and sequence is None:
            raise ValueError("Either 'sequence' or 'architecture' is required")
        if bond_style not in self.VALID_BOND_STYLES:
            raise ValueError(f"Bond style must be one of: {self.VALID_BOND_STYLES}")
        if generation_method not in self.VALID_GENERATION_METHODS:
            raise ValueError(f"Generation method must be one of: {self.VALID_GENERATION_METHODS}")
        if pair_style not in self.VALID_PAIR_STYLES:
            raise ValueError(f"Pair style must be one of: {self.VALID_PAIR_STYLES}")
        if backend not in self.VALID_BACKENDS:
            raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
        if not bead_types:
            raise ValueError("At least one bead type is required")

        self.name = name
        self.system = system
        self.path = f"{self.system.get_folder_path()}/{self.name}" if system else f"./{name}"
        self.n_chains = n_chains

        # Store bead types
        self.bead_types = bead_types
        self._bead_type_map: Dict[str, BeadType] = {bt.name: bt for bt in bead_types}
        self._bead_type_id: Dict[str, int] = {bt.name: i + 1 for i, bt in enumerate(bead_types)}

        # Build the chain graph (the single internal representation)
        if architecture is not None:
            architecture.validate(
                known_bead_types=[bt.name for bt in bead_types]
            )
            self._architecture = architecture
            self.topology = architecture.name
            self._sequence = architecture.bead_types
        else:
            self.topology = topology
            # Parse and validate sequence
            self._sequence = self._parse_sequence(sequence)
            self._validate()
            self._architecture = (
                _ring_arch(self._sequence) if topology == "ring"
                else _linear_arch(self._sequence)
            )
        if architecture is not None:
            self._validate()

        # Bond parameters
        self.bond_length = bond_length
        self.bond_style = bond_style
        self.k_bond = k_bond
        self.fene_r0 = fene_r0

        # Pair style parameter
        self._pair_style = pair_style

        # Angle parameters
        self.use_angles = use_angles
        self.default_k_angle = default_k_angle
        self.default_theta0 = default_theta0
        self._angle_types = angle_types or []
        self.include_branch_angles = include_branch_angles

        # Graph-derived bond/angle structure (local bead indices per chain)
        self._bonds_local: List[Tuple[int, int]] = list(self._architecture.bonds)
        self._angle_triplets_local: List[Tuple[int, int, int]] = (
            self._architecture.angle_triplets(
                include_branch=self.include_branch_angles
            )
        )

        # Box sizing parameters
        self.density = density
        self._explicit_box_size = box_size

        # Generation method parameters
        self._generation_method = generation_method
        self._saw_config = saw_config

        # Output backend
        self._backend = backend

        # MC equilibration parameters (legacy support)
        self._equilibrate = equilibrate
        self._mc_config = mc_config

        # If equilibrate=True is set, use mc generation method
        if equilibrate and generation_method == "geometric":
            self._generation_method = "mc"

        # Internal state for positions (populated during generate_data_file)
        self._positions: Optional[List[np.ndarray]] = None
        self._chain_indices: Optional[List[Tuple[int, int]]] = None
        self._bonds: Optional[List[Tuple[int, int]]] = None

        # Build internal maps
        self._pair_coeffs = self._build_pair_coeffs()
        self._angle_type_map: Dict[Tuple[str, str, str], int] = {}
        if self.use_angles:
            self._angle_type_map = self._build_angle_type_map()

        # Create output directory
        Path(self.path).mkdir(parents=True, exist_ok=True)

        logger.info(
            f"Initialized bead-spring polymer: {n_chains} chains, "
            f"{len(self._sequence)} beads each, {self.topology} architecture, "
            f"{len(bead_types)} bead type(s)"
        )

    @property
    def n_beads(self) -> int:
        """Number of beads per chain (derived from sequence)."""
        return len(self._sequence)

    def _parse_sequence(self, seq: Union[List[str], List[Tuple[str, int]], str]) -> List[str]:
        """
        Convert sequence input to explicit bead type list.

        Args:
            seq: Sequence as block pattern, explicit list, or string.

        Returns:
            List of bead type names.
        """
        if isinstance(seq, str):
            # String format: "AABB" -> ["A", "A", "B", "B"]
            return list(seq)

        result = []
        for item in seq:
            if isinstance(item, tuple):
                # Block format: ("A", 20) -> ["A"] * 20
                bead_name, count = item
                result.extend([bead_name] * count)
            else:
                # Explicit list format
                result.append(item)
        return result

    def _validate(self) -> None:
        """Validate bead types and sequence consistency."""
        if not self._sequence:
            raise ValueError("Sequence cannot be empty")

        for bead_name in self._sequence:
            if bead_name not in self._bead_type_map:
                raise ValueError(
                    f"Unknown bead type '{bead_name}' in sequence. "
                    f"Available types: {list(self._bead_type_map.keys())}"
                )

    def _get_canonical_triplet(self, t1: str, t2: str, t3: str) -> Tuple[str, str, str]:
        """
        Return canonical triplet (smaller endpoint first alphabetically).

        Args:
            t1, t2, t3: Bead type names.

        Returns:
            Canonical triplet tuple.
        """
        return canonical_bead_triplet(t1, t2, t3)

    def _build_pair_coeffs(self) -> Dict[Tuple[int, int], Tuple[float, float]]:
        """
        Calculate Lorentz-Berthelot mixing for all bead type pairs.

        Returns:
            Dict mapping (type_i, type_j) to (epsilon_ij, sigma_ij).
        """
        return lb_pair_coeffs(self.bead_types)

    def _build_angle_type_map(self) -> Dict[Tuple[str, str, str], int]:
        """
        Map canonical triplets to LAMMPS type IDs.

        Returns:
            Dict mapping canonical triplet to angle type ID.
        """
        # Collect all unique canonical triplets from the chain graph.
        # For linear/ring architectures this reproduces the legacy
        # path-based enumeration (including ring wrap-arounds) exactly;
        # branched architectures additionally contribute their triplets
        # (branch-point triplets only if include_branch_angles is True).
        unique_triplets = set()

        for i, j, k in self._angle_triplets_local:
            triplet = self._get_canonical_triplet(
                self._sequence[i],
                self._sequence[j],
                self._sequence[k]
            )
            unique_triplets.add(triplet)

        # Sort triplets for consistent ordering
        sorted_triplets = sorted(unique_triplets)

        return {triplet: i + 1 for i, triplet in enumerate(sorted_triplets)}

    def _get_angle_params(self, triplet: Tuple[str, str, str]) -> Tuple[float, float]:
        """
        Return (k, theta0) for a triplet, using default if not specified.

        Args:
            triplet: Canonical triplet tuple.

        Returns:
            Tuple of (k, theta0).
        """
        return resolve_angle_params(
            triplet, self._angle_types,
            self.default_k_angle, self.default_theta0,
        )

    def _calculate_box_size(self) -> float:
        """
        Calculate box size based on density or explicit setting.

        Returns:
            Box side length.
        """
        total_beads = self.n_chains * self.n_beads

        if self._explicit_box_size is not None:
            return self._explicit_box_size
        elif self.density is not None:
            return calculate_box_size(total_beads, self.density)
        else:
            # Default behavior (original logic)
            if self.topology == "ring":
                radius = self.bond_length * self.n_beads / (2 * np.pi)
                spacing = radius * 3
                n_per_dim = int(np.ceil(np.cbrt(self.n_chains)))
                return max(n_per_dim * spacing * 2, 50.0)
            else:
                return max(self.n_beads * self.bond_length * 2, 50.0)

    def _compute_total_energy(self) -> float:
        """
        Compute total system energy (LJ + bonds).

        Returns:
            Total energy.
        """
        if self._positions is None or self._bonds is None:
            raise ValueError("Positions and bonds must be initialized first")

        # Get average LJ parameters from bead types
        avg_sigma = np.mean([bt.sigma for bt in self.bead_types])
        avg_epsilon = np.mean([bt.epsilon for bt in self.bead_types])

        box_size = self._calculate_box_size()

        return compute_total_energy(
            self._positions,
            self._bonds,
            lj_sigma=avg_sigma,
            lj_epsilon=avg_epsilon,
            lj_cutoff=2.5,
            bond_k=self.k_bond,
            bond_r0=self.bond_length,
            box_size=box_size,
        )

    def _generate_initial_positions(self) -> None:
        """Generate initial chain positions and bonds."""
        n_beads = self.n_beads
        box_size = self._calculate_box_size()

        # Generate positions for each chain
        chain_positions = []

        for chain in range(self.n_chains):
            chain_pos = []
            if self.topology == "ring" and not self._architecture.is_branched:
                radius = self.bond_length * n_beads / (2 * np.pi)
                for bead in range(n_beads):
                    angle = 2 * np.pi * bead / n_beads
                    pos = np.array([
                        radius * np.cos(angle),
                        radius * np.sin(angle),
                        0.0
                    ])
                    chain_pos.append(pos)
            elif self._architecture.is_branched or self._architecture.is_cyclic:
                # Generic graph: grow along the spanning tree with random
                # directions (may contain overlaps; SAW/MC can relax it)
                order, parents, _ = self._architecture.growth_order(root=0)
                pos_map = {0: np.zeros(3)}
                for bead in order[1:]:
                    parent = parents[bead]
                    direction = np.random.normal(size=3)
                    direction /= np.linalg.norm(direction)
                    pos_map[bead] = pos_map[parent] + direction * self.bond_length
                chain_pos = [pos_map[i] for i in range(n_beads)]
            else:
                # Linear chain
                for bead in range(n_beads):
                    pos = np.array([
                        bead * self.bond_length,
                        0.0,
                        0.0
                    ])
                    chain_pos.append(pos)

            chain_positions.append(chain_pos)

        # Place chains in box
        if self.n_chains > 1 and (self.density is not None or self._explicit_box_size is not None):
            # Use random placement with separation check
            min_sep = max(2.0 * self.bead_types[0].sigma, self.bond_length * 2)
            self._positions, self._chain_indices = place_chains_in_box(
                chain_positions, box_size, min_separation=min_sep
            )
        else:
            # Simple grid/linear placement
            self._positions = []
            self._chain_indices = []

            for chain_idx, chain_pos in enumerate(chain_positions):
                start_idx = len(self._positions)

                if self.topology == "ring":
                    n_per_dim = int(np.ceil(np.cbrt(self.n_chains)))
                    radius = self.bond_length * n_beads / (2 * np.pi)
                    spacing = radius * 3

                    ix = chain_idx % n_per_dim
                    iy = (chain_idx // n_per_dim) % n_per_dim
                    iz = chain_idx // (n_per_dim * n_per_dim)

                    center = np.array([
                        (ix - n_per_dim / 2 + 0.5) * spacing,
                        (iy - n_per_dim / 2 + 0.5) * spacing,
                        (iz - n_per_dim / 2 + 0.5) * spacing
                    ])

                    R = _random_rotation_matrix(np.pi)

                    for pos in chain_pos:
                        rotated = R @ pos
                        self._positions.append(rotated + center)
                else:
                    # Simple offset for linear chains
                    offset = np.array([0.0, chain_idx * self.bond_length * 2, 0.0])
                    for pos in chain_pos:
                        self._positions.append(pos + offset)

                end_idx = len(self._positions)
                self._chain_indices.append((start_idx, end_idx))

        # Generate bonds from the chain graph (0-indexed for internal use)
        self._bonds = []
        for start, end in self._chain_indices:
            for i, j in self._bonds_local:
                self._bonds.append((start + i, start + j))

    def equilibrate(self, mc_config: Optional[MCConfig] = None) -> None:
        """
        Pre-equilibrate the polymer configuration using Monte Carlo moves.

        Updates internal positions in-place.

        Args:
            mc_config: Monte Carlo configuration. Uses instance config or defaults.
        """
        config = mc_config or self._mc_config or MCConfig()

        # Initialize positions if not done
        if self._positions is None:
            self._generate_initial_positions()

        box_size = self._calculate_box_size()

        # Get average LJ parameters
        avg_sigma = np.mean([bt.sigma for bt in self.bead_types])
        avg_epsilon = np.mean([bt.epsilon for bt in self.bead_types])

        logger.info(
            f"Starting MC equilibration: {config.n_steps} steps, "
            f"T={config.temperature}, box_size={box_size:.3f}"
        )

        # Per-chain graph metadata enables branched MC moves (tree-pivot,
        # segment crankshaft); linear chains use the legacy moves.
        chain_graphs = [
            build_chain_graph(self._architecture, start)
            for start, _ in self._chain_indices
        ]

        self._positions, acceptance_stats = mc_equilibrate(
            positions=self._positions,
            bonds=self._bonds,
            chain_indices=self._chain_indices,
            chain_graphs=chain_graphs,
            n_steps=config.n_steps,
            temperature=config.temperature,
            move_weights=config.move_weights,
            box_size=box_size,
            lj_sigma=config.lj_sigma if config.lj_sigma else avg_sigma,
            lj_epsilon=config.lj_epsilon if config.lj_epsilon else avg_epsilon,
            lj_cutoff=config.lj_cutoff,
            bond_k=config.bond_k,
            bond_r0=self.bond_length,
            max_displacement=config.max_displacement,
            max_angle=config.max_angle,
            verbose=True,
        )

        logger.info(f"MC equilibration complete. Acceptance rates: {acceptance_stats}")

    def saw_generate(self, saw_config: Optional[SAWConfig] = None) -> bool:
        """
        Generate configuration using Self-Avoiding Random Walk.

        This is a fast alternative to MC equilibration that generates
        overlap-free configurations directly.

        Args:
            saw_config: SAW configuration. Uses instance config or defaults.

        Returns:
            True if successful, False if SAW failed.
        """
        config = saw_config or self._saw_config or SAWConfig()

        # Set collision sigma based on bead type if not specified
        if config.collision_sigma == 1.0 and self.bead_types:
            config.collision_sigma = max(bt.sigma for bt in self.bead_types)

        box_size = self._calculate_box_size()

        logger.info(
            f"Starting SAW generation: {self.n_chains} chains, "
            f"{self.n_beads} beads each, box_size={box_size:.3f}"
        )

        # SAW success is stochastic per attempt (a single crowded chain
        # fails the whole system), so retry the whole system a few times
        # before giving up.
        stats = {"success": False}
        positions, chain_indices = None, None
        for attempt in range(max(1, config.system_retries)):
            if self.topology in self.VALID_TOPOLOGIES:
                # Legacy path for linear/ring (identical connectivity)
                positions, chain_indices, stats = saw_generate_multi_chain(
                    n_chains=self.n_chains,
                    n_beads_per_chain=self.n_beads,
                    bond_length=self.bond_length,
                    box_size=box_size,
                    config=config,
                    topology=self.topology,
                )
            else:
                # Graph path for arbitrary architectures (star, comb, ...)
                positions, chain_indices, stats = saw_generate_graphs(
                    architectures=[self._architecture] * self.n_chains,
                    bond_length=self.bond_length,
                    box_size=box_size,
                    config=config,
                )
            if stats["success"]:
                break
            logger.info(
                f"SAW attempt {attempt + 1}/{config.system_retries} failed "
                f"({stats['failure_reason']}), retrying with fresh state"
            )

        if not stats["success"]:
            logger.warning(
                f"SAW generation failed: {stats['failure_reason']}. "
                f"Chains completed: {stats['chains_completed']}, "
                f"Backtracks: {stats['total_backtracks']}"
            )
            return False

        self._positions = positions
        self._chain_indices = chain_indices

        # Generate bonds from the chain graph (0-indexed)
        self._bonds = []
        for start, end in self._chain_indices:
            for i, j in self._bonds_local:
                self._bonds.append((start + i, start + j))

        logger.info(
            f"SAW generation complete. Backtracks: {stats['total_backtracks']}"
        )
        return True

    def generate(
        self,
        backend: Optional[str] = None,
        run_moltemplate: bool = True,
    ) -> None:
        """
        Generate LAMMPS input files using the configured output backend.

        This is the standard entry point for producing simulation files.

        Args:
            backend: "moltemplate" (default; .lt files + moltemplate ->
                moltemplate/system.data + system.in.*) or "direct"
                (polymer.data + in.polymer written directly). Defaults to
                the constructor's ``backend`` parameter.
            run_moltemplate: Only for the moltemplate backend: run the
                bundled moltemplate after writing .lt files.
        """
        backend = backend or self._backend
        if backend not in self.VALID_BACKENDS:
            raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
        if backend == "moltemplate":
            self.generate_moltemplate(run_moltemplate=run_moltemplate)
        else:
            self.generate_data_file()

    def generate_data_file(self) -> None:
        """Generate LAMMPS data file for bead-spring polymer (direct backend)."""
        n_beads = self.n_beads
        # Bond/angle counts come from the chain graph edge/triplet lists
        # (a tree has N-1 bonds, a ring N, etc.)
        n_bonds_per_chain = len(self._bonds_local)
        n_angles_per_chain = 0
        if self.use_angles:
            n_angles_per_chain = len(self._angle_triplets_local)

        total_atoms = self.n_chains * n_beads
        total_bonds = self.n_chains * n_bonds_per_chain
        total_angles = self.n_chains * n_angles_per_chain if self.use_angles else 0

        n_atom_types = len(self.bead_types)
        n_angle_types = len(self._angle_type_map) if self.use_angles else 0

        # Calculate box size using the new method
        box_size = self._calculate_box_size()

        # Generate initial positions based on generation method
        if self._positions is None:
            if self._generation_method == "saw":
                success = self.saw_generate(self._saw_config)
                if not success:
                    logger.warning("SAW failed, falling back to geometric placement")
                    self._generate_initial_positions()
            else:
                self._generate_initial_positions()

        # Run MC equilibration if requested (for "mc" method or legacy equilibrate flag)
        if self._generation_method == "mc" or self._equilibrate:
            self.equilibrate(self._mc_config)

        # Positions are always available at this point (both SAW and
        # geometric placement populate self._positions)
        if self._positions is None:
            self._generate_initial_positions()

        with open(f"{self.path}/polymer.data", 'w') as f:
            # Header
            f.write("LAMMPS Bead-Spring Polymer Data File\n\n")
            f.write(f"{total_atoms} atoms\n")
            f.write(f"{total_bonds} bonds\n")
            if self.use_angles:
                f.write(f"{total_angles} angles\n")
            f.write("\n")
            f.write(f"{n_atom_types} atom types\n")
            f.write("1 bond types\n")
            if self.use_angles:
                f.write(f"{n_angle_types} angle types\n")
            f.write("\n")

            # Box dimensions
            f.write(f"{-box_size/2:.1f} {box_size/2:.1f} xlo xhi\n")
            f.write(f"{-box_size/2:.1f} {box_size/2:.1f} ylo yhi\n")
            f.write(f"{-box_size/2:.1f} {box_size/2:.1f} zlo zhi\n\n")

            # Masses
            f.write("Masses\n\n")
            for bt in self.bead_types:
                type_id = self._bead_type_id[bt.name]
                f.write(f"{type_id} {bt.mass:.3f}  # {bt.name}\n")
            f.write("\n")

            # Atoms section: atom-ID molecule-ID atom-type x y z
            f.write("Atoms  # molecular\n\n")
            atom_id = 1

            for chain_idx, (start, end) in enumerate(self._chain_indices):
                for local_bead, global_idx in enumerate(range(start, end)):
                    pos = self._positions[global_idx]
                    bead_name = self._sequence[local_bead]
                    type_id = self._bead_type_id[bead_name]
                    f.write(f"{atom_id} {chain_idx + 1} {type_id} {pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n")
                    atom_id += 1

            # Bonds (from the chain graph edge list)
            f.write("\nBonds\n\n")
            bond_id = 1
            for chain in range(self.n_chains):
                start_id = chain * n_beads + 1
                for i_local, j_local in self._bonds_local:
                    f.write(f"{bond_id} 1 {start_id + i_local} {start_id + j_local}\n")
                    bond_id += 1

            # Angles (from the chain graph triplet list)
            if self.use_angles:
                f.write("\nAngles\n\n")
                angle_id = 1
                for chain in range(self.n_chains):
                    start_id = chain * n_beads + 1

                    for i_local, j_local, k_local in self._angle_triplets_local:
                        triplet = self._get_canonical_triplet(
                            self._sequence[i_local],
                            self._sequence[j_local],
                            self._sequence[k_local]
                        )
                        angle_type_id = self._angle_type_map[triplet]
                        f.write(f"{angle_id} {angle_type_id} {start_id + i_local} {start_id + j_local} {start_id + k_local}\n")
                        angle_id += 1

        # Generate LAMMPS input script
        self._generate_input_script()
        logger.info(f"Generated bead-spring polymer files in {self.path}")

    def generate_moltemplate(self, run_moltemplate: bool = True) -> Path:
        """
        Generate moltemplate .lt files (and optionally run moltemplate) for
        this bead-spring polymer.

        Mirrors the atomistic pipeline layout under
        ``<path>/moltemplate/``: bead_spring.lt (CG force field),
        bead_<Type>.lt monomer objects, chains.lt (one object per chain
        with generated coordinates, explicit bond list, typed angle list),
        and system.lt. Works for any architecture, since bonds and angles
        come from the chain graph.

        Args:
            run_moltemplate: Run the bundled moltemplate after writing
                files (produces system.data, system.in.init/settings).

        Returns:
            Path to the moltemplate directory.
        """
        from .bead_spring_lt import generate_moltemplate_files

        # Ensure positions exist (same logic as generate_data_file)
        if self._positions is None:
            if self._generation_method == "saw":
                success = self.saw_generate(self._saw_config)
                if not success:
                    logger.warning("SAW failed, falling back to geometric placement")
                    self._generate_initial_positions()
            else:
                self._generate_initial_positions()

        if self._generation_method == "mc" or self._equilibrate:
            self.equilibrate(self._mc_config)

        box_size = self._calculate_box_size()

        return generate_moltemplate_files(
            path=self.path,
            bead_types=self.bead_types,
            chain_architectures=[self._architecture] * self.n_chains,
            positions=self._positions,
            chain_indices=self._chain_indices,
            box_size=box_size,
            pair_coeffs=self._pair_coeffs,
            bond_style=self.bond_style,
            k_bond=self.k_bond,
            bond_length=self.bond_length,
            fene_r0=self.fene_r0,
            pair_style=self._pair_style,
            use_angles=self.use_angles,
            angle_type_map=self._angle_type_map if self.use_angles else {},
            resolve_angle_params=self._get_angle_params,
            include_branch_angles=self.include_branch_angles,
            canonical_triplet=canonical_bead_triplet,
            run_moltemplate=run_moltemplate,
        )

    def _generate_input_script(self) -> None:
        """Generate LAMMPS input script for the bead-spring polymer.

        Note: For Kremer-Grest polymers using FENE bonds, the WCA cutoff
        (2^(1/6) * sigma ≈ 1.12246) should be used instead of full LJ cutoff.
        This is controlled by setting pair_style='wca' in the class constructor.
        The equilibrium bond length of ~0.97 emerges from the balance of
        FENE + WCA potentials - there is no explicit r0 parameter in FENE.
        """
        write_lammps_input_script(
            path=self.path,
            bead_types=self.bead_types,
            pair_coeffs=self._pair_coeffs,
            bond_style=self.bond_style,
            k_bond=self.k_bond,
            bond_length=self.bond_length,
            fene_r0=self.fene_r0,
            pair_style=self._pair_style,
            use_angles=self.use_angles,
            angle_type_map=self._angle_type_map,
            angle_types=self._angle_types,
            default_k_angle=self.default_k_angle,
            default_theta0=self.default_theta0,
        )

    def get_system_info(self) -> dict:
        """
        Get comprehensive information about the bead-spring polymer system.

        Returns:
            Dictionary containing system properties.
        """
        n_beads = self.n_beads
        n_bonds_per_chain = len(self._bonds_local)
        n_angles_per_chain = 0
        if self.use_angles:
            n_angles_per_chain = len(self._angle_triplets_local)

        total_atoms = self.n_chains * n_beads
        total_bonds = self.n_chains * n_bonds_per_chain
        total_angles = self.n_chains * n_angles_per_chain if self.use_angles else 0

        return {
            'name': self.name,
            'n_chains': self.n_chains,
            'n_beads_per_chain': n_beads,
            'topology': self.topology,
            'architecture': self._architecture.name,
            'is_branched': self._architecture.is_branched,
            'total_atoms': total_atoms,
            'total_bonds': total_bonds,
            'total_angles': total_angles,
            'bond_style': self.bond_style,
            'bond_length': self.bond_length,
            'k_bond': self.k_bond,
            'use_angles': self.use_angles,
            'bead_types': [bt.name for bt in self.bead_types],
            'sequence': self._sequence,
            'output_path': self.path,
        }

    @classmethod
    def kremer_grest(
        cls,
        name: str,
        system: object,
        n_chains: int,
        n_beads: int,
        topology: str = "linear",
        density: float = 0.74,
        generation_method: str = "saw",
    ) -> "BeadSpringPolymer":
        """
        Create a Kremer-Grest bead-spring polymer with standard parameters.

        The Kremer-Grest model is a standard coarse-grained polymer model used
        for universal polymer behavior studies. It uses:
        - FENE bonds (K=30, R0=1.5)
        - WCA purely repulsive interactions (cutoff = 2^(1/6)*sigma ≈ 1.12246)
        - Standard LJ parameters (epsilon=1.0, sigma=1.0, mass=1.0)

        The equilibrium bond length of ~0.97 EMERGES from the balance of
        FENE (attractive) + WCA (repulsive) - there is no explicit r0 parameter.

        Args:
            name: Name for output files.
            system: System object containing path information.
            n_chains: Number of polymer chains.
            n_beads: Number of beads per chain.
            topology: "linear" or "ring" topology.
            density: Target bead density (beads/sigma^3). Default 0.74 for
                initial placement (will compress to ~0.85-0.90 during NPT).
            generation_method: Method for generating initial configurations
                ("geometric", "saw", or "mc").

        Returns:
            BeadSpringPolymer instance configured for Kremer-Grest model.

        Example:
            >>> from AutoPoly import System
            >>> from AutoPoly import BeadSpringPolymer
            >>> system = System(out="kg_simulation")
            >>> kg_polymer = BeadSpringPolymer.kremer_grest(
            ...     name="kg_melt",
            ...     system=system,
            ...     n_chains=100,
            ...     n_beads=10,
            ...     topology="linear"
            ... )
            >>> kg_polymer.generate_data_file()

        References:
            Kremer, K., & Grest, G. S. (1990). Dynamics of entangled linear
            polymer melts: A molecular-dynamics simulation. J. Chem. Phys.
            92(8), 5057-5086.
        """
        # Standard Kremer-Grest bead type
        kg_bead_type = BeadType(name="KG", mass=1.0, epsilon=1.0, sigma=1.0)

        # Uniform sequence of KG beads
        sequence = [("KG", n_beads)]

        return cls(
            name=name,
            system=system,
            n_chains=n_chains,
            bead_types=[kg_bead_type],
            sequence=sequence,
            topology=topology,
            bond_length=0.97,  # Starting guess, equilibrium emerges from FENE+WCA
            bond_style="fene",
            k_bond=30.0,
            fene_r0=1.5,
            pair_style="wca",  # WCA purely repulsive for KG melts
            density=density,
            generation_method=generation_method,
        )

n_beads: int property

Number of beads per chain (derived from sequence).

equilibrate(mc_config: Optional[MCConfig] = None) -> None

Pre-equilibrate the polymer configuration using Monte Carlo moves.

Updates internal positions in-place.

Parameters:

Name Type Description Default
mc_config Optional[MCConfig]

Monte Carlo configuration. Uses instance config or defaults.

None
Source code in AutoPoly/models/bead_spring.py
def equilibrate(self, mc_config: Optional[MCConfig] = None) -> None:
    """
    Pre-equilibrate the polymer configuration using Monte Carlo moves.

    Updates internal positions in-place.

    Args:
        mc_config: Monte Carlo configuration. Uses instance config or defaults.
    """
    config = mc_config or self._mc_config or MCConfig()

    # Initialize positions if not done
    if self._positions is None:
        self._generate_initial_positions()

    box_size = self._calculate_box_size()

    # Get average LJ parameters
    avg_sigma = np.mean([bt.sigma for bt in self.bead_types])
    avg_epsilon = np.mean([bt.epsilon for bt in self.bead_types])

    logger.info(
        f"Starting MC equilibration: {config.n_steps} steps, "
        f"T={config.temperature}, box_size={box_size:.3f}"
    )

    # Per-chain graph metadata enables branched MC moves (tree-pivot,
    # segment crankshaft); linear chains use the legacy moves.
    chain_graphs = [
        build_chain_graph(self._architecture, start)
        for start, _ in self._chain_indices
    ]

    self._positions, acceptance_stats = mc_equilibrate(
        positions=self._positions,
        bonds=self._bonds,
        chain_indices=self._chain_indices,
        chain_graphs=chain_graphs,
        n_steps=config.n_steps,
        temperature=config.temperature,
        move_weights=config.move_weights,
        box_size=box_size,
        lj_sigma=config.lj_sigma if config.lj_sigma else avg_sigma,
        lj_epsilon=config.lj_epsilon if config.lj_epsilon else avg_epsilon,
        lj_cutoff=config.lj_cutoff,
        bond_k=config.bond_k,
        bond_r0=self.bond_length,
        max_displacement=config.max_displacement,
        max_angle=config.max_angle,
        verbose=True,
    )

    logger.info(f"MC equilibration complete. Acceptance rates: {acceptance_stats}")

saw_generate(saw_config: Optional[SAWConfig] = None) -> bool

Generate configuration using Self-Avoiding Random Walk.

This is a fast alternative to MC equilibration that generates overlap-free configurations directly.

Parameters:

Name Type Description Default
saw_config Optional[SAWConfig]

SAW configuration. Uses instance config or defaults.

None

Returns:

Type Description
bool

True if successful, False if SAW failed.

Source code in AutoPoly/models/bead_spring.py
def saw_generate(self, saw_config: Optional[SAWConfig] = None) -> bool:
    """
    Generate configuration using Self-Avoiding Random Walk.

    This is a fast alternative to MC equilibration that generates
    overlap-free configurations directly.

    Args:
        saw_config: SAW configuration. Uses instance config or defaults.

    Returns:
        True if successful, False if SAW failed.
    """
    config = saw_config or self._saw_config or SAWConfig()

    # Set collision sigma based on bead type if not specified
    if config.collision_sigma == 1.0 and self.bead_types:
        config.collision_sigma = max(bt.sigma for bt in self.bead_types)

    box_size = self._calculate_box_size()

    logger.info(
        f"Starting SAW generation: {self.n_chains} chains, "
        f"{self.n_beads} beads each, box_size={box_size:.3f}"
    )

    # SAW success is stochastic per attempt (a single crowded chain
    # fails the whole system), so retry the whole system a few times
    # before giving up.
    stats = {"success": False}
    positions, chain_indices = None, None
    for attempt in range(max(1, config.system_retries)):
        if self.topology in self.VALID_TOPOLOGIES:
            # Legacy path for linear/ring (identical connectivity)
            positions, chain_indices, stats = saw_generate_multi_chain(
                n_chains=self.n_chains,
                n_beads_per_chain=self.n_beads,
                bond_length=self.bond_length,
                box_size=box_size,
                config=config,
                topology=self.topology,
            )
        else:
            # Graph path for arbitrary architectures (star, comb, ...)
            positions, chain_indices, stats = saw_generate_graphs(
                architectures=[self._architecture] * self.n_chains,
                bond_length=self.bond_length,
                box_size=box_size,
                config=config,
            )
        if stats["success"]:
            break
        logger.info(
            f"SAW attempt {attempt + 1}/{config.system_retries} failed "
            f"({stats['failure_reason']}), retrying with fresh state"
        )

    if not stats["success"]:
        logger.warning(
            f"SAW generation failed: {stats['failure_reason']}. "
            f"Chains completed: {stats['chains_completed']}, "
            f"Backtracks: {stats['total_backtracks']}"
        )
        return False

    self._positions = positions
    self._chain_indices = chain_indices

    # Generate bonds from the chain graph (0-indexed)
    self._bonds = []
    for start, end in self._chain_indices:
        for i, j in self._bonds_local:
            self._bonds.append((start + i, start + j))

    logger.info(
        f"SAW generation complete. Backtracks: {stats['total_backtracks']}"
    )
    return True

generate(backend: Optional[str] = None, run_moltemplate: bool = True) -> None

Generate LAMMPS input files using the configured output backend.

This is the standard entry point for producing simulation files.

Parameters:

Name Type Description Default
backend Optional[str]

"moltemplate" (default; .lt files + moltemplate -> moltemplate/system.data + system.in.*) or "direct" (polymer.data + in.polymer written directly). Defaults to the constructor's backend parameter.

None
run_moltemplate bool

Only for the moltemplate backend: run the bundled moltemplate after writing .lt files.

True
Source code in AutoPoly/models/bead_spring.py
def generate(
    self,
    backend: Optional[str] = None,
    run_moltemplate: bool = True,
) -> None:
    """
    Generate LAMMPS input files using the configured output backend.

    This is the standard entry point for producing simulation files.

    Args:
        backend: "moltemplate" (default; .lt files + moltemplate ->
            moltemplate/system.data + system.in.*) or "direct"
            (polymer.data + in.polymer written directly). Defaults to
            the constructor's ``backend`` parameter.
        run_moltemplate: Only for the moltemplate backend: run the
            bundled moltemplate after writing .lt files.
    """
    backend = backend or self._backend
    if backend not in self.VALID_BACKENDS:
        raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
    if backend == "moltemplate":
        self.generate_moltemplate(run_moltemplate=run_moltemplate)
    else:
        self.generate_data_file()

generate_data_file() -> None

Generate LAMMPS data file for bead-spring polymer (direct backend).

Source code in AutoPoly/models/bead_spring.py
def generate_data_file(self) -> None:
    """Generate LAMMPS data file for bead-spring polymer (direct backend)."""
    n_beads = self.n_beads
    # Bond/angle counts come from the chain graph edge/triplet lists
    # (a tree has N-1 bonds, a ring N, etc.)
    n_bonds_per_chain = len(self._bonds_local)
    n_angles_per_chain = 0
    if self.use_angles:
        n_angles_per_chain = len(self._angle_triplets_local)

    total_atoms = self.n_chains * n_beads
    total_bonds = self.n_chains * n_bonds_per_chain
    total_angles = self.n_chains * n_angles_per_chain if self.use_angles else 0

    n_atom_types = len(self.bead_types)
    n_angle_types = len(self._angle_type_map) if self.use_angles else 0

    # Calculate box size using the new method
    box_size = self._calculate_box_size()

    # Generate initial positions based on generation method
    if self._positions is None:
        if self._generation_method == "saw":
            success = self.saw_generate(self._saw_config)
            if not success:
                logger.warning("SAW failed, falling back to geometric placement")
                self._generate_initial_positions()
        else:
            self._generate_initial_positions()

    # Run MC equilibration if requested (for "mc" method or legacy equilibrate flag)
    if self._generation_method == "mc" or self._equilibrate:
        self.equilibrate(self._mc_config)

    # Positions are always available at this point (both SAW and
    # geometric placement populate self._positions)
    if self._positions is None:
        self._generate_initial_positions()

    with open(f"{self.path}/polymer.data", 'w') as f:
        # Header
        f.write("LAMMPS Bead-Spring Polymer Data File\n\n")
        f.write(f"{total_atoms} atoms\n")
        f.write(f"{total_bonds} bonds\n")
        if self.use_angles:
            f.write(f"{total_angles} angles\n")
        f.write("\n")
        f.write(f"{n_atom_types} atom types\n")
        f.write("1 bond types\n")
        if self.use_angles:
            f.write(f"{n_angle_types} angle types\n")
        f.write("\n")

        # Box dimensions
        f.write(f"{-box_size/2:.1f} {box_size/2:.1f} xlo xhi\n")
        f.write(f"{-box_size/2:.1f} {box_size/2:.1f} ylo yhi\n")
        f.write(f"{-box_size/2:.1f} {box_size/2:.1f} zlo zhi\n\n")

        # Masses
        f.write("Masses\n\n")
        for bt in self.bead_types:
            type_id = self._bead_type_id[bt.name]
            f.write(f"{type_id} {bt.mass:.3f}  # {bt.name}\n")
        f.write("\n")

        # Atoms section: atom-ID molecule-ID atom-type x y z
        f.write("Atoms  # molecular\n\n")
        atom_id = 1

        for chain_idx, (start, end) in enumerate(self._chain_indices):
            for local_bead, global_idx in enumerate(range(start, end)):
                pos = self._positions[global_idx]
                bead_name = self._sequence[local_bead]
                type_id = self._bead_type_id[bead_name]
                f.write(f"{atom_id} {chain_idx + 1} {type_id} {pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n")
                atom_id += 1

        # Bonds (from the chain graph edge list)
        f.write("\nBonds\n\n")
        bond_id = 1
        for chain in range(self.n_chains):
            start_id = chain * n_beads + 1
            for i_local, j_local in self._bonds_local:
                f.write(f"{bond_id} 1 {start_id + i_local} {start_id + j_local}\n")
                bond_id += 1

        # Angles (from the chain graph triplet list)
        if self.use_angles:
            f.write("\nAngles\n\n")
            angle_id = 1
            for chain in range(self.n_chains):
                start_id = chain * n_beads + 1

                for i_local, j_local, k_local in self._angle_triplets_local:
                    triplet = self._get_canonical_triplet(
                        self._sequence[i_local],
                        self._sequence[j_local],
                        self._sequence[k_local]
                    )
                    angle_type_id = self._angle_type_map[triplet]
                    f.write(f"{angle_id} {angle_type_id} {start_id + i_local} {start_id + j_local} {start_id + k_local}\n")
                    angle_id += 1

    # Generate LAMMPS input script
    self._generate_input_script()
    logger.info(f"Generated bead-spring polymer files in {self.path}")

generate_moltemplate(run_moltemplate: bool = True) -> Path

Generate moltemplate .lt files (and optionally run moltemplate) for this bead-spring polymer.

Mirrors the atomistic pipeline layout under <path>/moltemplate/: bead_spring.lt (CG force field), bead_.lt monomer objects, chains.lt (one object per chain with generated coordinates, explicit bond list, typed angle list), and system.lt. Works for any architecture, since bonds and angles come from the chain graph.

Parameters:

Name Type Description Default
run_moltemplate bool

Run the bundled moltemplate after writing files (produces system.data, system.in.init/settings).

True

Returns:

Type Description
Path

Path to the moltemplate directory.

Source code in AutoPoly/models/bead_spring.py
def generate_moltemplate(self, run_moltemplate: bool = True) -> Path:
    """
    Generate moltemplate .lt files (and optionally run moltemplate) for
    this bead-spring polymer.

    Mirrors the atomistic pipeline layout under
    ``<path>/moltemplate/``: bead_spring.lt (CG force field),
    bead_<Type>.lt monomer objects, chains.lt (one object per chain
    with generated coordinates, explicit bond list, typed angle list),
    and system.lt. Works for any architecture, since bonds and angles
    come from the chain graph.

    Args:
        run_moltemplate: Run the bundled moltemplate after writing
            files (produces system.data, system.in.init/settings).

    Returns:
        Path to the moltemplate directory.
    """
    from .bead_spring_lt import generate_moltemplate_files

    # Ensure positions exist (same logic as generate_data_file)
    if self._positions is None:
        if self._generation_method == "saw":
            success = self.saw_generate(self._saw_config)
            if not success:
                logger.warning("SAW failed, falling back to geometric placement")
                self._generate_initial_positions()
        else:
            self._generate_initial_positions()

    if self._generation_method == "mc" or self._equilibrate:
        self.equilibrate(self._mc_config)

    box_size = self._calculate_box_size()

    return generate_moltemplate_files(
        path=self.path,
        bead_types=self.bead_types,
        chain_architectures=[self._architecture] * self.n_chains,
        positions=self._positions,
        chain_indices=self._chain_indices,
        box_size=box_size,
        pair_coeffs=self._pair_coeffs,
        bond_style=self.bond_style,
        k_bond=self.k_bond,
        bond_length=self.bond_length,
        fene_r0=self.fene_r0,
        pair_style=self._pair_style,
        use_angles=self.use_angles,
        angle_type_map=self._angle_type_map if self.use_angles else {},
        resolve_angle_params=self._get_angle_params,
        include_branch_angles=self.include_branch_angles,
        canonical_triplet=canonical_bead_triplet,
        run_moltemplate=run_moltemplate,
    )

get_system_info() -> dict

Get comprehensive information about the bead-spring polymer system.

Returns:

Type Description
dict

Dictionary containing system properties.

Source code in AutoPoly/models/bead_spring.py
def get_system_info(self) -> dict:
    """
    Get comprehensive information about the bead-spring polymer system.

    Returns:
        Dictionary containing system properties.
    """
    n_beads = self.n_beads
    n_bonds_per_chain = len(self._bonds_local)
    n_angles_per_chain = 0
    if self.use_angles:
        n_angles_per_chain = len(self._angle_triplets_local)

    total_atoms = self.n_chains * n_beads
    total_bonds = self.n_chains * n_bonds_per_chain
    total_angles = self.n_chains * n_angles_per_chain if self.use_angles else 0

    return {
        'name': self.name,
        'n_chains': self.n_chains,
        'n_beads_per_chain': n_beads,
        'topology': self.topology,
        'architecture': self._architecture.name,
        'is_branched': self._architecture.is_branched,
        'total_atoms': total_atoms,
        'total_bonds': total_bonds,
        'total_angles': total_angles,
        'bond_style': self.bond_style,
        'bond_length': self.bond_length,
        'k_bond': self.k_bond,
        'use_angles': self.use_angles,
        'bead_types': [bt.name for bt in self.bead_types],
        'sequence': self._sequence,
        'output_path': self.path,
    }

kremer_grest(name: str, system: object, n_chains: int, n_beads: int, topology: str = 'linear', density: float = 0.74, generation_method: str = 'saw') -> BeadSpringPolymer classmethod

Create a Kremer-Grest bead-spring polymer with standard parameters.

The Kremer-Grest model is a standard coarse-grained polymer model used for universal polymer behavior studies. It uses: - FENE bonds (K=30, R0=1.5) - WCA purely repulsive interactions (cutoff = 2^(1/6)*sigma ≈ 1.12246) - Standard LJ parameters (epsilon=1.0, sigma=1.0, mass=1.0)

The equilibrium bond length of ~0.97 EMERGES from the balance of FENE (attractive) + WCA (repulsive) - there is no explicit r0 parameter.

Parameters:

Name Type Description Default
name str

Name for output files.

required
system object

System object containing path information.

required
n_chains int

Number of polymer chains.

required
n_beads int

Number of beads per chain.

required
topology str

"linear" or "ring" topology.

'linear'
density float

Target bead density (beads/sigma^3). Default 0.74 for initial placement (will compress to ~0.85-0.90 during NPT).

0.74
generation_method str

Method for generating initial configurations ("geometric", "saw", or "mc").

'saw'

Returns:

Type Description
BeadSpringPolymer

BeadSpringPolymer instance configured for Kremer-Grest model.

Example

from AutoPoly import System from AutoPoly import BeadSpringPolymer system = System(out="kg_simulation") kg_polymer = BeadSpringPolymer.kremer_grest( ... name="kg_melt", ... system=system, ... n_chains=100, ... n_beads=10, ... topology="linear" ... ) kg_polymer.generate_data_file()

References

Kremer, K., & Grest, G. S. (1990). Dynamics of entangled linear polymer melts: A molecular-dynamics simulation. J. Chem. Phys. 92(8), 5057-5086.

Source code in AutoPoly/models/bead_spring.py
@classmethod
def kremer_grest(
    cls,
    name: str,
    system: object,
    n_chains: int,
    n_beads: int,
    topology: str = "linear",
    density: float = 0.74,
    generation_method: str = "saw",
) -> "BeadSpringPolymer":
    """
    Create a Kremer-Grest bead-spring polymer with standard parameters.

    The Kremer-Grest model is a standard coarse-grained polymer model used
    for universal polymer behavior studies. It uses:
    - FENE bonds (K=30, R0=1.5)
    - WCA purely repulsive interactions (cutoff = 2^(1/6)*sigma ≈ 1.12246)
    - Standard LJ parameters (epsilon=1.0, sigma=1.0, mass=1.0)

    The equilibrium bond length of ~0.97 EMERGES from the balance of
    FENE (attractive) + WCA (repulsive) - there is no explicit r0 parameter.

    Args:
        name: Name for output files.
        system: System object containing path information.
        n_chains: Number of polymer chains.
        n_beads: Number of beads per chain.
        topology: "linear" or "ring" topology.
        density: Target bead density (beads/sigma^3). Default 0.74 for
            initial placement (will compress to ~0.85-0.90 during NPT).
        generation_method: Method for generating initial configurations
            ("geometric", "saw", or "mc").

    Returns:
        BeadSpringPolymer instance configured for Kremer-Grest model.

    Example:
        >>> from AutoPoly import System
        >>> from AutoPoly import BeadSpringPolymer
        >>> system = System(out="kg_simulation")
        >>> kg_polymer = BeadSpringPolymer.kremer_grest(
        ...     name="kg_melt",
        ...     system=system,
        ...     n_chains=100,
        ...     n_beads=10,
        ...     topology="linear"
        ... )
        >>> kg_polymer.generate_data_file()

    References:
        Kremer, K., & Grest, G. S. (1990). Dynamics of entangled linear
        polymer melts: A molecular-dynamics simulation. J. Chem. Phys.
        92(8), 5057-5086.
    """
    # Standard Kremer-Grest bead type
    kg_bead_type = BeadType(name="KG", mass=1.0, epsilon=1.0, sigma=1.0)

    # Uniform sequence of KG beads
    sequence = [("KG", n_beads)]

    return cls(
        name=name,
        system=system,
        n_chains=n_chains,
        bead_types=[kg_bead_type],
        sequence=sequence,
        topology=topology,
        bond_length=0.97,  # Starting guess, equilibrium emerges from FENE+WCA
        bond_style="fene",
        k_bond=30.0,
        fene_r0=1.5,
        pair_style="wca",  # WCA purely repulsive for KG melts
        density=density,
        generation_method=generation_method,
    )

calculate_box_size(n_beads: int, density: float = DEFAULT_BEAD_DENSITY) -> float

Calculate cubic box size from number of beads and target density.

Parameters:

Name Type Description Default
n_beads int

Total number of beads in system.

required
density float

Target bead density (beads per sigma^3).

DEFAULT_BEAD_DENSITY

Returns:

Type Description
float

Side length of cubic box.

Formula: V = n_beads / density, box_size = V^(1/3)

Source code in AutoPoly/models/bead_spring.py
def calculate_box_size(n_beads: int, density: float = DEFAULT_BEAD_DENSITY) -> float:
    """
    Calculate cubic box size from number of beads and target density.

    Parameters:
        n_beads: Total number of beads in system.
        density: Target bead density (beads per sigma^3).

    Returns:
        Side length of cubic box.

    Formula: V = n_beads / density, box_size = V^(1/3)
    """
    volume = n_beads / density
    box_size = volume ** (1/3)
    return box_size

compute_lj_energy(positions: Union[List[np.ndarray], np.ndarray], sigma: float = 1.0, epsilon: float = 1.0, cutoff: float = 2.5, exclude_bonded: Optional[List[Tuple[int, int]]] = None, box_size: Optional[float] = None) -> float

Compute total LJ energy for non-bonded pairs.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array for each bead.

required
sigma float

LJ sigma parameter.

1.0
epsilon float

LJ epsilon parameter.

1.0
cutoff float

Cutoff distance in units of sigma.

2.5
exclude_bonded Optional[List[Tuple[int, int]]]

List of bonded pairs (i, j) to exclude from LJ calculation.

None
box_size Optional[float]

Box size for periodic boundary conditions (None = no PBC).

None

Returns:

Type Description
float

Total LJ energy.

Source code in AutoPoly/models/bead_spring.py
def compute_lj_energy(
    positions: Union[List[np.ndarray], np.ndarray],
    sigma: float = 1.0,
    epsilon: float = 1.0,
    cutoff: float = 2.5,
    exclude_bonded: Optional[List[Tuple[int, int]]] = None,
    box_size: Optional[float] = None,
) -> float:
    """
    Compute total LJ energy for non-bonded pairs.

    Parameters:
        positions: List of position arrays or (N, 3) array for each bead.
        sigma: LJ sigma parameter.
        epsilon: LJ epsilon parameter.
        cutoff: Cutoff distance in units of sigma.
        exclude_bonded: List of bonded pairs (i, j) to exclude from LJ calculation.
        box_size: Box size for periodic boundary conditions (None = no PBC).

    Returns:
        Total LJ energy.
    """
    n_beads = len(positions)
    cutoff_dist = cutoff * sigma
    cutoff_dist_sq = cutoff_dist ** 2
    energy = 0.0

    # Build set of excluded pairs for O(1) lookup
    excluded = set()
    if exclude_bonded:
        for i, j in exclude_bonded:
            excluded.add((min(i, j), max(i, j)))

    for i in range(n_beads):
        for j in range(i + 1, n_beads):
            if (i, j) in excluded:
                continue

            r_vec = positions[j] - positions[i]

            # Apply minimum image convention for PBC
            if box_size is not None:
                r_vec = r_vec - box_size * np.round(r_vec / box_size)

            r_sq = np.dot(r_vec, r_vec)

            if r_sq < cutoff_dist_sq and r_sq > 1e-10:
                r2_inv = (sigma * sigma) / r_sq
                r6_inv = r2_inv ** 3
                r12_inv = r6_inv ** 2
                energy += 4.0 * epsilon * (r12_inv - r6_inv)

    return energy

compute_lj_energy_vectorized(positions: np.ndarray, excluded_mask: np.ndarray, sigma: float = 1.0, epsilon: float = 1.0, cutoff: float = 2.5, box_size: Optional[float] = None) -> float

Vectorized LJ energy using numpy broadcasting.

Parameters:

Name Type Description Default
positions ndarray

(N, 3) array of bead positions.

required
excluded_mask ndarray

(N, N) boolean array where True means pair is excluded.

required
sigma float

LJ sigma parameter.

1.0
epsilon float

LJ epsilon parameter.

1.0
cutoff float

Cutoff distance in units of sigma.

2.5
box_size Optional[float]

Box size for periodic boundary conditions.

None

Returns:

Type Description
float

Total LJ energy.

Source code in AutoPoly/models/bead_spring.py
def compute_lj_energy_vectorized(
    positions: np.ndarray,
    excluded_mask: np.ndarray,
    sigma: float = 1.0,
    epsilon: float = 1.0,
    cutoff: float = 2.5,
    box_size: Optional[float] = None,
) -> float:
    """
    Vectorized LJ energy using numpy broadcasting.

    Parameters:
        positions: (N, 3) array of bead positions.
        excluded_mask: (N, N) boolean array where True means pair is excluded.
        sigma: LJ sigma parameter.
        epsilon: LJ epsilon parameter.
        cutoff: Cutoff distance in units of sigma.
        box_size: Box size for periodic boundary conditions.

    Returns:
        Total LJ energy.
    """
    cutoff_dist_sq = (cutoff * sigma) ** 2

    # Pairwise differences: (N, N, 3)
    diff = positions[:, None, :] - positions[None, :, :]

    # Apply PBC
    if box_size is not None:
        diff = diff - box_size * np.round(diff / box_size)

    # Squared distances: (N, N)
    r_sq = np.sum(diff ** 2, axis=2)

    # Mask for valid pairs (not excluded, within cutoff, not self)
    # Only consider upper triangle to avoid double counting
    upper_tri = np.triu(np.ones_like(r_sq, dtype=bool), k=1)
    mask = upper_tri & (r_sq < cutoff_dist_sq) & (r_sq > 1e-10) & ~excluded_mask

    # LJ calculation only for valid pairs
    r_sq_valid = np.where(mask, r_sq, 1.0)  # Avoid division by zero
    r2_inv = (sigma ** 2) / r_sq_valid
    r6_inv = r2_inv ** 3
    r12_inv = r6_inv ** 2

    energy = 4.0 * epsilon * np.sum(np.where(mask, r12_inv - r6_inv, 0.0))
    return energy

compute_local_lj_energy(positions: np.ndarray, bead_idx: int, excluded_set: set, sigma: float = 1.0, epsilon: float = 1.0, cutoff: float = 2.5, box_size: Optional[float] = None) -> float

Compute LJ energy contribution from one bead to all others - O(N).

This is the key optimization: instead of recomputing O(N²) energy, we only compute the O(N) interactions involving the moved bead.

Parameters:

Name Type Description Default
positions ndarray

(N, 3) array of bead positions.

required
bead_idx int

Index of the bead to compute interactions for.

required
excluded_set set

Set of bead indices that are bonded to bead_idx.

required
sigma float

LJ sigma parameter.

1.0
epsilon float

LJ epsilon parameter.

1.0
cutoff float

Cutoff distance in units of sigma.

2.5
box_size Optional[float]

Box size for periodic boundary conditions.

None

Returns:

Type Description
float

LJ energy contribution from bead_idx to all other beads.

Source code in AutoPoly/models/bead_spring.py
def compute_local_lj_energy(
    positions: np.ndarray,
    bead_idx: int,
    excluded_set: set,
    sigma: float = 1.0,
    epsilon: float = 1.0,
    cutoff: float = 2.5,
    box_size: Optional[float] = None,
) -> float:
    """
    Compute LJ energy contribution from one bead to all others - O(N).

    This is the key optimization: instead of recomputing O(N²) energy,
    we only compute the O(N) interactions involving the moved bead.

    Parameters:
        positions: (N, 3) array of bead positions.
        bead_idx: Index of the bead to compute interactions for.
        excluded_set: Set of bead indices that are bonded to bead_idx.
        sigma: LJ sigma parameter.
        epsilon: LJ epsilon parameter.
        cutoff: Cutoff distance in units of sigma.
        box_size: Box size for periodic boundary conditions.

    Returns:
        LJ energy contribution from bead_idx to all other beads.
    """
    cutoff_dist_sq = (cutoff * sigma) ** 2
    pos_i = positions[bead_idx]
    n_beads = len(positions)

    # Vectorized distance to all other beads
    diff = positions - pos_i  # (N, 3)

    if box_size is not None:
        diff = diff - box_size * np.round(diff / box_size)

    r_sq = np.sum(diff ** 2, axis=1)  # (N,)

    # Build mask: valid pairs (not excluded, within cutoff, not self)
    mask = (r_sq < cutoff_dist_sq) & (r_sq > 1e-10)
    mask[bead_idx] = False  # Exclude self

    # Exclude bonded neighbors
    for j in excluded_set:
        mask[j] = False

    # LJ only for valid pairs
    r_sq_valid = np.where(mask, r_sq, 1.0)  # Avoid division by zero
    r2_inv = (sigma ** 2) / r_sq_valid
    r6_inv = r2_inv ** 3
    r12_inv = r6_inv ** 2

    energy = 4.0 * epsilon * np.sum(np.where(mask, r12_inv - r6_inv, 0.0))
    return energy

compute_local_bond_energy(positions: np.ndarray, bead_idx: int, bead_bonds: List[int], k_bond: float = 100.0, r0: float = 1.0, box_size: Optional[float] = None) -> float

Compute bond energy for bonds involving a specific bead - O(degree).

Parameters:

Name Type Description Default
positions ndarray

(N, 3) array of bead positions.

required
bead_idx int

Index of the bead.

required
bead_bonds List[int]

List of bead indices that are bonded to bead_idx.

required
k_bond float

Bond spring constant.

100.0
r0 float

Equilibrium bond length.

1.0
box_size Optional[float]

Box size for periodic boundary conditions.

None

Returns:

Type Description
float

Bond energy contribution from bead_idx.

Source code in AutoPoly/models/bead_spring.py
def compute_local_bond_energy(
    positions: np.ndarray,
    bead_idx: int,
    bead_bonds: List[int],
    k_bond: float = 100.0,
    r0: float = 1.0,
    box_size: Optional[float] = None,
) -> float:
    """
    Compute bond energy for bonds involving a specific bead - O(degree).

    Parameters:
        positions: (N, 3) array of bead positions.
        bead_idx: Index of the bead.
        bead_bonds: List of bead indices that are bonded to bead_idx.
        k_bond: Bond spring constant.
        r0: Equilibrium bond length.
        box_size: Box size for periodic boundary conditions.

    Returns:
        Bond energy contribution from bead_idx.
    """
    if not bead_bonds:
        return 0.0

    pos_i = positions[bead_idx]
    energy = 0.0

    for j in bead_bonds:
        r_vec = positions[j] - pos_i

        if box_size is not None:
            r_vec = r_vec - box_size * np.round(r_vec / box_size)

        r = np.linalg.norm(r_vec)
        dr = r - r0
        energy += 0.5 * k_bond * dr * dr

    return energy

compute_bond_energy(positions: Union[List[np.ndarray], np.ndarray], bonds: List[Tuple[int, int]], k_bond: float = 100.0, r0: float = 1.0, box_size: Optional[float] = None) -> float

Compute harmonic bond energy.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array for each bead.

required
bonds List[Tuple[int, int]]

List of (atom1_idx, atom2_idx) tuples (0-indexed).

required
k_bond float

Bond spring constant.

100.0
r0 float

Equilibrium bond length.

1.0
box_size Optional[float]

Box size for periodic boundary conditions.

None

Returns:

Type Description
float

Total bond energy.

Source code in AutoPoly/models/bead_spring.py
def compute_bond_energy(
    positions: Union[List[np.ndarray], np.ndarray],
    bonds: List[Tuple[int, int]],
    k_bond: float = 100.0,
    r0: float = 1.0,
    box_size: Optional[float] = None,
) -> float:
    """
    Compute harmonic bond energy.

    Parameters:
        positions: List of position arrays or (N, 3) array for each bead.
        bonds: List of (atom1_idx, atom2_idx) tuples (0-indexed).
        k_bond: Bond spring constant.
        r0: Equilibrium bond length.
        box_size: Box size for periodic boundary conditions.

    Returns:
        Total bond energy.
    """
    energy = 0.0

    for i, j in bonds:
        r_vec = positions[j] - positions[i]

        # Apply minimum image convention for PBC
        if box_size is not None:
            r_vec = r_vec - box_size * np.round(r_vec / box_size)

        r = np.linalg.norm(r_vec)
        dr = r - r0
        energy += 0.5 * k_bond * dr * dr

    return energy

compute_bond_energy_vectorized(positions: np.ndarray, bonds: np.ndarray, k_bond: float = 100.0, r0: float = 1.0, box_size: Optional[float] = None) -> float

Vectorized bond energy calculation.

Parameters:

Name Type Description Default
positions ndarray

(N, 3) array of bead positions.

required
bonds ndarray

(M, 2) array of bond pairs.

required
k_bond float

Bond spring constant.

100.0
r0 float

Equilibrium bond length.

1.0
box_size Optional[float]

Box size for periodic boundary conditions.

None

Returns:

Type Description
float

Total bond energy.

Source code in AutoPoly/models/bead_spring.py
def compute_bond_energy_vectorized(
    positions: np.ndarray,
    bonds: np.ndarray,
    k_bond: float = 100.0,
    r0: float = 1.0,
    box_size: Optional[float] = None,
) -> float:
    """
    Vectorized bond energy calculation.

    Parameters:
        positions: (N, 3) array of bead positions.
        bonds: (M, 2) array of bond pairs.
        k_bond: Bond spring constant.
        r0: Equilibrium bond length.
        box_size: Box size for periodic boundary conditions.

    Returns:
        Total bond energy.
    """
    if len(bonds) == 0:
        return 0.0

    pos_i = positions[bonds[:, 0]]
    pos_j = positions[bonds[:, 1]]

    diff = pos_j - pos_i

    if box_size is not None:
        diff = diff - box_size * np.round(diff / box_size)

    r = np.linalg.norm(diff, axis=1)
    dr = r - r0
    return 0.5 * k_bond * np.sum(dr ** 2)

compute_total_energy(positions: Union[List[np.ndarray], np.ndarray], bonds: List[Tuple[int, int]], lj_sigma: float = 1.0, lj_epsilon: float = 1.0, lj_cutoff: float = 2.5, bond_k: float = 100.0, bond_r0: float = 1.0, box_size: Optional[float] = None) -> float

Compute total system energy for Metropolis criterion.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array for each bead.

required
bonds List[Tuple[int, int]]

List of (atom1_idx, atom2_idx) tuples.

required
lj_sigma float

LJ sigma parameter.

1.0
lj_epsilon float

LJ epsilon parameter.

1.0
lj_cutoff float

LJ cutoff in sigma units.

2.5
bond_k float

Bond spring constant.

100.0
bond_r0 float

Equilibrium bond length.

1.0
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
float

Total energy (LJ + bond).

Source code in AutoPoly/models/bead_spring.py
def compute_total_energy(
    positions: Union[List[np.ndarray], np.ndarray],
    bonds: List[Tuple[int, int]],
    lj_sigma: float = 1.0,
    lj_epsilon: float = 1.0,
    lj_cutoff: float = 2.5,
    bond_k: float = 100.0,
    bond_r0: float = 1.0,
    box_size: Optional[float] = None,
) -> float:
    """
    Compute total system energy for Metropolis criterion.

    Parameters:
        positions: List of position arrays or (N, 3) array for each bead.
        bonds: List of (atom1_idx, atom2_idx) tuples.
        lj_sigma: LJ sigma parameter.
        lj_epsilon: LJ epsilon parameter.
        lj_cutoff: LJ cutoff in sigma units.
        bond_k: Bond spring constant.
        bond_r0: Equilibrium bond length.
        box_size: Box size for PBC.

    Returns:
        Total energy (LJ + bond).
    """
    lj_energy = compute_lj_energy(
        positions, lj_sigma, lj_epsilon, lj_cutoff,
        exclude_bonded=bonds, box_size=box_size
    )
    bond_energy = compute_bond_energy(
        positions, bonds, bond_k, bond_r0, box_size
    )
    return lj_energy + bond_energy

build_exclusion_structures(n_beads: int, bonds: List[Tuple[int, int]]) -> Tuple[np.ndarray, List[set], List[List[int]]]

Build exclusion data structures for efficient energy calculations.

Parameters:

Name Type Description Default
n_beads int

Total number of beads.

required
bonds List[Tuple[int, int]]

List of (atom1_idx, atom2_idx) tuples.

required

Returns:

Type Description
ndarray

Tuple of:

List[set]
  • excluded_mask: (N, N) boolean array for vectorized LJ
List[List[int]]
  • excluded_neighbors: List of sets for local LJ energy
Tuple[ndarray, List[set], List[List[int]]]
  • bond_neighbors: List of lists for local bond energy
Source code in AutoPoly/models/bead_spring.py
def build_exclusion_structures(
    n_beads: int,
    bonds: List[Tuple[int, int]],
) -> Tuple[np.ndarray, List[set], List[List[int]]]:
    """
    Build exclusion data structures for efficient energy calculations.

    Parameters:
        n_beads: Total number of beads.
        bonds: List of (atom1_idx, atom2_idx) tuples.

    Returns:
        Tuple of:
        - excluded_mask: (N, N) boolean array for vectorized LJ
        - excluded_neighbors: List of sets for local LJ energy
        - bond_neighbors: List of lists for local bond energy
    """
    # Build excluded pair mask (N, N) for vectorized calculation
    excluded_mask = np.zeros((n_beads, n_beads), dtype=bool)
    for i, j in bonds:
        excluded_mask[i, j] = True
        excluded_mask[j, i] = True

    # Build per-bead exclusion sets for local LJ energy
    excluded_neighbors = [set() for _ in range(n_beads)]
    for i, j in bonds:
        excluded_neighbors[i].add(j)
        excluded_neighbors[j].add(i)

    # Build per-bead bond lists for local bond energy
    bond_neighbors = [[] for _ in range(n_beads)]
    for i, j in bonds:
        bond_neighbors[i].append(j)
        bond_neighbors[j].append(i)

    return excluded_mask, excluded_neighbors, bond_neighbors

metropolis_accept(delta_E: float, temperature: float = 1.0) -> bool

Metropolis acceptance criterion.

Accept if delta_E <= 0, else accept with probability exp(-delta_E/T).

Parameters:

Name Type Description Default
delta_E float

Energy change.

required
temperature float

Reduced temperature.

1.0

Returns:

Type Description
bool

True if move should be accepted.

Source code in AutoPoly/models/bead_spring.py
def metropolis_accept(delta_E: float, temperature: float = 1.0) -> bool:
    """
    Metropolis acceptance criterion.

    Accept if delta_E <= 0, else accept with probability exp(-delta_E/T).

    Parameters:
        delta_E: Energy change.
        temperature: Reduced temperature.

    Returns:
        True if move should be accepted.
    """
    if delta_E <= 0:
        return True
    return np.random.random() < np.exp(-delta_E / temperature)

mc_single_bead_displacement(positions: Union[List[np.ndarray], np.ndarray], bead_idx: int, max_disp: float = 0.5, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Displace a single bead by random vector.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
bead_idx int

Index of bead to displace.

required
max_disp float

Maximum displacement in each direction.

0.5
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_single_bead_displacement(
    positions: Union[List[np.ndarray], np.ndarray],
    bead_idx: int,
    max_disp: float = 0.5,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Displace a single bead by random vector.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        bead_idx: Index of bead to displace.
        max_disp: Maximum displacement in each direction.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    if isinstance(positions, np.ndarray):
        new_positions = positions.copy()
        delta = np.random.uniform(-max_disp, max_disp, 3)
        new_positions[bead_idx] = new_positions[bead_idx] + delta
        if box_size is not None:
            new_positions[bead_idx] = _apply_pbc(new_positions[bead_idx], box_size)
        return new_positions, True
    else:
        new_positions = [p.copy() for p in positions]
        delta = np.random.uniform(-max_disp, max_disp, 3)
        new_positions[bead_idx] = new_positions[bead_idx] + delta
        if box_size is not None:
            new_positions[bead_idx] = _apply_pbc(new_positions[bead_idx], box_size)
        return new_positions, True

mc_crankshaft_move(positions: Union[List[np.ndarray], np.ndarray], chain_start: int, chain_end: int, max_angle: float = 0.3, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Rotate beads between i and j around the i-j axis.

Keeps beads i and j fixed; rotates all beads strictly between them.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
chain_start int

Start index of the chain.

required
chain_end int

End index of the chain (exclusive).

required
max_angle float

Maximum rotation angle in radians.

0.3
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_crankshaft_move(
    positions: Union[List[np.ndarray], np.ndarray],
    chain_start: int,
    chain_end: int,
    max_angle: float = 0.3,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Rotate beads between i and j around the i-j axis.

    Keeps beads i and j fixed; rotates all beads strictly between them.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        chain_start: Start index of the chain.
        chain_end: End index of the chain (exclusive).
        max_angle: Maximum rotation angle in radians.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    chain_length = chain_end - chain_start

    # Need at least 4 beads for crankshaft (2 endpoints + at least 2 in between)
    if chain_length < 4:
        return positions, False

    # Select two beads i, j with at least one bead between them
    i_local = np.random.randint(0, chain_length - 3)
    j_local = np.random.randint(i_local + 3, chain_length)

    i = chain_start + i_local
    j = chain_start + j_local

    is_numpy = isinstance(positions, np.ndarray)
    if is_numpy:
        new_positions = positions.copy()
        pos_i = positions[i]
        pos_j = positions[j]
    else:
        new_positions = [p.copy() for p in positions]
        pos_i = positions[i]
        pos_j = positions[j]

    # Rotation axis
    axis = pos_j - pos_i
    axis_len = np.linalg.norm(axis)
    if axis_len < 1e-10:
        return positions, False

    # Random rotation angle
    angle = np.random.uniform(-max_angle, max_angle)
    R = _rotation_matrix_around_axis(axis, angle)

    # Rotate beads between i and j (exclusive of endpoints)
    for k in range(i + 1, j):
        rel_pos = new_positions[k] - pos_i
        new_rel_pos = R @ rel_pos
        new_positions[k] = pos_i + new_rel_pos

        if box_size is not None:
            new_positions[k] = _apply_pbc(new_positions[k], box_size)

    return new_positions, True

mc_pivot_move(positions: Union[List[np.ndarray], np.ndarray], chain_start: int, chain_end: int, max_angle: float = 0.3, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Rotate arm (pivot_idx+1 to chain_end) around pivot bead.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
chain_start int

Start index of the chain.

required
chain_end int

End index of the chain (exclusive).

required
max_angle float

Maximum rotation angle in radians.

0.3
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_pivot_move(
    positions: Union[List[np.ndarray], np.ndarray],
    chain_start: int,
    chain_end: int,
    max_angle: float = 0.3,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Rotate arm (pivot_idx+1 to chain_end) around pivot bead.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        chain_start: Start index of the chain.
        chain_end: End index of the chain (exclusive).
        max_angle: Maximum rotation angle in radians.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    chain_length = chain_end - chain_start

    # Need at least 2 beads
    if chain_length < 2:
        return positions, False

    # Select pivot (not the last bead)
    pivot_local = np.random.randint(0, chain_length - 1)
    pivot_idx = chain_start + pivot_local

    is_numpy = isinstance(positions, np.ndarray)
    if is_numpy:
        new_positions = positions.copy()
        pivot_pos = positions[pivot_idx].copy()
    else:
        new_positions = [p.copy() for p in positions]
        pivot_pos = positions[pivot_idx]

    # Random rotation
    R = _random_rotation_matrix(max_angle)

    # Rotate beads after pivot
    for k in range(pivot_idx + 1, chain_end):
        rel_pos = new_positions[k] - pivot_pos
        new_rel_pos = R @ rel_pos
        new_positions[k] = pivot_pos + new_rel_pos

        if box_size is not None:
            new_positions[k] = _apply_pbc(new_positions[k], box_size)

    return new_positions, True

mc_reptation_move(positions: Union[List[np.ndarray], np.ndarray], chain_start: int, chain_end: int, bond_length: float = 1.0, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Remove bead from one end (tail) and attach at other end (head).

Slithering snake move that maintains chain connectivity.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
chain_start int

Start index of the chain.

required
chain_end int

End index of the chain (exclusive).

required
bond_length float

Bond length for new position.

1.0
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_reptation_move(
    positions: Union[List[np.ndarray], np.ndarray],
    chain_start: int,
    chain_end: int,
    bond_length: float = 1.0,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Remove bead from one end (tail) and attach at other end (head).

    Slithering snake move that maintains chain connectivity.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        chain_start: Start index of the chain.
        chain_end: End index of the chain (exclusive).
        bond_length: Bond length for new position.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    chain_length = chain_end - chain_start

    # Need at least 2 beads
    if chain_length < 2:
        return positions, False

    is_numpy = isinstance(positions, np.ndarray)
    if is_numpy:
        new_positions = positions.copy()
    else:
        new_positions = [p.copy() for p in positions]

    # Randomly choose direction
    forward = np.random.random() < 0.5

    if forward:
        # Move bead from tail (chain_start) to head (chain_end-1)
        # Shift all beads toward chain_start
        head_pos = positions[chain_end - 1].copy() if is_numpy else positions[chain_end - 1]

        for k in range(chain_start, chain_end - 1):
            new_positions[k] = positions[k + 1].copy()

        # Generate new position at head
        random_dir = np.random.randn(3)
        random_dir = random_dir / np.linalg.norm(random_dir)
        new_positions[chain_end - 1] = head_pos + bond_length * random_dir

    else:
        # Move bead from head (chain_end-1) to tail (chain_start)
        # Shift all beads toward chain_end
        tail_pos = positions[chain_start].copy() if is_numpy else positions[chain_start]

        for k in range(chain_end - 1, chain_start, -1):
            new_positions[k] = positions[k - 1].copy()

        # Generate new position at tail
        random_dir = np.random.randn(3)
        random_dir = random_dir / np.linalg.norm(random_dir)
        new_positions[chain_start] = tail_pos + bond_length * random_dir

    # Apply PBC
    if box_size is not None:
        for k in range(chain_start, chain_end):
            new_positions[k] = _apply_pbc(new_positions[k], box_size)

    return new_positions, True

mc_tree_pivot_move(positions: Union[List[np.ndarray], np.ndarray], pivot_idx: int, subtree_indices: List[int], max_angle: float = 0.3, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Rotate a subtree of beads around a random axis through the pivot bead.

This is the graph generalization of the pivot move for branched architectures: cutting edge (pivot, q) splits the molecule; the subtree on q's side (subtree_indices, must include q) is rotated rigidly. Because the rotation axis passes through the pivot bead, the (pivot, q) bond length and all internal subtree bonds are preserved exactly.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
pivot_idx int

Index of the pivot bead (rotation axis passes through it).

required
subtree_indices List[int]

Indices of beads to rotate (the component beyond the cut edge, including q).

required
max_angle float

Maximum rotation angle (radians).

0.3
box_size Optional[float]

Box size for PBC wrapping.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_tree_pivot_move(
    positions: Union[List[np.ndarray], np.ndarray],
    pivot_idx: int,
    subtree_indices: List[int],
    max_angle: float = 0.3,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Rotate a subtree of beads around a random axis through the pivot bead.

    This is the graph generalization of the pivot move for branched
    architectures: cutting edge (pivot, q) splits the molecule; the subtree
    on q's side (``subtree_indices``, must include q) is rotated rigidly.
    Because the rotation axis passes through the pivot bead, the (pivot, q)
    bond length and all internal subtree bonds are preserved exactly.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        pivot_idx: Index of the pivot bead (rotation axis passes through it).
        subtree_indices: Indices of beads to rotate (the component beyond
            the cut edge, including q).
        max_angle: Maximum rotation angle (radians).
        box_size: Box size for PBC wrapping.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    if not subtree_indices:
        return positions, False

    if isinstance(positions, list):
        new_positions = [p.copy() for p in positions]
    else:
        new_positions = positions.copy()

    pivot_pos = np.array(positions[pivot_idx], dtype=float)
    angle = np.random.uniform(-max_angle, max_angle)
    R = _random_rotation_matrix(angle)

    for idx in subtree_indices:
        rel = np.array(positions[idx], dtype=float) - pivot_pos
        new_positions[idx] = pivot_pos + R @ rel
        if box_size is not None:
            new_positions[idx] = _apply_pbc(new_positions[idx], box_size)

    return new_positions, True

mc_segment_crankshaft_move(positions: Union[List[np.ndarray], np.ndarray], segment: List[int], max_angle: float = 0.3, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Crankshaft move along an explicit bead path (segment).

Graph generalization of :func:mc_crankshaft_move for branched architectures: two beads i, j are chosen along the segment path (with at least two path beads between them) and the path beads strictly between them are rotated around the i-j axis. The segment must be a genuine bond path so all rotated bonds are preserved.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
segment List[int]

Bead indices forming a connected path (length >= 4).

required
max_angle float

Maximum rotation angle in radians.

0.3
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_segment_crankshaft_move(
    positions: Union[List[np.ndarray], np.ndarray],
    segment: List[int],
    max_angle: float = 0.3,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Crankshaft move along an explicit bead path (segment).

    Graph generalization of :func:`mc_crankshaft_move` for branched
    architectures: two beads i, j are chosen along the segment path (with at
    least two path beads between them) and the path beads strictly between
    them are rotated around the i-j axis. The segment must be a genuine bond
    path so all rotated bonds are preserved.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        segment: Bead indices forming a connected path (length >= 4).
        max_angle: Maximum rotation angle in radians.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    if len(segment) < 4:
        return positions, False

    a = np.random.randint(0, len(segment) - 3)
    b = np.random.randint(a + 3, len(segment))

    i = segment[a]
    j = segment[b]

    is_numpy = isinstance(positions, np.ndarray)
    if is_numpy:
        new_positions = positions.copy()
    else:
        new_positions = [p.copy() for p in positions]

    pos_i = np.array(positions[i], dtype=float)
    pos_j = np.array(positions[j], dtype=float)

    axis = pos_j - pos_i
    if np.linalg.norm(axis) < 1e-10:
        return positions, False

    angle = np.random.uniform(-max_angle, max_angle)
    R = _rotation_matrix_around_axis(axis, angle)

    for k in range(a + 1, b):
        idx = segment[k]
        rel_pos = np.array(positions[idx], dtype=float) - pos_i
        new_positions[idx] = pos_i + R @ rel_pos
        if box_size is not None:
            new_positions[idx] = _apply_pbc(new_positions[idx], box_size)

    return new_positions, True

build_chain_graph(architecture: BeadArchitecture, start: int) -> Dict[str, any]

Build per-chain graph metadata for branched MC moves.

Parameters:

Name Type Description Default
architecture BeadArchitecture

The chain's BeadArchitecture.

required
start int

Global index of the chain's first bead (bead i of the architecture maps to global index start + i).

required

Returns:

Type Description
Dict[str, any]

Dict with keys: - "branched": True if any bead has degree > 2 or the graph is not a simple path - "adjacency": global-index adjacency dict - "edges": global-index bond list - "pivot_edges": bridge edges valid for tree-pivot moves - "segments": linear bead paths valid for segment crankshaft

Source code in AutoPoly/models/bead_spring.py
def build_chain_graph(
    architecture: BeadArchitecture,
    start: int,
) -> Dict[str, any]:
    """
    Build per-chain graph metadata for branched MC moves.

    Parameters:
        architecture: The chain's BeadArchitecture.
        start: Global index of the chain's first bead (bead i of the
            architecture maps to global index ``start + i``).

    Returns:
        Dict with keys:
            - "branched": True if any bead has degree > 2 or the graph is
              not a simple path
            - "adjacency": global-index adjacency dict
            - "edges": global-index bond list
            - "pivot_edges": bridge edges valid for tree-pivot moves
            - "segments": linear bead paths valid for segment crankshaft
    """
    n = architecture.n_beads
    adjacency: Dict[int, List[int]] = {start + i: [] for i in range(n)}
    edges = [(start + i, start + j) for i, j in architecture.bonds]
    for u, v in edges:
        adjacency[u].append(v)
        adjacency[v].append(u)

    degrees = architecture.degrees()
    # A simple path: exactly 2 ends (deg 1), all others deg 2, n-1 bonds
    is_simple_path = (
        architecture.n_bonds == n - 1
        and sum(1 for d in degrees if d == 1) == 2
        and all(d <= 2 for d in degrees)
    )
    branched = not is_simple_path

    return {
        "branched": branched,
        "adjacency": adjacency,
        "edges": edges,
        "pivot_edges": _find_bridge_edges(adjacency, edges) if branched else [],
        "segments": [
            [start + i for i in seg] for seg in architecture.linear_segments()
        ] if branched else [],
    }

place_chains_in_box(chain_positions: List[List[np.ndarray]], box_size: float, min_separation: float = 2.0, max_attempts: int = 1000) -> Tuple[List[np.ndarray], List[Tuple[int, int]]]

Place multiple chains randomly in periodic box.

Parameters:

Name Type Description Default
chain_positions List[List[ndarray]]

List of chain positions (each chain is list of np.array).

required
box_size float

Cubic box side length.

required
min_separation float

Minimum distance between chain COMs.

2.0
max_attempts int

Maximum placement attempts per chain.

1000

Returns:

Type Description
List[ndarray]

Tuple of (all_positions, chain_indices) where chain_indices is

List[Tuple[int, int]]

list of (start, end) indices for each chain.

Source code in AutoPoly/models/bead_spring.py
def place_chains_in_box(
    chain_positions: List[List[np.ndarray]],
    box_size: float,
    min_separation: float = 2.0,
    max_attempts: int = 1000,
) -> Tuple[List[np.ndarray], List[Tuple[int, int]]]:
    """
    Place multiple chains randomly in periodic box.

    Parameters:
        chain_positions: List of chain positions (each chain is list of np.array).
        box_size: Cubic box side length.
        min_separation: Minimum distance between chain COMs.
        max_attempts: Maximum placement attempts per chain.

    Returns:
        Tuple of (all_positions, chain_indices) where chain_indices is
        list of (start, end) indices for each chain.
    """
    all_positions = []
    chain_indices = []
    placed_coms = []

    for chain_idx, chain in enumerate(chain_positions):
        # Compute original COM
        orig_com = np.mean(chain, axis=0)

        # Center chain at origin
        centered_chain = [p - orig_com for p in chain]

        placed = False
        for attempt in range(max_attempts):
            # Random position in box
            new_com = np.random.uniform(-box_size/2, box_size/2, 3)

            # Check separation from existing chains
            too_close = False
            for existing_com in placed_coms:
                dist_vec = new_com - existing_com
                dist_vec = dist_vec - box_size * np.round(dist_vec / box_size)
                if np.linalg.norm(dist_vec) < min_separation:
                    too_close = True
                    break

            if too_close:
                continue

            # Random rotation
            R = _random_rotation_matrix(np.pi)

            # Transform chain
            start_idx = len(all_positions)
            for p in centered_chain:
                rotated = R @ p
                new_pos = rotated + new_com
                new_pos = _apply_pbc(new_pos, box_size)
                all_positions.append(new_pos)

            end_idx = len(all_positions)
            chain_indices.append((start_idx, end_idx))
            placed_coms.append(new_com)
            placed = True
            break

        if not placed:
            logger.warning(
                f"Could not place chain {chain_idx} with min_separation={min_separation}. "
                "Placing without separation constraint."
            )
            new_com = np.random.uniform(-box_size/2, box_size/2, 3)
            R = _random_rotation_matrix(np.pi)

            start_idx = len(all_positions)
            for p in centered_chain:
                rotated = R @ p
                new_pos = rotated + new_com
                new_pos = _apply_pbc(new_pos, box_size)
                all_positions.append(new_pos)

            end_idx = len(all_positions)
            chain_indices.append((start_idx, end_idx))
            placed_coms.append(new_com)

    return all_positions, chain_indices

mc_chain_translation(positions: Union[List[np.ndarray], np.ndarray], chain_indices: List[Tuple[int, int]], chain_idx: int, max_disp: float, box_size: float) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Translate entire chain by random displacement with PBC.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
chain_indices List[Tuple[int, int]]

List of (start, end) indices for each chain.

required
chain_idx int

Index of chain to translate.

required
max_disp float

Maximum displacement.

required
box_size float

Box size for PBC.

required

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_chain_translation(
    positions: Union[List[np.ndarray], np.ndarray],
    chain_indices: List[Tuple[int, int]],
    chain_idx: int,
    max_disp: float,
    box_size: float,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Translate entire chain by random displacement with PBC.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        chain_indices: List of (start, end) indices for each chain.
        chain_idx: Index of chain to translate.
        max_disp: Maximum displacement.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    start, end = chain_indices[chain_idx]
    is_numpy = isinstance(positions, np.ndarray)

    if is_numpy:
        new_positions = positions.copy()
    else:
        new_positions = [p.copy() for p in positions]

    delta = np.random.uniform(-max_disp, max_disp, 3)

    for k in range(start, end):
        new_positions[k] = new_positions[k] + delta
        new_positions[k] = _apply_pbc(new_positions[k], box_size)

    return new_positions, True

mc_chain_rotation(positions: Union[List[np.ndarray], np.ndarray], chain_indices: List[Tuple[int, int]], chain_idx: int, max_angle: float, box_size: Optional[float] = None) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]

Rotate entire chain around its center of mass.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of position arrays or (N, 3) array.

required
chain_indices List[Tuple[int, int]]

List of (start, end) indices for each chain.

required
chain_idx int

Index of chain to rotate.

required
max_angle float

Maximum rotation angle.

required
box_size Optional[float]

Box size for PBC.

None

Returns:

Type Description
Tuple[Union[List[ndarray], ndarray], bool]

Tuple of (new_positions, is_valid).

Source code in AutoPoly/models/bead_spring.py
def mc_chain_rotation(
    positions: Union[List[np.ndarray], np.ndarray],
    chain_indices: List[Tuple[int, int]],
    chain_idx: int,
    max_angle: float,
    box_size: Optional[float] = None,
) -> Tuple[Union[List[np.ndarray], np.ndarray], bool]:
    """
    Rotate entire chain around its center of mass.

    Parameters:
        positions: List of position arrays or (N, 3) array.
        chain_indices: List of (start, end) indices for each chain.
        chain_idx: Index of chain to rotate.
        max_angle: Maximum rotation angle.
        box_size: Box size for PBC.

    Returns:
        Tuple of (new_positions, is_valid).
    """
    start, end = chain_indices[chain_idx]
    is_numpy = isinstance(positions, np.ndarray)

    if is_numpy:
        new_positions = positions.copy()
        chain_pos = positions[start:end]
    else:
        new_positions = [p.copy() for p in positions]
        chain_pos = [positions[k] for k in range(start, end)]

    com = np.mean(chain_pos, axis=0)

    # Random rotation
    R = _random_rotation_matrix(max_angle)

    # Rotate around COM
    for k in range(start, end):
        rel_pos = new_positions[k] - com
        new_rel_pos = R @ rel_pos
        new_positions[k] = com + new_rel_pos

        if box_size is not None:
            new_positions[k] = _apply_pbc(new_positions[k], box_size)

    return new_positions, True

saw_grow_chain(n_beads: int, bond_length: float, start_position: np.ndarray, collision_detector: CollisionDetector, config: SAWConfig, topology: str = 'linear', chain_id_offset: int = 0) -> Tuple[Optional[List[np.ndarray]], int]

Grow a single polymer chain using Self-Avoiding Random Walk with backtracking.

Parameters:

Name Type Description Default
n_beads int

Number of beads in the chain.

required
bond_length float

Distance between consecutive beads.

required
start_position ndarray

Position of the first bead.

required
collision_detector CollisionDetector

CollisionDetector for checking overlaps.

required
config SAWConfig

SAWConfig with algorithm parameters.

required
topology str

"linear" or "ring".

'linear'
chain_id_offset int

Offset for bead IDs in collision detector.

0

Returns:

Type Description
Tuple[Optional[List[ndarray]], int]

Tuple of (positions, backtracks_used) where positions is None if failed.

Source code in AutoPoly/models/bead_spring.py
def saw_grow_chain(
    n_beads: int,
    bond_length: float,
    start_position: np.ndarray,
    collision_detector: CollisionDetector,
    config: SAWConfig,
    topology: str = "linear",
    chain_id_offset: int = 0,
) -> Tuple[Optional[List[np.ndarray]], int]:
    """
    Grow a single polymer chain using Self-Avoiding Random Walk with backtracking.

    Parameters:
        n_beads: Number of beads in the chain.
        bond_length: Distance between consecutive beads.
        start_position: Position of the first bead.
        collision_detector: CollisionDetector for checking overlaps.
        config: SAWConfig with algorithm parameters.
        topology: "linear" or "ring".
        chain_id_offset: Offset for bead IDs in collision detector.

    Returns:
        Tuple of (positions, backtracks_used) where positions is None if failed.
    """
    if n_beads < 1:
        return [], 0

    positions = [start_position.copy()]
    backtrack_count = 0
    backtrack_depth = 1  # Current backtrack depth (exponential increase)

    # Add first bead to collision detector
    collision_detector.add_monomer(
        chain_id_offset,
        start_position,
        config.collision_sigma / 2
    )

    bead_idx = 1
    while bead_idx < n_beads:
        # Get previous direction for angle constraint
        if bead_idx >= 2:
            prev_direction = positions[bead_idx - 1] - positions[bead_idx - 2]
        else:
            prev_direction = None

        # For ring closure: last bead needs to connect back to first
        is_closing_ring = (topology == "ring" and bead_idx == n_beads - 1)

        # Generate trial positions
        n_trials = config.ring_closure_trials if is_closing_ring else config.n_trials
        trial_positions = _generate_trial_positions(
            positions[bead_idx - 1],
            bond_length,
            n_trials,
            prev_direction,
            config.bond_angle_min,
            config.bond_angle_max,
        )

        # Shuffle trials for randomness
        if len(trial_positions) > 0:
            np.random.shuffle(trial_positions)

        # Find valid position
        valid_position = None
        exclude_set = {chain_id_offset + bead_idx - 1}  # Exclude bonded neighbor

        for trial_pos in trial_positions:
            # Check collision with existing beads
            has_collision = collision_detector.check_collision(
                trial_pos,
                config.collision_sigma / 2,
                exclude_ids=exclude_set,
                tolerance=config.collision_tolerance,
            )

            if has_collision:
                continue

            # For ring closure: check distance to first bead
            if is_closing_ring:
                dist_to_first = np.linalg.norm(trial_pos - positions[0])
                if abs(dist_to_first - bond_length) > config.ring_closure_tolerance:
                    continue

            valid_position = trial_pos
            break

        if valid_position is not None:
            # Accept position
            positions.append(valid_position.copy())
            collision_detector.add_monomer(
                chain_id_offset + bead_idx,
                valid_position,
                config.collision_sigma / 2
            )
            bead_idx += 1
            backtrack_depth = 1  # Reset backtrack depth on success
        else:
            # Backtrack
            if backtrack_count >= config.max_total_backtracks:
                # Failed - remove all beads we added from detector
                for i in range(len(positions)):
                    collision_detector.remove_monomer(chain_id_offset + i)
                return None, backtrack_count

            # Determine how many beads to remove
            n_remove = min(backtrack_depth, bead_idx - 1, config.max_backtrack_depth)
            if n_remove == 0:
                # Can't backtrack further - failed
                for i in range(len(positions)):
                    collision_detector.remove_monomer(chain_id_offset + i)
                return None, backtrack_count

            # Remove beads from end
            for _ in range(n_remove):
                bead_idx -= 1
                collision_detector.remove_monomer(chain_id_offset + bead_idx)
                positions.pop()

            backtrack_count += 1
            backtrack_depth = min(backtrack_depth * 2, config.max_backtrack_depth)

    return positions, backtrack_count

saw_generate_multi_chain(n_chains: int, n_beads_per_chain: int, bond_length: float, box_size: float, config: SAWConfig, topology: str = 'linear', max_start_attempts: int = 100) -> Tuple[Optional[List[np.ndarray]], Optional[List[Tuple[int, int]]], Dict[str, any]]

Generate multiple polymer chains using SAW.

Parameters:

Name Type Description Default
n_chains int

Number of chains to generate.

required
n_beads_per_chain int

Beads per chain.

required
bond_length float

Bond length between consecutive beads.

required
box_size float

Cubic box side length.

required
config SAWConfig

SAWConfig with algorithm parameters.

required
topology str

"linear" or "ring".

'linear'
max_start_attempts int

Max attempts to find valid starting position per chain.

100

Returns:

Type Description
Tuple[Optional[List[ndarray]], Optional[List[Tuple[int, int]]], Dict[str, any]]

Tuple of (all_positions, chain_indices, stats) or (None, None, stats) if failed.

Source code in AutoPoly/models/bead_spring.py
def saw_generate_multi_chain(
    n_chains: int,
    n_beads_per_chain: int,
    bond_length: float,
    box_size: float,
    config: SAWConfig,
    topology: str = "linear",
    max_start_attempts: int = 100,
) -> Tuple[Optional[List[np.ndarray]], Optional[List[Tuple[int, int]]], Dict[str, any]]:
    """
    Generate multiple polymer chains using SAW.

    Parameters:
        n_chains: Number of chains to generate.
        n_beads_per_chain: Beads per chain.
        bond_length: Bond length between consecutive beads.
        box_size: Cubic box side length.
        config: SAWConfig with algorithm parameters.
        topology: "linear" or "ring".
        max_start_attempts: Max attempts to find valid starting position per chain.

    Returns:
        Tuple of (all_positions, chain_indices, stats) or (None, None, stats) if failed.
    """
    half_box = box_size / 2
    box_bounds = ((-half_box, half_box), (-half_box, half_box), (-half_box, half_box))

    # Cell size should be at least collision diameter
    cell_size = max(config.collision_sigma * 2, bond_length * 2)
    collision_detector = CollisionDetector(box_bounds, cell_size)

    all_positions = []
    chain_indices = []
    total_backtracks = 0
    chains_completed = 0

    for chain_idx in range(n_chains):
        chain_offset = len(all_positions)

        # Find valid starting position
        start_found = False
        for attempt in range(max_start_attempts):
            # Random position within box (with margin)
            margin = config.collision_sigma * 2
            start_pos = np.random.uniform(
                -half_box + margin,
                half_box - margin,
                3
            )

            # Check if position is collision-free
            if not collision_detector.check_collision(
                start_pos,
                config.collision_sigma / 2,
                tolerance=config.collision_tolerance
            ):
                start_found = True
                break

        if not start_found:
            logger.warning(
                f"SAW: Could not find valid start position for chain {chain_idx}"
            )
            return None, None, {
                "success": False,
                "chains_completed": chains_completed,
                "total_backtracks": total_backtracks,
                "failure_reason": "start_position",
            }

        # Grow chain
        chain_positions, backtracks = saw_grow_chain(
            n_beads_per_chain,
            bond_length,
            start_pos,
            collision_detector,
            config,
            topology,
            chain_offset,
        )

        total_backtracks += backtracks

        if chain_positions is None:
            logger.warning(
                f"SAW: Failed to grow chain {chain_idx} after {backtracks} backtracks"
            )
            return None, None, {
                "success": False,
                "chains_completed": chains_completed,
                "total_backtracks": total_backtracks,
                "failure_reason": "chain_growth",
            }

        # Store chain
        all_positions.extend(chain_positions)
        chain_indices.append((chain_offset, chain_offset + len(chain_positions)))
        chains_completed += 1

    return all_positions, chain_indices, {
        "success": True,
        "chains_completed": chains_completed,
        "total_backtracks": total_backtracks,
    }

saw_grow_graph(architecture: BeadArchitecture, bond_length: float, start_position: np.ndarray, collision_detector: CollisionDetector, config: SAWConfig, chain_id_offset: int = 0) -> Tuple[Optional[List[np.ndarray]], int]

Grow a single chain of arbitrary architecture using SAW with backtracking.

Beads are placed along the spanning-tree growth order of the architecture (BFS from bead 0): each bead is placed at bond_length from its already-placed parent. Cycle-closing edges (e.g. the ring closure) are enforced as distance constraints when the second endpoint is placed.

Parameters:

Name Type Description Default
architecture BeadArchitecture

BeadArchitecture defining bead connectivity.

required
bond_length float

Distance between bonded beads.

required
start_position ndarray

Position of the root bead (bead 0).

required
collision_detector CollisionDetector

CollisionDetector for checking overlaps.

required
config SAWConfig

SAWConfig with algorithm parameters.

required
chain_id_offset int

Offset for bead IDs in collision detector.

0

Returns:

Type Description
Optional[List[ndarray]]

Tuple of (positions, backtracks_used); positions is None if failed.

int

positions[i] corresponds to bead i of the architecture.

Source code in AutoPoly/models/bead_spring.py
def saw_grow_graph(
    architecture: BeadArchitecture,
    bond_length: float,
    start_position: np.ndarray,
    collision_detector: CollisionDetector,
    config: SAWConfig,
    chain_id_offset: int = 0,
) -> Tuple[Optional[List[np.ndarray]], int]:
    """
    Grow a single chain of arbitrary architecture using SAW with backtracking.

    Beads are placed along the spanning-tree growth order of the architecture
    (BFS from bead 0): each bead is placed at ``bond_length`` from its
    already-placed parent. Cycle-closing edges (e.g. the ring closure) are
    enforced as distance constraints when the second endpoint is placed.

    Parameters:
        architecture: BeadArchitecture defining bead connectivity.
        bond_length: Distance between bonded beads.
        start_position: Position of the root bead (bead 0).
        collision_detector: CollisionDetector for checking overlaps.
        config: SAWConfig with algorithm parameters.
        chain_id_offset: Offset for bead IDs in collision detector.

    Returns:
        Tuple of (positions, backtracks_used); positions is None if failed.
        ``positions[i]`` corresponds to bead ``i`` of the architecture.
    """
    n_beads = architecture.n_beads
    if n_beads < 1:
        return [], 0

    order, parents, closing_edges = architecture.growth_order(root=0)

    # Closing constraints per bead: list of already-placed neighbors that a
    # bead must land within ring_closure_tolerance of bond_length from.
    closing_neighbors: Dict[int, List[int]] = {}
    for u, v in closing_edges:
        closing_neighbors.setdefault(u, []).append(v)
        closing_neighbors.setdefault(v, []).append(u)

    positions: Dict[int, np.ndarray] = {0: start_position.copy()}
    placed: List[int] = [0]  # placement stack in growth order
    backtrack_count = 0
    backtrack_depth = 1

    collision_detector.add_monomer(
        chain_id_offset, start_position, config.collision_sigma / 2
    )

    step = 1  # next index into order
    while step < n_beads:
        bead = order[step]
        parent = parents[bead]
        assert parent is not None
        grandparent = parents[parent]
        prev_direction = (
            positions[parent] - positions[grandparent]
            if grandparent is not None else None
        )

        # Beads with closing constraints get extra trials (like ring closure)
        pending_closure = [
            nbr for nbr in closing_neighbors.get(bead, []) if nbr in positions
        ]
        n_trials = config.ring_closure_trials if pending_closure else config.n_trials

        trial_positions = _generate_trial_positions(
            positions[parent],
            bond_length,
            n_trials,
            prev_direction,
            config.bond_angle_min,
            config.bond_angle_max,
        )
        if len(trial_positions) > 0:
            np.random.shuffle(trial_positions)

        valid_position = None
        exclude_set = {chain_id_offset + parent}
        for trial_pos in trial_positions:
            if collision_detector.check_collision(
                trial_pos,
                config.collision_sigma / 2,
                exclude_ids=exclude_set,
                tolerance=config.collision_tolerance,
            ):
                continue
            # Enforce closing-edge distance constraints
            closure_ok = True
            for nbr in pending_closure:
                dist = np.linalg.norm(trial_pos - positions[nbr])
                if abs(dist - bond_length) > config.ring_closure_tolerance:
                    closure_ok = False
                    break
            if closure_ok:
                valid_position = trial_pos
                break

        if valid_position is not None:
            positions[bead] = valid_position.copy()
            placed.append(bead)
            collision_detector.add_monomer(
                chain_id_offset + bead, valid_position, config.collision_sigma / 2
            )
            step += 1
            backtrack_depth = 1
        else:
            # Backtrack: remove the most recently placed beads (growth order)
            if backtrack_count >= config.max_total_backtracks or len(placed) <= 1:
                for b in placed:
                    collision_detector.remove_monomer(chain_id_offset + b)
                return None, backtrack_count

            n_remove = min(backtrack_depth, len(placed) - 1,
                           config.max_backtrack_depth)
            for _ in range(n_remove):
                b = placed.pop()
                del positions[b]
                collision_detector.remove_monomer(chain_id_offset + b)
            # Resume from the first unplaced bead in growth order
            placed_set = set(placed)
            step = next(
                i for i, b in enumerate(order) if b not in placed_set
            )
            backtrack_count += 1
            backtrack_depth = min(backtrack_depth * 2, config.max_backtrack_depth)

    return [positions[i] for i in range(n_beads)], backtrack_count

saw_generate_graphs(architectures: List[BeadArchitecture], bond_length: float, box_size: float, config: SAWConfig, max_start_attempts: int = 100, obstacles: Optional[Tuple[np.ndarray, np.ndarray]] = None) -> Tuple[Optional[List[np.ndarray]], Optional[List[Tuple[int, int]]], Dict[str, any]]

Generate multiple chains of (possibly different) architectures using SAW.

This is the graph-based generalization of :func:saw_generate_multi_chain and also the driver for mixtures: each chain may have its own architecture.

Parameters:

Name Type Description Default
architectures List[BeadArchitecture]

One BeadArchitecture per chain to generate.

required
bond_length float

Bond length between bonded beads.

required
box_size float

Cubic box side length.

required
config SAWConfig

SAWConfig with algorithm parameters.

required
max_start_attempts int

Max attempts to find valid starting position.

100
obstacles Optional[Tuple[ndarray, ndarray]]

Optional (centers (k, 3), exclusion radii (k,)) of fixed spheres (coarse-grained fillers) no bead may enter. With obstacles, all overlap checks (obstacles and beads) use the periodic minimum image of the box. None (default) leaves the generator unchanged.

None

Returns:

Type Description
Optional[List[ndarray]]

Tuple of (all_positions, chain_indices, stats) or

Optional[List[Tuple[int, int]]]

(None, None, stats) if failed.

Source code in AutoPoly/models/bead_spring.py
def saw_generate_graphs(
    architectures: List[BeadArchitecture],
    bond_length: float,
    box_size: float,
    config: SAWConfig,
    max_start_attempts: int = 100,
    obstacles: Optional[Tuple[np.ndarray, np.ndarray]] = None,
) -> Tuple[Optional[List[np.ndarray]], Optional[List[Tuple[int, int]]], Dict[str, any]]:
    """
    Generate multiple chains of (possibly different) architectures using SAW.

    This is the graph-based generalization of :func:`saw_generate_multi_chain`
    and also the driver for mixtures: each chain may have its own
    architecture.

    Parameters:
        architectures: One BeadArchitecture per chain to generate.
        bond_length: Bond length between bonded beads.
        box_size: Cubic box side length.
        config: SAWConfig with algorithm parameters.
        max_start_attempts: Max attempts to find valid starting position.
        obstacles: Optional (centers (k, 3), exclusion radii (k,)) of fixed
            spheres (coarse-grained fillers) no bead may enter.  With
            obstacles, all overlap checks (obstacles and beads) use the
            periodic minimum image of the box.  None (default) leaves the
            generator unchanged.

    Returns:
        Tuple of (all_positions, chain_indices, stats) or
        (None, None, stats) if failed.
    """
    half_box = box_size / 2
    box_bounds = ((-half_box, half_box), (-half_box, half_box), (-half_box, half_box))

    cell_size = max(config.collision_sigma * 2, bond_length * 2)
    if obstacles is None:
        collision_detector = CollisionDetector(box_bounds, cell_size)
    else:
        collision_detector = ObstacleCollisionDetector(
            box_bounds, cell_size, obstacles[0], obstacles[1], period=box_size
        )

    all_positions: List[np.ndarray] = []
    chain_indices: List[Tuple[int, int]] = []
    total_backtracks = 0
    chains_completed = 0

    for chain_idx, architecture in enumerate(architectures):
        chain_offset = len(all_positions)

        # Find valid starting position
        start_found = False
        for attempt in range(max_start_attempts):
            margin = config.collision_sigma * 2
            start_pos = np.random.uniform(-half_box + margin, half_box - margin, 3)
            if not collision_detector.check_collision(
                start_pos,
                config.collision_sigma / 2,
                tolerance=config.collision_tolerance,
            ):
                start_found = True
                break

        if not start_found:
            logger.warning(
                f"SAW: Could not find valid start position for chain {chain_idx}"
            )
            return None, None, {
                "success": False,
                "chains_completed": chains_completed,
                "total_backtracks": total_backtracks,
                "failure_reason": "start_position",
            }

        chain_positions, backtracks = saw_grow_graph(
            architecture,
            bond_length,
            start_pos,
            collision_detector,
            config,
            chain_offset,
        )

        total_backtracks += backtracks

        if chain_positions is None:
            logger.warning(
                f"SAW: Failed to grow chain {chain_idx} after {backtracks} backtracks"
            )
            return None, None, {
                "success": False,
                "chains_completed": chains_completed,
                "total_backtracks": total_backtracks,
                "failure_reason": "chain_growth",
            }

        all_positions.extend(chain_positions)
        chain_indices.append((chain_offset, chain_offset + len(chain_positions)))
        chains_completed += 1

    return all_positions, chain_indices, {
        "success": True,
        "chains_completed": chains_completed,
        "total_backtracks": total_backtracks,
    }

mc_equilibrate(positions: Union[List[np.ndarray], np.ndarray], bonds: List[Tuple[int, int]], chain_indices: Optional[List[Tuple[int, int]]] = None, chain_graphs: Optional[List[Dict[str, any]]] = None, n_steps: int = 10000, temperature: float = 1.0, move_weights: Optional[Dict[str, float]] = None, box_size: Optional[float] = None, lj_sigma: float = 1.0, lj_epsilon: float = 1.0, lj_cutoff: float = 2.5, bond_k: float = 100.0, bond_r0: float = 1.0, max_displacement: float = 0.5, max_angle: float = 0.3, verbose: bool = False) -> Tuple[List[np.ndarray], Dict[str, float]]

Pre-equilibrate polymer configuration using MC moves.

This implementation uses local energy updates for single-bead moves, reducing complexity from O(N²) to O(N) per step for the most common move type. For multi-bead moves, full energy recalculation is used.

Parameters:

Name Type Description Default
positions Union[List[ndarray], ndarray]

List of np.array or (N, 3) array, atom positions.

required
bonds List[Tuple[int, int]]

List of (atom1_idx, atom2_idx) tuples (0-indexed).

required
chain_indices Optional[List[Tuple[int, int]]]

List of (start, end) tuples for each chain. If None, treats entire system as one chain.

None
chain_graphs Optional[List[Dict[str, any]]]

Optional per-chain graph metadata for branched architectures (see :func:build_chain_graph). For chains marked "branched", pivot moves become tree-pivots across bridge edges, crankshaft moves are restricted to linear segments, and reptation is disabled. Linear chains (or chain_graphs=None) use the legacy path-based moves.

None
n_steps int

Number of MC steps.

10000
temperature float

Reduced temperature.

1.0
move_weights Optional[Dict[str, float]]

Dict of move type probabilities.

None
box_size Optional[float]

Apply PBC if specified.

None
lj_sigma float

LJ sigma parameter.

1.0
lj_epsilon float

LJ epsilon parameter.

1.0
lj_cutoff float

LJ cutoff in sigma units.

2.5
bond_k float

Bond spring constant.

100.0
bond_r0 float

Equilibrium bond length.

1.0
max_displacement float

Max displacement for single bead moves.

0.5
max_angle float

Max rotation angle for pivot/crankshaft.

0.3
verbose bool

Print progress.

False

Returns:

Type Description
Tuple[List[ndarray], Dict[str, float]]

Tuple of (equilibrated_positions, acceptance_stats).

Source code in AutoPoly/models/bead_spring.py
def mc_equilibrate(
    positions: Union[List[np.ndarray], np.ndarray],
    bonds: List[Tuple[int, int]],
    chain_indices: Optional[List[Tuple[int, int]]] = None,
    chain_graphs: Optional[List[Dict[str, any]]] = None,
    n_steps: int = 10000,
    temperature: float = 1.0,
    move_weights: Optional[Dict[str, float]] = None,
    box_size: Optional[float] = None,
    lj_sigma: float = 1.0,
    lj_epsilon: float = 1.0,
    lj_cutoff: float = 2.5,
    bond_k: float = 100.0,
    bond_r0: float = 1.0,
    max_displacement: float = 0.5,
    max_angle: float = 0.3,
    verbose: bool = False,
) -> Tuple[List[np.ndarray], Dict[str, float]]:
    """
    Pre-equilibrate polymer configuration using MC moves.

    This implementation uses local energy updates for single-bead moves,
    reducing complexity from O(N²) to O(N) per step for the most common
    move type. For multi-bead moves, full energy recalculation is used.

    Parameters:
        positions: List of np.array or (N, 3) array, atom positions.
        bonds: List of (atom1_idx, atom2_idx) tuples (0-indexed).
        chain_indices: List of (start, end) tuples for each chain.
            If None, treats entire system as one chain.
        chain_graphs: Optional per-chain graph metadata for branched
            architectures (see :func:`build_chain_graph`). For chains marked
            "branched", pivot moves become tree-pivots across bridge edges,
            crankshaft moves are restricted to linear segments, and
            reptation is disabled. Linear chains (or chain_graphs=None)
            use the legacy path-based moves.
        n_steps: Number of MC steps.
        temperature: Reduced temperature.
        move_weights: Dict of move type probabilities.
        box_size: Apply PBC if specified.
        lj_sigma: LJ sigma parameter.
        lj_epsilon: LJ epsilon parameter.
        lj_cutoff: LJ cutoff in sigma units.
        bond_k: Bond spring constant.
        bond_r0: Equilibrium bond length.
        max_displacement: Max displacement for single bead moves.
        max_angle: Max rotation angle for pivot/crankshaft.
        verbose: Print progress.

    Returns:
        Tuple of (equilibrated_positions, acceptance_stats).
    """
    n_beads = len(positions)

    # Default chain indices
    if chain_indices is None:
        chain_indices = [(0, n_beads)]

    is_multi_chain = len(chain_indices) > 1

    # Default move weights - favor displacement moves for efficiency
    if move_weights is None:
        if is_multi_chain:
            move_weights = {
                "displacement": 0.4,  # Increased - most efficient move
                "crankshaft": 0.1,
                "pivot": 0.15,
                "reptation": 0.1,
                "chain_translation": 0.15,
                "chain_rotation": 0.1,
            }
        else:
            move_weights = {
                "displacement": 0.5,  # Increased - most efficient move
                "crankshaft": 0.15,
                "pivot": 0.2,
                "reptation": 0.15,
            }

    # Reptation is a linear-chain move; drop it when all chains are branched
    if chain_graphs is not None and chain_graphs:
        if all(g.get("branched", False) for g in chain_graphs):
            move_weights = {k: v for k, v in move_weights.items()
                            if k != "reptation"}

    # Normalize weights
    total_weight = sum(move_weights.values())
    move_probs = {k: v / total_weight for k, v in move_weights.items()}

    # Build move list and cumulative probabilities
    moves = list(move_probs.keys())
    cum_probs = np.cumsum([move_probs[m] for m in moves])

    # Statistics
    move_attempts = {m: 0 for m in moves}
    move_accepts = {m: 0 for m in moves}

    # Convert to numpy array for efficient operations
    if isinstance(positions, list):
        current_positions = np.array([p.copy() for p in positions])
    else:
        current_positions = positions.copy()

    # Build exclusion structures once (O(N + M) where M = num bonds)
    excluded_mask, excluded_neighbors, bond_neighbors = build_exclusion_structures(
        n_beads, bonds
    )

    # Convert bonds to numpy array for vectorized bond energy
    bonds_array = np.array(bonds) if bonds else np.zeros((0, 2), dtype=int)

    # Compute initial total energy
    current_energy = compute_lj_energy_vectorized(
        current_positions, excluded_mask, lj_sigma, lj_epsilon, lj_cutoff, box_size
    ) + compute_bond_energy_vectorized(
        current_positions, bonds_array, bond_k, bond_r0, box_size
    )

    # Progress reporting interval
    report_interval = max(1, n_steps // 10)

    # MC loop
    for step in range(n_steps):
        # Select move type using searchsorted for efficiency
        r = np.random.random()
        move_idx = np.searchsorted(cum_probs, r)
        move_type = moves[move_idx]

        move_attempts[move_type] += 1

        # Select a chain for moves that operate on chains
        chain_idx = np.random.randint(len(chain_indices))
        start, end = chain_indices[chain_idx]

        # Perform move and compute energy change
        accepted = False

        if move_type == "displacement":
            # Single bead displacement - use LOCAL energy update (O(N) instead of O(N²))
            bead_idx = np.random.randint(start, end)

            # Store old position
            old_pos = current_positions[bead_idx].copy()

            # Compute old local energy (LJ + bonds involving this bead)
            old_lj = compute_local_lj_energy(
                current_positions, bead_idx, excluded_neighbors[bead_idx],
                lj_sigma, lj_epsilon, lj_cutoff, box_size
            )
            old_bond = compute_local_bond_energy(
                current_positions, bead_idx, bond_neighbors[bead_idx],
                bond_k, bond_r0, box_size
            )

            # Apply displacement in-place
            delta = np.random.uniform(-max_displacement, max_displacement, 3)
            current_positions[bead_idx] = old_pos + delta
            if box_size is not None:
                current_positions[bead_idx] = _apply_pbc(current_positions[bead_idx], box_size)

            # Compute new local energy
            new_lj = compute_local_lj_energy(
                current_positions, bead_idx, excluded_neighbors[bead_idx],
                lj_sigma, lj_epsilon, lj_cutoff, box_size
            )
            new_bond = compute_local_bond_energy(
                current_positions, bead_idx, bond_neighbors[bead_idx],
                bond_k, bond_r0, box_size
            )

            delta_E = (new_lj + new_bond) - (old_lj + old_bond)

            if metropolis_accept(delta_E, temperature):
                current_energy += delta_E
                accepted = True
            else:
                # Reject: restore old position
                current_positions[bead_idx] = old_pos

        else:
            # Multi-bead moves - use full energy recalculation
            new_positions = current_positions
            is_valid = False

            graph = chain_graphs[chain_idx] if chain_graphs is not None else None
            branched = graph is not None and graph.get("branched", False)

            if move_type == "crankshaft":
                if branched:
                    segments = graph.get("segments", [])
                    if segments:
                        segment = segments[np.random.randint(len(segments))]
                        new_positions, is_valid = mc_segment_crankshaft_move(
                            current_positions, segment, max_angle, box_size
                        )
                else:
                    new_positions, is_valid = mc_crankshaft_move(
                        current_positions, start, end, max_angle, box_size
                    )

            elif move_type == "pivot":
                if branched:
                    pivot_edges = graph.get("pivot_edges", [])
                    if pivot_edges:
                        u, v = pivot_edges[np.random.randint(len(pivot_edges))]
                        adjacency = graph["adjacency"]
                        subtree_v = _subtree_excluding(adjacency, u, v)
                        subtree_u = _subtree_excluding(adjacency, v, u)
                        # Rotate the smaller side for efficiency
                        if len(subtree_v) <= len(subtree_u):
                            pivot_idx, subtree = u, subtree_v
                        else:
                            pivot_idx, subtree = v, subtree_u
                        new_positions, is_valid = mc_tree_pivot_move(
                            current_positions, pivot_idx, subtree,
                            max_angle, box_size
                        )
                else:
                    new_positions, is_valid = mc_pivot_move(
                        current_positions, start, end, max_angle, box_size
                    )

            elif move_type == "reptation":
                if not branched:
                    new_positions, is_valid = mc_reptation_move(
                        current_positions, start, end, bond_r0, box_size
                    )

            elif move_type == "chain_translation":
                if box_size is not None:
                    new_positions, is_valid = mc_chain_translation(
                        current_positions, chain_indices, chain_idx,
                        max_displacement, box_size
                    )

            elif move_type == "chain_rotation":
                new_positions, is_valid = mc_chain_rotation(
                    current_positions, chain_indices, chain_idx,
                    max_angle, box_size
                )

            if is_valid:
                # Compute new total energy using vectorized functions
                new_energy = compute_lj_energy_vectorized(
                    new_positions, excluded_mask, lj_sigma, lj_epsilon, lj_cutoff, box_size
                ) + compute_bond_energy_vectorized(
                    new_positions, bonds_array, bond_k, bond_r0, box_size
                )

                delta_E = new_energy - current_energy
                if metropolis_accept(delta_E, temperature):
                    current_positions = new_positions
                    current_energy = new_energy
                    accepted = True

        if accepted:
            move_accepts[move_type] += 1

        # Progress report
        if verbose and (step + 1) % report_interval == 0:
            logger.info(
                f"MC step {step + 1}/{n_steps}, Energy: {current_energy:.4f}"
            )

    # Compute acceptance rates
    acceptance_stats = {}
    for m in moves:
        if move_attempts[m] > 0:
            acceptance_stats[m] = move_accepts[m] / move_attempts[m]
        else:
            acceptance_stats[m] = 0.0

    if verbose:
        logger.info(f"Final energy: {current_energy:.4f}")
        logger.info(f"Acceptance rates: {acceptance_stats}")

    # Convert back to list for backward compatibility
    result_positions = [current_positions[i].copy() for i in range(n_beads)]
    return result_positions, acceptance_stats

canonical_bead_triplet(t1: str, t2: str, t3: str) -> Tuple[str, str, str]

Return canonical triplet (smaller endpoint first alphabetically).

Source code in AutoPoly/models/bead_spring.py
def canonical_bead_triplet(t1: str, t2: str, t3: str) -> Tuple[str, str, str]:
    """Return canonical triplet (smaller endpoint first alphabetically)."""
    if t1 <= t3:
        return (t1, t2, t3)
    return (t3, t2, t1)

lb_pair_coeffs(bead_types: List[BeadType]) -> Dict[Tuple[int, int], Tuple[float, float]]

Lorentz-Berthelot mixing for all bead type pairs.

Returns:

Type Description
Dict[Tuple[int, int], Tuple[float, float]]

Dict mapping (type_i, type_j) (1-based) to (epsilon_ij, sigma_ij).

Source code in AutoPoly/models/bead_spring.py
def lb_pair_coeffs(
    bead_types: List["BeadType"],
) -> Dict[Tuple[int, int], Tuple[float, float]]:
    """
    Lorentz-Berthelot mixing for all bead type pairs.

    Returns:
        Dict mapping (type_i, type_j) (1-based) to (epsilon_ij, sigma_ij).
    """
    coeffs = {}
    n_types = len(bead_types)
    for i in range(n_types):
        for j in range(i, n_types):
            bt_i = bead_types[i]
            bt_j = bead_types[j]
            sigma_ij = (bt_i.sigma + bt_j.sigma) / 2
            epsilon_ij = math.sqrt(bt_i.epsilon * bt_j.epsilon)
            coeffs[(i + 1, j + 1)] = (epsilon_ij, sigma_ij)
    return coeffs

resolve_angle_params(triplet: Tuple[str, str, str], angle_types: List[AngleType], default_k: float, default_theta0: float) -> Tuple[float, float]

Return (k, theta0) for a canonical triplet, using defaults if unset.

Source code in AutoPoly/models/bead_spring.py
def resolve_angle_params(
    triplet: Tuple[str, str, str],
    angle_types: List["AngleType"],
    default_k: float,
    default_theta0: float,
) -> Tuple[float, float]:
    """Return (k, theta0) for a canonical triplet, using defaults if unset."""
    for angle_type in angle_types:
        if canonical_bead_triplet(*angle_type.triplet) == triplet:
            return (angle_type.k, angle_type.theta0)
    return (default_k, default_theta0)

build_angle_type_map(chain_bead_types: List[List[str]], chain_triplets: List[List[Tuple[int, int, int]]]) -> Dict[Tuple[str, str, str], int]

Map canonical triplets to LAMMPS angle type IDs across all chains.

Parameters:

Name Type Description Default
chain_bead_types List[List[str]]

Bead type names per chain.

required
chain_triplets List[List[Tuple[int, int, int]]]

Local (i, j, k) triplets per chain.

required

Returns:

Type Description
Dict[Tuple[str, str, str], int]

Dict mapping canonical triplet to 1-based angle type ID.

Source code in AutoPoly/models/bead_spring.py
def build_angle_type_map(
    chain_bead_types: List[List[str]],
    chain_triplets: List[List[Tuple[int, int, int]]],
) -> Dict[Tuple[str, str, str], int]:
    """
    Map canonical triplets to LAMMPS angle type IDs across all chains.

    Args:
        chain_bead_types: Bead type names per chain.
        chain_triplets: Local (i, j, k) triplets per chain.

    Returns:
        Dict mapping canonical triplet to 1-based angle type ID.
    """
    unique_triplets = set()
    for bead_types_seq, triplets in zip(chain_bead_types, chain_triplets):
        for i, j, k in triplets:
            unique_triplets.add(
                canonical_bead_triplet(
                    bead_types_seq[i], bead_types_seq[j], bead_types_seq[k]
                )
            )
    sorted_triplets = sorted(unique_triplets)
    return {triplet: i + 1 for i, triplet in enumerate(sorted_triplets)}

write_lammps_input_script(path: str, bead_types: List[BeadType], pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]], bond_style: str, k_bond: float, bond_length: float, fene_r0: float, pair_style: str, use_angles: bool, angle_type_map: Dict[Tuple[str, str, str], int], angle_types: List[AngleType], default_k_angle: float, default_theta0: float, fillers: Optional[Dict[str, List[str]]] = None) -> None

Write the LAMMPS input script (in.polymer) for a bead-spring system.

Shared by BeadSpringPolymer (single species) and BeadSpringSystem (mixtures).

Note: For Kremer-Grest polymers using FENE bonds, the WCA cutoff (2^(1/6) * sigma ≈ 1.12246) should be used instead of full LJ cutoff (pair_style="wca"). The equilibrium bond length of ~0.97 emerges from the balance of FENE + WCA potentials - there is no explicit r0 in FENE.

fillers (motion -> filler atom-type ids) adds the CG-filler groups, the held-filler minimization and rigid/frozen filler integration (see AutoPoly.nanoparticles.cg); a pair coefficient may carry a third value, its own cutoff.

Source code in AutoPoly/models/bead_spring.py
def write_lammps_input_script(
    path: str,
    bead_types: List["BeadType"],
    pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]],
    bond_style: str,
    k_bond: float,
    bond_length: float,
    fene_r0: float,
    pair_style: str,
    use_angles: bool,
    angle_type_map: Dict[Tuple[str, str, str], int],
    angle_types: List["AngleType"],
    default_k_angle: float,
    default_theta0: float,
    fillers: Optional[Dict[str, List[str]]] = None,
) -> None:
    """
    Write the LAMMPS input script (in.polymer) for a bead-spring system.

    Shared by BeadSpringPolymer (single species) and BeadSpringSystem
    (mixtures).

    Note: For Kremer-Grest polymers using FENE bonds, the WCA cutoff
    (2^(1/6) * sigma ≈ 1.12246) should be used instead of full LJ cutoff
    (pair_style="wca"). The equilibrium bond length of ~0.97 emerges from
    the balance of FENE + WCA potentials - there is no explicit r0 in FENE.

    ``fillers`` (motion -> filler atom-type ids) adds the CG-filler groups,
    the held-filler minimization and rigid/frozen filler integration (see
    AutoPoly.nanoparticles.cg); a pair coefficient may carry a third value,
    its own cutoff.
    """
    if fillers:
        from ..nanoparticles import cg
    max_sigma = max(bt.sigma for bt in bead_types)

    if pair_style == 'wca':
        cutoff = (2 ** (1/6)) * max_sigma
        pair_modify = "pair_modify     shift yes\n"
    else:
        cutoff = 2.5 * max_sigma
        pair_modify = ""

    with open(f"{path}/in.polymer", 'w') as f:
        f.write("# LAMMPS input script for bead-spring polymer\n")
        f.write("# Auto-generated by AutoPoly BeadSpringPolymer\n\n")

        f.write("units           lj\n")
        f.write("atom_style      molecular\n")
        f.write("boundary        p p p\n\n")

        f.write("read_data       polymer.data\n\n")

        f.write(f"pair_style      lj/cut {cutoff:.5f}\n")
        for (i, j), coeff in sorted(pair_coeffs.items()):
            eps, sig = coeff[:2]
            rc = f" {coeff[2]:.5f}" if len(coeff) > 2 else ""
            f.write(f"pair_coeff      {i} {j} {eps:.4f} {sig:.4f}{rc}\n")
        if pair_modify:
            f.write(pair_modify)
        f.write("\n")

        if bond_style == "fene":
            eps = bead_types[0].epsilon
            sig = bead_types[0].sigma
            f.write("bond_style      fene\n")
            # FENE bond: K, R0, epsilon, sigma
            # Note: No r0 parameter - equilibrium emerges from FENE+WCA
            f.write(f"bond_coeff      1 {k_bond:.1f} {fene_r0:.4f} {eps:.4f} {sig:.4f}\n")
            f.write("special_bonds   fene\n\n")
        else:
            f.write("bond_style      harmonic\n")
            f.write(f"bond_coeff      1 {k_bond:.1f} {bond_length:.4f}\n\n")

        if use_angles:
            f.write("angle_style     harmonic\n")
            for triplet, type_id in sorted(angle_type_map.items(), key=lambda x: x[1]):
                k, theta0 = resolve_angle_params(
                    triplet, angle_types, default_k_angle, default_theta0
                )
                triplet_str = "-".join(triplet)
                f.write(f"angle_coeff     {type_id} {k:.4f} {theta0:.1f}  # {triplet_str}\n")
            f.write("\n")

        # Larger skin (2.0) for FENE to prevent lost atoms
        f.write("neighbor        2.0 bin\n")
        f.write("neigh_modify    every 2 delay 4 check yes\n\n")

        if fillers:
            for line in cg.group_lines(fillers):
                f.write(line + "\n")
            f.write(cg.SETUP + "\n")
            f.write(cg.THERMO)
        else:
            f.write("thermo_style    custom step temp pe ke etotal press vol density\n")
        f.write("thermo          1000\n\n")

        f.write("dump            1 all custom 1000 dump.lammpstrj id type mol x y z\n")
        f.write("dump_modify     1 sort id\n\n")

        f.write("# Energy minimization\n")
        if fillers:
            f.write(cg.HOLD)
        f.write("minimize        1.0e-4 1.0e-6 1000 10000\n")
        if fillers:
            f.write(cg.UNHOLD)
        f.write("write_restart   min.restart\n")
        f.write("write_data      min.data\n")
        f.write("reset_timestep  0\n\n")

        # Timestep: 0.001 is standard for Kremer-Grest with FENE bonds
        f.write("# Production MD\n")
        f.write("timestep        0.001\n")
        # Tdamp = 0.1 (100x timestep) for proper temperature control
        if fillers:
            f.write(cg.production_lines(fillers))
        else:
            f.write("fix             1 all nvt temp 1.0 1.0 0.1 tchain 3\n")
        f.write("run             100000\n")
        f.write("write_restart   prod.restart\n")
        f.write("write_data      prod.data\n")
        if fillers:
            f.write(cg.compression_hint(fillers))

Architectures (graph core)

AutoPoly.models.architectures

Polymer Architecture Graph Core

This module provides the graph representation that underlies all bead-spring polymer architectures. A chain is described as an explicit graph:

  • nodes = beads (each carrying a bead-type name)
  • edges = bonds (explicit index pairs)

Linear chains, rings, stars, combs/grafts, tadpoles, dendrimers and arbitrary user-defined topologies are all the same kind of object; they differ only in their edge list. Everything downstream (bond/angle enumeration, SAW growth order, branched MC moves, data-file writing, mixtures) is derived from this single representation.

Two levels of construction are provided:

  1. MonomerTemplate — a reusable multi-bead monomer unit (e.g. one backbone bead + one side-group bead) with named connection points ("head", "tail", "side"...). Architectures are assembled by connecting monomer instances through their named connection points.
  2. Factory functions (linear, ring, star, comb, graft, tadpole, dendrimer, custom) — convenient constructors returning bead-level BeadArchitecture graphs directly.

Copolymer sequence generators (block_sequence, alternating_sequence, random_sequence, gradient_sequence) produce bead-type sequences that can be used in any sequence slot (backbone, arm, side chain, ...).

Classes:

Name Description
MonomerTemplate

A reusable monomer unit: one or more beads with internal bonds and named

BeadArchitecture

Explicit bead-level graph of one polymer chain.

Functions:

Name Description
normalize_sequence

Convert any supported sequence input to an explicit bead-type list.

linear

Linear chain: 0-1-2-...-(N-1).

ring

Ring (cyclic) chain: linear bonds + closure bond (N-1, 0).

star

Star polymer: one center bead with f arms.

graft

Graft/comb polymer with explicitly placed side chains.

comb

Regular comb polymer: identical side chains grafted every every

tadpole

Tadpole (lariat) polymer: a ring with a linear tail attached.

dendrimer

Dendrimer / regularly branched polymer.

custom

Arbitrary user-defined architecture from an explicit bead list and

block_sequence

Block copolymer sequence: [("A", 50), ("B", 50)] -> A50-b-B50.

alternating_sequence

Alternating copolymer: types cycle along the chain ("ABABAB...").

random_sequence

Statistical (random) copolymer sequence.

gradient_sequence

Gradient copolymer: probability of type_end grows linearly from 0

MonomerTemplate dataclass

A reusable monomer unit: one or more beads with internal bonds and named connection points.

Example — a graft monomer with one backbone bead and one side-group bead::

MonomerTemplate(
    name="G",
    beads=["A", "B"],                 # bead 0 = backbone, bead 1 = side
    internal_bonds=[(0, 1)],
    connections={"head": 0, "tail": 0, "side": 1},
)

Attributes:

Name Type Description
name str

Template name (used to reference it in instance lists).

beads List[str]

Bead type names, one per internal bead.

internal_bonds List[Tuple[int, int]]

Bonds between internal beads (local indices).

connections Dict[str, int]

Named connection points mapping a name ("head", "tail", "side", ...) to a local bead index. Inter-monomer bonds are defined between connection points.

Methods:

Name Description
single_bead

Convenience: a single-bead monomer with connection points on the bead.

Source code in AutoPoly/models/architectures.py
@dataclass
class MonomerTemplate:
    """
    A reusable monomer unit: one or more beads with internal bonds and named
    connection points.

    Example — a graft monomer with one backbone bead and one side-group bead::

        MonomerTemplate(
            name="G",
            beads=["A", "B"],                 # bead 0 = backbone, bead 1 = side
            internal_bonds=[(0, 1)],
            connections={"head": 0, "tail": 0, "side": 1},
        )

    Attributes:
        name: Template name (used to reference it in instance lists).
        beads: Bead type names, one per internal bead.
        internal_bonds: Bonds between internal beads (local indices).
        connections: Named connection points mapping a name ("head", "tail",
            "side", ...) to a local bead index. Inter-monomer bonds are
            defined between connection points.
    """
    name: str
    beads: List[str]
    internal_bonds: List[Tuple[int, int]] = field(default_factory=list)
    connections: Dict[str, int] = field(default_factory=dict)

    def __post_init__(self) -> None:
        n = len(self.beads)
        if n == 0:
            raise ValueError(f"MonomerTemplate '{self.name}' has no beads")
        for i, j in self.internal_bonds:
            if not (0 <= i < n and 0 <= j < n):
                raise ValueError(
                    f"MonomerTemplate '{self.name}': internal bond ({i}, {j}) "
                    f"out of range for {n} beads"
                )
            if i == j:
                raise ValueError(
                    f"MonomerTemplate '{self.name}': self bond ({i}, {i})"
                )
        for conn_name, idx in self.connections.items():
            if not 0 <= idx < n:
                raise ValueError(
                    f"MonomerTemplate '{self.name}': connection '{conn_name}' "
                    f"points to bead {idx}, out of range for {n} beads"
                )

    @classmethod
    def single_bead(cls, bead_type: str, name: Optional[str] = None,
                    connections: Tuple[str, ...] = ("head", "tail")) -> "MonomerTemplate":
        """Convenience: a single-bead monomer with connection points on the bead."""
        return cls(
            name=name or bead_type,
            beads=[bead_type],
            internal_bonds=[],
            connections={c: 0 for c in connections},
        )

single_bead(bead_type: str, name: Optional[str] = None, connections: Tuple[str, ...] = ('head', 'tail')) -> MonomerTemplate classmethod

Convenience: a single-bead monomer with connection points on the bead.

Source code in AutoPoly/models/architectures.py
@classmethod
def single_bead(cls, bead_type: str, name: Optional[str] = None,
                connections: Tuple[str, ...] = ("head", "tail")) -> "MonomerTemplate":
    """Convenience: a single-bead monomer with connection points on the bead."""
    return cls(
        name=name or bead_type,
        beads=[bead_type],
        internal_bonds=[],
        connections={c: 0 for c in connections},
    )

BeadArchitecture dataclass

Explicit bead-level graph of one polymer chain.

Attributes:

Name Type Description
bead_types List[str]

Bead type name per bead (node labels), length N.

bonds List[Tuple[int, int]]

Explicit bond list as (i, j) bead index pairs, i != j.

name str

Architecture name ("linear", "ring", "star", "comb", ...).

Everything else — angle triplets, SAW growth order, MC subtree structure — is derived from these two lists.

Methods:

Name Description
adjacency

Adjacency list (sorted neighbor indices per bead).

validate

Validate the graph.

angle_triplets

All angle triplets as (i, j, k) with j the center bead.

angle_triplets_classified

Like :meth:angle_triplets but returns ((i, j, k), is_branch) pairs,

growth_order

DFS spanning-tree growth order from root.

subtree_beyond_edge

Beads reachable from v without crossing the edge (u, v).

linear_segments

Maximal paths of degree-2 beads (plus their endpoints) suitable for

from_monomers

Expand monomer instances into a bead-level architecture.

Source code in AutoPoly/models/architectures.py
@dataclass
class BeadArchitecture:
    """
    Explicit bead-level graph of one polymer chain.

    Attributes:
        bead_types: Bead type name per bead (node labels), length N.
        bonds: Explicit bond list as (i, j) bead index pairs, i != j.
        name: Architecture name ("linear", "ring", "star", "comb", ...).

    Everything else — angle triplets, SAW growth order, MC subtree structure —
    is derived from these two lists.
    """
    bead_types: List[str]
    bonds: List[Tuple[int, int]]
    name: str = "custom"

    # ------------------------------------------------------------------ #
    # Basic properties
    # ------------------------------------------------------------------ #

    @property
    def n_beads(self) -> int:
        return len(self.bead_types)

    @property
    def n_bonds(self) -> int:
        return len(self.bonds)

    def adjacency(self) -> List[List[int]]:
        """Adjacency list (sorted neighbor indices per bead)."""
        adj: List[List[int]] = [[] for _ in range(self.n_beads)]
        for i, j in self.bonds:
            adj[i].append(j)
            adj[j].append(i)
        for nbrs in adj:
            nbrs.sort()
        return adj

    def degrees(self) -> List[int]:
        return [len(nbrs) for nbrs in self.adjacency()]

    @property
    def max_degree(self) -> int:
        return max(self.degrees()) if self.n_beads else 0

    @property
    def is_branched(self) -> bool:
        """True if any bead has degree > 2 (star center, graft point, ...)."""
        return self.max_degree > 2

    @property
    def is_cyclic(self) -> bool:
        """True if the (connected) graph contains at least one cycle."""
        return self.n_bonds >= self.n_beads

    # ------------------------------------------------------------------ #
    # Validation
    # ------------------------------------------------------------------ #

    def validate(self, known_bead_types: Optional[Sequence[str]] = None) -> None:
        """
        Validate the graph.

        Checks: non-empty, bond indices in range, no duplicate/self bonds,
        connectedness, and (optionally) that all bead types are known.

        Raises:
            ValueError: On any violation.
        """
        n = self.n_beads
        if n == 0:
            raise ValueError("Architecture has no beads")

        seen = set()
        for i, j in self.bonds:
            if not (0 <= i < n and 0 <= j < n):
                raise ValueError(
                    f"Bond ({i}, {j}) out of range for {n} beads"
                )
            if i == j:
                raise ValueError(f"Self bond ({i}, {i}) is not allowed")
            key = (min(i, j), max(i, j))
            if key in seen:
                raise ValueError(f"Duplicate bond ({i}, {j})")
            seen.add(key)

        if known_bead_types is not None:
            known = set(known_bead_types)
            unknown = [t for t in self.bead_types if t not in known]
            if unknown:
                raise ValueError(
                    f"Unknown bead type(s) in architecture: {sorted(set(unknown))}. "
                    f"Known types: {sorted(known)}"
                )

        # Connectedness via BFS from bead 0
        adj = self.adjacency()
        visited = {0}
        queue = deque([0])
        while queue:
            u = queue.popleft()
            for v in adj[u]:
                if v not in visited:
                    visited.add(v)
                    queue.append(v)
        if len(visited) != n:
            missing = sorted(set(range(n)) - visited)
            raise ValueError(
                f"Architecture graph is not connected; unreachable beads: {missing}"
            )

    # ------------------------------------------------------------------ #
    # Angle triplets (branch-aware)
    # ------------------------------------------------------------------ #

    def angle_triplets(self, include_branch: bool = True) -> List[Tuple[int, int, int]]:
        """
        All angle triplets as (i, j, k) with j the center bead.

        Enumerated by center bead in node order; for each center, all
        neighbor pairs (i, k) with i < k. Triplets centered on a branch
        point (degree > 2) are included only if ``include_branch`` is True.

        For linear chains this yields exactly (i, i+1, i+2); for rings it
        additionally yields the wrap-around triplets — matching the legacy
        path-based enumeration.
        """
        return [t for t, _ in self.angle_triplets_classified(include_branch)]

    def angle_triplets_classified(
        self, include_branch: bool = True
    ) -> List[Tuple[Tuple[int, int, int], bool]]:
        """
        Like :meth:`angle_triplets` but returns ((i, j, k), is_branch) pairs,
        where is_branch marks triplets centered on a branch point (degree > 2).
        """
        adj = self.adjacency()
        result: List[Tuple[Tuple[int, int, int], bool]] = []
        for center in range(self.n_beads):
            nbrs = adj[center]
            is_branch = len(nbrs) > 2
            if is_branch and not include_branch:
                continue
            for a in range(len(nbrs)):
                for b in range(a + 1, len(nbrs)):
                    result.append(((nbrs[a], center, nbrs[b]), is_branch))
        return result

    # ------------------------------------------------------------------ #
    # Growth order (spanning tree) for SAW / geometric generation
    # ------------------------------------------------------------------ #

    def growth_order(
        self, root: int = 0
    ) -> Tuple[List[int], Dict[int, Optional[int]], List[Tuple[int, int]]]:
        """
        DFS spanning-tree growth order from ``root``.

        DFS (rather than BFS) keeps cycles as single long arcs with one
        closing edge at the far end — the same growth pattern as the
        legacy path-based ring SAW — which makes ring-closure constraints
        far easier to satisfy during placement. For trees (stars, combs,
        dendrimers) the spanning tree coincides with the full edge set
        either way.

        Returns:
            order: Bead indices in placement order (each bead's parent
                appears before it).
            parents: Map bead -> parent bead (None for root).
            closing_edges: Bonds not in the spanning tree (cycle-closing
                edges, e.g. the ring-closure bond). These are constraints
                to satisfy during placement rather than growth directions.
        """
        adj = self.adjacency()
        parents: Dict[int, Optional[int]] = {root: None}
        order: List[int] = []
        tree_edges = set()
        # Iterative DFS (preorder); parents are assigned at push time so
        # each node is pushed exactly once
        stack = [root]
        while stack:
            u = stack.pop()
            order.append(u)
            # Push neighbors in reverse so lower indices are visited first
            for v in reversed(adj[u]):
                if v not in parents:
                    parents[v] = u
                    tree_edges.add((min(u, v), max(u, v)))
                    stack.append(v)
        closing_edges = [
            (i, j) for i, j in self.bonds
            if (min(i, j), max(i, j)) not in tree_edges
        ]
        return order, parents, closing_edges

    # ------------------------------------------------------------------ #
    # Subtree structure for branched MC moves
    # ------------------------------------------------------------------ #

    def subtree_beyond_edge(self, u: int, v: int) -> List[int]:
        """
        Beads reachable from ``v`` without crossing the edge (u, v).

        Cutting edge (u, v) splits the molecule; this returns the component
        containing ``v``. Used by the tree-pivot MC move: rotating this set
        around any axis through bead ``u`` preserves the (u, v) bond length
        and all internal bonds of the subtree.
        """
        adj = self.adjacency()
        visited = {u, v}
        queue = deque([v])
        while queue:
            x = queue.popleft()
            for y in adj[x]:
                if y not in visited:
                    visited.add(y)
                    queue.append(y)
        visited.discard(u)
        return sorted(visited)

    def linear_segments(self, min_length: int = 3) -> List[List[int]]:
        """
        Maximal paths of degree-2 beads (plus their endpoints) suitable for
        crankshaft MC moves on branched architectures.

        Returns:
            List of bead-index paths, each of length >= min_length. For a
            linear chain this returns the whole chain as one segment.
        """
        adj = self.adjacency()
        deg = [len(nbrs) for nbrs in adj]
        n = self.n_beads
        segments: List[List[int]] = []
        visited_edges = set()

        def mark(a: int, b: int) -> None:
            visited_edges.add((min(a, b), max(a, b)))

        # Segments starting at non-degree-2 nodes (branch points, ends)
        starts = [i for i in range(n) if deg[i] != 2]
        for s in starts:
            for nbr in adj[s]:
                if (min(s, nbr), max(s, nbr)) in visited_edges:
                    continue
                path = [s, nbr]
                mark(s, nbr)
                while deg[path[-1]] == 2:
                    a, b = path[-2], path[-1]
                    nxt = adj[b][0] if adj[b][0] != a else adj[b][1]
                    if (min(b, nxt), max(b, nxt)) in visited_edges:
                        # cycle returning to an already-used edge
                        path.append(nxt)
                        mark(b, nxt)
                        break
                    path.append(nxt)
                    mark(b, nxt)
                    if nxt == s:
                        break
                if len(path) >= min_length:
                    segments.append(path)

        # Pure cycles with no branch/end beads (e.g. rings): pick them up
        if not starts and n >= min_length:
            # Whole graph is a single cycle
            path = [0]
            prev, cur = -1, 0
            while True:
                nxt_candidates = [x for x in adj[cur] if x != prev]
                if not nxt_candidates:
                    break
                nxt = nxt_candidates[0]
                if nxt == 0:
                    path.append(nxt)
                    break
                path.append(nxt)
                prev, cur = cur, nxt
            segments.append(path)

        return segments

    # ------------------------------------------------------------------ #
    # Assembly from monomer templates
    # ------------------------------------------------------------------ #

    @classmethod
    def from_monomers(
        cls,
        templates: Dict[str, MonomerTemplate],
        instances: List[str],
        inter_bonds: List[Tuple[int, str, int, str]],
        name: str = "custom",
    ) -> "BeadArchitecture":
        """
        Expand monomer instances into a bead-level architecture.

        Args:
            templates: Map template name -> MonomerTemplate.
            instances: Ordered list of template names (monomer instances).
            inter_bonds: Inter-monomer bonds as
                (instance_i, connection_i, instance_j, connection_j).
            name: Architecture name.

        Returns:
            BeadArchitecture with all internal + inter-monomer bonds.

        Example — three graft monomers polymerized head-to-tail::

            BeadArchitecture.from_monomers(
                templates={"G": graft_monomer},
                instances=["G", "G", "G"],
                inter_bonds=[(0, "tail", 1, "head"), (1, "tail", 2, "head")],
            )
        """
        bead_types: List[str] = []
        bonds: List[Tuple[int, int]] = []
        offsets: List[int] = []

        for inst_name in instances:
            if inst_name not in templates:
                raise ValueError(f"Unknown monomer template '{inst_name}'")
            tpl = templates[inst_name]
            offsets.append(len(bead_types))
            bead_types.extend(tpl.beads)
            for i, j in tpl.internal_bonds:
                bonds.append((offsets[-1] + i, offsets[-1] + j))

        for inst_i, conn_i, inst_j, conn_j in inter_bonds:
            if not (0 <= inst_i < len(instances) and 0 <= inst_j < len(instances)):
                raise ValueError(
                    f"Inter-monomer bond references instance "
                    f"({inst_i}, {inst_j}) but only {len(instances)} instances exist"
                )
            tpl_i = templates[instances[inst_i]]
            tpl_j = templates[instances[inst_j]]
            if conn_i not in tpl_i.connections:
                raise ValueError(
                    f"Template '{tpl_i.name}' has no connection '{conn_i}'"
                )
            if conn_j not in tpl_j.connections:
                raise ValueError(
                    f"Template '{tpl_j.name}' has no connection '{conn_j}'"
                )
            bonds.append((
                offsets[inst_i] + tpl_i.connections[conn_i],
                offsets[inst_j] + tpl_j.connections[conn_j],
            ))

        arch = cls(bead_types=bead_types, bonds=bonds, name=name)
        arch.validate()
        return arch

is_branched: bool property

True if any bead has degree > 2 (star center, graft point, ...).

is_cyclic: bool property

True if the (connected) graph contains at least one cycle.

adjacency() -> List[List[int]]

Adjacency list (sorted neighbor indices per bead).

Source code in AutoPoly/models/architectures.py
def adjacency(self) -> List[List[int]]:
    """Adjacency list (sorted neighbor indices per bead)."""
    adj: List[List[int]] = [[] for _ in range(self.n_beads)]
    for i, j in self.bonds:
        adj[i].append(j)
        adj[j].append(i)
    for nbrs in adj:
        nbrs.sort()
    return adj

validate(known_bead_types: Optional[Sequence[str]] = None) -> None

Validate the graph.

Checks: non-empty, bond indices in range, no duplicate/self bonds, connectedness, and (optionally) that all bead types are known.

Raises:

Type Description
ValueError

On any violation.

Source code in AutoPoly/models/architectures.py
def validate(self, known_bead_types: Optional[Sequence[str]] = None) -> None:
    """
    Validate the graph.

    Checks: non-empty, bond indices in range, no duplicate/self bonds,
    connectedness, and (optionally) that all bead types are known.

    Raises:
        ValueError: On any violation.
    """
    n = self.n_beads
    if n == 0:
        raise ValueError("Architecture has no beads")

    seen = set()
    for i, j in self.bonds:
        if not (0 <= i < n and 0 <= j < n):
            raise ValueError(
                f"Bond ({i}, {j}) out of range for {n} beads"
            )
        if i == j:
            raise ValueError(f"Self bond ({i}, {i}) is not allowed")
        key = (min(i, j), max(i, j))
        if key in seen:
            raise ValueError(f"Duplicate bond ({i}, {j})")
        seen.add(key)

    if known_bead_types is not None:
        known = set(known_bead_types)
        unknown = [t for t in self.bead_types if t not in known]
        if unknown:
            raise ValueError(
                f"Unknown bead type(s) in architecture: {sorted(set(unknown))}. "
                f"Known types: {sorted(known)}"
            )

    # Connectedness via BFS from bead 0
    adj = self.adjacency()
    visited = {0}
    queue = deque([0])
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if v not in visited:
                visited.add(v)
                queue.append(v)
    if len(visited) != n:
        missing = sorted(set(range(n)) - visited)
        raise ValueError(
            f"Architecture graph is not connected; unreachable beads: {missing}"
        )

angle_triplets(include_branch: bool = True) -> List[Tuple[int, int, int]]

All angle triplets as (i, j, k) with j the center bead.

Enumerated by center bead in node order; for each center, all neighbor pairs (i, k) with i < k. Triplets centered on a branch point (degree > 2) are included only if include_branch is True.

For linear chains this yields exactly (i, i+1, i+2); for rings it additionally yields the wrap-around triplets — matching the legacy path-based enumeration.

Source code in AutoPoly/models/architectures.py
def angle_triplets(self, include_branch: bool = True) -> List[Tuple[int, int, int]]:
    """
    All angle triplets as (i, j, k) with j the center bead.

    Enumerated by center bead in node order; for each center, all
    neighbor pairs (i, k) with i < k. Triplets centered on a branch
    point (degree > 2) are included only if ``include_branch`` is True.

    For linear chains this yields exactly (i, i+1, i+2); for rings it
    additionally yields the wrap-around triplets — matching the legacy
    path-based enumeration.
    """
    return [t for t, _ in self.angle_triplets_classified(include_branch)]

angle_triplets_classified(include_branch: bool = True) -> List[Tuple[Tuple[int, int, int], bool]]

Like :meth:angle_triplets but returns ((i, j, k), is_branch) pairs, where is_branch marks triplets centered on a branch point (degree > 2).

Source code in AutoPoly/models/architectures.py
def angle_triplets_classified(
    self, include_branch: bool = True
) -> List[Tuple[Tuple[int, int, int], bool]]:
    """
    Like :meth:`angle_triplets` but returns ((i, j, k), is_branch) pairs,
    where is_branch marks triplets centered on a branch point (degree > 2).
    """
    adj = self.adjacency()
    result: List[Tuple[Tuple[int, int, int], bool]] = []
    for center in range(self.n_beads):
        nbrs = adj[center]
        is_branch = len(nbrs) > 2
        if is_branch and not include_branch:
            continue
        for a in range(len(nbrs)):
            for b in range(a + 1, len(nbrs)):
                result.append(((nbrs[a], center, nbrs[b]), is_branch))
    return result

growth_order(root: int = 0) -> Tuple[List[int], Dict[int, Optional[int]], List[Tuple[int, int]]]

DFS spanning-tree growth order from root.

DFS (rather than BFS) keeps cycles as single long arcs with one closing edge at the far end — the same growth pattern as the legacy path-based ring SAW — which makes ring-closure constraints far easier to satisfy during placement. For trees (stars, combs, dendrimers) the spanning tree coincides with the full edge set either way.

Returns:

Name Type Description
order List[int]

Bead indices in placement order (each bead's parent appears before it).

parents Dict[int, Optional[int]]

Map bead -> parent bead (None for root).

closing_edges List[Tuple[int, int]]

Bonds not in the spanning tree (cycle-closing edges, e.g. the ring-closure bond). These are constraints to satisfy during placement rather than growth directions.

Source code in AutoPoly/models/architectures.py
def growth_order(
    self, root: int = 0
) -> Tuple[List[int], Dict[int, Optional[int]], List[Tuple[int, int]]]:
    """
    DFS spanning-tree growth order from ``root``.

    DFS (rather than BFS) keeps cycles as single long arcs with one
    closing edge at the far end — the same growth pattern as the
    legacy path-based ring SAW — which makes ring-closure constraints
    far easier to satisfy during placement. For trees (stars, combs,
    dendrimers) the spanning tree coincides with the full edge set
    either way.

    Returns:
        order: Bead indices in placement order (each bead's parent
            appears before it).
        parents: Map bead -> parent bead (None for root).
        closing_edges: Bonds not in the spanning tree (cycle-closing
            edges, e.g. the ring-closure bond). These are constraints
            to satisfy during placement rather than growth directions.
    """
    adj = self.adjacency()
    parents: Dict[int, Optional[int]] = {root: None}
    order: List[int] = []
    tree_edges = set()
    # Iterative DFS (preorder); parents are assigned at push time so
    # each node is pushed exactly once
    stack = [root]
    while stack:
        u = stack.pop()
        order.append(u)
        # Push neighbors in reverse so lower indices are visited first
        for v in reversed(adj[u]):
            if v not in parents:
                parents[v] = u
                tree_edges.add((min(u, v), max(u, v)))
                stack.append(v)
    closing_edges = [
        (i, j) for i, j in self.bonds
        if (min(i, j), max(i, j)) not in tree_edges
    ]
    return order, parents, closing_edges

subtree_beyond_edge(u: int, v: int) -> List[int]

Beads reachable from v without crossing the edge (u, v).

Cutting edge (u, v) splits the molecule; this returns the component containing v. Used by the tree-pivot MC move: rotating this set around any axis through bead u preserves the (u, v) bond length and all internal bonds of the subtree.

Source code in AutoPoly/models/architectures.py
def subtree_beyond_edge(self, u: int, v: int) -> List[int]:
    """
    Beads reachable from ``v`` without crossing the edge (u, v).

    Cutting edge (u, v) splits the molecule; this returns the component
    containing ``v``. Used by the tree-pivot MC move: rotating this set
    around any axis through bead ``u`` preserves the (u, v) bond length
    and all internal bonds of the subtree.
    """
    adj = self.adjacency()
    visited = {u, v}
    queue = deque([v])
    while queue:
        x = queue.popleft()
        for y in adj[x]:
            if y not in visited:
                visited.add(y)
                queue.append(y)
    visited.discard(u)
    return sorted(visited)

linear_segments(min_length: int = 3) -> List[List[int]]

Maximal paths of degree-2 beads (plus their endpoints) suitable for crankshaft MC moves on branched architectures.

Returns:

Type Description
List[List[int]]

List of bead-index paths, each of length >= min_length. For a

List[List[int]]

linear chain this returns the whole chain as one segment.

Source code in AutoPoly/models/architectures.py
def linear_segments(self, min_length: int = 3) -> List[List[int]]:
    """
    Maximal paths of degree-2 beads (plus their endpoints) suitable for
    crankshaft MC moves on branched architectures.

    Returns:
        List of bead-index paths, each of length >= min_length. For a
        linear chain this returns the whole chain as one segment.
    """
    adj = self.adjacency()
    deg = [len(nbrs) for nbrs in adj]
    n = self.n_beads
    segments: List[List[int]] = []
    visited_edges = set()

    def mark(a: int, b: int) -> None:
        visited_edges.add((min(a, b), max(a, b)))

    # Segments starting at non-degree-2 nodes (branch points, ends)
    starts = [i for i in range(n) if deg[i] != 2]
    for s in starts:
        for nbr in adj[s]:
            if (min(s, nbr), max(s, nbr)) in visited_edges:
                continue
            path = [s, nbr]
            mark(s, nbr)
            while deg[path[-1]] == 2:
                a, b = path[-2], path[-1]
                nxt = adj[b][0] if adj[b][0] != a else adj[b][1]
                if (min(b, nxt), max(b, nxt)) in visited_edges:
                    # cycle returning to an already-used edge
                    path.append(nxt)
                    mark(b, nxt)
                    break
                path.append(nxt)
                mark(b, nxt)
                if nxt == s:
                    break
            if len(path) >= min_length:
                segments.append(path)

    # Pure cycles with no branch/end beads (e.g. rings): pick them up
    if not starts and n >= min_length:
        # Whole graph is a single cycle
        path = [0]
        prev, cur = -1, 0
        while True:
            nxt_candidates = [x for x in adj[cur] if x != prev]
            if not nxt_candidates:
                break
            nxt = nxt_candidates[0]
            if nxt == 0:
                path.append(nxt)
                break
            path.append(nxt)
            prev, cur = cur, nxt
        segments.append(path)

    return segments

from_monomers(templates: Dict[str, MonomerTemplate], instances: List[str], inter_bonds: List[Tuple[int, str, int, str]], name: str = 'custom') -> BeadArchitecture classmethod

Expand monomer instances into a bead-level architecture.

Parameters:

Name Type Description Default
templates Dict[str, MonomerTemplate]

Map template name -> MonomerTemplate.

required
instances List[str]

Ordered list of template names (monomer instances).

required
inter_bonds List[Tuple[int, str, int, str]]

Inter-monomer bonds as (instance_i, connection_i, instance_j, connection_j).

required
name str

Architecture name.

'custom'

Returns:

Type Description
BeadArchitecture

BeadArchitecture with all internal + inter-monomer bonds.

Example — three graft monomers polymerized head-to-tail::

BeadArchitecture.from_monomers(
    templates={"G": graft_monomer},
    instances=["G", "G", "G"],
    inter_bonds=[(0, "tail", 1, "head"), (1, "tail", 2, "head")],
)
Source code in AutoPoly/models/architectures.py
@classmethod
def from_monomers(
    cls,
    templates: Dict[str, MonomerTemplate],
    instances: List[str],
    inter_bonds: List[Tuple[int, str, int, str]],
    name: str = "custom",
) -> "BeadArchitecture":
    """
    Expand monomer instances into a bead-level architecture.

    Args:
        templates: Map template name -> MonomerTemplate.
        instances: Ordered list of template names (monomer instances).
        inter_bonds: Inter-monomer bonds as
            (instance_i, connection_i, instance_j, connection_j).
        name: Architecture name.

    Returns:
        BeadArchitecture with all internal + inter-monomer bonds.

    Example — three graft monomers polymerized head-to-tail::

        BeadArchitecture.from_monomers(
            templates={"G": graft_monomer},
            instances=["G", "G", "G"],
            inter_bonds=[(0, "tail", 1, "head"), (1, "tail", 2, "head")],
        )
    """
    bead_types: List[str] = []
    bonds: List[Tuple[int, int]] = []
    offsets: List[int] = []

    for inst_name in instances:
        if inst_name not in templates:
            raise ValueError(f"Unknown monomer template '{inst_name}'")
        tpl = templates[inst_name]
        offsets.append(len(bead_types))
        bead_types.extend(tpl.beads)
        for i, j in tpl.internal_bonds:
            bonds.append((offsets[-1] + i, offsets[-1] + j))

    for inst_i, conn_i, inst_j, conn_j in inter_bonds:
        if not (0 <= inst_i < len(instances) and 0 <= inst_j < len(instances)):
            raise ValueError(
                f"Inter-monomer bond references instance "
                f"({inst_i}, {inst_j}) but only {len(instances)} instances exist"
            )
        tpl_i = templates[instances[inst_i]]
        tpl_j = templates[instances[inst_j]]
        if conn_i not in tpl_i.connections:
            raise ValueError(
                f"Template '{tpl_i.name}' has no connection '{conn_i}'"
            )
        if conn_j not in tpl_j.connections:
            raise ValueError(
                f"Template '{tpl_j.name}' has no connection '{conn_j}'"
            )
        bonds.append((
            offsets[inst_i] + tpl_i.connections[conn_i],
            offsets[inst_j] + tpl_j.connections[conn_j],
        ))

    arch = cls(bead_types=bead_types, bonds=bonds, name=name)
    arch.validate()
    return arch

normalize_sequence(seq: SequenceInput) -> List[str]

Convert any supported sequence input to an explicit bead-type list.

Parameters:

Name Type Description Default
seq SequenceInput

Sequence as string ("AABB"), explicit list (["A", "B"]), block format ([("A", 20), ("B", 10)]), or a single bare block tuple (("A", 20)).

required

Returns:

Type Description
List[str]

Explicit list of bead type names.

Raises:

Type Description
ValueError

If the sequence is empty or malformed.

Source code in AutoPoly/models/architectures.py
def normalize_sequence(seq: SequenceInput) -> List[str]:
    """
    Convert any supported sequence input to an explicit bead-type list.

    Args:
        seq: Sequence as string ("AABB"), explicit list (["A", "B"]),
            block format ([("A", 20), ("B", 10)]), or a single bare block
            tuple (("A", 20)).

    Returns:
        Explicit list of bead type names.

    Raises:
        ValueError: If the sequence is empty or malformed.
    """
    # Bare block tuple: ("A", 20) -> ["A"] * 20
    if (isinstance(seq, tuple) and len(seq) == 2
            and isinstance(seq[0], str) and isinstance(seq[1], int)):
        seq = [seq]
    if isinstance(seq, str):
        result = list(seq)
    else:
        result = []
        for item in seq:
            if isinstance(item, tuple):
                bead_name, count = item
                if count < 1:
                    raise ValueError(f"Block count must be >= 1, got {count}")
                result.extend([bead_name] * count)
            else:
                result.append(item)
    if not result:
        raise ValueError("Sequence must contain at least one bead")
    return result

linear(sequence: SequenceInput, name: str = 'linear') -> BeadArchitecture

Linear chain: 0-1-2-...-(N-1).

Source code in AutoPoly/models/architectures.py
def linear(sequence: SequenceInput, name: str = "linear") -> BeadArchitecture:
    """Linear chain: 0-1-2-...-(N-1)."""
    beads = normalize_sequence(sequence)
    bonds = [(i, i + 1) for i in range(len(beads) - 1)]
    return BeadArchitecture(bead_types=beads, bonds=bonds, name=name)

ring(sequence: SequenceInput, name: str = 'ring') -> BeadArchitecture

Ring (cyclic) chain: linear bonds + closure bond (N-1, 0).

Source code in AutoPoly/models/architectures.py
def ring(sequence: SequenceInput, name: str = "ring") -> BeadArchitecture:
    """Ring (cyclic) chain: linear bonds + closure bond (N-1, 0)."""
    beads = normalize_sequence(sequence)
    if len(beads) < 3:
        raise ValueError(f"Ring topology requires at least 3 beads, got {len(beads)}")
    bonds = [(i, i + 1) for i in range(len(beads) - 1)]
    bonds.append((len(beads) - 1, 0))
    return BeadArchitecture(bead_types=beads, bonds=bonds, name=name)

star(center: str, arms: List[SequenceInput], name: str = 'star') -> BeadArchitecture

Star polymer: one center bead with f arms.

Parameters:

Name Type Description Default
center str

Bead type of the center bead.

required
arms List[SequenceInput]

List of arm sequences; arms may differ in length and composition (miktoarm / asymmetric stars).

required

Bead numbering: 0 = center; arm a occupies consecutive indices in the order given.

Source code in AutoPoly/models/architectures.py
def star(
    center: str,
    arms: List[SequenceInput],
    name: str = "star",
) -> BeadArchitecture:
    """
    Star polymer: one center bead with f arms.

    Args:
        center: Bead type of the center bead.
        arms: List of arm sequences; arms may differ in length and
            composition (miktoarm / asymmetric stars).

    Bead numbering: 0 = center; arm a occupies consecutive indices in the
    order given.
    """
    if len(arms) < 2:
        raise ValueError(f"Star requires at least 2 arms, got {len(arms)}")
    bead_types = [center]
    bonds: List[Tuple[int, int]] = []
    for arm in arms:
        arm_beads = normalize_sequence(arm)
        start = len(bead_types)
        bead_types.extend(arm_beads)
        bonds.append((0, start))
        bonds.extend((start + k, start + k + 1) for k in range(len(arm_beads) - 1))
    arch = BeadArchitecture(bead_types=bead_types, bonds=bonds, name=name)
    arch.validate()
    return arch

graft(backbone: SequenceInput, grafts: Dict[int, SequenceInput], name: str = 'graft') -> BeadArchitecture

Graft/comb polymer with explicitly placed side chains.

Parameters:

Name Type Description Default
backbone SequenceInput

Backbone sequence.

required
grafts Dict[int, SequenceInput]

Map backbone bead index -> side-chain sequence. A side chain may be a single bead (a literal "side group", e.g. "B") or an oligomer (e.g. [("B", 5)]).

required

Bead numbering: backbone beads 0..N-1, then side chains in order of sorted graft index.

Source code in AutoPoly/models/architectures.py
def graft(
    backbone: SequenceInput,
    grafts: Dict[int, SequenceInput],
    name: str = "graft",
) -> BeadArchitecture:
    """
    Graft/comb polymer with explicitly placed side chains.

    Args:
        backbone: Backbone sequence.
        grafts: Map backbone bead index -> side-chain sequence. A side chain
            may be a single bead (a literal "side group", e.g. "B") or an
            oligomer (e.g. [("B", 5)]).

    Bead numbering: backbone beads 0..N-1, then side chains in order of
    sorted graft index.
    """
    bb = normalize_sequence(backbone)
    bead_types = list(bb)
    bonds: List[Tuple[int, int]] = [(i, i + 1) for i in range(len(bb) - 1)]

    for idx in sorted(grafts.keys()):
        if not 0 <= idx < len(bb):
            raise ValueError(
                f"Graft point {idx} out of range for backbone of {len(bb)} beads"
            )
        side = normalize_sequence(grafts[idx])
        start = len(bead_types)
        bead_types.extend(side)
        bonds.append((idx, start))
        bonds.extend((start + k, start + k + 1) for k in range(len(side) - 1))

    arch = BeadArchitecture(bead_types=bead_types, bonds=bonds, name=name)
    arch.validate()
    return arch

comb(backbone: SequenceInput, side: SequenceInput, every: int, offset: int = 0, name: str = 'comb') -> BeadArchitecture

Regular comb polymer: identical side chains grafted every every backbone beads, starting at offset.

Parameters:

Name Type Description Default
backbone SequenceInput

Backbone sequence.

required
side SequenceInput

Side-chain sequence (single bead or oligomer).

required
every int

Grafting spacing along the backbone.

required
offset int

Backbone index of the first graft point.

0
Source code in AutoPoly/models/architectures.py
def comb(
    backbone: SequenceInput,
    side: SequenceInput,
    every: int,
    offset: int = 0,
    name: str = "comb",
) -> BeadArchitecture:
    """
    Regular comb polymer: identical side chains grafted every ``every``
    backbone beads, starting at ``offset``.

    Args:
        backbone: Backbone sequence.
        side: Side-chain sequence (single bead or oligomer).
        every: Grafting spacing along the backbone.
        offset: Backbone index of the first graft point.
    """
    bb = normalize_sequence(backbone)
    if every < 1:
        raise ValueError(f"'every' must be >= 1, got {every}")
    grafts = {i: side for i in range(offset, len(bb), every)}
    if not grafts:
        raise ValueError(
            f"No graft points: offset={offset}, every={every}, "
            f"backbone length={len(bb)}"
        )
    return graft(bb, grafts, name=name)

tadpole(ring_seq: SequenceInput, tail: SequenceInput, attach: int = 0, name: str = 'tadpole') -> BeadArchitecture

Tadpole (lariat) polymer: a ring with a linear tail attached.

Parameters:

Name Type Description Default
ring_seq SequenceInput

Ring sequence (beads 0..N-1, cyclically bonded).

required
tail SequenceInput

Tail sequence, attached by its first bead to ring bead attach.

required
attach int

Ring bead index where the tail attaches.

0
Source code in AutoPoly/models/architectures.py
def tadpole(
    ring_seq: SequenceInput,
    tail: SequenceInput,
    attach: int = 0,
    name: str = "tadpole",
) -> BeadArchitecture:
    """
    Tadpole (lariat) polymer: a ring with a linear tail attached.

    Args:
        ring_seq: Ring sequence (beads 0..N-1, cyclically bonded).
        tail: Tail sequence, attached by its first bead to ring bead
            ``attach``.
        attach: Ring bead index where the tail attaches.
    """
    ring_beads = normalize_sequence(ring_seq)
    if len(ring_beads) < 3:
        raise ValueError(
            f"Tadpole ring requires at least 3 beads, got {len(ring_beads)}"
        )
    if not 0 <= attach < len(ring_beads):
        raise ValueError(
            f"Attachment index {attach} out of range for ring of {len(ring_beads)}"
        )
    tail_beads = normalize_sequence(tail)

    bead_types = ring_beads + tail_beads
    n_ring = len(ring_beads)
    bonds = [(i, i + 1) for i in range(n_ring - 1)]
    bonds.append((n_ring - 1, 0))  # ring closure
    tail_start = n_ring
    bonds.append((attach, tail_start))
    bonds.extend(
        (tail_start + k, tail_start + k + 1) for k in range(len(tail_beads) - 1)
    )
    arch = BeadArchitecture(bead_types=bead_types, bonds=bonds, name=name)
    arch.validate()
    return arch

dendrimer(core: str, branch: str, branch_factor: int = 2, generations: int = 2, name: str = 'dendrimer') -> BeadArchitecture

Dendrimer / regularly branched polymer.

Parameters:

Name Type Description Default
core str

Bead type of the core bead.

required
branch str

Bead type of all branch beads.

required
branch_factor int

Number of children per node (core degree = branch_factor; internal branch beads have degree branch_factor + 1).

2
generations int

Number of branching shells. generations=1 gives a star with branch_factor arms of length 1.

2
Source code in AutoPoly/models/architectures.py
def dendrimer(
    core: str,
    branch: str,
    branch_factor: int = 2,
    generations: int = 2,
    name: str = "dendrimer",
) -> BeadArchitecture:
    """
    Dendrimer / regularly branched polymer.

    Args:
        core: Bead type of the core bead.
        branch: Bead type of all branch beads.
        branch_factor: Number of children per node (core degree =
            branch_factor; internal branch beads have degree
            branch_factor + 1).
        generations: Number of branching shells. generations=1 gives a star
            with branch_factor arms of length 1.
    """
    if branch_factor < 2:
        raise ValueError(f"branch_factor must be >= 2, got {branch_factor}")
    if generations < 1:
        raise ValueError(f"generations must be >= 1, got {generations}")

    bead_types = [core]
    bonds: List[Tuple[int, int]] = []
    current_shell = [0]
    for _gen in range(generations):
        next_shell = []
        for parent in current_shell:
            for _ in range(branch_factor):
                child = len(bead_types)
                bead_types.append(branch)
                bonds.append((parent, child))
                next_shell.append(child)
        current_shell = next_shell
    arch = BeadArchitecture(bead_types=bead_types, bonds=bonds, name=name)
    arch.validate()
    return arch

custom(bead_types: List[str], bonds: List[Tuple[int, int]], name: str = 'custom') -> BeadArchitecture

Arbitrary user-defined architecture from an explicit bead list and bond list (the escape hatch for topologies without a factory).

Source code in AutoPoly/models/architectures.py
def custom(
    bead_types: List[str],
    bonds: List[Tuple[int, int]],
    name: str = "custom",
) -> BeadArchitecture:
    """
    Arbitrary user-defined architecture from an explicit bead list and
    bond list (the escape hatch for topologies without a factory).
    """
    arch = BeadArchitecture(
        bead_types=list(bead_types),
        bonds=[(int(i), int(j)) for i, j in bonds],
        name=name,
    )
    arch.validate()
    return arch

block_sequence(blocks: List[Tuple[str, int]]) -> List[str]

Block copolymer sequence: [("A", 50), ("B", 50)] -> A50-b-B50.

Source code in AutoPoly/models/architectures.py
def block_sequence(blocks: List[Tuple[str, int]]) -> List[str]:
    """Block copolymer sequence: [("A", 50), ("B", 50)] -> A50-b-B50."""
    return normalize_sequence(blocks)

alternating_sequence(types: Sequence[str], n_beads: int) -> List[str]

Alternating copolymer: types cycle along the chain ("ABABAB...").

Source code in AutoPoly/models/architectures.py
def alternating_sequence(types: Sequence[str], n_beads: int) -> List[str]:
    """Alternating copolymer: types cycle along the chain ("ABABAB...")."""
    if not types:
        raise ValueError("alternating_sequence requires at least one bead type")
    if n_beads < 1:
        raise ValueError(f"n_beads must be >= 1, got {n_beads}")
    return [types[i % len(types)] for i in range(n_beads)]

random_sequence(types: Sequence[str], n_beads: int, weights: Optional[Sequence[float]] = None, seed: Optional[int] = None) -> List[str]

Statistical (random) copolymer sequence.

Parameters:

Name Type Description Default
types Sequence[str]

Bead type names to draw from.

required
n_beads int

Chain length.

required
weights Optional[Sequence[float]]

Sampling probability per type (uniform if None).

None
seed Optional[int]

Random seed for reproducibility.

None
Source code in AutoPoly/models/architectures.py
def random_sequence(
    types: Sequence[str],
    n_beads: int,
    weights: Optional[Sequence[float]] = None,
    seed: Optional[int] = None,
) -> List[str]:
    """
    Statistical (random) copolymer sequence.

    Args:
        types: Bead type names to draw from.
        n_beads: Chain length.
        weights: Sampling probability per type (uniform if None).
        seed: Random seed for reproducibility.
    """
    if not types:
        raise ValueError("random_sequence requires at least one bead type")
    if n_beads < 1:
        raise ValueError(f"n_beads must be >= 1, got {n_beads}")
    if weights is not None:
        if len(weights) != len(types):
            raise ValueError("weights must have the same length as types")
        if any(w < 0 for w in weights):
            raise ValueError("weights must be non-negative")
        total = sum(weights)
        if total <= 0:
            raise ValueError("weights must sum to a positive value")
        probs = [w / total for w in weights]
    else:
        probs = None
    rng = np.random.default_rng(seed)
    draws = rng.choice(len(types), size=n_beads, p=probs)
    return [types[i] for i in draws]

gradient_sequence(type_start: str, type_end: str, n_beads: int, seed: Optional[int] = None) -> List[str]

Gradient copolymer: probability of type_end grows linearly from 0 at the first bead to 1 at the last bead.

Source code in AutoPoly/models/architectures.py
def gradient_sequence(
    type_start: str,
    type_end: str,
    n_beads: int,
    seed: Optional[int] = None,
) -> List[str]:
    """
    Gradient copolymer: probability of ``type_end`` grows linearly from 0
    at the first bead to 1 at the last bead.
    """
    if n_beads < 2:
        raise ValueError(f"gradient_sequence requires n_beads >= 2, got {n_beads}")
    rng = np.random.default_rng(seed)
    seq = []
    for i in range(n_beads):
        p_end = i / (n_beads - 1)
        seq.append(type_end if rng.random() < p_end else type_start)
    return seq

Mixtures

AutoPoly.models.bead_spring_system

Bead-Spring System (Mixtures)

This module provides BeadSpringSystem: a multi-species bead-spring melt builder. Each species is a (BeadArchitecture, n_chains) pair — linear chains, rings, stars, combs, or any custom graph can be mixed freely in one simulation box with one shared LAMMPS data file.

Example — a ring/linear blend::

from AutoPoly import System
from AutoPoly.models.bead_spring_system import BeadSpringSystem
from AutoPoly.models import architectures as arch
from AutoPoly.models.bead_spring import BeadType

system = System(out="ring_linear_blend")
bss = BeadSpringSystem(
    name="blend",
    system=system,
    bead_types=[BeadType("A")],
    bond_style="fene",
    pair_style="wca",
    density=0.85,
)
bss.add_species(arch.ring([("A", 50)]), n_chains=20)
bss.add_species(arch.linear([("A", 50)]), n_chains=20)
bss.generate_data_file()

Coarse-grained fillers (AutoPoly.nanoparticles.CGFiller) are added with :meth:BeadSpringSystem.add_filler: they are placed first, chains grow around them by SAW, and the run script integrates them as rigid bodies (or keeps them frozen).

Classes:

Name Description
BeadSpringSystem

Multi-species bead-spring system (mixture) generator.

BeadSpringSystem

Multi-species bead-spring system (mixture) generator.

All species share one bead-type table, one box, and one LAMMPS data file. Chains are placed collision-free with the graph-based SAW generator; branched species are equilibrated with the branched MC moves (tree-pivot, segment crankshaft).

Parameters:

Name Type Description Default
name str

Name for output files.

required
system object

System object containing path information.

required
bead_types List[BeadType]

List of BeadType objects covering ALL bead types used by any species.

required
bond_length float

Equilibrium bond length.

1.0
bond_style str

"harmonic" or "fene".

'harmonic'
k_bond float

Bond force constant.

30.0
fene_r0 float

FENE maximum extension (only used if bond_style="fene").

1.5
pair_style str

"lj" (full LJ, cutoff 2.5) or "wca" (repulsive).

'lj'
use_angles bool

Whether to include angle potentials.

False
default_k_angle float

Default angle force constant.

10.0
default_theta0 float

Default equilibrium angle.

180.0
angle_types Optional[List[AngleType]]

Per-triplet AngleType parameters.

None
include_branch_angles bool

Whether to include angle triplets centered on branch points.

True
density Optional[float]

Target bead density (beads/sigma^3) for box sizing (with CG fillers: chain-bead density of the volume outside the filler envelopes).

None
box_size Optional[float]

Explicit box size (overrides density).

None
generation_method str

"geometric", "saw" (default), or "mc".

'saw'
saw_config Optional[SAWConfig]

SAW configuration.

None
mc_config Optional[MCConfig]

MC equilibration configuration.

None
backend str

Output backend used by :meth:generate: "moltemplate" (default) or "direct".

'moltemplate'

Raises:

Type Description
ValueError

If parameters are invalid.

Methods:

Name Description
add_species

Add a chain species to the mixture.

add_filler

Add a coarse-grained filler species (AutoPoly.nanoparticles.CGFiller).

set_pair_coeff

Override the Lorentz-Berthelot pair coefficients of one bead-type

saw_generate

Generate the mixture configuration using graph-based SAW.

equilibrate

Pre-equilibrate the mixture with Monte Carlo moves.

generate

Generate LAMMPS input files using the configured output backend.

generate_data_file

Generate the LAMMPS data file (and input script) for the mixture

generate_moltemplate

Generate moltemplate .lt files (and optionally run moltemplate) for

get_system_info

Get comprehensive information about the bead-spring mixture.

Attributes:

Name Type Description
n_fillers int

Number of CG filler particles.

Source code in AutoPoly/models/bead_spring_system.py
 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
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
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
class BeadSpringSystem:
    """
    Multi-species bead-spring system (mixture) generator.

    All species share one bead-type table, one box, and one LAMMPS data
    file. Chains are placed collision-free with the graph-based SAW
    generator; branched species are equilibrated with the branched MC
    moves (tree-pivot, segment crankshaft).

    Args:
        name: Name for output files.
        system: System object containing path information.
        bead_types: List of BeadType objects covering ALL bead types used
            by any species.
        bond_length: Equilibrium bond length.
        bond_style: "harmonic" or "fene".
        k_bond: Bond force constant.
        fene_r0: FENE maximum extension (only used if bond_style="fene").
        pair_style: "lj" (full LJ, cutoff 2.5) or "wca" (repulsive).
        use_angles: Whether to include angle potentials.
        default_k_angle: Default angle force constant.
        default_theta0: Default equilibrium angle.
        angle_types: Per-triplet AngleType parameters.
        include_branch_angles: Whether to include angle triplets centered
            on branch points.
        density: Target bead density (beads/sigma^3) for box sizing (with
            CG fillers: chain-bead density of the volume outside the
            filler envelopes).
        box_size: Explicit box size (overrides density).
        generation_method: "geometric", "saw" (default), or "mc".
        saw_config: SAW configuration.
        mc_config: MC equilibration configuration.
        backend: Output backend used by :meth:`generate`: "moltemplate"
            (default) or "direct".

    Raises:
        ValueError: If parameters are invalid.
    """

    VALID_BOND_STYLES = ["harmonic", "fene"]
    VALID_PAIR_STYLES = ["lj", "wca"]
    VALID_GENERATION_METHODS = ["geometric", "saw", "mc"]
    VALID_BACKENDS = ["moltemplate", "direct"]

    def __init__(
        self,
        name: str,
        system: object,
        bead_types: List[BeadType],
        bond_length: float = 1.0,
        bond_style: str = "harmonic",
        k_bond: float = 30.0,
        fene_r0: float = 1.5,
        pair_style: str = "lj",
        use_angles: bool = False,
        default_k_angle: float = 10.0,
        default_theta0: float = 180.0,
        angle_types: Optional[List[AngleType]] = None,
        include_branch_angles: bool = True,
        density: Optional[float] = None,
        box_size: Optional[float] = None,
        generation_method: str = "saw",
        saw_config: Optional[SAWConfig] = None,
        mc_config: Optional[MCConfig] = None,
        backend: str = "moltemplate",
    ) -> None:
        if backend not in self.VALID_BACKENDS:
            raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
        if bond_style not in self.VALID_BOND_STYLES:
            raise ValueError(f"Bond style must be one of: {self.VALID_BOND_STYLES}")
        if pair_style not in self.VALID_PAIR_STYLES:
            raise ValueError(f"Pair style must be one of: {self.VALID_PAIR_STYLES}")
        if generation_method not in self.VALID_GENERATION_METHODS:
            raise ValueError(
                f"Generation method must be one of: {self.VALID_GENERATION_METHODS}"
            )
        if not bead_types:
            raise ValueError("At least one bead type is required")

        self.name = name
        self.system = system
        self.path = f"{self.system.get_folder_path()}/{self.name}" if system else f"./{name}"

        self.bead_types = bead_types
        self._bead_type_map: Dict[str, BeadType] = {bt.name: bt for bt in bead_types}
        self._bead_type_id: Dict[str, int] = {bt.name: i + 1 for i, bt in enumerate(bead_types)}

        # Bond/pair/angle parameters
        self.bond_length = bond_length
        self.bond_style = bond_style
        self.k_bond = k_bond
        self.fene_r0 = fene_r0
        self._pair_style = pair_style
        self.use_angles = use_angles
        self.default_k_angle = default_k_angle
        self.default_theta0 = default_theta0
        self._angle_types = angle_types or []
        self.include_branch_angles = include_branch_angles

        # Box sizing
        self.density = density
        self._explicit_box_size = box_size

        # Generation
        self._generation_method = generation_method
        self._saw_config = saw_config
        self._mc_config = mc_config

        # Output backend ("moltemplate" default, or "direct")
        self._backend = backend

        # Species: list of (architecture, n_chains, species_name)
        self._species: List[Tuple[BeadArchitecture, int, str]] = []

        # Internal state (populated during generation)
        self._positions: Optional[List[np.ndarray]] = None
        self._chain_indices: Optional[List[Tuple[int, int]]] = None
        self._chain_architectures: Optional[List[BeadArchitecture]] = None
        self._bonds: Optional[List[Tuple[int, int]]] = None

        self._pair_coeffs = lb_pair_coeffs(bead_types)

        # Coarse-grained fillers (AutoPoly.nanoparticles.cg)
        self._fillers: List = []
        self._placed_fillers: Optional[List] = None
        self.filler_min_gap = 1.0

        Path(self.path).mkdir(parents=True, exist_ok=True)

    # ------------------------------------------------------------------ #
    # Species management
    # ------------------------------------------------------------------ #

    def add_species(
        self,
        architecture: BeadArchitecture,
        n_chains: int,
        name: Optional[str] = None,
    ) -> None:
        """
        Add a chain species to the mixture.

        Args:
            architecture: BeadArchitecture of the chains.
            n_chains: Number of chains of this species.
            name: Optional species label (defaults to the architecture name).

        Raises:
            ValueError: If n_chains < 1 or the architecture is invalid.
        """
        if n_chains < 1:
            raise ValueError(f"n_chains must be >= 1, got {n_chains}")
        architecture.validate(
            known_bead_types=[bt.name for bt in self.bead_types]
        )
        species_name = name or architecture.name
        self._species.append((architecture, n_chains, species_name))
        # Invalidate generated state
        self._placed_fillers = None
        self._positions = None
        self._chain_indices = None
        self._chain_architectures = None
        self._bonds = None
        logger.info(
            f"Added species '{species_name}': {n_chains} chains, "
            f"{architecture.n_beads} beads each"
        )

    def add_filler(self, filler) -> None:
        """
        Add a coarse-grained filler species (AutoPoly.nanoparticles.CGFiller).

        Fillers are placed before the chains (random positions and
        orientations, envelope gaps >= ``filler_min_gap``); chains then
        grow around them by SAW, so only generation_method="saw" is
        supported.  Filler beads are written as one molecule per particle.

        Raises:
            ValueError: Unknown filler bead type.
        """
        from ..nanoparticles.cg import CGFiller
        if not isinstance(filler, CGFiller):
            raise ValueError("add_filler() expects an AutoPoly.nanoparticles.CGFiller")
        if filler.bead_type not in self._bead_type_map:
            raise ValueError(
                f"CG filler bead type '{filler.bead_type}' is not among the "
                f"bead types {list(self._bead_type_map)}"
            )
        self._fillers.append(filler)
        self._placed_fillers = None
        self._positions = None
        self._chain_indices = None
        self._chain_architectures = None
        self._bonds = None
        logger.info(
            f"Added CG filler '{filler.name}': {filler.count} x R="
            f"{filler.radius} ({filler.structure}, {filler.n_beads} beads, "
            f"{filler.motion})"
        )

    def set_pair_coeff(self, type_a: str, type_b: str, epsilon: float,
                       sigma: Optional[float] = None,
                       cutoff: Optional[float] = None) -> None:
        """
        Override the Lorentz-Berthelot pair coefficients of one bead-type
        pair (e.g. the polymer-filler attraction), optionally with its own
        cutoff (e.g. an attractive 2.5 sigma pair in a WCA melt).
        """
        for t in (type_a, type_b):
            if t not in self._bead_type_id:
                raise ValueError(f"Unknown bead type '{t}'")
        i, j = sorted((self._bead_type_id[type_a], self._bead_type_id[type_b]))
        sig = sigma if sigma is not None else self._pair_coeffs[(i, j)][1]
        self._pair_coeffs[(i, j)] = (
            (epsilon, sig) if cutoff is None else (epsilon, sig, cutoff)
        )

    @property
    def n_fillers(self) -> int:
        """Number of CG filler particles."""
        return sum(f.count for f in self._fillers)

    def _check_fillers(self) -> None:
        """Filler bead types are exclusive and have one motion each."""
        from ..nanoparticles.cg import motion_groups
        chain_types = {t for arch, _, _ in self._species for t in arch.bead_types}
        for f in self._fillers:
            if f.bead_type in chain_types:
                raise ValueError(
                    f"CG filler bead type '{f.bead_type}' is also used by a "
                    "chain species; fillers need their own bead type"
                )
        if self._generation_method != "saw":
            raise ValueError(
                "CG fillers need generation_method='saw' (chains are grown "
                "around the placed fillers)"
            )
        motion_groups(self._fillers)

    def _filler_groups(self, numeric: bool) -> Dict[str, List[str]]:
        """motion -> filler type tokens (numeric ids or type names)."""
        from ..nanoparticles.cg import motion_groups
        groups = motion_groups(self._fillers)
        if not numeric:
            return groups
        return {m: [str(self._bead_type_id[t]) for t in ts]
                for m, ts in groups.items()}

    @property
    def n_species(self) -> int:
        return len(self._species)

    @property
    def n_chains(self) -> int:
        return sum(n for _, n, _ in self._species)

    @property
    def total_beads(self) -> int:
        return sum(arch.n_beads * n for arch, n, _ in self._species)

    def _expanded_chain_architectures(self) -> List[BeadArchitecture]:
        """One architecture entry per chain, in species order."""
        chains = []
        for arch, n, _ in self._species:
            chains.extend([arch] * n)
        return chains

    # ------------------------------------------------------------------ #
    # Box sizing
    # ------------------------------------------------------------------ #

    def _calculate_box_size(self) -> float:
        """Box size from explicit value, density, or default density."""
        if self._explicit_box_size is not None:
            return self._explicit_box_size
        density = self.density if self.density is not None else DEFAULT_BEAD_DENSITY
        if self._fillers:
            from ..nanoparticles.cg import filler_volume
            sigma = {bt.name: bt.sigma for bt in self.bead_types}
            volume = self.total_beads / density + filler_volume(self._fillers, sigma)
            return volume ** (1 / 3)
        return calculate_box_size(self.total_beads, density)

    # ------------------------------------------------------------------ #
    # Configuration generation
    # ------------------------------------------------------------------ #

    def _require_species(self) -> None:
        if not self._species:
            raise ValueError("No species added. Call add_species() first.")

    def _generate_geometric_positions(self) -> None:
        """Grow each chain along its spanning tree with random directions."""
        if self._fillers:
            raise ValueError(
                "Geometric placement ignores CG fillers; use generation_method='saw'"
            )
        chains = self._expanded_chain_architectures()
        self._positions = []
        self._chain_indices = []
        self._chain_architectures = chains
        for chain_idx, arch in enumerate(chains):
            start_idx = len(self._positions)
            order, parents, _ = arch.growth_order(root=0)
            offset = np.array([0.0, chain_idx * self.bond_length * 2, 0.0])
            pos_map = {0: offset.copy()}
            for bead in order[1:]:
                parent = parents[bead]
                direction = np.random.normal(size=3)
                direction /= np.linalg.norm(direction)
                pos_map[bead] = pos_map[parent] + direction * self.bond_length
            for i in range(arch.n_beads):
                self._positions.append(pos_map[i])
            self._chain_indices.append((start_idx, len(self._positions)))
        self._generate_bonds()

    def _generate_bonds(self) -> None:
        """Global bond list from per-chain architectures (0-indexed)."""
        self._bonds = []
        assert self._chain_indices is not None
        assert self._chain_architectures is not None
        for (start, _), arch in zip(self._chain_indices, self._chain_architectures):
            for i, j in arch.bonds:
                self._bonds.append((start + i, start + j))

    def saw_generate(self, saw_config: Optional[SAWConfig] = None) -> bool:
        """
        Generate the mixture configuration using graph-based SAW.

        Returns:
            True if successful, False otherwise.
        """
        self._require_species()
        config = saw_config or self._saw_config or SAWConfig()
        if self._fillers:
            self._check_fillers()
        filler_types = {f.bead_type for f in self._fillers}
        if config.collision_sigma == 1.0 and self.bead_types:
            config.collision_sigma = max(
                bt.sigma for bt in self.bead_types if bt.name not in filler_types
            )

        box_size = self._calculate_box_size()
        chains = self._expanded_chain_architectures()
        if self._fillers:
            from ..nanoparticles.cg import place_fillers
            sigma = {bt.name: bt.sigma for bt in self.bead_types}

        logger.info(
            f"Starting SAW generation: {len(chains)} chains "
            f"({self.n_species} species), box_size={box_size:.3f}"
        )

        # Whole-system retries (see BeadSpringPolymer.saw_generate)
        stats = {"success": False}
        positions, chain_indices = None, None
        for attempt in range(max(1, config.system_retries)):
            obstacles = None
            if self._fillers:
                self._placed_fillers = place_fillers(
                    self._fillers, box_size, sigma, self.filler_min_gap
                )
                obstacles = (
                    np.array([p.center for p in self._placed_fillers]),
                    np.array([p.envelope for p in self._placed_fillers]),
                )
            positions, chain_indices, stats = saw_generate_graphs(
                architectures=chains,
                bond_length=self.bond_length,
                box_size=box_size,
                config=config,
                obstacles=obstacles,
            )
            if stats["success"]:
                break
            logger.info(
                f"SAW attempt {attempt + 1}/{config.system_retries} failed "
                f"({stats['failure_reason']}), retrying with fresh state"
            )

        if not stats["success"]:
            logger.warning(
                f"SAW generation failed: {stats['failure_reason']}. "
                f"Chains completed: {stats['chains_completed']}, "
                f"Backtracks: {stats['total_backtracks']}"
            )
            if self._fillers:
                # the geometric fallback would ignore the fillers
                raise RuntimeError(
                    "SAW generation around the CG fillers failed "
                    f"({stats['failure_reason']}): lower the density or the "
                    "filler loading, or enlarge the box"
                )
            return False

        self._positions = positions
        self._chain_indices = chain_indices
        self._chain_architectures = chains
        self._generate_bonds()

        logger.info(
            f"SAW generation complete. Backtracks: {stats['total_backtracks']}"
        )
        return True

    def equilibrate(self, mc_config: Optional[MCConfig] = None) -> None:
        """
        Pre-equilibrate the mixture with Monte Carlo moves.

        Branched chains use tree-pivot and segment-crankshaft moves;
        linear chains additionally use reptation.
        """
        self._require_species()
        if self._fillers:
            raise ValueError(
                "MC equilibration does not see CG fillers; use "
                "generation_method='saw'"
            )
        config = mc_config or self._mc_config or MCConfig()

        if self._positions is None:
            if self._generation_method == "saw":
                if not self.saw_generate(self._saw_config):
                    self._generate_geometric_positions()
            else:
                self._generate_geometric_positions()

        box_size = self._calculate_box_size()
        avg_sigma = np.mean([bt.sigma for bt in self.bead_types])
        avg_epsilon = np.mean([bt.epsilon for bt in self.bead_types])

        chain_graphs = [
            build_chain_graph(arch, start)
            for arch, (start, _) in zip(
                self._chain_architectures, self._chain_indices
            )
        ]

        logger.info(
            f"Starting MC equilibration: {config.n_steps} steps, "
            f"T={config.temperature}, box_size={box_size:.3f}"
        )

        self._positions, acceptance_stats = mc_equilibrate(
            positions=self._positions,
            bonds=self._bonds,
            chain_indices=self._chain_indices,
            chain_graphs=chain_graphs,
            n_steps=config.n_steps,
            temperature=config.temperature,
            move_weights=config.move_weights,
            box_size=box_size,
            lj_sigma=config.lj_sigma if config.lj_sigma else avg_sigma,
            lj_epsilon=config.lj_epsilon if config.lj_epsilon else avg_epsilon,
            lj_cutoff=config.lj_cutoff,
            bond_k=config.bond_k,
            bond_r0=self.bond_length,
            max_displacement=config.max_displacement,
            max_angle=config.max_angle,
            verbose=True,
        )

        logger.info(f"MC equilibration complete. Acceptance rates: {acceptance_stats}")

    # ------------------------------------------------------------------ #
    # Output
    # ------------------------------------------------------------------ #

    def _chain_triplets(self) -> List[List[Tuple[int, int, int]]]:
        """Local angle triplets per chain (empty lists if not use_angles)."""
        assert self._chain_architectures is not None
        if not self.use_angles:
            return [[] for _ in self._chain_architectures]
        return [
            arch.angle_triplets(include_branch=self.include_branch_angles)
            for arch in self._chain_architectures
        ]

    def generate(
        self,
        backend: Optional[str] = None,
        run_moltemplate: bool = True,
    ) -> None:
        """
        Generate LAMMPS input files using the configured output backend.

        This is the standard entry point for producing simulation files.

        Args:
            backend: "moltemplate" (default; .lt files + moltemplate ->
                moltemplate/system.data + system.in.*) or "direct"
                (polymer.data + in.polymer written directly). Defaults to
                the constructor's ``backend`` parameter.
            run_moltemplate: Only for the moltemplate backend: run the
                bundled moltemplate after writing .lt files.
        """
        backend = backend or self._backend
        if backend not in self.VALID_BACKENDS:
            raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
        if backend == "moltemplate":
            self.generate_moltemplate(run_moltemplate=run_moltemplate)
        else:
            self.generate_data_file()

    def generate_data_file(self) -> None:
        """Generate the LAMMPS data file (and input script) for the mixture
        (direct backend)."""
        self._require_species()

        # Generate positions
        if self._positions is None:
            if self._generation_method == "saw":
                if not self.saw_generate(self._saw_config):
                    logger.warning("SAW failed, falling back to geometric placement")
                    self._generate_geometric_positions()
            elif self._generation_method == "mc":
                self._generate_geometric_positions()
                self.equilibrate(self._mc_config)
            else:
                self._generate_geometric_positions()

        assert self._chain_architectures is not None
        assert self._chain_indices is not None

        chain_triplets = self._chain_triplets()
        chain_bead_types = [arch.bead_types for arch in self._chain_architectures]

        placed = self._placed_fillers or []
        total_atoms = sum(arch.n_beads for arch in self._chain_architectures)
        total_atoms += sum(len(p.positions) for p in placed)
        total_bonds = sum(arch.n_bonds for arch in self._chain_architectures)
        total_angles = sum(len(t) for t in chain_triplets)

        n_atom_types = len(self.bead_types)
        angle_type_map = (
            build_angle_type_map(chain_bead_types, chain_triplets)
            if self.use_angles else {}
        )
        n_angle_types = len(angle_type_map)

        box_size = self._calculate_box_size()

        with open(f"{self.path}/polymer.data", 'w') as f:
            # Header
            f.write("LAMMPS Bead-Spring Polymer Data File (mixture)\n\n")
            f.write(f"{total_atoms} atoms\n")
            f.write(f"{total_bonds} bonds\n")
            if self.use_angles:
                f.write(f"{total_angles} angles\n")
            f.write("\n")
            f.write(f"{n_atom_types} atom types\n")
            f.write("1 bond types\n")
            if self.use_angles:
                f.write(f"{n_angle_types} angle types\n")
            f.write("\n")

            # Box dimensions (exact with CG fillers: the filler-aware SAW
            # checks overlaps with the periodic image of this box)
            lo = f"{-box_size/2:.6f}" if placed else f"{-box_size/2:.1f}"
            hi = f"{box_size/2:.6f}" if placed else f"{box_size/2:.1f}"
            f.write(f"{lo} {hi} xlo xhi\n")
            f.write(f"{lo} {hi} ylo yhi\n")
            f.write(f"{lo} {hi} zlo zhi\n\n")

            # Masses
            f.write("Masses\n\n")
            for bt in self.bead_types:
                type_id = self._bead_type_id[bt.name]
                f.write(f"{type_id} {bt.mass:.3f}  # {bt.name}\n")
            f.write("\n")

            # Atoms section: atom-ID molecule-ID atom-type x y z
            f.write("Atoms  # molecular\n\n")
            atom_id = 1
            for chain_idx, ((start, end), arch) in enumerate(
                zip(self._chain_indices, self._chain_architectures)
            ):
                for local_bead, global_idx in enumerate(range(start, end)):
                    pos = self._positions[global_idx]
                    bead_name = arch.bead_types[local_bead]
                    type_id = self._bead_type_id[bead_name]
                    f.write(
                        f"{atom_id} {chain_idx + 1} {type_id} "
                        f"{pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n"
                    )
                    atom_id += 1
            # CG fillers: one molecule per particle, after the chains
            for k, p in enumerate(placed):
                mol_id = len(self._chain_architectures) + k + 1
                type_id = self._bead_type_id[p.filler.bead_type]
                for pos in p.positions:
                    f.write(
                        f"{atom_id} {mol_id} {type_id} "
                        f"{pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n"
                    )
                    atom_id += 1

            # Bonds
            f.write("\nBonds\n\n")
            bond_id = 1
            atom_offset = 0
            for arch in self._chain_architectures:
                for i, j in arch.bonds:
                    f.write(
                        f"{bond_id} 1 {atom_offset + i + 1} {atom_offset + j + 1}\n"
                    )
                    bond_id += 1
                atom_offset += arch.n_beads

            # Angles
            if self.use_angles:
                from .bead_spring import canonical_bead_triplet
                f.write("\nAngles\n\n")
                angle_id = 1
                atom_offset = 0
                for arch, triplets in zip(self._chain_architectures, chain_triplets):
                    for i, j, k in triplets:
                        triplet = canonical_bead_triplet(
                            arch.bead_types[i],
                            arch.bead_types[j],
                            arch.bead_types[k],
                        )
                        angle_type_id = angle_type_map[triplet]
                        f.write(
                            f"{angle_id} {angle_type_id} "
                            f"{atom_offset + i + 1} {atom_offset + j + 1} "
                            f"{atom_offset + k + 1}\n"
                        )
                        angle_id += 1
                    atom_offset += arch.n_beads

        # LAMMPS input script
        write_lammps_input_script(
            path=self.path,
            bead_types=self.bead_types,
            pair_coeffs=self._pair_coeffs,
            bond_style=self.bond_style,
            k_bond=self.k_bond,
            bond_length=self.bond_length,
            fene_r0=self.fene_r0,
            pair_style=self._pair_style,
            use_angles=self.use_angles,
            angle_type_map=angle_type_map,
            angle_types=self._angle_types,
            default_k_angle=self.default_k_angle,
            default_theta0=self.default_theta0,
            fillers=self._filler_groups(numeric=True) if placed else None,
        )
        logger.info(f"Generated bead-spring mixture files in {self.path}")

    def generate_moltemplate(self, run_moltemplate: bool = True) -> Path:
        """
        Generate moltemplate .lt files (and optionally run moltemplate) for
        this mixture.

        Each chain becomes its own moltemplate object with generated
        coordinates; species share the bead-type table, so mixed systems
        (rings + stars + combs + ...) land in one system.data.

        Args:
            run_moltemplate: Run the bundled moltemplate after writing
                files (produces system.data, system.in.init/settings).

        Returns:
            Path to the moltemplate directory.
        """
        from .bead_spring import canonical_bead_triplet, resolve_angle_params
        from .bead_spring_lt import generate_moltemplate_files

        self._require_species()

        # Ensure positions exist (same logic as generate_data_file)
        if self._positions is None:
            if self._generation_method == "saw":
                if not self.saw_generate(self._saw_config):
                    logger.warning("SAW failed, falling back to geometric placement")
                    self._generate_geometric_positions()
            elif self._generation_method == "mc":
                self._generate_geometric_positions()
                self.equilibrate(self._mc_config)
            else:
                self._generate_geometric_positions()

        assert self._chain_architectures is not None
        assert self._chain_indices is not None

        chain_triplets = self._chain_triplets()
        chain_bead_types = [arch.bead_types for arch in self._chain_architectures]
        angle_type_map = (
            build_angle_type_map(chain_bead_types, chain_triplets)
            if self.use_angles else {}
        )

        box_size = self._calculate_box_size()

        return generate_moltemplate_files(
            path=self.path,
            bead_types=self.bead_types,
            chain_architectures=self._chain_architectures,
            positions=self._positions,
            chain_indices=self._chain_indices,
            box_size=box_size,
            pair_coeffs=self._pair_coeffs,
            bond_style=self.bond_style,
            k_bond=self.k_bond,
            bond_length=self.bond_length,
            fene_r0=self.fene_r0,
            pair_style=self._pair_style,
            use_angles=self.use_angles,
            angle_type_map=angle_type_map,
            resolve_angle_params=lambda t: resolve_angle_params(
                t, self._angle_types, self.default_k_angle, self.default_theta0
            ),
            include_branch_angles=self.include_branch_angles,
            canonical_triplet=canonical_bead_triplet,
            run_moltemplate=run_moltemplate,
            fillers=((self._placed_fillers, self._filler_groups(numeric=False))
                     if self._placed_fillers else None),
        )

    def get_system_info(self) -> dict:
        """
        Get comprehensive information about the bead-spring mixture.

        Returns:
            Dictionary containing system properties.
        """
        chain_triplets = (
            [
                arch.angle_triplets(include_branch=self.include_branch_angles)
                for arch, n, _ in self._species for _ in range(n)
            ]
            if self.use_angles else []
        )
        info = {
            'name': self.name,
            'n_species': self.n_species,
            'n_chains': self.n_chains,
            'species': [
                {
                    'name': sname,
                    'architecture': arch.name,
                    'n_chains': n,
                    'n_beads_per_chain': arch.n_beads,
                    'n_bonds_per_chain': arch.n_bonds,
                    'is_branched': arch.is_branched,
                }
                for arch, n, sname in self._species
            ],
            'total_atoms': self.total_beads,
            'total_bonds': sum(arch.n_bonds * n for arch, n, _ in self._species),
            'total_angles': sum(len(t) for t in chain_triplets),
            'bond_style': self.bond_style,
            'bond_length': self.bond_length,
            'k_bond': self.k_bond,
            'use_angles': self.use_angles,
            'bead_types': [bt.name for bt in self.bead_types],
            'output_path': self.path,
        }
        if self._fillers:
            from ..nanoparticles.cg import summary
            if self._placed_fillers:
                info['fillers'] = summary(
                    self._placed_fillers, self._calculate_box_size()
                )
            else:
                info['fillers'] = {
                    'species': {f.name: {'count': f.count, 'radius': f.radius}
                                for f in self._fillers},
                    'n_particles': self.n_fillers,
                }
        return info

n_fillers: int property

Number of CG filler particles.

add_species(architecture: BeadArchitecture, n_chains: int, name: Optional[str] = None) -> None

Add a chain species to the mixture.

Parameters:

Name Type Description Default
architecture BeadArchitecture

BeadArchitecture of the chains.

required
n_chains int

Number of chains of this species.

required
name Optional[str]

Optional species label (defaults to the architecture name).

None

Raises:

Type Description
ValueError

If n_chains < 1 or the architecture is invalid.

Source code in AutoPoly/models/bead_spring_system.py
def add_species(
    self,
    architecture: BeadArchitecture,
    n_chains: int,
    name: Optional[str] = None,
) -> None:
    """
    Add a chain species to the mixture.

    Args:
        architecture: BeadArchitecture of the chains.
        n_chains: Number of chains of this species.
        name: Optional species label (defaults to the architecture name).

    Raises:
        ValueError: If n_chains < 1 or the architecture is invalid.
    """
    if n_chains < 1:
        raise ValueError(f"n_chains must be >= 1, got {n_chains}")
    architecture.validate(
        known_bead_types=[bt.name for bt in self.bead_types]
    )
    species_name = name or architecture.name
    self._species.append((architecture, n_chains, species_name))
    # Invalidate generated state
    self._placed_fillers = None
    self._positions = None
    self._chain_indices = None
    self._chain_architectures = None
    self._bonds = None
    logger.info(
        f"Added species '{species_name}': {n_chains} chains, "
        f"{architecture.n_beads} beads each"
    )

add_filler(filler) -> None

Add a coarse-grained filler species (AutoPoly.nanoparticles.CGFiller).

Fillers are placed before the chains (random positions and orientations, envelope gaps >= filler_min_gap); chains then grow around them by SAW, so only generation_method="saw" is supported. Filler beads are written as one molecule per particle.

Raises:

Type Description
ValueError

Unknown filler bead type.

Source code in AutoPoly/models/bead_spring_system.py
def add_filler(self, filler) -> None:
    """
    Add a coarse-grained filler species (AutoPoly.nanoparticles.CGFiller).

    Fillers are placed before the chains (random positions and
    orientations, envelope gaps >= ``filler_min_gap``); chains then
    grow around them by SAW, so only generation_method="saw" is
    supported.  Filler beads are written as one molecule per particle.

    Raises:
        ValueError: Unknown filler bead type.
    """
    from ..nanoparticles.cg import CGFiller
    if not isinstance(filler, CGFiller):
        raise ValueError("add_filler() expects an AutoPoly.nanoparticles.CGFiller")
    if filler.bead_type not in self._bead_type_map:
        raise ValueError(
            f"CG filler bead type '{filler.bead_type}' is not among the "
            f"bead types {list(self._bead_type_map)}"
        )
    self._fillers.append(filler)
    self._placed_fillers = None
    self._positions = None
    self._chain_indices = None
    self._chain_architectures = None
    self._bonds = None
    logger.info(
        f"Added CG filler '{filler.name}': {filler.count} x R="
        f"{filler.radius} ({filler.structure}, {filler.n_beads} beads, "
        f"{filler.motion})"
    )

set_pair_coeff(type_a: str, type_b: str, epsilon: float, sigma: Optional[float] = None, cutoff: Optional[float] = None) -> None

Override the Lorentz-Berthelot pair coefficients of one bead-type pair (e.g. the polymer-filler attraction), optionally with its own cutoff (e.g. an attractive 2.5 sigma pair in a WCA melt).

Source code in AutoPoly/models/bead_spring_system.py
def set_pair_coeff(self, type_a: str, type_b: str, epsilon: float,
                   sigma: Optional[float] = None,
                   cutoff: Optional[float] = None) -> None:
    """
    Override the Lorentz-Berthelot pair coefficients of one bead-type
    pair (e.g. the polymer-filler attraction), optionally with its own
    cutoff (e.g. an attractive 2.5 sigma pair in a WCA melt).
    """
    for t in (type_a, type_b):
        if t not in self._bead_type_id:
            raise ValueError(f"Unknown bead type '{t}'")
    i, j = sorted((self._bead_type_id[type_a], self._bead_type_id[type_b]))
    sig = sigma if sigma is not None else self._pair_coeffs[(i, j)][1]
    self._pair_coeffs[(i, j)] = (
        (epsilon, sig) if cutoff is None else (epsilon, sig, cutoff)
    )

saw_generate(saw_config: Optional[SAWConfig] = None) -> bool

Generate the mixture configuration using graph-based SAW.

Returns:

Type Description
bool

True if successful, False otherwise.

Source code in AutoPoly/models/bead_spring_system.py
def saw_generate(self, saw_config: Optional[SAWConfig] = None) -> bool:
    """
    Generate the mixture configuration using graph-based SAW.

    Returns:
        True if successful, False otherwise.
    """
    self._require_species()
    config = saw_config or self._saw_config or SAWConfig()
    if self._fillers:
        self._check_fillers()
    filler_types = {f.bead_type for f in self._fillers}
    if config.collision_sigma == 1.0 and self.bead_types:
        config.collision_sigma = max(
            bt.sigma for bt in self.bead_types if bt.name not in filler_types
        )

    box_size = self._calculate_box_size()
    chains = self._expanded_chain_architectures()
    if self._fillers:
        from ..nanoparticles.cg import place_fillers
        sigma = {bt.name: bt.sigma for bt in self.bead_types}

    logger.info(
        f"Starting SAW generation: {len(chains)} chains "
        f"({self.n_species} species), box_size={box_size:.3f}"
    )

    # Whole-system retries (see BeadSpringPolymer.saw_generate)
    stats = {"success": False}
    positions, chain_indices = None, None
    for attempt in range(max(1, config.system_retries)):
        obstacles = None
        if self._fillers:
            self._placed_fillers = place_fillers(
                self._fillers, box_size, sigma, self.filler_min_gap
            )
            obstacles = (
                np.array([p.center for p in self._placed_fillers]),
                np.array([p.envelope for p in self._placed_fillers]),
            )
        positions, chain_indices, stats = saw_generate_graphs(
            architectures=chains,
            bond_length=self.bond_length,
            box_size=box_size,
            config=config,
            obstacles=obstacles,
        )
        if stats["success"]:
            break
        logger.info(
            f"SAW attempt {attempt + 1}/{config.system_retries} failed "
            f"({stats['failure_reason']}), retrying with fresh state"
        )

    if not stats["success"]:
        logger.warning(
            f"SAW generation failed: {stats['failure_reason']}. "
            f"Chains completed: {stats['chains_completed']}, "
            f"Backtracks: {stats['total_backtracks']}"
        )
        if self._fillers:
            # the geometric fallback would ignore the fillers
            raise RuntimeError(
                "SAW generation around the CG fillers failed "
                f"({stats['failure_reason']}): lower the density or the "
                "filler loading, or enlarge the box"
            )
        return False

    self._positions = positions
    self._chain_indices = chain_indices
    self._chain_architectures = chains
    self._generate_bonds()

    logger.info(
        f"SAW generation complete. Backtracks: {stats['total_backtracks']}"
    )
    return True

equilibrate(mc_config: Optional[MCConfig] = None) -> None

Pre-equilibrate the mixture with Monte Carlo moves.

Branched chains use tree-pivot and segment-crankshaft moves; linear chains additionally use reptation.

Source code in AutoPoly/models/bead_spring_system.py
def equilibrate(self, mc_config: Optional[MCConfig] = None) -> None:
    """
    Pre-equilibrate the mixture with Monte Carlo moves.

    Branched chains use tree-pivot and segment-crankshaft moves;
    linear chains additionally use reptation.
    """
    self._require_species()
    if self._fillers:
        raise ValueError(
            "MC equilibration does not see CG fillers; use "
            "generation_method='saw'"
        )
    config = mc_config or self._mc_config or MCConfig()

    if self._positions is None:
        if self._generation_method == "saw":
            if not self.saw_generate(self._saw_config):
                self._generate_geometric_positions()
        else:
            self._generate_geometric_positions()

    box_size = self._calculate_box_size()
    avg_sigma = np.mean([bt.sigma for bt in self.bead_types])
    avg_epsilon = np.mean([bt.epsilon for bt in self.bead_types])

    chain_graphs = [
        build_chain_graph(arch, start)
        for arch, (start, _) in zip(
            self._chain_architectures, self._chain_indices
        )
    ]

    logger.info(
        f"Starting MC equilibration: {config.n_steps} steps, "
        f"T={config.temperature}, box_size={box_size:.3f}"
    )

    self._positions, acceptance_stats = mc_equilibrate(
        positions=self._positions,
        bonds=self._bonds,
        chain_indices=self._chain_indices,
        chain_graphs=chain_graphs,
        n_steps=config.n_steps,
        temperature=config.temperature,
        move_weights=config.move_weights,
        box_size=box_size,
        lj_sigma=config.lj_sigma if config.lj_sigma else avg_sigma,
        lj_epsilon=config.lj_epsilon if config.lj_epsilon else avg_epsilon,
        lj_cutoff=config.lj_cutoff,
        bond_k=config.bond_k,
        bond_r0=self.bond_length,
        max_displacement=config.max_displacement,
        max_angle=config.max_angle,
        verbose=True,
    )

    logger.info(f"MC equilibration complete. Acceptance rates: {acceptance_stats}")

generate(backend: Optional[str] = None, run_moltemplate: bool = True) -> None

Generate LAMMPS input files using the configured output backend.

This is the standard entry point for producing simulation files.

Parameters:

Name Type Description Default
backend Optional[str]

"moltemplate" (default; .lt files + moltemplate -> moltemplate/system.data + system.in.*) or "direct" (polymer.data + in.polymer written directly). Defaults to the constructor's backend parameter.

None
run_moltemplate bool

Only for the moltemplate backend: run the bundled moltemplate after writing .lt files.

True
Source code in AutoPoly/models/bead_spring_system.py
def generate(
    self,
    backend: Optional[str] = None,
    run_moltemplate: bool = True,
) -> None:
    """
    Generate LAMMPS input files using the configured output backend.

    This is the standard entry point for producing simulation files.

    Args:
        backend: "moltemplate" (default; .lt files + moltemplate ->
            moltemplate/system.data + system.in.*) or "direct"
            (polymer.data + in.polymer written directly). Defaults to
            the constructor's ``backend`` parameter.
        run_moltemplate: Only for the moltemplate backend: run the
            bundled moltemplate after writing .lt files.
    """
    backend = backend or self._backend
    if backend not in self.VALID_BACKENDS:
        raise ValueError(f"Backend must be one of: {self.VALID_BACKENDS}")
    if backend == "moltemplate":
        self.generate_moltemplate(run_moltemplate=run_moltemplate)
    else:
        self.generate_data_file()

generate_data_file() -> None

Generate the LAMMPS data file (and input script) for the mixture (direct backend).

Source code in AutoPoly/models/bead_spring_system.py
def generate_data_file(self) -> None:
    """Generate the LAMMPS data file (and input script) for the mixture
    (direct backend)."""
    self._require_species()

    # Generate positions
    if self._positions is None:
        if self._generation_method == "saw":
            if not self.saw_generate(self._saw_config):
                logger.warning("SAW failed, falling back to geometric placement")
                self._generate_geometric_positions()
        elif self._generation_method == "mc":
            self._generate_geometric_positions()
            self.equilibrate(self._mc_config)
        else:
            self._generate_geometric_positions()

    assert self._chain_architectures is not None
    assert self._chain_indices is not None

    chain_triplets = self._chain_triplets()
    chain_bead_types = [arch.bead_types for arch in self._chain_architectures]

    placed = self._placed_fillers or []
    total_atoms = sum(arch.n_beads for arch in self._chain_architectures)
    total_atoms += sum(len(p.positions) for p in placed)
    total_bonds = sum(arch.n_bonds for arch in self._chain_architectures)
    total_angles = sum(len(t) for t in chain_triplets)

    n_atom_types = len(self.bead_types)
    angle_type_map = (
        build_angle_type_map(chain_bead_types, chain_triplets)
        if self.use_angles else {}
    )
    n_angle_types = len(angle_type_map)

    box_size = self._calculate_box_size()

    with open(f"{self.path}/polymer.data", 'w') as f:
        # Header
        f.write("LAMMPS Bead-Spring Polymer Data File (mixture)\n\n")
        f.write(f"{total_atoms} atoms\n")
        f.write(f"{total_bonds} bonds\n")
        if self.use_angles:
            f.write(f"{total_angles} angles\n")
        f.write("\n")
        f.write(f"{n_atom_types} atom types\n")
        f.write("1 bond types\n")
        if self.use_angles:
            f.write(f"{n_angle_types} angle types\n")
        f.write("\n")

        # Box dimensions (exact with CG fillers: the filler-aware SAW
        # checks overlaps with the periodic image of this box)
        lo = f"{-box_size/2:.6f}" if placed else f"{-box_size/2:.1f}"
        hi = f"{box_size/2:.6f}" if placed else f"{box_size/2:.1f}"
        f.write(f"{lo} {hi} xlo xhi\n")
        f.write(f"{lo} {hi} ylo yhi\n")
        f.write(f"{lo} {hi} zlo zhi\n\n")

        # Masses
        f.write("Masses\n\n")
        for bt in self.bead_types:
            type_id = self._bead_type_id[bt.name]
            f.write(f"{type_id} {bt.mass:.3f}  # {bt.name}\n")
        f.write("\n")

        # Atoms section: atom-ID molecule-ID atom-type x y z
        f.write("Atoms  # molecular\n\n")
        atom_id = 1
        for chain_idx, ((start, end), arch) in enumerate(
            zip(self._chain_indices, self._chain_architectures)
        ):
            for local_bead, global_idx in enumerate(range(start, end)):
                pos = self._positions[global_idx]
                bead_name = arch.bead_types[local_bead]
                type_id = self._bead_type_id[bead_name]
                f.write(
                    f"{atom_id} {chain_idx + 1} {type_id} "
                    f"{pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n"
                )
                atom_id += 1
        # CG fillers: one molecule per particle, after the chains
        for k, p in enumerate(placed):
            mol_id = len(self._chain_architectures) + k + 1
            type_id = self._bead_type_id[p.filler.bead_type]
            for pos in p.positions:
                f.write(
                    f"{atom_id} {mol_id} {type_id} "
                    f"{pos[0]:.3f} {pos[1]:.3f} {pos[2]:.3f}\n"
                )
                atom_id += 1

        # Bonds
        f.write("\nBonds\n\n")
        bond_id = 1
        atom_offset = 0
        for arch in self._chain_architectures:
            for i, j in arch.bonds:
                f.write(
                    f"{bond_id} 1 {atom_offset + i + 1} {atom_offset + j + 1}\n"
                )
                bond_id += 1
            atom_offset += arch.n_beads

        # Angles
        if self.use_angles:
            from .bead_spring import canonical_bead_triplet
            f.write("\nAngles\n\n")
            angle_id = 1
            atom_offset = 0
            for arch, triplets in zip(self._chain_architectures, chain_triplets):
                for i, j, k in triplets:
                    triplet = canonical_bead_triplet(
                        arch.bead_types[i],
                        arch.bead_types[j],
                        arch.bead_types[k],
                    )
                    angle_type_id = angle_type_map[triplet]
                    f.write(
                        f"{angle_id} {angle_type_id} "
                        f"{atom_offset + i + 1} {atom_offset + j + 1} "
                        f"{atom_offset + k + 1}\n"
                    )
                    angle_id += 1
                atom_offset += arch.n_beads

    # LAMMPS input script
    write_lammps_input_script(
        path=self.path,
        bead_types=self.bead_types,
        pair_coeffs=self._pair_coeffs,
        bond_style=self.bond_style,
        k_bond=self.k_bond,
        bond_length=self.bond_length,
        fene_r0=self.fene_r0,
        pair_style=self._pair_style,
        use_angles=self.use_angles,
        angle_type_map=angle_type_map,
        angle_types=self._angle_types,
        default_k_angle=self.default_k_angle,
        default_theta0=self.default_theta0,
        fillers=self._filler_groups(numeric=True) if placed else None,
    )
    logger.info(f"Generated bead-spring mixture files in {self.path}")

generate_moltemplate(run_moltemplate: bool = True) -> Path

Generate moltemplate .lt files (and optionally run moltemplate) for this mixture.

Each chain becomes its own moltemplate object with generated coordinates; species share the bead-type table, so mixed systems (rings + stars + combs + ...) land in one system.data.

Parameters:

Name Type Description Default
run_moltemplate bool

Run the bundled moltemplate after writing files (produces system.data, system.in.init/settings).

True

Returns:

Type Description
Path

Path to the moltemplate directory.

Source code in AutoPoly/models/bead_spring_system.py
def generate_moltemplate(self, run_moltemplate: bool = True) -> Path:
    """
    Generate moltemplate .lt files (and optionally run moltemplate) for
    this mixture.

    Each chain becomes its own moltemplate object with generated
    coordinates; species share the bead-type table, so mixed systems
    (rings + stars + combs + ...) land in one system.data.

    Args:
        run_moltemplate: Run the bundled moltemplate after writing
            files (produces system.data, system.in.init/settings).

    Returns:
        Path to the moltemplate directory.
    """
    from .bead_spring import canonical_bead_triplet, resolve_angle_params
    from .bead_spring_lt import generate_moltemplate_files

    self._require_species()

    # Ensure positions exist (same logic as generate_data_file)
    if self._positions is None:
        if self._generation_method == "saw":
            if not self.saw_generate(self._saw_config):
                logger.warning("SAW failed, falling back to geometric placement")
                self._generate_geometric_positions()
        elif self._generation_method == "mc":
            self._generate_geometric_positions()
            self.equilibrate(self._mc_config)
        else:
            self._generate_geometric_positions()

    assert self._chain_architectures is not None
    assert self._chain_indices is not None

    chain_triplets = self._chain_triplets()
    chain_bead_types = [arch.bead_types for arch in self._chain_architectures]
    angle_type_map = (
        build_angle_type_map(chain_bead_types, chain_triplets)
        if self.use_angles else {}
    )

    box_size = self._calculate_box_size()

    return generate_moltemplate_files(
        path=self.path,
        bead_types=self.bead_types,
        chain_architectures=self._chain_architectures,
        positions=self._positions,
        chain_indices=self._chain_indices,
        box_size=box_size,
        pair_coeffs=self._pair_coeffs,
        bond_style=self.bond_style,
        k_bond=self.k_bond,
        bond_length=self.bond_length,
        fene_r0=self.fene_r0,
        pair_style=self._pair_style,
        use_angles=self.use_angles,
        angle_type_map=angle_type_map,
        resolve_angle_params=lambda t: resolve_angle_params(
            t, self._angle_types, self.default_k_angle, self.default_theta0
        ),
        include_branch_angles=self.include_branch_angles,
        canonical_triplet=canonical_bead_triplet,
        run_moltemplate=run_moltemplate,
        fillers=((self._placed_fillers, self._filler_groups(numeric=False))
                 if self._placed_fillers else None),
    )

get_system_info() -> dict

Get comprehensive information about the bead-spring mixture.

Returns:

Type Description
dict

Dictionary containing system properties.

Source code in AutoPoly/models/bead_spring_system.py
def get_system_info(self) -> dict:
    """
    Get comprehensive information about the bead-spring mixture.

    Returns:
        Dictionary containing system properties.
    """
    chain_triplets = (
        [
            arch.angle_triplets(include_branch=self.include_branch_angles)
            for arch, n, _ in self._species for _ in range(n)
        ]
        if self.use_angles else []
    )
    info = {
        'name': self.name,
        'n_species': self.n_species,
        'n_chains': self.n_chains,
        'species': [
            {
                'name': sname,
                'architecture': arch.name,
                'n_chains': n,
                'n_beads_per_chain': arch.n_beads,
                'n_bonds_per_chain': arch.n_bonds,
                'is_branched': arch.is_branched,
            }
            for arch, n, sname in self._species
        ],
        'total_atoms': self.total_beads,
        'total_bonds': sum(arch.n_bonds * n for arch, n, _ in self._species),
        'total_angles': sum(len(t) for t in chain_triplets),
        'bond_style': self.bond_style,
        'bond_length': self.bond_length,
        'k_bond': self.k_bond,
        'use_angles': self.use_angles,
        'bead_types': [bt.name for bt in self.bead_types],
        'output_path': self.path,
    }
    if self._fillers:
        from ..nanoparticles.cg import summary
        if self._placed_fillers:
            info['fillers'] = summary(
                self._placed_fillers, self._calculate_box_size()
            )
        else:
            info['fillers'] = {
                'species': {f.name: {'count': f.count, 'radius': f.radius}
                            for f in self._fillers},
                'n_particles': self.n_fillers,
            }
    return info

Moltemplate backend

AutoPoly.models.bead_spring_lt

Moltemplate backend for bead-spring models.

Emits .lt files mirroring AutoPoly's atomistic pipeline conventions (monomer .lt objects, per-chain polymer .lt objects with explicit coordinates and "Data Bond List"/"Data Angles" sections, and a system.lt), then optionally runs the bundled moltemplate to produce system.data + system.in.init/settings.

Layout produced under <path>/moltemplate/::

bead_spring.lt      CG force field: masses, styles, pair/bond/angle coeffs
bead_<Type>.lt      one single-bead monomer object per bead type
chains.lt           one object per chain: beads at generated coordinates
                    + explicit bond list + typed angle list
fillers.lt          (CG fillers only) one rigid particle object each
                    + filler groups in "In Settings"
system.lt           instantiates every chain + Data Boundary
in.polymer          LAMMPS driver (includes system.in.init/settings)

Because coordinates are generated by the Python SAW/MC machinery before .lt emission, arbitrary architectures (stars, combs, rings, mixtures) work uniformly: the graph edge list becomes "Data Bond List" entries and graph angle triplets become "Data Angles" entries with per-triplet @angle: types (branch angles fully configurable).

Functions:

Name Description
write_bead_spring_lt

Write bead_spring.lt: the coarse-grained force-field object.

write_bead_lt

Write one single-bead monomer object for a bead type.

write_chains_lt

Write chains.lt: one moltemplate object per chain with beads at their

write_fillers_lt

Write fillers.lt: one object (one molecule ID) per placed CG filler

write_system_lt

Write system.lt: imports, one instance per chain (and CG filler),

write_moltemplate_input_script

Write in.polymer for the moltemplate backend.

generate_moltemplate_files

Generate all moltemplate .lt files for a bead-spring system and

write_bead_spring_lt(filepath: Path, bead_types: List[BeadType], pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]], bond_style: str, k_bond: float, bond_length: float, fene_r0: float, pair_style: str, use_angles: bool, angle_type_map: Dict[Tuple[str, str, str], int], resolve_angle_params: Callable[[Tuple[str, str, str]], Tuple[float, float]]) -> None

Write bead_spring.lt: the coarse-grained force-field object.

Atom types are named @atom:<bead_name>; the single bond type is @bond:bs1; angle types are @angle:at<id> per canonical triplet.

Source code in AutoPoly/models/bead_spring_lt.py
def write_bead_spring_lt(
    filepath: Path,
    bead_types: List[BeadType],
    pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]],
    bond_style: str,
    k_bond: float,
    bond_length: float,
    fene_r0: float,
    pair_style: str,
    use_angles: bool,
    angle_type_map: Dict[Tuple[str, str, str], int],
    resolve_angle_params: Callable[[Tuple[str, str, str]], Tuple[float, float]],
) -> None:
    """
    Write bead_spring.lt: the coarse-grained force-field object.

    Atom types are named ``@atom:<bead_name>``; the single bond type is
    ``@bond:bs1``; angle types are ``@angle:at<id>`` per canonical triplet.
    """
    max_sigma = max(bt.sigma for bt in bead_types)
    if pair_style == "wca":
        cutoff = (2 ** (1 / 6)) * max_sigma
    else:
        cutoff = 2.5 * max_sigma

    with open(filepath, "w") as f:
        f.write("# Coarse-grained bead-spring force field\n")
        f.write("# Auto-generated by AutoPoly\n\n")
        f.write("BeadSpringFF {\n\n")

        # Atom type names
        f.write("  # Atom type definitions\n")
        for bt in bead_types:
            f.write(f"  # @atom:{bt.name}  mass={bt.mass}\n")
        f.write("\n")

        # Masses
        f.write('  write_once("Data Masses") {\n')
        for bt in bead_types:
            f.write(f"    @atom:{bt.name} {bt.mass:.3f}\n")
        f.write("  }\n\n")

        # Init: units, atom_style, styles
        f.write('  write_once("In Init") {\n')
        f.write("    units lj\n")
        f.write("    atom_style full\n")
        f.write(f"    pair_style lj/cut {cutoff:.5f}\n")
        if bond_style == "fene":
            f.write("    bond_style fene\n")
            f.write("    special_bonds fene\n")
        else:
            f.write("    bond_style harmonic\n")
        if use_angles:
            f.write("    angle_style harmonic\n")
        f.write("  }\n\n")

        # Settings: coeffs
        f.write('  write_once("In Settings") {\n')
        for (i, j), coeff in sorted(pair_coeffs.items()):
            eps, sig = coeff[:2]
            rc = f" {coeff[2]:.5f}" if len(coeff) > 2 else ""
            name_i = bead_types[i - 1].name
            name_j = bead_types[j - 1].name
            f.write(
                f"    pair_coeff @atom:{name_i} @atom:{name_j} "
                f"{eps:.4f} {sig:.4f}{rc}\n"
            )
        if pair_style == "wca":
            f.write("    pair_modify shift yes\n")

        if bond_style == "fene":
            eps = bead_types[0].epsilon
            sig = bead_types[0].sigma
            f.write(
                f"    bond_coeff @bond:bs1 {k_bond:.1f} {fene_r0:.4f} "
                f"{eps:.4f} {sig:.4f}\n"
            )
        else:
            f.write(f"    bond_coeff @bond:bs1 {k_bond:.1f} {bond_length:.4f}\n")

        if use_angles:
            for triplet, type_id in sorted(
                angle_type_map.items(), key=lambda x: x[1]
            ):
                k, theta0 = resolve_angle_params(triplet)
                triplet_str = "-".join(triplet)
                f.write(
                    f"    angle_coeff @angle:at{type_id} {k:.4f} "
                    f"{theta0:.1f}  # {triplet_str}\n"
                )
        f.write("  }\n")
        f.write("}\n")

write_bead_lt(filepath: Path, bead_type: BeadType) -> None

Write one single-bead monomer object for a bead type.

Source code in AutoPoly/models/bead_spring_lt.py
def write_bead_lt(filepath: Path, bead_type: BeadType) -> None:
    """Write one single-bead monomer object for a bead type."""
    with open(filepath, "w") as f:
        f.write(f'import "bead_spring.lt"\n')
        f.write(f"bead_{bead_type.name} inherits BeadSpringFF {{\n")
        f.write('  write("Data Atoms") {\n')
        f.write(
            f"    $atom:b $mol:... @atom:{bead_type.name} 0.0 0.0 0.0 0.0\n"
        )
        f.write("  }\n")
        f.write(f"}}  # bead_{bead_type.name}\n")

write_chains_lt(filepath: Path, chain_architectures: List[BeadArchitecture], positions: List[np.ndarray], chain_indices: List[Tuple[int, int]], use_angles: bool, angle_type_map: Dict[Tuple[str, str, str], int], include_branch_angles: bool, canonical_triplet: Callable[[str, str, str], Tuple[str, str, str]]) -> None

Write chains.lt: one moltemplate object per chain with beads at their generated coordinates, explicit "Data Bond List" entries from the graph edge list, and typed "Data Angles" entries from graph triplets.

Source code in AutoPoly/models/bead_spring_lt.py
def write_chains_lt(
    filepath: Path,
    chain_architectures: List[BeadArchitecture],
    positions: List[np.ndarray],
    chain_indices: List[Tuple[int, int]],
    use_angles: bool,
    angle_type_map: Dict[Tuple[str, str, str], int],
    include_branch_angles: bool,
    canonical_triplet: Callable[[str, str, str], Tuple[str, str, str]],
) -> None:
    """
    Write chains.lt: one moltemplate object per chain with beads at their
    generated coordinates, explicit "Data Bond List" entries from the
    graph edge list, and typed "Data Angles" entries from graph triplets.
    """
    with open(filepath, "w") as f:
        f.write('import "bead_spring.lt"\n')
        seen_imports = set()
        for arch in chain_architectures:
            for bt_name in arch.bead_types:
                if bt_name not in seen_imports:
                    f.write(f'import "bead_{bt_name}.lt"\n')
                    seen_imports.add(bt_name)
        f.write("\n")

        for chain_idx, (arch, (start, end)) in enumerate(
            zip(chain_architectures, chain_indices)
        ):
            obj = f"chain_{chain_idx + 1}"
            f.write(f"{obj} inherits BeadSpringFF {{\n")
            f.write("  create_var {$mol}\n\n")

            # Bead instances at generated coordinates
            for local_bead, global_idx in enumerate(range(start, end)):
                pos = positions[global_idx]
                bt_name = arch.bead_types[local_bead]
                f.write(
                    f"  bead[{local_bead}] = new bead_{bt_name}"
                    f".move({pos[0]:.4f},{pos[1]:.4f},{pos[2]:.4f})\n"
                )
            f.write("\n")

            # Bonds (all share the single @bond:bs1 type)
            f.write('  write("Data Bonds") {\n')
            for bond_idx, (i, j) in enumerate(arch.bonds):
                f.write(
                    f"    $bond:b{bond_idx + 1} @bond:bs1 "
                    f"$atom:bead[{i}]/b $atom:bead[{j}]/b\n"
                )
            f.write("  }\n")

            # Angles with per-triplet @angle types (branch-aware)
            if use_angles:
                triplets = arch.angle_triplets(include_branch=include_branch_angles)
                if triplets:
                    f.write("\n")
                    f.write('  write("Data Angles") {\n')
                    for angle_idx, (i, j, k) in enumerate(triplets):
                        triplet = canonical_triplet(
                            arch.bead_types[i],
                            arch.bead_types[j],
                            arch.bead_types[k],
                        )
                        type_id = angle_type_map[triplet]
                        f.write(
                            f"    $angle:a{angle_idx + 1} @angle:at{type_id} "
                            f"$atom:bead[{i}]/b $atom:bead[{j}]/b "
                            f"$atom:bead[{k}]/b\n"
                        )
                    f.write("  }\n")
            f.write(f"}}  # {obj} ({arch.name})\n\n")

write_fillers_lt(filepath: Path, placed, groups: Dict[str, List[str]]) -> None

Write fillers.lt: one object (one molecule ID) per placed CG filler with its beads at world coordinates, plus the filler groups (@atom: types resolved by moltemplate) in "In Settings".

Source code in AutoPoly/models/bead_spring_lt.py
def write_fillers_lt(filepath: Path, placed, groups: Dict[str, List[str]]) -> None:
    """
    Write fillers.lt: one object (one molecule ID) per placed CG filler
    with its beads at world coordinates, plus the filler groups
    (``@atom:`` types resolved by moltemplate) in "In Settings".
    """
    from ..nanoparticles import cg
    with open(filepath, "w") as f:
        f.write('import "bead_spring.lt"\n')
        for bt_name in sorted({p.filler.bead_type for p in placed}):
            f.write(f'import "bead_{bt_name}.lt"\n')
        f.write("\n")
        for k, p in enumerate(placed):
            f.write(f"filler_{k + 1} inherits BeadSpringFF {{\n")
            f.write("  create_var {$mol}\n")
            for b, pos in enumerate(p.positions):
                f.write(
                    f"  bead[{b}] = new bead_{p.filler.bead_type}"
                    f".move({pos[0]:.4f},{pos[1]:.4f},{pos[2]:.4f})\n"
                )
            f.write(f"}}  # filler_{k + 1} ({p.filler.name})\n\n")
        tokens = {m: [f"@atom:{t}" for t in ts] for m, ts in groups.items()}
        f.write('write_once("In Settings") {\n')
        for line in cg.group_lines(tokens):
            f.write(f"  {line}\n")
        f.write("}\n")

write_system_lt(filepath: Path, n_chains: int, box_size: float, bead_type_names: List[str], n_fillers: int = 0) -> None

Write system.lt: imports, one instance per chain (and CG filler), Data Boundary.

Source code in AutoPoly/models/bead_spring_lt.py
def write_system_lt(
    filepath: Path,
    n_chains: int,
    box_size: float,
    bead_type_names: List[str],
    n_fillers: int = 0,
) -> None:
    """Write system.lt: imports, one instance per chain (and CG filler),
    Data Boundary."""
    with open(filepath, "w") as f:
        f.write('import "bead_spring.lt"\n')
        for bt_name in bead_type_names:
            f.write(f'import "bead_{bt_name}.lt"\n')
        f.write('import "chains.lt"\n')
        if n_fillers:
            f.write('import "fillers.lt"\n')
        f.write("\n")
        for chain_idx in range(n_chains):
            f.write(f"chains[{chain_idx}] = new chain_{chain_idx + 1}\n")
        for k in range(n_fillers):
            f.write(f"fillers[{k}] = new filler_{k + 1}\n")
        f.write("\n")
        f.write('write_once("Data Boundary") {\n')
        f.write(f"   {-box_size / 2:.4f}  {box_size / 2:.4f}  xlo xhi\n")
        f.write(f"   {-box_size / 2:.4f}  {box_size / 2:.4f}  ylo yhi\n")
        f.write(f"   {-box_size / 2:.4f}  {box_size / 2:.4f}  zlo zhi\n")
        f.write("}\n")

write_moltemplate_input_script(filepath: Path, fillers: Optional[Dict[str, List[str]]] = None) -> None

Write in.polymer for the moltemplate backend.

Styles come from system.in.init and coeffs from system.in.settings (both generated by moltemplate from bead_spring.lt). fillers (motion -> bead types) adds the CG-filler run commands; the groups themselves are defined in system.in.settings (fillers.lt).

Source code in AutoPoly/models/bead_spring_lt.py
def write_moltemplate_input_script(
    filepath: Path, fillers: Optional[Dict[str, List[str]]] = None
) -> None:
    """
    Write in.polymer for the moltemplate backend.

    Styles come from system.in.init and coeffs from system.in.settings
    (both generated by moltemplate from bead_spring.lt). ``fillers``
    (motion -> bead types) adds the CG-filler run commands; the groups
    themselves are defined in system.in.settings (fillers.lt).
    """
    if fillers:
        from ..nanoparticles import cg
    with open(filepath, "w") as f:
        f.write("# LAMMPS input script for bead-spring polymer (moltemplate backend)\n")
        f.write("# Auto-generated by AutoPoly\n\n")

        f.write("boundary        p p p\n\n")

        # styles (atom_style full, bond style) must precede read_data
        f.write("include         system.in.init\n")
        f.write("read_data       system.data\n")
        f.write("include         system.in.settings\n\n")

        # Larger skin (2.0) for FENE to prevent lost atoms
        f.write("neighbor        2.0 bin\n")
        f.write("neigh_modify    every 2 delay 4 check yes\n\n")

        if fillers:
            f.write(cg.SETUP + "\n")
            f.write(cg.THERMO)
        else:
            f.write("thermo_style    custom step temp pe ke etotal press vol density\n")
        f.write("thermo          1000\n\n")

        f.write("dump            1 all custom 1000 dump.lammpstrj id type mol x y z\n")
        f.write("dump_modify     1 sort id\n\n")

        f.write("# Energy minimization\n")
        if fillers:
            f.write(cg.HOLD)
        f.write("minimize        1.0e-4 1.0e-6 1000 10000\n")
        if fillers:
            f.write(cg.UNHOLD)
        f.write("write_restart   min.restart\n")
        f.write("write_data      min.data\n")
        f.write("reset_timestep  0\n\n")

        f.write("# Production MD\n")
        f.write("timestep        0.001\n")
        if fillers:
            f.write(cg.production_lines(fillers))
        else:
            f.write("fix             1 all nvt temp 1.0 1.0 0.1 tchain 3\n")
        f.write("run             100000\n")
        f.write("write_restart   prod.restart\n")
        f.write("write_data      prod.data\n")
        if fillers:
            f.write(cg.compression_hint(fillers))

generate_moltemplate_files(path: str, bead_types: List[BeadType], chain_architectures: List[BeadArchitecture], positions: List[np.ndarray], chain_indices: List[Tuple[int, int]], box_size: float, pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]], bond_style: str, k_bond: float, bond_length: float, fene_r0: float, pair_style: str, use_angles: bool, angle_type_map: Dict[Tuple[str, str, str], int], resolve_angle_params: Callable[[Tuple[str, str, str]], Tuple[float, float]], include_branch_angles: bool, canonical_triplet: Callable[[str, str, str], Tuple[str, str, str]], run_moltemplate: bool = True, fillers: Optional[Tuple[list, Dict[str, List[str]]]] = None) -> Path

Generate all moltemplate .lt files for a bead-spring system and optionally run moltemplate.

All structural information comes from the per-chain architectures (graph edge lists and angle triplets) and the generated coordinates, so arbitrary architectures and mixtures are supported uniformly.

Parameters:

Name Type Description Default
path str

Project directory; files go under <path>/moltemplate/.

required
bead_types List[BeadType]

Shared bead type table.

required
chain_architectures List[BeadArchitecture]

One BeadArchitecture per chain.

required
positions List[ndarray]

Flat position list (global indexing).

required
chain_indices List[Tuple[int, int]]

(start, end) per chain into positions.

required
box_size float

Cubic box side length.

required
pair_coeffs Dict[Tuple[int, int], Tuple[float, float]]

Mixed pair coefficients (1-based type ids).

required
bond_style str

"harmonic" or "fene".

required
k_bond float

Bond force constant.

required
bond_length float

Equilibrium bond length (harmonic).

required
fene_r0 float

FENE maximum extension.

required
pair_style str

"lj" or "wca".

required
use_angles bool

Whether angles are included.

required
angle_type_map Dict[Tuple[str, str, str], int]

Canonical triplet -> angle type id.

required
resolve_angle_params Callable[[Tuple[str, str, str]], Tuple[float, float]]

triplet -> (k, theta0).

required
include_branch_angles bool

Whether branch triplets are included.

required
canonical_triplet Callable[[str, str, str], Tuple[str, str, str]]

(t1, t2, t3) -> canonical triplet.

required
run_moltemplate bool

Run the bundled moltemplate after writing files.

True
fillers Optional[Tuple[list, Dict[str, List[str]]]]

Optional (placed CG fillers, motion -> bead types) from AutoPoly.nanoparticles.cg.

None

Returns:

Type Description
Path

Path to the moltemplate directory.

Raises:

Type Description
WorkflowError

If moltemplate fails.

Source code in AutoPoly/models/bead_spring_lt.py
def generate_moltemplate_files(
    path: str,
    bead_types: List[BeadType],
    chain_architectures: List[BeadArchitecture],
    positions: List[np.ndarray],
    chain_indices: List[Tuple[int, int]],
    box_size: float,
    pair_coeffs: Dict[Tuple[int, int], Tuple[float, float]],
    bond_style: str,
    k_bond: float,
    bond_length: float,
    fene_r0: float,
    pair_style: str,
    use_angles: bool,
    angle_type_map: Dict[Tuple[str, str, str], int],
    resolve_angle_params: Callable[[Tuple[str, str, str]], Tuple[float, float]],
    include_branch_angles: bool,
    canonical_triplet: Callable[[str, str, str], Tuple[str, str, str]],
    run_moltemplate: bool = True,
    fillers: Optional[Tuple[list, Dict[str, List[str]]]] = None,
) -> Path:
    """
    Generate all moltemplate .lt files for a bead-spring system and
    optionally run moltemplate.

    All structural information comes from the per-chain architectures
    (graph edge lists and angle triplets) and the generated coordinates,
    so arbitrary architectures and mixtures are supported uniformly.

    Args:
        path: Project directory; files go under ``<path>/moltemplate/``.
        bead_types: Shared bead type table.
        chain_architectures: One BeadArchitecture per chain.
        positions: Flat position list (global indexing).
        chain_indices: (start, end) per chain into ``positions``.
        box_size: Cubic box side length.
        pair_coeffs: Mixed pair coefficients (1-based type ids).
        bond_style: "harmonic" or "fene".
        k_bond: Bond force constant.
        bond_length: Equilibrium bond length (harmonic).
        fene_r0: FENE maximum extension.
        pair_style: "lj" or "wca".
        use_angles: Whether angles are included.
        angle_type_map: Canonical triplet -> angle type id.
        resolve_angle_params: triplet -> (k, theta0).
        include_branch_angles: Whether branch triplets are included.
        canonical_triplet: (t1, t2, t3) -> canonical triplet.
        run_moltemplate: Run the bundled moltemplate after writing files.
        fillers: Optional (placed CG fillers, motion -> bead types) from
            AutoPoly.nanoparticles.cg.

    Returns:
        Path to the moltemplate directory.

    Raises:
        WorkflowError: If moltemplate fails.
    """
    moltemplate_dir = Path(path) / "moltemplate"
    if moltemplate_dir.exists():
        import shutil
        shutil.rmtree(moltemplate_dir)
    moltemplate_dir.mkdir(parents=True, exist_ok=True)

    write_bead_spring_lt(
        moltemplate_dir / "bead_spring.lt",
        bead_types, pair_coeffs, bond_style, k_bond, bond_length, fene_r0,
        pair_style, use_angles, angle_type_map, resolve_angle_params,
    )
    for bt in bead_types:
        write_bead_lt(moltemplate_dir / f"bead_{bt.name}.lt", bt)
    write_chains_lt(
        moltemplate_dir / "chains.lt",
        chain_architectures, positions, chain_indices,
        use_angles, angle_type_map, include_branch_angles, canonical_triplet,
    )
    placed, groups = fillers if fillers else ([], None)
    if placed:
        write_fillers_lt(moltemplate_dir / "fillers.lt", placed, groups)
    write_system_lt(
        moltemplate_dir / "system.lt",
        len(chain_architectures), box_size,
        [bt.name for bt in bead_types],
        n_fillers=len(placed),
    )
    write_moltemplate_input_script(moltemplate_dir / "in.polymer", groups)

    if run_moltemplate:
        moltemplate_sh = _moltemplate_scripts_dir() / "moltemplate.sh"
        process = subprocess.run(
            ["bash", str(moltemplate_sh), "-nocheck", "./system.lt"],
            cwd=moltemplate_dir,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
        )
        if process.returncode != 0:
            logger.error("Moltemplate execution failed:")
            logger.error(process.stderr)
            stdout_lines = process.stdout.splitlines()
            if stdout_lines:
                logger.error("Last output lines:")
                for line in stdout_lines[-5:]:
                    logger.error(line)
            raise WorkflowError("Moltemplate execution failed")

        for required in ("system.data", "system.in.settings", "system.in.init"):
            if not (moltemplate_dir / required).exists():
                raise WorkflowError(
                    f"Moltemplate did not generate {required} in {moltemplate_dir}"
                )
        logger.info(f"Moltemplate output generated in {moltemplate_dir}")

    return moltemplate_dir