Nonlinear polariton freezing and condensation in a multimode Fabry-Perot cavity

Authors: Xinwei Ji, Tao E. Li

In this tutorial, we will try to understand how vibrational polaritons transport and condense inside a planar Fabry-Perot cavity. Specifically, we will adopt the built-in GPU molecular dynamics drivers inside MaxwellLink for these calculations (while external LAMMPS drivers are not needed).

This tutorial aims to deliver a few pieces of results in the following two papers:

  1. Xinwei Ji, Tao E. Li. Nonlinear Freezing of Vibrational Polariton Transport via Mesoscale Simulations. Nano Lett. 26 (38), 13012–13018 (2026).

  2. Xinwei Ji, Tao E. Li. Atomistic Emergence of Vibrational Polariton Condensation. arXiv:2610.41133 (2026).

To reduce the computational cost, we will focus mostly on a 1D Fabry-Perot cavity. We expect a cusomer-grade NVIDIA graphics card (such as RTX 5070 Ti) for running this tutorial.

1. 1D nonlinear freezing of polariton transport

This section sets up a 1D Fabry-Perot model for studying the polariton transport discussed in the first paper. Here, a short laser pulse locally excites the cavity mirrors.

CO₂ molecules between two mirrors, with a laser launching a wave along the cavity.

1.1. Initialize the cavity and molecular drivers

The light-matter model consists of 144 photon modes coupled to 144 molecular cells distributed along the x-axis. Each cell contains 36 CO2 molecules under periodic boundary conditions described by an anharmonic empirical force field (co2jcp2021). The cavity frequency at normal incidence is 2320 cm-1, at resonance with the asymmetric bending mode of CO2. Along the in-plane direction, we set the cavity mode frequency spacing to be 12.5 cm-1. We further adopt the absorbing boundary conditions along the cavity plane to avoid polariton reflection near the boundaries (with parameter abc_cutoff=0.05).

In our simulations, the multimode-cavity EM solver runs on CPU, whereas the heavy molecular dynamics are propagated on GPU. They connect with each other through the AggregatedSocketHub socket hub in MaxwellLink for communication.

[ ]:
import numpy as np
import maxwelllink as mxl

from maxwelllink.em_solvers.multimode_cavity import (
    FabryPerotCavity,
    MultiModeSimulation,
)
from maxwelllink.sockets import (
    AggregatedSocketHub,
    get_available_host_port,
)
from maxwelllink.tools import gaussian_pulse, k_parallel_pulse
from maxwelllink.tools.harmonic_oscillator_helper import (
    MaxwellBoltzmannInitializer,
    LangevinThermostat,
)
from maxwelllink.units import unit

N_grid_freezing = 144
coupling_strength_freezing = 2.5e-5
damping_au_freezing = 0e-4
dt_fs_freezing = 0.5

# define the Fabry-Perot cavity parameters
fbcavity_freezing = FabryPerotCavity(
    frequency_au=2320*unit("cm_inv"),
    coupling_strength=coupling_strength_freezing,
    coupling_axis="xy",
    n_grid_x=N_grid_freezing,
    y_grid_1d=[0.0],
    delta_omega_x_au=12.5*unit("cm_inv"),
    delta_omega_y_au=0.0*unit("cm_inv"),
    n_mode_x=N_grid_freezing,
    n_mode_y=1,
    abc_cutoff=0.05,
    save_mode_functions=True,
)
print(f"Coupling strength: {coupling_strength_freezing:.3e} au")

# Initialize the communication protocal
host_freezing, port_freezing = get_available_host_port(localhost=True)
hub_freezing = AggregatedSocketHub(host=host_freezing, port=port_freezing, timeout=6000.0, latency=1e-3)
print(f"SocketHub listening on {host_freezing}:{port_freezing}")

# Define the abstract Molecules. One socket-side molecule represents one complete MD cell
molecule_list_freezing = []
for _ in range(N_grid_freezing):
    molecule_list_freezing.append(
        mxl.Molecule(hub=hub_freezing, rescaling_factor=1.0, store_additional_data=False)
    )

# Set up the necessary parameters for the communication protocol
hub_freezing.init_remote_bridges(
    molecule_list_freezing,
    molecules_per_bridge=N_grid_freezing,
    unix_prefix="freezing_",
    save_file="aggregation_freezing.json",
)
[MultiModeCavity] omega_parallel in cm-1 [  12.5   25.    37.5   50.    62.5   75.    87.5  100.   112.5  125.
  137.5  150.   162.5  175.   187.5  200.   212.5  225.   237.5  250.
  262.5  275.   287.5  300.   312.5  325.   337.5  350.   362.5  375.
  387.5  400.   412.5  425.   437.5  450.   462.5  475.   487.5  500.
  512.5  525.   537.5  550.   562.5  575.   587.5  600.   612.5  625.
  637.5  650.   662.5  675.   687.5  700.   712.5  725.   737.5  750.
  762.5  775.   787.5  800.   812.5  825.   837.5  850.   862.5  875.
  887.5  900.   912.5  925.   937.5  950.   962.5  975.   987.5 1000.
 1012.5 1025.  1037.5 1050.  1062.5 1075.  1087.5 1100.  1112.5 1125.
 1137.5 1150.  1162.5 1175.  1187.5 1200.  1212.5 1225.  1237.5 1250.
 1262.5 1275.  1287.5 1300.  1312.5 1325.  1337.5 1350.  1362.5 1375.
 1387.5 1400.  1412.5 1425.  1437.5 1450.  1462.5 1475.  1487.5 1500.
 1512.5 1525.  1537.5 1550.  1562.5 1575.  1587.5 1600.  1612.5 1625.
 1637.5 1650.  1662.5 1675.  1687.5 1700.  1712.5 1725.  1737.5 1750.
 1762.5 1775.  1787.5 1800. ]
[MultiModeCavity] omega_k in cm-1 [2320.03367432 2320.13469437 2320.30305133 2320.53873055 2320.84171153
 2321.21196792 2321.64946751 2322.15417232 2322.72603852 2323.36501652
 2324.07105098 2324.84408079 2325.68403916 2326.59085359 2327.56444594
 2328.60473245 2329.71162379 2330.88502505 2332.12483585 2333.43095034
 2334.80325724 2336.2416399  2337.74597636 2339.31613939 2340.95199652
 2342.65341013 2344.4202375  2346.25233085 2348.1495374  2350.11169947
 2352.1386545  2354.23023513 2356.38626927 2358.60658017 2360.89098647
 2363.23930231 2365.65133737 2368.12689694 2370.66578201 2373.26778936
 2375.93271159 2378.66033725 2381.45045088 2384.30283311 2387.21726075
 2390.19350681 2393.23134068 2396.33052812 2399.49083141 2402.71200938
 2405.99381753 2409.33600812 2412.7383302  2416.20052976 2419.72234977
 2423.30353031 2426.94380858 2430.64291906 2434.40059358 2438.21656134
 2442.0905491  2446.02228117 2450.01147956 2454.05786403 2458.16115216
 2462.32105949 2466.53729954 2470.80958392 2475.13762244 2479.52112312
 2483.95979235 2488.45333491 2493.00145407 2497.60385169 2502.26022827
 2506.97028303 2511.73371399 2516.55021806 2521.41949108 2526.34122794
 2531.31512262 2536.34086826 2541.41815725 2546.54668129 2551.72613146
 2556.9561983  2562.23657183 2567.56694168 2572.94699712 2578.37642713
 2583.85492046 2589.38216569 2594.9578513  2600.5816657  2606.25329736
 2611.97243477 2617.73876657 2623.55198157 2629.41176882 2635.31781765
 2641.26981772 2647.2674591  2653.31043227 2659.39842822 2665.53113844
 2671.70825503 2677.92947069 2684.1944788  2690.50297342 2696.8546494
 2703.24920235 2709.68632871 2716.1657258  2722.68709183 2729.25012595
 2735.8545283  2742.5        2749.18624324 2755.91296125 2762.6798584
 2769.48664016 2776.33301317 2783.21868526 2790.14336549 2797.10676414
 2804.10859276 2811.1485642  2818.22639261 2825.34179348 2832.49448367
 2839.68418138 2846.91060625 2854.17347931 2861.47252302 2868.8074613
 2876.17801953 2883.58392456 2891.02490477 2898.50069001 2906.01101168
 2913.5556027  2921.13419753 2928.74653222 2936.39234436]
[MultiModeCavity] smooth_x:
 [0.         0.00630853 0.16051358 0.46002142 0.77123146 0.97702263
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 1.         1.         1.         1.         1.         1.
 0.97702263 0.77123146 0.46002142 0.16051358 0.00630853 0.        ]
[MultiModeCavity] smooth_y:
 [1.]
[MultiModeCavity] Applying Absorbing Boundary Condition: True, cutoff: [0.05, 0.05]
Coupling strength: 2.500e-05 au
SocketHub listening on 127.0.0.1:57881
[Init Molecule] Under socket mode, registered molecule with ID 0
[SocketHub] Prepared 1 remote aggregate bridge(s); manifest saved to 'aggregation_freezing.json'.
[SocketHub] REMOTE BRIDGE 0: unix='freezing_0' group='freezing_0' molecules=144
[RemoteBridgeSpec(idx=0, group_id='freezing_0', unixsocket='freezing_0', n_molecules=144)]

1.2. Define the laser pulse

The pulse drives the y-polarized photon field. Its spatial center is x=0.2 (assuming the cavity plane spans [0, 1] in the units of cavity plane length Lx), with the spatial width set to 30% of the cavity plane length. The pulse frequency is set to 2438.84 cm-1, whereas the in-plane wave number of the pulse is 450 cm-1. This setting ensures that the pulse to excite the upper polariton branch near this in-plane wave number.

The pulse has a Gaussian envelope (centered at 0 fs and width 500 fs). During time 0 to 1000 fs, this pulse is turned on and then turned off afterwards.

[2]:
pulse_envelope_freezing = gaussian_pulse(
    amplitude_au=1.0,
    t0_au=0*unit("fs"),
    sigma_au=5e2*unit("fs"),
    t_start_au=0.0*unit("fs"),
    t_end_au=1e3*unit("fs"),
)

photon_source_freezing = k_parallel_pulse(
    cavity=fbcavity_freezing,
    envelope=pulse_envelope_freezing,
    omega_au=2438.84*unit("cm_inv"),
    k_parallel_au=36*12.5*unit("cm_inv"),
    direction="x",
    center=(0.2, 0.0),
    size=(0.3, 1.0),
    target="photon",
    amplitude_au=0.007,
)

1.3. Define the multimode cavity coupled to molecules

Here, we define a multimode cavity EM solver on the CPU. This EM solver connects to the molecules via the hub_freezing socket protocal.

[ ]:
rng_freezing = np.random.default_rng(seed=114514)
random_seed_freezing = rng_freezing.integers(1919810)

sim_freezing = MultiModeSimulation(
    hub=hub_freezing,
    molecules=molecule_list_freezing,
    dt_au=dt_fs_freezing*unit("fs"),
    damping_au=damping_au_freezing,
    include_dse=True,
    cavity_geometry=fbcavity_freezing,
    # here we assume that the pulse directly drives the cavity modes, which then couples to the molecules
    excited_mode_list=photon_source_freezing.excited_mode_list,
    photon_pulse_drive=photon_source_freezing,
    photon_pulse_axis="y",
    photon_partial_charge=0.066,
    # we set the cavity photons to obey a Maxwell-Boltzmann distribution at 300 K
    initializer=MaxwellBoltzmannInitializer(temperature_au=300.0*unit("K"), random_seed=random_seed_freezing),
    # always couple the cavity photon modes to a Langevin thermostat at 300 K, with a cavity loss lifetime of 5000 fs
    thermostat=LangevinThermostat(
        temperature_au=300.0*unit("K"),
        dt_au=dt_fs_freezing*unit("fs"),
        # cavity loss lifetime
        tau_au=5000*unit("fs"),
        random_seed=random_seed_freezing,
    ),
)
[LangevinThermostat] NVT thermostat enabled with T = 300.0 K = 0.0009500434689 a.u., Langevin tau = 5000.0 fs = 206706.866675 a.u.
[Maxwell-Boltzmann Initializer] Initializing positions with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.
[Maxwell-Boltzmann Initializer] Initializing momenta with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.

Now let’s define the molecular drivers. The default setting in MaxwellLink uses either mxl_driver (for a few external drivers) or mxl_bridge (for a large number of drivers) to initialize the molecular drivers. We can run this command in a separate bash script.

However, here in this notebook, we launch this bash command inside Python.

Note that this simulation will take about 4 minutes to finish on RTX 4090.

[ ]:
import shlex
import subprocess

# we can directly run this command in a new separate terminal (this setting allows the EM to connect to a wide range of molecular drivers, as the EM is not aware of the specific molecular drivers).
# Here, each molecular driver runs on GPU (pre-equilibrated for 10 ps before coupling to the EM)
command_freezing = """
mxl_bridge --info aggregation_freezing.json --idx 0 \
    --backend gpu --model md \
    --param "ff=co2jcp2021,thermostat=nve,temperature_K=300.0,pre_nvt=True,pre_nvt_duration_ps=10.0,reset_dipole=True,seed=114514"
"""

# local Python process to direclty run this command in this notebook
bridge_process_freezing = subprocess.Popen(shlex.split(command_freezing))

try:
    print("Waiting for MD initialization and pre-NVT equilibration (if enabled)...", flush=True)
    sim_freezing._ensure_socket_connections()
    print("MD initialization and pre-NVT equilibration are complete. Starting the coupled simulation.", flush=True)

    # Run the coupled simulation directly
    sim_freezing.run(
        steps=20001,
        record_history=True,
        record_filename=None,
        record_every_steps=200,
        # save the E field dynamics during the simulations
        record_list=['effective_efield'],
    )
finally:
    hub_freezing.stop()
    bridge_process_freezing.wait()
Waiting for MD initialization and pre-NVT equilibration (if enabled)...
[SocketHub] CONNECTED: aggregate group 'freezing_0' <- 127.0.0.1:42396
MD initialization and pre-NVT equilibration are complete. Starting the coupled simulation.
[MultiModeCavity] Recording history: True, to disk: False, record_every_steps: 200, record_max_steps: 101
[MultiModeCavity] Recording fields : none
[MultiModeCavity] Recording address: N/A, filename: N/A
[MultiModeCavity] Temporary folder : N/A
[MultiModeCavity] Completed 1000/20001 [5.0%] steps, time/step: 6.04e-03 seconds, remaining time: 114.83 seconds.
[MultiModeCavity] Completed 2000/20001 [10.0%] steps, time/step: 5.88e-03 seconds, remaining time: 107.30 seconds.
[MultiModeCavity] Completed 3000/20001 [15.0%] steps, time/step: 5.97e-03 seconds, remaining time: 101.39 seconds.
[MultiModeCavity] Completed 4000/20001 [20.0%] steps, time/step: 5.98e-03 seconds, remaining time: 95.49 seconds.
[MultiModeCavity] Completed 5000/20001 [25.0%] steps, time/step: 6.08e-03 seconds, remaining time: 89.85 seconds.
[MultiModeCavity] Completed 6000/20001 [30.0%] steps, time/step: 6.06e-03 seconds, remaining time: 84.02 seconds.
[MultiModeCavity] Completed 7000/20001 [35.0%] steps, time/step: 5.87e-03 seconds, remaining time: 77.78 seconds.
[MultiModeCavity] Completed 8000/20001 [40.0%] steps, time/step: 5.83e-03 seconds, remaining time: 71.58 seconds.
[MultiModeCavity] Completed 9000/20001 [45.0%] steps, time/step: 5.84e-03 seconds, remaining time: 65.47 seconds.
[MultiModeCavity] Completed 10000/20001 [50.0%] steps, time/step: 5.89e-03 seconds, remaining time: 59.46 seconds.
[MultiModeCavity] Completed 11000/20001 [55.0%] steps, time/step: 5.93e-03 seconds, remaining time: 53.50 seconds.
[MultiModeCavity] Completed 12000/20001 [60.0%] steps, time/step: 5.94e-03 seconds, remaining time: 47.55 seconds.
[MultiModeCavity] Completed 13000/20001 [65.0%] steps, time/step: 5.91e-03 seconds, remaining time: 41.59 seconds.
[MultiModeCavity] Completed 14000/20001 [70.0%] steps, time/step: 5.90e-03 seconds, remaining time: 35.63 seconds.
[MultiModeCavity] Completed 15000/20001 [75.0%] steps, time/step: 5.92e-03 seconds, remaining time: 29.69 seconds.
[MultiModeCavity] Completed 16000/20001 [80.0%] steps, time/step: 5.93e-03 seconds, remaining time: 23.75 seconds.
[MultiModeCavity] Completed 17000/20001 [85.0%] steps, time/step: 6.00e-03 seconds, remaining time: 17.83 seconds.
[MultiModeCavity] Completed 18000/20001 [90.0%] steps, time/step: 6.00e-03 seconds, remaining time: 11.89 seconds.
[MultiModeCavity] Completed 19000/20001 [95.0%] steps, time/step: 5.99e-03 seconds, remaining time: 5.95 seconds.
[MultiModeCavity] Completed 20000/20001 [100.0%] steps, time/step: 6.02e-03 seconds, remaining time: 0.01 seconds.
[SocketHub] DISCONNECTED: aggregate group 'freezing_0'

1.4. Plot the electric field

Now let’s read sim_freezing.effective_efield_history to plot the EM field dynamics from the completed simulation.

Here, we see that after a while of polariton propagation, the EM field ceases to propagate and freezes. This is because the upper polariton at finite in-plane wave number transfers population to that at the polariton band edge (with almost zero group velocity).

[ ]:
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LogNorm

# Select the y direction of the effective electric field from memory
sp_avg = (np.asarray(sim_freezing.effective_efield_history)[:, :, 1] ** 2).T
ntimes = sp_avg.shape[1]
time_ps_freezing = (
    1 + np.arange(ntimes) * sim_freezing.record_every_steps
) * sim_freezing.dt / unit("ps")
vmax = np.max(sp_avg)
vmin = vmax * 0.005

fig_freezing, ax_freezing = plt.subplots(figsize=(5.7, 4), layout="constrained")
pos = ax_freezing.imshow(
    sp_avg, aspect="auto", extent=[time_ps_freezing[0], time_ps_freezing[-1], 0, N_grid_freezing],
    origin="lower", cmap=cm.hot, interpolation="nearest",
    norm=LogNorm(vmin=vmin, vmax=vmax),
)

# the coeff is the analytical group velocity of this polariton in units of c (speed of light)
coeff = 0.11638023
t = time_ps_freezing[time_ps_freezing <= 5.2]
ax_freezing.plot(t, N_grid_freezing*0.2 + N_grid_freezing*0.75*coeff*t, "c--", lw=1.5)

ax_freezing.set_xlim(0, time_ps_freezing[-1])
ax_freezing.set_ylim(0, N_grid_freezing)
ax_freezing.set_yticks([0, N_grid_freezing / 2, N_grid_freezing])
ax_freezing.set_yticklabels([r"$0$", r"$200$", r"$400$"])
ax_freezing.set_xlabel("time [ps]", fontsize=12)
ax_freezing.set_ylabel(r"$L_x$ position [$\mu\mathrm{m}$]", fontsize=12)
ax_freezing.tick_params(labelsize=12)
ax_freezing.text(
    0.6, 0.95, r"$k_{\parallel}=450\ \mathrm{cm}^{-1}$",
    transform=ax_freezing.transAxes, fontsize=12, va="top", color="w",
)
ax_freezing.text(
    0.6, 0.85, r"$W_{\rm ph}=0.61$",
    transform=ax_freezing.transAxes, fontsize=12, va="top", color="w",
)
ax_freezing.text(
    0.98, 0.1, r"$E_0=7\times10^{-3}$ a.u.",
    transform=ax_freezing.transAxes, fontsize=12, va="top", ha="right", color="w",
)
ax_freezing.text(
    0.02, 0.1, r"$\tilde{v}_g=%.3f\,c$" % coeff,
    transform=ax_freezing.transAxes, fontsize=12, va="top", color="c",
)
cbar = fig_freezing.colorbar(pos, ax=ax_freezing, pad=0.04, fraction=0.055)
cbar.ax.tick_params(labelsize=12)
cbar.set_label(r"$|E_{\mathrm{eff},y}|^2$ [a.u.]", fontsize=12)
plt.show()

../../_images/tutorials_notebook_12_multimode_gpu_md_transport_condensation_10_0.png

2. 1D polariton condensation

This section follows the second paper listed above, aiming to reproduce the vibrational polariton condensation in a 1D Fabry-Perot multimode cavity.

Here we send a strong continuous-wave (CW) pulse with a large wave k-vector to excite the central region of the system throughout the simulation (unlike the Gaussian pulse above).

CO₂ molecules between two cavity mirrors, with a laser shining on a small region.

The same as above, the light-matter system consists of 144 photon modes coupled to 144 molecular cells, with 36 CO2 molecules in each cell. We tune the cavity frequency to 655 cm^-1, at resonance with the asymmetric bending of CO2. (Note that in the above paper, the productive simulations used 720 cavity photon modes coupled to 720 molecular cells.)

2.1. Initialize the cavity and molecular drivers

We largely follow the above numerical settings.

[ ]:
import numpy as np
import maxwelllink as mxl

from maxwelllink.em_solvers.multimode_cavity import (
    FabryPerotCavity,
    MultiModeSimulation,
)
from maxwelllink.sockets import (
    AggregatedSocketHub,
    get_available_host_port,
)
from maxwelllink.tools import k_parallel_pulse
from maxwelllink.tools.harmonic_oscillator_helper import (
    MaxwellBoltzmannInitializer,
    LangevinThermostat,
)
from maxwelllink.units import unit

fbcavity = FabryPerotCavity(
    frequency_au=655.0 * unit("cm_inv"),
    coupling_strength=1e-6 * np.sqrt(5),
    coupling_axis="xy",
    n_grid_x=144,
    y_grid_1d=[0.0],
    delta_omega_x_au=5.0 * unit("cm_inv"),
    delta_omega_y_au=0.0 * unit("cm_inv"),
    n_mode_x=144,
    n_mode_y=1,
    # we do not apply abosrbing boundary conditions here as no polariton propagation is observed
    abc_cutoff=0.0,
    save_mode_functions=True,
)

print(f"Coupling strength: {fbcavity.coupling_strength:.3e} au")

host, port = get_available_host_port(localhost=True)
hub = AggregatedSocketHub(host=host, port=port, timeout=6000.0, latency=1e-3)

molecule_list = []
for _ in range(fbcavity.n_grid):
    molecule_list.append(mxl.Molecule(hub=hub, rescaling_factor=1.0, store_additional_data=False))

hub.init_remote_bridges(
    molecule_list,
    molecules_per_bridge=fbcavity.n_grid,
    unix_prefix="bridge_",
    save_file="aggregation.json",
)
[MultiModeCavity] omega_parallel in cm-1 [  5.  10.  15.  20.  25.  30.  35.  40.  45.  50.  55.  60.  65.  70.
  75.  80.  85.  90.  95. 100. 105. 110. 115. 120. 125. 130. 135. 140.
 145. 150. 155. 160. 165. 170. 175. 180. 185. 190. 195. 200. 205. 210.
 215. 220. 225. 230. 235. 240. 245. 250. 255. 260. 265. 270. 275. 280.
 285. 290. 295. 300. 305. 310. 315. 320. 325. 330. 335. 340. 345. 350.
 355. 360. 365. 370. 375. 380. 385. 390. 395. 400. 405. 410. 415. 420.
 425. 430. 435. 440. 445. 450. 455. 460. 465. 470. 475. 480. 485. 490.
 495. 500. 505. 510. 515. 520. 525. 530. 535. 540. 545. 550. 555. 560.
 565. 570. 575. 580. 585. 590. 595. 600. 605. 610. 615. 620. 625. 630.
 635. 640. 645. 650. 655. 660. 665. 670. 675. 680. 685. 690. 695. 700.
 705. 710. 715. 720.]
[MultiModeCavity] omega_k in cm-1 [655.01908369 655.07633143 655.17173321 655.30527237 655.4769256
 655.68666297 655.93444794 656.22023742 656.54398177 656.90562488
 657.30510419 657.74235077 658.21728935 658.7298384  659.27991021
 659.86741092 660.49224068 661.15429364 661.8534581  662.58961658
 663.36264592 664.17241737 665.01879673 665.90164439 666.82081551
 667.7761601  668.76752313 669.79474468 670.85766001 671.95609976
 673.08988998 674.25885237 675.46280431 676.70155903 677.97492579
 679.28270992 680.62471304 682.00073314 683.41056474 684.85399904
 686.33082402 687.84082461 689.38378281 690.95947783 692.56768622
 694.20818203 695.88073691 697.58512025 699.32109935 701.0884395
 702.88690413 704.71625496 706.57625208 708.46665412 710.38721835
 712.33770081 714.31785642 716.32743909 718.36620188 720.43389704
 722.53027618 724.65509037 726.80809021 728.98902598 731.1976477
 733.43370525 735.69694848 737.98712726 740.30399161 742.64729179
 745.01677833 747.4122022  749.83331481 752.27986813 754.75161477
 757.24830802 759.76970195 762.31555146 764.88561236 767.47964142
 770.09739644 772.73863628 775.40312096 778.09061169 780.8008709
 783.53366233 786.28875103 789.06590346 791.86488747 794.68547237
 797.527429   800.39052968 803.27454833 806.17926046 809.1044432
 812.04987532 815.01533728 818.00061125 821.0054811  824.02973247
 827.07315275 830.1355311  833.2166585  836.31632771 839.43433335
 842.57047183 845.72454144 848.89634232 852.08567644 855.29234768
 858.51616176 861.75692628 865.01445075 868.28854651 871.57902682
 874.88570682 878.20840351 881.54693579 884.90112442 888.27079204
 891.65576317 895.05586418 898.47092329 901.9007706  905.34523802
 908.80415932 912.2773701  915.76470777 919.26601155 922.78112248
 926.30988335 929.85213878 933.40773513 936.97652052 940.55834481
 944.15305963 947.76051827 951.38057579 955.01308892 958.65791605
 962.31491727 965.98395432 969.66489057 973.35759102]
[MultiModeCavity] Applying Absorbing Boundary Condition: False, cutoff: [0.0, 0.0]
Coupling strength: 2.236e-06 au
[Init Molecule] Under socket mode, registered molecule with ID 0
[SocketHub] Prepared 1 remote aggregate bridge(s); manifest saved to 'aggregation.json'.
[SocketHub] REMOTE BRIDGE 0: unix='bridge_0' group='bridge_0' molecules=144
[RemoteBridgeSpec(idx=0, group_id='bridge_0', unixsocket='bridge_0', n_molecules=144)]

2.2. Define the continuous-wave drive

We apply a spatially localized CW drive on the photon degrees of freedom. The CW pulse with wave number 144 * fbcavity.delta_omega_x_au=720 cm^{-1} and drive frequency 652.0 cm^{-1}, corresponding to the highest LP mode along the dispersion curve, is attached to the central 30% region along the cavity plane.

[7]:
photon_source = k_parallel_pulse(
    cavity=fbcavity,
    envelope=1.0,
    omega_au=652.0 * unit("cm_inv"),
    k_parallel_au=144 * fbcavity.delta_omega_x_au,
    direction="x",
    center=(0.5, 0.0),
    size=(0.3, 1.0),
    target="photon",
    amplitude_au=0.035,
)

2.3. Coupled light-matter dynamics

[8]:
rng = np.random.default_rng(seed=114514)
random_seed = int(rng.integers(1919810))

sim = MultiModeSimulation(
    hub=hub,
    molecules=molecule_list,
    dt_au=0.5 * unit("fs"),
    damping_au=0.0,
    include_dse=True,
    cavity_geometry=fbcavity,
    excited_mode_list=photon_source.excited_mode_list,
    photon_pulse_drive=photon_source,
    photon_pulse_axis="y",
    photon_partial_charge=0.066,
    initializer=MaxwellBoltzmannInitializer(
        temperature_au=300.0 * unit("K"),
        random_seed=random_seed,
    ),
    thermostat=LangevinThermostat(
        temperature_au=300.0 * unit("K"),
        dt_au=0.5 * unit("fs"),
        tau_au=5000.0 * unit("fs"),
        random_seed=random_seed,
        xp=np,
    ),
)
[LangevinThermostat] NVT thermostat enabled with T = 300.0 K = 0.0009500434689 a.u., Langevin tau = 5000.0 fs = 206706.866675 a.u.
[Maxwell-Boltzmann Initializer] Initializing positions with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.
[Maxwell-Boltzmann Initializer] Initializing momenta with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.
[9]:
import shlex
import subprocess

command = """
mxl_bridge --info aggregation.json --idx 0 \
    --backend gpu --model md \
    --param "ff=co2jcp2021,thermostat=nvt,friction_fs=5000.0,temperature_K=300.0,pre_nvt=True,pre_nvt_duration_ps=10.0,reset_dipole=True,seed=114514"
"""

bridge_process = subprocess.Popen(shlex.split(command))

try:
    sim._ensure_socket_connections()
    print("MD initialization complete. Starting the coupled simulation.", flush=True)
    sim.run(
        steps=80001,
        record_history=True,
        record_filename=None,
        record_every_steps=20,
        record_list=["qc", "photonic_energy_with_dse"],
    )
finally:
    hub.stop()
    bridge_process.wait()
[SocketHub] CONNECTED: aggregate group 'bridge_0' <- 127.0.0.1:59330
MD initialization complete. Starting the coupled simulation.
[MultiModeCavity] Recording history: True, to disk: False, record_every_steps: 20, record_max_steps: 4001
[MultiModeCavity] Recording fields : none
[MultiModeCavity] Recording address: N/A, filename: N/A
[MultiModeCavity] Temporary folder : N/A
[MultiModeCavity] Completed 1000/80001 [1.2%] steps, time/step: 5.93e-03 seconds, remaining time: 468.09 seconds.
[MultiModeCavity] Completed 2000/80001 [2.5%] steps, time/step: 5.92e-03 seconds, remaining time: 462.12 seconds.
[MultiModeCavity] Completed 3000/80001 [3.7%] steps, time/step: 5.93e-03 seconds, remaining time: 456.29 seconds.
[MultiModeCavity] Completed 4000/80001 [5.0%] steps, time/step: 5.92e-03 seconds, remaining time: 450.29 seconds.
[MultiModeCavity] Completed 5000/80001 [6.2%] steps, time/step: 5.91e-03 seconds, remaining time: 444.20 seconds.
[MultiModeCavity] Completed 6000/80001 [7.5%] steps, time/step: 5.90e-03 seconds, remaining time: 438.05 seconds.
[MultiModeCavity] Completed 7000/80001 [8.7%] steps, time/step: 5.92e-03 seconds, remaining time: 432.12 seconds.
[MultiModeCavity] Completed 8000/80001 [10.0%] steps, time/step: 5.93e-03 seconds, remaining time: 426.28 seconds.
[MultiModeCavity] Completed 9000/80001 [11.2%] steps, time/step: 5.91e-03 seconds, remaining time: 420.31 seconds.
[MultiModeCavity] Completed 10000/80001 [12.5%] steps, time/step: 5.97e-03 seconds, remaining time: 414.74 seconds.
[MultiModeCavity] Completed 11000/80001 [13.7%] steps, time/step: 5.92e-03 seconds, remaining time: 408.76 seconds.
[MultiModeCavity] Completed 12000/80001 [15.0%] steps, time/step: 5.96e-03 seconds, remaining time: 403.07 seconds.
[MultiModeCavity] Completed 13000/80001 [16.2%] steps, time/step: 5.96e-03 seconds, remaining time: 397.29 seconds.
[MultiModeCavity] Completed 14000/80001 [17.5%] steps, time/step: 5.91e-03 seconds, remaining time: 391.27 seconds.
[MultiModeCavity] Completed 15000/80001 [18.7%] steps, time/step: 5.81e-03 seconds, remaining time: 384.84 seconds.
[MultiModeCavity] Completed 16000/80001 [20.0%] steps, time/step: 5.91e-03 seconds, remaining time: 378.90 seconds.
[MultiModeCavity] Completed 17000/80001 [21.2%] steps, time/step: 5.96e-03 seconds, remaining time: 373.13 seconds.
[MultiModeCavity] Completed 18000/80001 [22.5%] steps, time/step: 5.94e-03 seconds, remaining time: 367.26 seconds.
[MultiModeCavity] Completed 19000/80001 [23.7%] steps, time/step: 5.94e-03 seconds, remaining time: 361.39 seconds.
[MultiModeCavity] Completed 20000/80001 [25.0%] steps, time/step: 5.95e-03 seconds, remaining time: 355.54 seconds.
[MultiModeCavity] Completed 21000/80001 [26.2%] steps, time/step: 5.91e-03 seconds, remaining time: 349.57 seconds.
[MultiModeCavity] Completed 22000/80001 [27.5%] steps, time/step: 5.95e-03 seconds, remaining time: 343.71 seconds.
[MultiModeCavity] Completed 23000/80001 [28.7%] steps, time/step: 5.86e-03 seconds, remaining time: 337.61 seconds.
[MultiModeCavity] Completed 24000/80001 [30.0%] steps, time/step: 6.03e-03 seconds, remaining time: 331.95 seconds.
[MultiModeCavity] Completed 25000/80001 [31.2%] steps, time/step: 6.00e-03 seconds, remaining time: 326.17 seconds.
[MultiModeCavity] Completed 26000/80001 [32.5%] steps, time/step: 6.09e-03 seconds, remaining time: 320.57 seconds.
[MultiModeCavity] Completed 27000/80001 [33.7%] steps, time/step: 6.01e-03 seconds, remaining time: 314.79 seconds.
[MultiModeCavity] Completed 28000/80001 [35.0%] steps, time/step: 5.91e-03 seconds, remaining time: 308.80 seconds.
[MultiModeCavity] Completed 29000/80001 [36.2%] steps, time/step: 5.80e-03 seconds, remaining time: 302.62 seconds.
[MultiModeCavity] Completed 30000/80001 [37.5%] steps, time/step: 5.77e-03 seconds, remaining time: 296.40 seconds.
[MultiModeCavity] Completed 31000/80001 [38.7%] steps, time/step: 5.81e-03 seconds, remaining time: 290.29 seconds.
[MultiModeCavity] Completed 32000/80001 [40.0%] steps, time/step: 5.80e-03 seconds, remaining time: 284.17 seconds.
[MultiModeCavity] Completed 33000/80001 [41.2%] steps, time/step: 5.75e-03 seconds, remaining time: 278.00 seconds.
[MultiModeCavity] Completed 34000/80001 [42.5%] steps, time/step: 5.74e-03 seconds, remaining time: 271.85 seconds.
[MultiModeCavity] Completed 35000/80001 [43.7%] steps, time/step: 5.74e-03 seconds, remaining time: 265.72 seconds.
[MultiModeCavity] Completed 36000/80001 [45.0%] steps, time/step: 5.74e-03 seconds, remaining time: 259.61 seconds.
[MultiModeCavity] Completed 37000/80001 [46.2%] steps, time/step: 5.74e-03 seconds, remaining time: 253.53 seconds.
[MultiModeCavity] Completed 38000/80001 [47.5%] steps, time/step: 5.85e-03 seconds, remaining time: 247.58 seconds.
[MultiModeCavity] Completed 39000/80001 [48.7%] steps, time/step: 5.84e-03 seconds, remaining time: 241.63 seconds.
[MultiModeCavity] Completed 40000/80001 [50.0%] steps, time/step: 5.78e-03 seconds, remaining time: 235.62 seconds.
[MultiModeCavity] Completed 41000/80001 [51.2%] steps, time/step: 5.75e-03 seconds, remaining time: 229.60 seconds.
[MultiModeCavity] Completed 42000/80001 [52.5%] steps, time/step: 5.85e-03 seconds, remaining time: 223.68 seconds.
[MultiModeCavity] Completed 43000/80001 [53.7%] steps, time/step: 5.83e-03 seconds, remaining time: 217.74 seconds.
[MultiModeCavity] Completed 44000/80001 [55.0%] steps, time/step: 5.84e-03 seconds, remaining time: 211.82 seconds.
[MultiModeCavity] Completed 45000/80001 [56.2%] steps, time/step: 5.88e-03 seconds, remaining time: 205.94 seconds.
[MultiModeCavity] Completed 46000/80001 [57.5%] steps, time/step: 5.85e-03 seconds, remaining time: 200.03 seconds.
[MultiModeCavity] Completed 47000/80001 [58.7%] steps, time/step: 5.79e-03 seconds, remaining time: 194.08 seconds.
[MultiModeCavity] Completed 48000/80001 [60.0%] steps, time/step: 5.79e-03 seconds, remaining time: 188.14 seconds.
[MultiModeCavity] Completed 49000/80001 [61.2%] steps, time/step: 5.79e-03 seconds, remaining time: 182.20 seconds.
[MultiModeCavity] Completed 50000/80001 [62.5%] steps, time/step: 5.79e-03 seconds, remaining time: 176.27 seconds.
[MultiModeCavity] Completed 51000/80001 [63.7%] steps, time/step: 5.80e-03 seconds, remaining time: 170.35 seconds.
[MultiModeCavity] Completed 52000/80001 [65.0%] steps, time/step: 5.80e-03 seconds, remaining time: 164.44 seconds.
[MultiModeCavity] Completed 53000/80001 [66.2%] steps, time/step: 5.79e-03 seconds, remaining time: 158.52 seconds.
[MultiModeCavity] Completed 54000/80001 [67.5%] steps, time/step: 5.79e-03 seconds, remaining time: 152.61 seconds.
[MultiModeCavity] Completed 55000/80001 [68.7%] steps, time/step: 5.87e-03 seconds, remaining time: 146.74 seconds.
[MultiModeCavity] Completed 56000/80001 [70.0%] steps, time/step: 5.95e-03 seconds, remaining time: 140.91 seconds.
[MultiModeCavity] Completed 57000/80001 [71.2%] steps, time/step: 5.94e-03 seconds, remaining time: 135.06 seconds.
[MultiModeCavity] Completed 58000/80001 [72.5%] steps, time/step: 5.92e-03 seconds, remaining time: 129.21 seconds.
[MultiModeCavity] Completed 59000/80001 [73.7%] steps, time/step: 5.86e-03 seconds, remaining time: 123.33 seconds.
[MultiModeCavity] Completed 60000/80001 [75.0%] steps, time/step: 5.87e-03 seconds, remaining time: 117.46 seconds.
[MultiModeCavity] Completed 61000/80001 [76.2%] steps, time/step: 5.91e-03 seconds, remaining time: 111.59 seconds.
[MultiModeCavity] Completed 62000/80001 [77.5%] steps, time/step: 5.92e-03 seconds, remaining time: 105.73 seconds.
[MultiModeCavity] Completed 63000/80001 [78.7%] steps, time/step: 5.96e-03 seconds, remaining time: 99.88 seconds.
[MultiModeCavity] Completed 64000/80001 [80.0%] steps, time/step: 5.91e-03 seconds, remaining time: 94.02 seconds.
[MultiModeCavity] Completed 65000/80001 [81.2%] steps, time/step: 5.91e-03 seconds, remaining time: 88.15 seconds.
[MultiModeCavity] Completed 66000/80001 [82.5%] steps, time/step: 5.91e-03 seconds, remaining time: 82.28 seconds.
[MultiModeCavity] Completed 67000/80001 [83.7%] steps, time/step: 5.92e-03 seconds, remaining time: 76.41 seconds.
[MultiModeCavity] Completed 68000/80001 [85.0%] steps, time/step: 5.91e-03 seconds, remaining time: 70.54 seconds.
[MultiModeCavity] Completed 69000/80001 [86.2%] steps, time/step: 5.92e-03 seconds, remaining time: 64.67 seconds.
[MultiModeCavity] Completed 70000/80001 [87.5%] steps, time/step: 5.93e-03 seconds, remaining time: 58.80 seconds.
[MultiModeCavity] Completed 71000/80001 [88.7%] steps, time/step: 5.86e-03 seconds, remaining time: 52.92 seconds.
[MultiModeCavity] Completed 72000/80001 [90.0%] steps, time/step: 5.79e-03 seconds, remaining time: 47.03 seconds.
[MultiModeCavity] Completed 73000/80001 [91.2%] steps, time/step: 5.84e-03 seconds, remaining time: 41.15 seconds.
[MultiModeCavity] Completed 74000/80001 [92.5%] steps, time/step: 5.78e-03 seconds, remaining time: 35.26 seconds.
[MultiModeCavity] Completed 75000/80001 [93.7%] steps, time/step: 5.89e-03 seconds, remaining time: 29.39 seconds.
[MultiModeCavity] Completed 76000/80001 [95.0%] steps, time/step: 5.87e-03 seconds, remaining time: 23.51 seconds.
[MultiModeCavity] Completed 77000/80001 [96.2%] steps, time/step: 5.92e-03 seconds, remaining time: 17.64 seconds.
[MultiModeCavity] Completed 78000/80001 [97.5%] steps, time/step: 5.92e-03 seconds, remaining time: 11.76 seconds.
[MultiModeCavity] Completed 79000/80001 [98.7%] steps, time/step: 5.91e-03 seconds, remaining time: 5.88 seconds.
[MultiModeCavity] Completed 80000/80001 [100.0%] steps, time/step: 5.82e-03 seconds, remaining time: 0.01 seconds.
[SocketHub] DISCONNECTED: aggregate group 'bridge_0'

3. Polariton spectrum and photon energy

Here, let’s plot the nonequilibrium polariton spectrum and photonic energy dynamics from the memory.

Clearly, the LP band edge gains strong population during this nonequilibrium procedure, and the photonic energy dynamics also show that the photon modes at small in-plane wave numbers gain significant population. These results suggest the formation of vibrational polariton condensation from this mesoscale CavMD simulations.

[ ]:
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib import cm
from maxwelllink.tools import ir_spectrum
from maxwelllink.tools.ir import smooth

# Plotting parameters
sample_dt_fs = sim.dt * sim.record_every_steps / unit("fs")
analysis_start_fs = 0.0
frequency_min_cm = 600.0
frequency_max_cm = 1000.0
molecular_frequency_cm = 655.0
first_mode_index = 1
relative_intensity_min = 1e-3
smooth_window_len = 11
modes_per_group = 24
energy_smooth_window_len = 21

# Select the y-polarized photon coordinates from memory
start_frame = int(np.ceil(analysis_start_fs / sample_dt_fs))
qc_y = np.asarray(sim.qc_history)[start_frame:, :, 1]

# Apply the same autocorrelation-based spectral helper as Tutorial 11
mode_spectra = []
for mode_index in range(qc_y.shape[1]):
    frequency_cm, spectrum = ir_spectrum(
        qc_y[:, mode_index],
        sample_dt_fs,
        smooth_window_len=smooth_window_len,
    )
    mode_spectra.append(spectrum)

spectrum_full = np.abs(np.column_stack(mode_spectra))
omega_parallel_cm = (
    np.arange(qc_y.shape[1]) + first_mode_index
) * (fbcavity.delta_omega_x_au / unit("cm_inv"))

frequency_mask = (
    (frequency_cm >= frequency_min_cm)
    & (frequency_cm <= frequency_max_cm)
)
plot_frequency_cm = frequency_cm[frequency_mask]
# Display only the first 90% of modes
n_plot_modes = int(0.9 * spectrum_full.shape[1])
plot_omega_parallel_cm = omega_parallel_cm[:n_plot_modes]
plot_spectrum = spectrum_full[frequency_mask, :n_plot_modes]

intensity_max = np.max(plot_spectrum)
if not np.isfinite(intensity_max) or intensity_max <= 0:
    raise ValueError("The selected frequency window has no finite, positive intensity.")
plot_spectrum = np.ma.masked_less_equal(plot_spectrum / intensity_max, 0.0)

fig, (ax, energy_ax) = plt.subplots(1, 2, figsize=(12, 4), layout="constrained")
image = ax.pcolormesh(
    plot_omega_parallel_cm,
    plot_frequency_cm,
    plot_spectrum,
    shading="auto",
    cmap=cm.inferno,
    norm=LogNorm(vmin=relative_intensity_min, vmax=1.0),
)
cbar = fig.colorbar(image, ax=ax)
cbar.set_label("spectral intensity [arb. units]")

ax.axhline(
    molecular_frequency_cm,
    color="c",
    linewidth=2,
    label="asym. C=O bending",
)
ax.plot(
    plot_omega_parallel_cm,
    np.sqrt((fbcavity.frequency_au / unit("cm_inv"))**2 + plot_omega_parallel_cm**2),
    color="orange",
    linewidth=2,
    label="cavity photon",
)

ax.set_xlim(plot_omega_parallel_cm[0], plot_omega_parallel_cm[-1])
ax.set_ylim(frequency_min_cm, frequency_max_cm)
ax.set_xlabel(r"$\omega_{\parallel}$ [cm$^{-1}$]")
ax.set_ylabel(r"frequency [cm$^{-1}$]")
ax.tick_params(labelsize=12)
ax.legend(frameon=False, loc="upper left", fontsize=10, labelcolor="linecolor")

# Group all photon modes together
photonic_energy = np.asarray(sim.photonic_energy_with_dse_history)
grouped_energy = photonic_energy.reshape(
    photonic_energy.shape[0], -1, modes_per_group
).sum(axis=2)

time_ps = (
    1 + np.arange(grouped_energy.shape[0]) * sim.record_every_steps
) * sim.dt / unit("ps")

energy_scale = modes_per_group * sim.thermostat.temperature_au
energy_ys = [
    smooth(trace, energy_smooth_window_len) / energy_scale - 2
    for trace in grouped_energy.T
]

energy_labels = [
    f"{omega_parallel_cm[group_index * modes_per_group]:.0f}–"
    f"{omega_parallel_cm[(group_index + 1) * modes_per_group - 1]:.0f}"
    for group_index in range(grouped_energy.shape[1])
]

energy_ax.set_prop_cycle(
    color=cm.viridis(np.linspace(0, 1, grouped_energy.shape[1]))
)
for energy_trace, label in zip(energy_ys, energy_labels):
    energy_ax.plot(time_ps, energy_trace, label=label, linewidth=1.0)

energy_ax.set_xlim(0, time_ps[-1])
energy_ax.set_ylim(bottom=0)
energy_ax.set_xlabel("time [ps]")
energy_ax.set_ylabel(r"energy gain per mode [$k_{\mathrm{B}}T$]")
energy_ax.tick_params(labelsize=12)
energy_ax.legend(
    title=r"$\omega_{\parallel}$ [cm$^{-1}$]",
    ncols=3,
    loc="upper center",
    bbox_to_anchor=(0.5, -0.2),
    fontsize=9,
    frameon=False,
)
ax.set_title("(a) Polariton spectrum", loc="left")
energy_ax.set_title("(b) Photon energy", loc="left")
plt.show()
../../_images/tutorials_notebook_12_multimode_gpu_md_transport_condensation_20_0.png

4. 2D simulation for condensation dynamics

To conclude this tutorial, let’s run a final 2D Fabry-Perot simulation to directly capture the condensation movie along the cavity mirror plane.

Here, we place the molecular cells on a 144 × 144=20,736 grid between the cavity mirrors. Each cell contains 36 CO2 molecules along the periodic boundary conditions.

To save some computation cost, we turn off the pre-equilibration pre_nvt=False (which should be turned on in production runs). This simulation will take about 17 minutes to finish on a single RTX 4090.

We observe some rough fluid-like dynamics of the EM field. Note that for gaining high spectral resolution, the paper reports the runs with a 720x720 grid, which requires running for ~36 hours on a H100 GPU card.

[ ]:
import numpy as np
import maxwelllink as mxl

from maxwelllink.em_solvers.multimode_cavity import (
    FabryPerotCavity,
    MultiModeSimulation,
)
from maxwelllink.sockets import (
    AggregatedSocketHub,
    get_available_host_port,
)
from maxwelllink.tools import k_parallel_pulse
from maxwelllink.tools.harmonic_oscillator_helper import (
    MaxwellBoltzmannInitializer,
    LangevinThermostat,
)
from maxwelllink.units import unit

rng_2d = np.random.default_rng(seed=114514)
random_seed_2d = int(rng_2d.integers(1919810))
N_grid_x = 144
N_grid_y = 144
N_grid = N_grid_x * N_grid_y
coupling_strength_2d = 1e-6 / np.sqrt(144*144/720)
damping_au_2d = 0e-4
dt_fs_2d = 0.5

fbcavity_2d = FabryPerotCavity(
    frequency_au=655*unit("cm_inv"),
    coupling_strength=coupling_strength_2d,
    coupling_axis="xy",
    n_grid_x=N_grid_x,
    n_grid_y=N_grid_y,
    delta_omega_x_au=5.0*unit("cm_inv"),
    delta_omega_y_au=5.0*unit("cm_inv"),
    n_mode_x=N_grid_x,
    n_mode_y=N_grid_y,
    save_mode_functions=False,
    mode_start_index_x=1,
    mode_start_index_y=0,
)
print(f"Coupling strength: {coupling_strength_2d:.3e} au")

# One socket-side molecule represents one complete MD cell
host_2d, port_2d = get_available_host_port(localhost=True)
hub_2d = AggregatedSocketHub(host=host_2d, port=port_2d, timeout=6000.0, latency=1e-3)
print(f"SocketHub listening on {host_2d}:{port_2d}")

molecule_list_2d = []
for _ in range(N_grid):
    molecule_list_2d.append(mxl.Molecule(hub=hub_2d, rescaling_factor=1.0, store_additional_data=False))

hub_2d.init_remote_bridges(
    molecule_list_2d,
    molecules_per_bridge=N_grid,
    unix_prefix="gpu0.002_",
    save_file="aggregation_2d.json",
)

# Apply a continuous photon drive to the center of the 2D cavity mirror plane
photon_source_2d = k_parallel_pulse(
    cavity=fbcavity_2d,
    envelope=1.0,
    omega_au=652*unit("cm_inv"),
    k_parallel_au=[720*unit("cm_inv"),0*unit("cm_inv")],
    direction="xy",
    center=(0.5, 0.5),
    size=(0.3, 0.3),
    target="photon",
    amplitude_au=0.064,
)

sim_2d = MultiModeSimulation(
    hub=hub_2d,
    molecules=molecule_list_2d,
    dt_au=dt_fs_2d*unit("fs"),
    damping_au=damping_au_2d,
    include_dse=True,
    cavity_geometry=fbcavity_2d,
    excited_mode_list=photon_source_2d.excited_mode_list,
    photon_pulse_drive=photon_source_2d,
    photon_pulse_axis="y",
    photon_partial_charge=0.43,
    initializer=MaxwellBoltzmannInitializer(temperature_au=300.0*unit("K"), random_seed=random_seed_2d),
    thermostat=LangevinThermostat(
        temperature_au=300.0*unit("K"),
        dt_au=dt_fs_2d*unit("fs"),
        tau_au=5000*unit("fs"),
        random_seed=random_seed_2d,
    ),
)

import shlex
import subprocess

command_2d = """
mxl_bridge --info aggregation_2d.json --idx 0 \
    --backend gpu --model md \
    --param "ff=co2jcp2021,thermostat=nvt,friction_fs=5000.0,temperature_K=300.0,pre_nvt=False,pre_nvt_duration_ps=10.0,reset_dipole=True,seed=114514"
"""

bridge_process_2d = subprocess.Popen(shlex.split(command_2d))

try:
    sim_2d._ensure_socket_connections()
    print("MD initialization complete. Starting the coupled simulation.", flush=True)
    sim_2d.run(
        steps=30001,
        record_history=True,
        record_filename=None,
        record_every_steps=300,
        record_list=["effective_efield"],
    )
finally:
    hub_2d.stop()
    bridge_process_2d.wait()

[MultiModeCavity] omega_parallel in cm-1 [   5.           10.           15.         ... 1007.63336586 1011.1626971
 1014.70439045]
[MultiModeCavity] omega_k in cm-1 [ 655.01908369  655.07633143  655.17173321 ... 1201.81113325 1204.77176262
 1207.74583419]
[MultiModeCavity] Applying Absorbing Boundary Condition: False, cutoff: [0.0, 0.0]
Coupling strength: 1.863e-07 au
SocketHub listening on 127.0.0.1:50339
[Init Molecule] Under socket mode, registered molecule with ID 0
[SocketHub] Prepared 1 remote aggregate bridge(s); manifest saved to 'aggregation_2d.json'.
[SocketHub] REMOTE BRIDGE 0: unix='gpu0.002_0' group='gpu0.002_0' molecules=20736
[LangevinThermostat] NVT thermostat enabled with T = 300.0 K = 0.0009500434689 a.u., Langevin tau = 5000.0 fs = 206706.866675 a.u.
[Maxwell-Boltzmann Initializer] Initializing positions with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.
[Maxwell-Boltzmann Initializer] Initializing momenta with Maxwell-Boltzmann distribution at temperature 0.0009500434689 au.
[SocketHub] CONNECTED: aggregate group 'gpu0.002_0' <- 127.0.0.1:51102
MD initialization complete. Starting the coupled simulation.
[MultiModeCavity] Recording history: True, to disk: False, record_every_steps: 300, record_max_steps: 101
[MultiModeCavity] Recording fields : none
[MultiModeCavity] Recording address: N/A, filename: N/A
[MultiModeCavity] Temporary folder : N/A
[MultiModeCavity] Completed 1000/30001 [3.3%] steps, time/step: 3.79e-02 seconds, remaining time: 1097.79 seconds.
[MultiModeCavity] Completed 2000/30001 [6.7%] steps, time/step: 3.30e-02 seconds, remaining time: 992.46 seconds.
[MultiModeCavity] Completed 3000/30001 [10.0%] steps, time/step: 3.29e-02 seconds, remaining time: 933.90 seconds.
[MultiModeCavity] Completed 4000/30001 [13.3%] steps, time/step: 3.35e-02 seconds, remaining time: 891.96 seconds.
[MultiModeCavity] Completed 5000/30001 [16.7%] steps, time/step: 3.34e-02 seconds, remaining time: 853.32 seconds.
[MultiModeCavity] Completed 6000/30001 [20.0%] steps, time/step: 3.35e-02 seconds, remaining time: 816.69 seconds.
[MultiModeCavity] Completed 7000/30001 [23.3%] steps, time/step: 3.36e-02 seconds, remaining time: 781.29 seconds.
[MultiModeCavity] Completed 8000/30001 [26.7%] steps, time/step: 3.35e-02 seconds, remaining time: 746.06 seconds.
[MultiModeCavity] Completed 9000/30001 [30.0%] steps, time/step: 3.35e-02 seconds, remaining time: 711.14 seconds.
[MultiModeCavity] Completed 10000/30001 [33.3%] steps, time/step: 3.41e-02 seconds, remaining time: 677.85 seconds.
[MultiModeCavity] Completed 11000/30001 [36.7%] steps, time/step: 3.34e-02 seconds, remaining time: 643.19 seconds.
[MultiModeCavity] Completed 12000/30001 [40.0%] steps, time/step: 3.35e-02 seconds, remaining time: 608.86 seconds.
[MultiModeCavity] Completed 13000/30001 [43.3%] steps, time/step: 3.46e-02 seconds, remaining time: 576.09 seconds.
[MultiModeCavity] Completed 14000/30001 [46.7%] steps, time/step: 3.45e-02 seconds, remaining time: 542.93 seconds.
[MultiModeCavity] Completed 15000/30001 [50.0%] steps, time/step: 3.46e-02 seconds, remaining time: 509.67 seconds.
[MultiModeCavity] Completed 16000/30001 [53.3%] steps, time/step: 3.36e-02 seconds, remaining time: 475.34 seconds.
[MultiModeCavity] Completed 17000/30001 [56.7%] steps, time/step: 3.36e-02 seconds, remaining time: 441.13 seconds.
[MultiModeCavity] Completed 18000/30001 [60.0%] steps, time/step: 3.32e-02 seconds, remaining time: 406.74 seconds.
[MultiModeCavity] Completed 19000/30001 [63.3%] steps, time/step: 3.36e-02 seconds, remaining time: 372.65 seconds.
[MultiModeCavity] Completed 20000/30001 [66.7%] steps, time/step: 3.32e-02 seconds, remaining time: 338.43 seconds.
[MultiModeCavity] Completed 21000/30001 [70.0%] steps, time/step: 3.34e-02 seconds, remaining time: 304.40 seconds.
[MultiModeCavity] Completed 22000/30001 [73.3%] steps, time/step: 3.36e-02 seconds, remaining time: 270.48 seconds.
[MultiModeCavity] Completed 23000/30001 [76.7%] steps, time/step: 3.38e-02 seconds, remaining time: 236.67 seconds.
[MultiModeCavity] Completed 24000/30001 [80.0%] steps, time/step: 3.35e-02 seconds, remaining time: 202.79 seconds.
[MultiModeCavity] Completed 25000/30001 [83.3%] steps, time/step: 3.34e-02 seconds, remaining time: 168.92 seconds.
[MultiModeCavity] Completed 26000/30001 [86.7%] steps, time/step: 3.35e-02 seconds, remaining time: 135.10 seconds.
[MultiModeCavity] Completed 27000/30001 [90.0%] steps, time/step: 3.36e-02 seconds, remaining time: 101.31 seconds.
[MultiModeCavity] Completed 28000/30001 [93.3%] steps, time/step: 3.37e-02 seconds, remaining time: 67.55 seconds.
[MultiModeCavity] Completed 29000/30001 [96.7%] steps, time/step: 3.35e-02 seconds, remaining time: 33.78 seconds.
[MultiModeCavity] Completed 30000/30001 [100.0%] steps, time/step: 3.35e-02 seconds, remaining time: 0.03 seconds.
[SocketHub] DISCONNECTED: aggregate group 'gpu0.002_0'

5. Animate the y-polarized electric field

After the 2D simulation, we take the y component from sim_2d.effective_efield_history in memory and square it to show \(|E_{\mathrm{eff},y}|^2\).

[ ]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LogNorm
from matplotlib.animation import FuncAnimation
from IPython.display import HTML, display
from maxwelllink.units import unit

# Use the completed 2D run and adjust the movie settings here
shape = (fbcavity_2d.n_grid_y, fbcavity_2d.n_grid_x)
fps = 25
dpi = 120
frame_interval_fs = 150
box_length_mm = 1.0
amplitude_label = r"$E_0=6.4 \times 10^{-2}$ a.u."
record_dt_fs = sim_2d.dt * sim_2d.record_every_steps / unit("fs")
frame_stride = max(1, int(round(frame_interval_fs / record_dt_fs)))

efield_data = sim_2d.effective_efield_history
frame_indices = np.arange(0, len(efield_data), frame_stride)

# Cartesian index 1 denotes y-direction
efield_vmax = max(
    float(np.max(efield_data[frame_id][:, 1] ** 2))
    for frame_id in frame_indices
)
if not np.isfinite(efield_vmax) or efield_vmax <= 0:
    raise ValueError("The selected y-field frames have no finite, positive intensity.")
norm = LogNorm(vmin=efield_vmax * 0.005, vmax=efield_vmax)

fig_efield, ax_efield = plt.subplots(figsize=(5.7, 4.8), dpi=dpi, layout="constrained")
image_efield = ax_efield.imshow(
    (efield_data[frame_indices[0]][:, 1] ** 2).reshape(shape),
    aspect="equal",
    extent=[0, box_length_mm, 0, box_length_mm],
    origin="lower",
    cmap=cm.hot,
    interpolation="nearest",
    norm=norm,
)
ax_efield.set_box_aspect(1)
ax_efield.set_xlabel("x position [mm]", fontsize=12)
ax_efield.set_ylabel("y position [mm]", fontsize=12)
ax_efield.set_xticks([0, box_length_mm / 2, box_length_mm])
ax_efield.set_yticks([0, box_length_mm / 2, box_length_mm])
ax_efield.tick_params(labelsize=12)
ax_efield.text(
    0.98, 0.98, "CO₂ bending", transform=ax_efield.transAxes,
    fontsize=12, fontweight="bold", va="top", ha="right", color="w",
)
time_text = ax_efield.text(
    0.98, 0.18, "", transform=ax_efield.transAxes,
    fontsize=12, fontweight="bold", va="top", ha="right", color="w",
)
ax_efield.text(
    0.98, 0.08, amplitude_label, transform=ax_efield.transAxes,
    fontsize=12, fontweight="bold", va="top", ha="right", color="w",
)
colorbar = fig_efield.colorbar(image_efield, ax=ax_efield, pad=0.04, fraction=0.046)
colorbar.ax.tick_params(labelsize=12)
colorbar.set_label(r"$|E_{\mathrm{eff},y}|^2$ [a.u.]", fontsize=12)

def update_frame(frame_id):
    image_efield.set_data((efield_data[frame_id][:, 1] ** 2).reshape(shape))
    time_ps = (1 + frame_id * sim_2d.record_every_steps) * sim_2d.dt / unit("ps")
    time_text.set_text(r"$t=%.2f$ ps" % time_ps)
    return image_efield, time_text

movie = FuncAnimation(
    fig_efield, update_frame, frames=frame_indices,
    interval=1000 / fps, blit=False,
)

with plt.rc_context({"animation.embed_limit": float("inf")}):
    animation_html = movie.to_jshtml(fps=fps, embed_frames=True)
plt.close(fig_efield)
display(HTML(animation_html.replace(
    "<img ", '<img style="max-width: 480px; height: auto;" ', 1
)))