<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://jpkrowe.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://jpkrowe.github.io/" rel="alternate" type="text/html" /><updated>2026-12-04T10:01:24+00:00</updated><id>https://jpkrowe.github.io/feed.xml</id><title type="html">James Rowe</title><subtitle>James (Jamie) Rowe&apos;s blog on molecular simulation, computational chemistry and biophysics.</subtitle><author><name>James (Jamie) Rowe</name></author><entry><title type="html">Week 10-11: Detailed Benchmarking Analysis</title><link href="https://jpkrowe.github.io/week10-11/" rel="alternate" type="text/html" title="Week 10-11: Detailed Benchmarking Analysis" /><published>2025-08-26T23:00:00+00:00</published><updated>2025-08-26T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week10-11</id><content type="html" xml:base="https://jpkrowe.github.io/week10-11/"><![CDATA[<h1 id="follow-on-from-the-last-post">Follow on from the Last Post</h1>
<p>In the last blog post, I discussed the creation of a test system to evaluate the performance improvement of streaming the WESTPA trajectories. In that post I was using the chignolin protein as a test system. Using this system as a benchmark, I found that there was no significant performance improvement from analysing on-the-fly versus analysing after the simulation was finished. To diagnose the lack of improvement, I timed the analysis script in order to identify whether any speed up would be expected from the streaming approach. Timing the analysis script revealed that the script only takes 3.3 seconds to run. This explains why no speed up was seen from the streaming approach as this time is insignificant compared to the simulation time. Even though in this analysis we are calculating a number of pairwise distances, the small size of the chignolin protein means that the computational cost of the analysis is low and no speed up is seen. To see a speed up from the streaming approach, we need to use a system where the analysis takes a significant amount of time.</p>

<h1 id="theoretical-analysis-of-speed-up">Theoretical Analysis of Speed Up</h1>
<p>To understand the potential speed up from the streaming approach, we can perform a theoretical analysis. The total time taken for one WESTPA iteration can be approximately expressed as (ignoring overhead from starting and ending the iteration itself):</p>

<p>\begin{equation}
\tau_{iteration} = \frac{N_{segments}}{N_{sims}} \cdot \tau_{segment}
\label{eq:iteration_time}
\end{equation}</p>

<p>Where \(N_{segments}\) is the number of segments in the iteration, \(N_{sims}\) is the number of simulations that can be run in parallel and \(\tau_{segment}\) is the time taken for one segment. Without streaming, the time taken for one segment can be approximated as a sum of the simulation time and the analysis time:</p>

<p>\begin{equation}
\tau_{segment - no streaming} = \tau_{sim} + \tau_{analysis}
\label{eq:segment_time_no_streaming}
\end{equation}</p>

<p>Combining equation \ref{eq:iteration_time} and \ref{eq:segment_time_no_streaming} leads to an expression for the total iteration time without streaming:</p>

<p>\begin{equation}
\tau_{iteration - no streaming} = \frac{N_{segments}}{N_{
sims}} \cdot (\tau_{sim} + \tau_{analysis})
\label{eq:iteration_time_no_streaming}
\end{equation}</p>

<p>For the streaming approach, the analysis is performed on-the-fly during the simulation. In this case, a simple model can approximate the time taken for one segment as the maximum of the simulation time and the analysis time:</p>

<p>\begin{equation}
\tau_{segment - streaming} = \max(\tau_{sim}, \tau_{analysis})
\label{eq:segment_time_streaming}
\end{equation}</p>

<p>However, this assumes that the analysis and the simulation can be performed in perfect parallel. In reality, the analysis will always only be able to end after the simulation has ended as the final frame has to be analysed. We can adjust equation \ref{eq:segment_time_streaming} to account for this by adding a small overhead term \(\tau_{analysis-singleframe}\) which accounts for the time taken to analyse the final frame:
\begin{equation}
\tau_{segment - streaming} = \max(\tau_{sim} + \tau_{analysis-singleframe}, \tau_{analysis})
\label{eq:segment_time_streaming_adjusted}
\end{equation}</p>

<p>Combining equation \ref{eq:iteration_time} and \ref{eq:segment_time_streaming_adjusted} leads to an expression for the total iteration time with streaming:
\begin{equation}
\tau_{iteration - streaming} = \frac{N_{segments}}{N_{s
ims}} \cdot \max(\tau_{sim} + \tau_{analysis-singleframe}, \tau_{analysis})
\label{eq:iteration_time_streaming}
\end{equation}
From equations \ref{eq:iteration_time_no_streaming} and \ref{eq:iteration_time_streaming}, we can derive an expression for the theoretical speed up, \(S\), from using the streaming approach:
\begin{equation}
S = \frac{\tau_{iteration - no streaming}}{\tau_{iteration - streaming}} = \frac{\tau_{sim} + \tau_{analysis}}{\max(\tau_{sim} + \tau_{analysis-singleframe}, \tau_{analysis})}
\label{eq:speed_up}
\end{equation}
Writing in terms of the ratio of analysis time to simulation time \(\alpha = \frac{\tau_{analysis}}{\tau_{sim}}\) and assuming that \(\tau_{analysis-singleframe}\) is negligible, we can get a very simple expression for \(S\):
\begin{equation}
S = \frac{1 + \alpha}{\max(1, \alpha)}
\label{eq:speed_up_simple}
\end{equation}</p>

<p>This function is plotted below:
<img src="/assets/img/theoretical_performance_boost.png" alt="Theoretical performance boost as a function of analysis/simulation time ratio" /></p>

<p>From this graph, we can see that peak speed up occurs when \(\alpha = 1\), i.e. when \(\tau_{analysis} \approx \tau_{sim}\). This corresponds to a factor of 2 speed up. When \(\tau_{analysis} \ll \tau_{sim}\), \(\alpha \approx 0\) and there is no speed up from the streaming approach as the analysis time is negligible compared to the simulation time. This was the case with the chignolin test system. When \(\tau_{analysis} \gg \tau_{sim}\), \(\alpha \gg 1\) and there is again little speed up from the streaming approach. This is because the analysis time is so long that performing it on-the-fly does not significantly reduce the total time taken. In this case, it would be better to optimise the analysis code to reduce \(\tau_{analysis}\). From this analysis, we can conclude that to see a significant speed up from the streaming approach, we need to use a test system where the analysis time is approximately equal to the simulation time.</p>

<h1 id="the-collagen-fibril-as-a-new-test-system">The Collagen Fibril as a New Test System</h1>
<p>To achieve a better balance between analysis time and simulation time and to explore the potential benefits of the streaming approach, I decided to use a collagen fibril model as a new test system. I chose this system as I have spent many years of my PhD studying collagen and so I had the simulation files already set up! In the collagen molecule, there are around 3000 protein residues in total making it significantly larger than the chignolin protein. Similar to the chignolin test system, I am calculating a number of pairwise distances between residues. However, due to the larger size of the collagen molecule, the number of pairwise distances is much larger leading to a longer analysis time. Due to wanting quick benchmarking and availability of resources, I used a segment time of only 2 ps with only 5 cores per segment. This leads to a single simulation taking around 1 minute. By adjusting the frequency at which the system is analysed (i.e. analysing every 10 steps vs every 100 steps), we can modify the ratio of the analysis time to the simulation time and get real estimates for the speed up. The actual performance gain as a function of alpha from using the streaming approach is shown in the graph below:
<img src="/assets/img/realised_performance_boost.png" alt="Realised performance boost as a function of analysis/simulation time ratio" />
As can be seen from the graph, the realised performance boost closely follows the theoretical predictions, with peak speed up occurring at the same point where \(\alpha = 1\). The max performance boost we obtain is only 1.3 times compared to the theoretical value of 2.0. This is because some part of the iteration will have to be performed in serial and there will be some overhead caused by setting up the streaming. Another important graph is the plot of iteration time against number of analysed points. This gives us an idea of how much the streaming approach unlocks the possibility of more complicated analyses.
<img src="/assets/img/Iteration_times.png" alt="Plot of iteration time against number of points" />
As can be seen from the graph, as long as the time to analyse a segment is less than the time taken to simulate the segment, it is relatively “free” to increase the complexity of the analysis or to increase the number of analysed points. This means that we can perform more analyses as the simulation is running without incurring significant additional costs, potentially reducing the amount of data that has to be stored.</p>

<h1 id="when-is-streaming-useful">When is Streaming Useful?</h1>
<p>The analysis above gives us some simple rules for when streaming is likely to be beneficial. I recommend the user measures the time it takes for a single segment to be simulated and measures the time it takes to perform the desired analysis on the data for that segment. If the analysis time is comparable to or shorter than the simulation time, then streaming is likely to provide a speed up. In addition, the user can increase the number of analysed points for very little cost as long as the analysis time remains shorter than the simulation time.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 10-11 focused on benchmarking and improving the test systems.]]></summary></entry><entry><title type="html">GSoC 2025 Final Blog Post - On-the-fly Analysis of WESTPA Segments using Trajectory Streaming</title><link href="https://jpkrowe.github.io/finalblogpost/" rel="alternate" type="text/html" title="GSoC 2025 Final Blog Post - On-the-fly Analysis of WESTPA Segments using Trajectory Streaming" /><published>2025-08-26T23:00:00+00:00</published><updated>2025-08-26T23:00:00+00:00</updated><id>https://jpkrowe.github.io/finalblogpost</id><content type="html" xml:base="https://jpkrowe.github.io/finalblogpost/"><![CDATA[<p>My Google Summer of Code project has been an amazing experience, and I’m deeply grateful to my mentors: Oliver Beckstein (<a href="https://github.com/orbeckst">@orbeckst</a>), Jeremy Leung (<a href="https://github.com/jeremyleung521">@jeremyleung521</a>), Lawson Woods (<a href="https://github.com/ljwoods2">@ljwoods2</a>), and Lillian Chong (<a href="https://github.com/ltchong">@ltchong</a>). In this final post, I’ll describe the work I accomplished during the program.</p>

<h1 id="why-on-the-fly-analysis">Why On-the-fly Analysis?</h1>
<p>The goal of implementing on-the-fly analysis of WESTPA segments using trajectory streaming is to improve the efficiency of weighted ensemble simulations. Weighted ensemble simulations operate by running many short simulations (potentially thousands) in parallel. These short simulations are often called ‘segments.’ The segments are propagated in iterations with the progress of the segment being tracked using a progress coordinate, which is some function of the atomic positions. Currently, the WESTPA workflow separates the simulation and the calculation of the progress coordinate into two distinct steps. The simulation runs first, and the progress coordinate is calculated afterward. This can be inefficient because if the analysis takes a significant amount of time, the overall time for the segment to complete increases. This project uses Interactive Molecular Dynamics (IMD), along with the <a href="https://github.com/Becksteinlab/imdclient">IMDClient</a> and MDAnalysis, to stream trajectory data while the simulations run. This allows the analysis to be executed in parallel with the simulation, increasing the efficiency of the WESTPA run. Theoretical analysis (the derivation is <a href="https://jpkrowe.github.io/week10-11/">here</a>), predicts a speed-up of up to two times, depending on the type of analysis performed. The theoretical analysis showed that the speed-up, \(S\) is given by \(S=\frac{1 + \alpha}{\max(1, \alpha)}\), where \(\alpha\) is the ratio of analysis time to simulation time for a segment. Additional benefits of on-the-fly analysis include the ability to analyze more points along each segment trajectory and to perform more complex analyses. By increasing the number of analyzed points, trajectory data can be saved less frequently, reducing disk space usage. This also enables investigation of correlations over shorter time intervals.</p>

<h1 id="creating-a-framework-for-streaming-westpa-segments">Creating a Framework for Streaming WESTPA segments</h1>
<p>My primary goal was to create a framework for streaming and analyzing segment simulation data on-the-fly. Initially, I tried to integrate this directly into WESTPA by creating a new executable in <code class="language-plaintext highlighter-rouge">executable.py</code> (see WESTPA <a href="https://github.com/westpa/westpa/pull/495">PR #495</a>). The aim was to create an executable that would be launched alongside the executable for the segment and run the analysis. However, this approach proved tricky because a port had to be assigned to each segment and communicated to both the segment executable and the analysis executable. While WESTPA could find and assign an available port to the segment, ensuring the port remained open long enough for the simulation engine to bind to it was difficult. Instead, I opted for a simpler approach: using a Python script to launch both the simulation and analysis for each segment. This script is run within the executable for the segment. First, the script launches the simulation engine with IMD enabled, instructing it to use port 0. By assigning the port to 0, the simulation engine automatically finds an available port. The script then reads the output of the simulation engine to identify which port has been assigned. Once the port has been identified, an MDAnalysis universe can be created that connects to the simulation engine using the IMDClient. The analysis can then be performed on-the-fly as the simulation is running. The contents of this script are now encapsulated in the <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class (WESTPA <a href="https://github.com/westpa/westpa/pull/501">PR #501</a>).</p>

<h1 id="how-can-i-access-the-code">How Can I Access the Code?</h1>
<p>The code is currently available in the <code class="language-plaintext highlighter-rouge">traj-streaming-tools</code> branch of my WESTPA fork, which you can find <a href="https://github.com/jpkrowe/westpa/tree/traj-streaming-tools">here</a>. To install it, clone the repository and run <code class="language-plaintext highlighter-rouge">python -m pip install -e</code> from within the <code class="language-plaintext highlighter-rouge">westpa</code> directory. You will also need to install the <a href="https://github.com/Becksteinlab/imdclient">IMDClient package</a>. After installation, you can import the <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class using <code class="language-plaintext highlighter-rouge">from westpa.tools.trajectory_streaming import TrajectoryStreamer</code>. Once the code is reviewed and merged, it will be available in the main <a href="https://github.com/westpa/westpa">WESTPA repository</a>.</p>

<h1 id="using-the-trajectorystreamer-class">Using the TrajectoryStreamer Class</h1>
<p>The <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class offers a convenient interface for streaming trajectory data from the simulation engine to the analysis code. It manages port assignment and connects to the simulation engine using the IMDClient, providing an MDAnalysis universe for analyzing the streamed data. The <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> requires three inputs: the simulation engine name (currently supporting GROMACS, LAMMPS, and NAMD), an MDAnalysis-compatible template file, and a string used to launch the simulation. A typical usage of the TrajectoryStreamer class is as follows:</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">westpa.tools.trajectory_streaming</span> <span class="kn">import</span> <span class="n">TrajectoryStreamer</span>
<span class="n">stream</span> <span class="o">=</span> <span class="nc">TrajectoryStreamer</span><span class="p">(</span><span class="sh">"</span><span class="s">gromacs</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">template.gro</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">gmx_imd mdrun -s seg.tpr -o seg.trr -c seg.gro -e seg.edr -cpo seg.cpt -g seg.log -nt 5 -imdwait -imdport 0</span><span class="sh">"</span><span class="p">)</span>
<span class="c1"># The following function starts the simulation and returns the corresponding MDAnalysis universe
</span><span class="n">u</span> <span class="o">=</span> <span class="n">stream</span><span class="p">.</span><span class="nf">start_sim_and_get_universe</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="c1"># We can create an atom group from the universe
</span><span class="n">ag</span> <span class="o">=</span> <span class="n">u</span><span class="p">.</span><span class="nf">select_atoms</span><span class="p">(</span><span class="sh">"</span><span class="s">protein and name CA</span><span class="sh">"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">ts</span> <span class="ow">in</span> <span class="n">u</span><span class="p">.</span><span class="n">trajectory</span><span class="p">:</span>
    <span class="c1"># Perform your analysis here
</span>    <span class="n">dists</span> <span class="o">=</span> <span class="nf">self_distance_array</span><span class="p">(</span><span class="n">ag</span><span class="p">,</span> <span class="n">box</span><span class="o">=</span><span class="n">ts</span><span class="p">.</span><span class="n">dimensions</span><span class="p">)</span>
<span class="c1"># Once the analysis is complete the end_sim function is used to get the simulation output
# and end the simulation if it is still running
</span><span class="n">stream</span><span class="p">.</span><span class="nf">end_sim</span><span class="p">()</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">timeout</code> keyword is important if the frequency of trajectory frames sent for analysis is low. This value should be greater than the time between frames. The Python file containing this code should be called within the WESTPA runseg.sh script (see the <a href="https://github.com/westpa/westpa_tutorials">WESTPA tutorials</a> for more information on running weighted ensemble simulations in WESTPA), replacing the lines that normally launch the simulation and run the analysis. For example this snippet from a runseg.sh script:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">############################## Run the dynamics ################################</span>
<span class="c"># Propagate the segment using gmx mdrun</span>
<span class="nv">$GMX</span> mdrun <span class="nt">-s</span> seg.tpr <span class="nt">-o</span> seg.trr <span class="nt">-c</span> seg.gro <span class="nt">-e</span> seg.edr <span class="se">\</span>
  <span class="nt">-cpo</span> seg.cpt <span class="nt">-g</span> seg.log <span class="nt">-nt</span> 6

<span class="c">########################## Calculate and return data ###########################</span>

<span class="c"># Calculate the progress coordinate and return it to westpa</span>
python <span class="nv">$WEST_SIM_ROOT</span>/common_files/get_pairwise_dists.py
<span class="nb">cat </span>pcoord_out.dat <span class="o">&gt;</span> <span class="nv">$WEST_PCOORD_RETURN</span>
</code></pre></div></div>
<p>will now become:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">############### Run the dynamics and calculate progress coordinate #############</span>
<span class="c"># This script needs to contain the creation of the TrajectoryStreamer object</span>
python <span class="nv">$WEST_SIM_ROOT</span>/common_files/run_sim_and_get_pairwise_dists.py
<span class="nb">cat </span>pcoord_out.dat <span class="o">&gt;</span> <span class="nv">$WEST_PCOORD_RETURN</span>
</code></pre></div></div>

<h1 id="when-is-it-appropriate-to-stream-the-segments">When is it Appropriate to Stream the Segments?</h1>
<p>By benchmarking WESTPA simulations, I have determined when streaming segments is beneficial. My benchmarks (detailed in <a href="https://jpkrowe.github.io/posts/week10-11">my previous post</a>) suggest that streaming provides the best performance boost when the time to analyze a segment’s simulation is similar to the simulation time. This is shown in the below graph:
<img src="/assets/img/realised_performance_boost.png" alt="Realised performance boost as a function of analysis/simulation time ratio" />Therefore, I recommend first benchmarking both the simulation time for one segment and the time to analyze that segment’s simulation. If these times are comparable, then streaming the segments is likely to be beneficial. It is important to note that the overhead of streaming is relatively low, and it enables significantly more analysis. This is shown in this graph:
<img src="/assets/img/Iteration_times.png" alt="Plot of iteration time against number of points" /></p>

<h1 id="what-next">What Next?</h1>
<p>The upcoming IMDClient release will significantly change its interaction with MDAnalysis. The <code class="language-plaintext highlighter-rouge">IMDReader</code> functionality, previously part of IMDClient, has moved into MDAnalysis itself. My immediate plan is to update the <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class to use this new approach. During testing, the analysis sometimes ended prematurely, even while the simulation was running. This was due to IMDClient timeouts, which occur when there’s a long delay between frames. This issue can be resolved by increasing the stream_timeout parameter. However, as noted in <a href="https://github.com/Becksteinlab/imdclient/issues/111">this GitHub issue</a>, the reason for the analysis failure isn’t always clear to users. I aim to improve how IMDClient handles timeouts to provide clearer feedback. Additionally, I plan to add more comprehensive tests and documentation for TrajectoryStreamer to make it easier to use and understand. Currently, the analysis and simulation of a segment must occur on the same computing node. However, the IMD protocol can transmit data across non-local hosts. In the future, I plan to enable running the analysis and simulation on separate nodes, offering users greater flexibility.</p>

<h1 id="what-have-i-learned">What Have I Learned?</h1>
<p>I learned a great deal during the GSOC process. These things include:</p>
<ul>
  <li>The importance of benchmarking and profiling code to identify performance bottlenecks.</li>
  <li>Learning to be practical about what is achievable.</li>
  <li>Focusing on implementations that work first before trying to do things perfectly.</li>
  <li>Learning to build upon existing code and frameworks.</li>
  <li>Using git and GitHub effectively for version control and collaboration.</li>
</ul>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 10-11 focused on benchmarking and improving the test systems.]]></summary></entry><entry><title type="html">Week 8-9: Creating Test Systems for Benchmarking</title><link href="https://jpkrowe.github.io/week8-9/" rel="alternate" type="text/html" title="Week 8-9: Creating Test Systems for Benchmarking" /><published>2025-08-12T23:00:00+00:00</published><updated>2025-08-12T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week8-9</id><content type="html" xml:base="https://jpkrowe.github.io/week8-9/"><![CDATA[<p>As I mentioned at the end of the last post, now that the trajectory streaming setup is relatively complete, the next step is to create a set of test systems that can be used to benchmark the performance of the trajectory streaming setup. The goal is to create a set of systems that are representative of typical use cases, but also vary in size and complexity to provide a range of performance metrics.</p>

<h1 id="chignolin-folding-using-the-aimmd-progress-coordinate">Chignolin Folding using the AIMMD Progress Coordinate</h1>
<p>The first system I used to test the trajectory streaming setup is the chignolin folding system using the AI for Molecular Mechanism Discovery (AIMMD) progress coordinate: https://arxiv.org/abs/2307.11240(https://arxiv.org/abs/2307.11240). This system was taken from the <a href="https://github.com/westpa/westpa-test-systems">WESTPA test systems repository</a>. This is a good test case for the trajectory streaming setup as for the progress coordinate to be calculated, a large number of pairwise distances have to be calculated and then these distances are used as input to a neural network to calculate the progress coordinate. That such a large number of pairwise distances have to be caculated means that there is potential for speedup from analysing the trajectory on-the-fly.</p>

<p>The analysis as done in the repository is done using the <code class="language-plaintext highlighter-rouge">mdtraj</code> library, rather than <code class="language-plaintext highlighter-rouge">MDAnalysis</code>. Therefore, the first task was to adapt the existing analysis code to use <code class="language-plaintext highlighter-rouge">MDAnalysis</code>. Once this was done, I then had to convert the analysis code to use the <code class="language-plaintext highlighter-rouge">TrajectoryStreaming</code> class that I had developed in the previous weeks. The key code is as follows:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Create TrajectoryStreamer object
</span><span class="n">stream</span> <span class="o">=</span> <span class="nc">TrajectoryStreamer</span><span class="p">(</span><span class="sh">"</span><span class="s">gromacs</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">template.gro</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">gmx_imd mdrun -s seg.tpr -o seg.trr -c seg.gro -e seg.edr -cpo seg.cpt -g seg.log -nt 2 -imdwait -imdport 0</span><span class="sh">"</span><span class="p">)</span>
<span class="c1"># Create universe
</span><span class="n">u</span> <span class="o">=</span> <span class="n">stream</span><span class="p">.</span><span class="nf">start_sim_and_get_universe</span><span class="p">(</span><span class="n">stream_timeout</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
<span class="n">ag1</span><span class="p">,</span> <span class="n">ag2</span> <span class="o">=</span> <span class="nf">atom_select</span><span class="p">(</span><span class="n">u</span><span class="p">)</span>

<span class="c1"># Compute descriptors
# Need to convert to float32 for compatibility with the model
</span><span class="n">descriptors</span><span class="o">=</span><span class="p">[]</span>
<span class="k">for</span> <span class="n">ts</span> <span class="ow">in</span> <span class="n">u</span><span class="p">.</span><span class="n">trajectory</span><span class="p">:</span>
    <span class="n">descriptors</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">numpy</span><span class="p">.</span><span class="nf">float32</span><span class="p">(</span><span class="nf">featurize</span><span class="p">(</span><span class="n">ag1</span><span class="p">,</span> <span class="n">ag2</span><span class="p">,</span> <span class="n">box</span><span class="o">=</span><span class="n">ts</span><span class="p">.</span><span class="n">dimensions</span><span class="p">,</span> <span class="n">dmin_file</span><span class="o">=</span><span class="sh">'</span><span class="s">dmin.npy</span><span class="sh">'</span><span class="p">,</span> <span class="n">dmax_file</span><span class="o">=</span><span class="sh">'</span><span class="s">dmax.npy</span><span class="sh">'</span><span class="p">)))</span>
</code></pre></div></div>
<p>The featurize function calculates the distances between all pairs of heavy atoms that are at least 3 residues away from each other. A list of all the descriptors for each frame is updated as the trajectory is streamed. The descriptors are then fed into the neural network to calculate the progress coordinate.</p>

<h2 id="stream-timeout-issues">Stream Timeout Issues</h2>
<p>The first attempt using this script resulted in the analysis ending before the simulation had completed. This meant that the length of the progress coordinate sent to WESTPA was incorrect and WESTPA would end the job. In addition, the simulations would be left in the background waiting for an IMD signal to continue the simulation. This is due to a timeout being coded into the IMDClient, which stops the client if it does not receive a frame after a certain amount of time. This timeout is used so that the client is not left waiting indefinitely if the simulation does not correctly send the end signal. With this simulation, data was only being sent to the client every 6250 steps. Therefore, more than 5 seconds would pass between frames being sent to the client and the client would end prematurely. In the IMDClient there is an (untested) option to modify the timeout behaviour by changing the <code class="language-plaintext highlighter-rouge">timeout</code> kwarg. In order to allow for longer times between frames being sent to the client, the <code class="language-plaintext highlighter-rouge">timeout</code> kwarg was added to the <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class. This is shown above, where the <code class="language-plaintext highlighter-rouge">stream_timeout</code> kwarg, is passed to the client.</p>

<p>Currently there is no error message or information given in the <code class="language-plaintext highlighter-rouge">TrajectoryStreamer</code> class that informs the user that the client is timing out. In addition the simulations are left running in the background. I need to implement a proper protocol when these errors arise. Further issues with the <code class="language-plaintext highlighter-rouge">timeout</code> kwarg are discussed in <a href="https://github.com/Becksteinlab/imdclient/issues/111">IMDClient issue 111</a>.</p>

<h2 id="benchmarking">Benchmarking</h2>
<p>Now that the system has been setup with trajectory streaming we can benchmark to see if analysing on-the-fly actually leads to a speed up. In order to benchmark I run the system for 25 iterations with 16 segments per iteration and 2 cores per segment. The wall time for each iteration is measured and compared to the wall time for the same analysis done without trajectory streaming. Without trajectory streaming the mean wall clock time is: 115 \(\pm\) 5 s and with trajectory streaming the mean wall clock time is: 118 \(\pm\) 5 s. So within error the two options give essentially the same performance. This is dissapointing but potentially expected for this setup. Since we are only analysing 5 points for each segment, the amount of analysis to be performed is relatively minimal and therefore there is limited speed up to be obtained from accelerating the analysis. We would likely see much better performance improvements with a more complex analysis that involves more data. In the next week I am going to explore this further.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 8-9 creating test systems for benchmarking.]]></summary></entry><entry><title type="html">Week 6-7: Testing with LAMMPS and NAMD and integrating into WESTPA</title><link href="https://jpkrowe.github.io/week6-7/" rel="alternate" type="text/html" title="Week 6-7: Testing with LAMMPS and NAMD and integrating into WESTPA" /><published>2025-07-22T23:00:00+00:00</published><updated>2025-07-22T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week6-7</id><content type="html" xml:base="https://jpkrowe.github.io/week6-7/"><![CDATA[<p>These past two weeks I have focused on two different tasks: testing the trajectory streaming scripts with LAMMPS and NAMD, and integrating the scripts into WESTPA.</p>

<h1 id="testing-with-lammps-and-namd">Testing with LAMMPS and NAMD</h1>

<p>The previous post focused on using GROMACS to run the MD simulation. In the previous script, GROMACS was instructed to use port 0, which allowed the operating system to assign an available port. In order to use the same approach with LAMMPS and NAMD, we need to check that these MD engines support the same “port 0 trick”. When we instruct NAMD to use port 0, it throws an error: <code class="language-plaintext highlighter-rouge">'IMDport' was set to 0 but it should be positive</code>. Clearly, we have to be more careful with NAMD and provide a specific port number. In the case of LAMMPS, it throws a similar error: <code class="language-plaintext highlighter-rouge">ERROR: Illegal fix imd parameter: port &lt; 1024</code>. This means that for both LAMMPS and NAMD we will have to pass the port number explicitly. Since we are already starting the simulation from within a Python script, this can be performed quite easily by using a simple python function:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">get_available_port</span><span class="p">():</span>
    <span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="p">.</span><span class="nf">socket</span><span class="p">(</span><span class="n">socket</span><span class="p">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="p">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
    <span class="n">sock</span><span class="p">.</span><span class="nf">bind</span><span class="p">((</span><span class="sh">''</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>  <span class="c1"># Bind to an ephemeral port using the port 0 trick
</span>    <span class="n">port</span> <span class="o">=</span> <span class="n">sock</span><span class="p">.</span><span class="nf">getsockname</span><span class="p">()[</span><span class="mi">1</span><span class="p">]</span>
    <span class="n">sock</span><span class="p">.</span><span class="nf">close</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">port</span>
</code></pre></div></div>

<p>This port number can be passed to the MD engine when the <code class="language-plaintext highlighter-rouge">subprocess.Popen</code> command is called. This solution works for both LAMMPS and NAMD. There is a slight issue here as the port number is not immediately bound to the simulation, leading to a potential point of failure if another process binds to the port before the simulation starts. This is most likely going to be a problem when many (thousands) of simulations are being started simultaneously by WESTPA. In my testing, I have not encountered this issue yet, but I have not tested with a very large number of simulations. In LAMMPS, there is quite a nice potential solution. LAMMPS allows the use of python code to define variables within the input script. Importantly, the code is only executed when the variable is used, which means that the simulation should bind the port immediately after being assigned it. This can be done by doing the following within the LAMMPS input script.</p>

<p>First the variable needs to be defined:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>variable portfunc python get_port
python get_port input 0 return v_portfunc format i here """
def get_port():
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('', 0))  # Bind to an ephemeral port
    port = sock.getsockname()[1]
    sock.close()
    return port
"""
</code></pre></div></div>

<p>Then the variable can be used in the <code class="language-plaintext highlighter-rouge">fix imd</code> command:</p>
<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fix 2 all imd ${portfunc} version 3 unwrap off nowait off
</code></pre></div></div>
<p>The port number will be assigned when the <code class="language-plaintext highlighter-rouge">fix imd</code> command is executed, ensuring that the port is bound to the simulation. This is quite a nice solution, but requires building LAMMPS with the <code class="language-plaintext highlighter-rouge">PYTHON</code> package enabled.</p>

<h1 id="integrating-scripts-into-westpa">Integrating scripts into WESTPA</h1>
<p>After developing the trajectory streaming scripts, the next step was to integrate them further into WESTPA. The goal was to reduce the code the user needs to supply. These changes are being tracked in the following two pull requests: <a href="https://github.com/westpa/westpa/pull/501">WESTPA pull request #501</a> and <a href="https://github.com/jpkrowe/westpa-traj-streaming/pull/2">westpa-traj-streaming pull request #2</a>.</p>

<p>Within WESTPA tools a new file was created <code class="language-plaintext highlighter-rouge">traj_streaming.py</code> which contains the <code class="language-plaintext highlighter-rouge">TrajectoryStreaming</code> class. This class is responsible for starting the MD simulation and the trajectory streaming client. The class is initialised as follows:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">md_engine</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">topology</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">simulation_string</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Initialize the trajectory streamer.

        Args:
            md_engine: Name of the molecular dynamics engine (e.g., </span><span class="sh">'</span><span class="s">gromacs</span><span class="sh">'</span><span class="s">)
            topology: Path to the topology file for the simulation. Any format supported by MDAnalysis.
            simulation_string: String representing the simulation command to be executed.
        </span><span class="sh">"""</span>
        <span class="n">self</span><span class="p">.</span><span class="n">md_engine</span> <span class="o">=</span> <span class="n">md_engine</span><span class="p">.</span><span class="nf">lower</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">md_engine</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">ACCEPTABLE_MD_ENGINES</span><span class="p">:</span>
            <span class="k">raise</span> <span class="nc">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Unsupported MD engine: </span><span class="si">{</span><span class="n">self</span><span class="p">.</span><span class="n">md_engine</span><span class="si">}</span><span class="s">. </span><span class="sh">"</span> <span class="sa">f</span><span class="sh">"</span><span class="s">Supported engines: </span><span class="si">{</span><span class="sh">'</span><span class="s">, </span><span class="sh">'</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">ACCEPTABLE_MD_ENGINES</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
        <span class="n">self</span><span class="p">.</span><span class="n">topology</span> <span class="o">=</span> <span class="n">topology</span>
        <span class="n">self</span><span class="p">.</span><span class="nf">set_simulation_function</span><span class="p">(</span><span class="n">simulation_string</span><span class="p">)</span>

</code></pre></div></div>

<p>The user needs to provide the name of the MD engine, the path to the topology file, and a string representing the simulation command. The <code class="language-plaintext highlighter-rouge">set_simulation_function</code> method is used to check the command to ensure that it is using the required imd flags.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">set_simulation_function</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">sim_func</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
        <span class="sh">"""</span><span class="s">
        Set the simulation function.

        Args:
            sim_func: String representing the simulation function to be used.
        </span><span class="sh">"""</span>
        <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span> <span class="o">=</span> <span class="n">sim_func</span><span class="p">.</span><span class="nf">split</span><span class="p">()</span>
        <span class="c1"># Check and fix IMD flags
</span>        <span class="n">md_engine_flags</span> <span class="o">=</span> <span class="n">IMD_FLAGS</span><span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">md_engine</span><span class="p">]</span>
        <span class="k">for</span> <span class="n">flag</span> <span class="ow">in</span> <span class="n">md_engine_flags</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">]</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">flag</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">:</span>
                    <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">flag</span><span class="p">)</span>
                    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Adding </span><span class="si">{</span><span class="n">flag</span><span class="si">}</span><span class="s"> to simulation function</span><span class="sh">"</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">flag</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">:</span>
                    <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="si">{</span><span class="n">flag</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
                    <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">])</span>
                    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Adding </span><span class="si">{</span><span class="n">flag</span><span class="si">}</span><span class="s"> with value </span><span class="si">{</span><span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">]</span><span class="si">}</span><span class="s"> to simulation function</span><span class="sh">"</span><span class="p">)</span>
                <span class="k">elif</span> <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">.</span><span class="nf">index</span><span class="p">(</span><span class="n">flag</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="o">!=</span> <span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">]:</span>
                    <span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">[</span><span class="n">self</span><span class="p">.</span><span class="n">simulation_function</span><span class="p">.</span><span class="nf">index</span><span class="p">(</span><span class="n">flag</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">]</span>
                    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Updating </span><span class="si">{</span><span class="n">flag</span><span class="si">}</span><span class="s"> with value </span><span class="si">{</span><span class="n">md_engine_flags</span><span class="p">[</span><span class="n">flag</span><span class="p">]</span><span class="si">}</span><span class="s"> in simulation function</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">IMD_FLAGS</code> dictionary is defined at the top of the file and contains the required flags for each engine. I have currently only implemented it for GROMACS, but it can be easily extended to include LAMMPS and NAMD. The user then calls the function <code class="language-plaintext highlighter-rouge">start_sim_and_get_universe</code> to start the simulation and obtain the MDAnalysis universe object. This function operates the same as the previous script, but it is now encapsulated within the <code class="language-plaintext highlighter-rouge">TrajectoryStreaming</code> class. The user can then use the universe object to stream the trajectory data.</p>

<p>A typical usage of the <code class="language-plaintext highlighter-rouge">TrajectoryStreaming</code> class would look like this:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">westpa.tools.trajectory_streaming</span> <span class="kn">import</span> <span class="n">TrajectoryStreamer</span>
<span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="n">MDAnalysis.analysis.distances</span> <span class="kn">import</span> <span class="n">self_distance_array</span>


<span class="n">numthreads</span> <span class="o">=</span> <span class="mi">1</span>

<span class="c1"># Create a TrajectoryStreamer object
</span><span class="n">stream</span> <span class="o">=</span> <span class="nc">TrajectoryStreamer</span><span class="p">(</span>
    <span class="sh">"</span><span class="s">gromacs</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">bstate.gro</span><span class="sh">"</span><span class="p">,</span>
    <span class="sa">f</span><span class="sh">"</span><span class="s">gmx_imd mdrun -s seg.tpr -o seg.trr -c seg.gro -e seg.edr -cpo seg.cpt -g seg.log -nt </span><span class="si">{</span><span class="n">numthreads</span><span class="si">}</span><span class="s"> -imdwait -imdport 0</span><span class="sh">"</span>
<span class="p">)</span>
<span class="c1"># Start the simulation and get the MDAnalysis universe object
</span><span class="n">u</span> <span class="o">=</span> <span class="n">stream</span><span class="p">.</span><span class="nf">start_sim_and_get_universe</span><span class="p">()</span>

<span class="n">ag</span> <span class="o">=</span> <span class="n">u</span><span class="p">.</span><span class="nf">select_atoms</span><span class="p">(</span><span class="sh">"</span><span class="s">not water</span><span class="sh">"</span><span class="p">)</span>

<span class="n">dist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">ts</span> <span class="ow">in</span> <span class="n">u</span><span class="p">.</span><span class="n">trajectory</span><span class="p">:</span>
    <span class="n">dist</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="nf">self_distance_array</span><span class="p">(</span><span class="n">ag</span><span class="p">)[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">np</span><span class="p">.</span><span class="nf">savetxt</span><span class="p">(</span><span class="sh">"</span><span class="s">dist.dat</span><span class="sh">"</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="nf">array</span><span class="p">(</span><span class="n">dist</span><span class="p">))</span>
</code></pre></div></div>
<h1 id="next-steps">Next steps</h1>
<p>The next steps will be to rigorously test the integration with WESTPA and ensure that it speeds up the workflow. I will need to test with all three MD engines (GROMACS, LAMMPS and NAMD).</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 6-7 testing with LAMMPS and NAMD and integrating into WESTPA.]]></summary></entry><entry><title type="html">Week 4-5: Implementing Trajectory Streaming via a Python Script</title><link href="https://jpkrowe.github.io/week4-5/" rel="alternate" type="text/html" title="Week 4-5: Implementing Trajectory Streaming via a Python Script" /><published>2025-07-06T23:00:00+00:00</published><updated>2025-07-06T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week4-5</id><content type="html" xml:base="https://jpkrowe.github.io/week4-5/"><![CDATA[<p>What I have been working on in the last few days follows on from the discussion in my week 1-2 blog post. In that post, I discussed the issues with port assignment and the difficulties of trying to use WESTPA to assign ports to the segments. A proposed solution was to use a python script to start the simulation, with the simulation choosing a port and then communicating that port back to the python script. The python script could then start the MDAnalysis trajectory streaming client. This would ensure that the port is available and that both the simulation and the client are using the same port. In this blog post, I will discuss the implementation of this solution.</p>

<p>The code discussed in this post is being tracked in the following <a href="https://github.com/jpkrowe/westpa-traj-streaming/pull/1">pull request</a>.</p>

<h1 id="starting-the-simulation-using-a-python-script-and-assigning-a-port">Starting the simulation using a python script and assigning a port</h1>
<p>The first job was to use the script to start simulations and find a way to communicate the port back to the python script. It had been suggested previously to use a wrapper like <a href="https://gromacswrapper.readthedocs.io/en/latest/">GromacsWrapper</a> to start the simulation, but I decided instead to use the <code class="language-plaintext highlighter-rouge">subprocess</code> module. This makes the script more adaptable to other MD engines. The below code shows how <code class="language-plaintext highlighter-rouge">subprocess.Popen</code> is used to start the GROMACS simulation.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">numthreads</span> <span class="o">=</span> <span class="mi">1</span>

<span class="n">proc</span> <span class="o">=</span> <span class="n">subprocess</span><span class="p">.</span><span class="nc">Popen</span><span class="p">(</span>
    <span class="p">[</span>
        <span class="sh">"</span><span class="s">gmx_imd</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">mdrun</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">-deffnm</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">seg</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">-nt</span><span class="sh">"</span><span class="p">,</span>
        <span class="nf">str</span><span class="p">(</span><span class="n">numthreads</span><span class="p">),</span>
        <span class="sh">"</span><span class="s">-imdwait</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">-imdport</span><span class="sh">"</span><span class="p">,</span>
        <span class="sh">"</span><span class="s">0</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">],</span>
    <span class="n">stdout</span><span class="o">=</span><span class="n">subprocess</span><span class="p">.</span><span class="n">PIPE</span><span class="p">,</span>
    <span class="n">stderr</span><span class="o">=</span><span class="n">subprocess</span><span class="p">.</span><span class="n">STDOUT</span><span class="p">,</span>
    <span class="n">text</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">bufsize</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
<span class="p">)</span>
</code></pre></div></div>
<p>An important question is how to tell the simulation to find an available port. For this we can use the “port 0 trick”. When a program attempts to bind to port 0, the operating system should automatically assign an available port. When this is used with GROMACS, the following output is produced:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>IMD: Setting port for connection requests to 0.
IMD: Setting up incoming socket.
IMD: Listening for IMD connection on port 60159.
</code></pre></div></div>

<p>We can see that GROMACS is attempting to bind to port 0, and the operating system has assigned port 60159. By capturing the output of the simulation, we can extract the port number from this output. The following code snippet shows how to do this:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">assigned_port</span> <span class="o">=</span> <span class="bp">None</span>

<span class="n">retcode</span> <span class="o">=</span> <span class="n">proc</span><span class="p">.</span><span class="nf">poll</span><span class="p">()</span>
<span class="k">if</span> <span class="n">retcode</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">retcode</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
    <span class="k">raise</span> <span class="nc">RuntimeError</span><span class="p">(</span>
        <span class="sa">f</span><span class="sh">"</span><span class="s">Simulation returned with error code </span><span class="si">{</span><span class="n">retcode</span><span class="si">}</span><span class="s">. Check the simulation log for details.</span><span class="sh">"</span>
    <span class="p">)</span>

<span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="p">.</span><span class="nf">time</span><span class="p">()</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">proc</span><span class="p">.</span><span class="n">stdout</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="sh">""</span><span class="p">)</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="p">.</span><span class="nf">search</span><span class="p">(</span><span class="sa">r</span><span class="sh">"</span><span class="s">IMD connection on port (\d+)</span><span class="sh">"</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">m</span><span class="p">:</span>
        <span class="n">assigned_port</span> <span class="o">=</span> <span class="nf">int</span><span class="p">(</span><span class="n">m</span><span class="p">.</span><span class="nf">group</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
        <span class="k">break</span>
    <span class="k">if</span> <span class="n">time</span><span class="p">.</span><span class="nf">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span> <span class="o">&gt;</span> <span class="mi">60</span><span class="p">:</span>  <span class="c1"># 2 minutes timeout
</span>        <span class="k">raise</span> <span class="nc">RuntimeError</span><span class="p">(</span>
            <span class="sh">"</span><span class="s">IMD port assignment was not printed within 1 minute. Make sure an IMD simulation is being run.</span><span class="sh">"</span>
        <span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">raise</span> <span class="nc">RuntimeError</span><span class="p">(</span>
        <span class="sh">"</span><span class="s">GROMACS output did not contain expected </span><span class="sh">'</span><span class="s">IMD connection on port</span><span class="sh">'</span><span class="s">. Check the simulation log for details.</span><span class="sh">"</span>
    <span class="p">)</span>

<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Assigned IMD port: </span><span class="si">{</span><span class="n">assigned_port</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div>
<p>Now that there is a port number that is unique to the segment and is consistent between the simulation and the analysis, the analysis can be started. This follows a similar pattern to the script shown in the week 1-2 blog post.</p>

<h1 id="testing-using-westpa">Testing using WESTPA</h1>
<p>We can check whether this is working as expected by starting a weighted ensemble simulation and checking the output from each segment. No significant modifications to the standard wESTPA setup are needed, aside from modifying the <code class="language-plaintext highlighter-rouge">runseg.sh</code> script to run the new python script instead of launching the GROMACS simulation directly. In the first iteration of the simulation, 5 segments are run. Snippets of the output from two of the segments are shown below:</p>

<p><code class="language-plaintext highlighter-rouge">Segment 0</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>IMD: Setting port for connection requests to 0.
IMD: Setting up incoming socket.
IMD: Listening for IMD connection on port 60159.
Assigned IMD port: 60159
Port 60159 on localhost is now open!
</code></pre></div></div>
<p><code class="language-plaintext highlighter-rouge">Segment 1</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>IMD: Setting port for connection requests to 0.
IMD: Setting up incoming socket.
IMD: Listening for IMD connection on port 39119.
Assigned IMD port: 39119
Port 39119 on localhost is now open!
</code></pre></div></div>
<p>We can see that the two segments have been assigned different ports.</p>

<h1 id="improvements">Improvements</h1>
<p>This is a good solution but there are some improvements that can be made. It was suggested by Jeremy Leung that a lot of this code could be embedded into WESTPA as a static class. This would reduce the amount of code that needs to be exposed to the user and would make it easier to use. All the user would need to do is define the command to run the simulation and the analysis functions to be run.</p>

<p>I need to test the script with the other molecular dynamics engines which can use IMDv3, NAMD and LAMMPS. What needs to be tested is whether the “port 0 trick” works with these engines, and whether the simulation engines output the assigned port.</p>

<p>As I discussed last week, I started trying to implement trajectory streaming as an additional executable in WESTPA. The script here is essentially an alternative to this, and avoids issues with port assignment. I do wonder whether the “port 0 trick” could be used within python to obtain a list of available ports, but this still has issues with multinode setups and the port being taken by another process before the simulation starts. The <a href="https://pypi.org/project/ephemeral-port-reserve/#description">ephemeral-port-reserve</a> package has a method to reserve a port, but this is not compatible (as far as I can tell) with GROMACS IMD as it does not use <code class="language-plaintext highlighter-rouge">SO_REUSEADDR</code>. Nevertheless, I will continue to explore this option.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 4-5 trajectory streaming using python.]]></summary></entry><entry><title type="html">Week 3: Attempting to Create a Trajectory Streaming Propagator in WESTPA</title><link href="https://jpkrowe.github.io/week3/" rel="alternate" type="text/html" title="Week 3: Attempting to Create a Trajectory Streaming Propagator in WESTPA" /><published>2025-06-25T23:00:00+00:00</published><updated>2025-06-25T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week3</id><content type="html" xml:base="https://jpkrowe.github.io/week3/"><![CDATA[<p>As mentioned in my previous blog post I have started to explore the integration of trajectory streaming into the WESTPA framework. The goal is to edit the <code class="language-plaintext highlighter-rouge">executable.py</code> file in WESTPA to create a new propagator that is started by the WESTPA work manager and runs analysis processes. These changes are being tracked in pull request <a href="https://github.com/westpa/westpa/pull/495">#495</a>.</p>

<h1 id="modifications-to-the-westpa-executablepropagator">Modifications to the WESTPA ExecutablePropagator</h1>
<p><code class="language-plaintext highlighter-rouge">ExecutablePropagator</code> is a class in WESTPA, in which executables are defined to be run by the WESTPA work manager. In WESTPA, there are currently five executables defined: <code class="language-plaintext highlighter-rouge">propagator</code>, <code class="language-plaintext highlighter-rouge">pre_iteration</code>, <code class="language-plaintext highlighter-rouge">post_iteration</code>, <code class="language-plaintext highlighter-rouge">get_pcoord</code> and <code class="language-plaintext highlighter-rouge">gen_istate</code>. I added a new executable called <code class="language-plaintext highlighter-rouge">stream_trajectory</code>. This can be activated by adding the following lines to the <code class="language-plaintext highlighter-rouge">west.cfg</code> file:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>stream_trajectory:
    enabled:    true
    executable: $WEST_SIM_ROOT/westpa_scripts/analysis_streaming.sh
    stderr:     stdout
    stdout:     $WEST_SIM_ROOT/seg_logs/{segment.n_iter:06d}-{segment.seg_id:06d}_analysis.log
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">executable</code> line specifies the path to the script that will be run. The <code class="language-plaintext highlighter-rouge">stderr</code> and <code class="language-plaintext highlighter-rouge">stdout</code> lines specify where the standard error and standard output of the script will be written. The <code class="language-plaintext highlighter-rouge">{segment.n_iter:06d}</code> and <code class="language-plaintext highlighter-rouge">{segment.seg_id:06d}</code> placeholders are replaced with the current iteration number and segment ID, respectively. This allows the script to write its output to a log file that is specific to the current segment and iteration.</p>

<h2 id="addition-of-a-function-to-run-the-streaming-executable">Addition of a function to run the streaming executable</h2>
<p>In the <code class="language-plaintext highlighter-rouge">ExecutablePropagator</code> class, I added a new function called <code class="language-plaintext highlighter-rouge">stream_trajectory</code>. This function is called by the WESTPA work manager and launches the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executable. The function is defined as follows:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">stream_trajectory</span><span class="p">(</span><span class="n">self</span><span class="p">,</span> <span class="n">segments</span><span class="p">):</span>
    <span class="n">child_info</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">exe_info</span><span class="p">[</span><span class="sh">'</span><span class="s">stream_trajectory</span><span class="sh">'</span><span class="p">]</span>
    <span class="n">log</span><span class="p">.</span><span class="nf">debug</span><span class="p">(</span><span class="sh">'</span><span class="s">trajectory streaming executable: %s</span><span class="sh">'</span> <span class="o">%</span> <span class="n">child_info</span><span class="p">[</span><span class="sh">'</span><span class="s">executable</span><span class="sh">'</span><span class="p">])</span>
    <span class="k">for</span> <span class="n">segment</span> <span class="ow">in</span> <span class="n">segments</span><span class="p">:</span>
        <span class="n">addtl_env</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="n">addtl_env</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="nf">port_env_vars</span><span class="p">(</span><span class="n">segment</span><span class="p">.</span><span class="n">seg_id</span><span class="p">))</span>
        <span class="c1"># Pass the additional environment variables to the trajectory streaming executable
</span>        <span class="n">rc_stream</span><span class="p">,</span> <span class="n">rusage_stream</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="nf">exec_for_trajectory_streaming</span><span class="p">(</span><span class="n">child_info</span><span class="p">,</span> <span class="n">segment</span><span class="p">,</span> <span class="n">addtl_env</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">rc_stream</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">log</span><span class="p">.</span><span class="nf">debug</span><span class="p">(</span><span class="sh">'</span><span class="s">trajectory streaming child process for segment %d completed successfully</span><span class="sh">'</span> <span class="o">%</span> <span class="n">segment</span><span class="p">.</span><span class="n">seg_id</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">rc_stream</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">log</span><span class="p">.</span><span class="nf">error</span><span class="p">(</span>
                <span class="sh">'</span><span class="s">trajectory streaming child process for segment %d exited on signal %d (%s)</span><span class="sh">'</span>
                <span class="o">%</span> <span class="p">(</span><span class="n">segment</span><span class="p">.</span><span class="n">seg_id</span><span class="p">,</span> <span class="o">-</span><span class="n">rc_stream</span><span class="p">,</span> <span class="n">SIGNAL_NAMES</span><span class="p">[</span><span class="o">-</span><span class="n">rc_stream</span><span class="p">])</span>
            <span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">log</span><span class="p">.</span><span class="nf">error</span><span class="p">(</span><span class="sh">'</span><span class="s">trajectory streaming child process for segment %d exited with code %d</span><span class="sh">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">segment</span><span class="p">.</span><span class="n">seg_id</span><span class="p">,</span> <span class="n">rc_stream</span><span class="p">))</span>
</code></pre></div></div>
<p>This function receives a list of segments to run analysis for and adds the port to the environment variables that are passed to the executable (I will discuss port assignment later). It then calls the <code class="language-plaintext highlighter-rouge">exec_for_trajectory_streaming</code> function, which adds additional environment variables and executes the predefined executable for trajectory streaming. In WESTPA, there is currently the <code class="language-plaintext highlighter-rouge">exec_for_segment</code> function, which is used to execute the <code class="language-plaintext highlighter-rouge">propagator</code> executable. I had hoped to reuse this function, but it requires istate and bstate information, which is not needed for the trajectory streaming executable.</p>

<h1 id="modifications-to-the-westpa-sim-and-work-managers">Modifications to the WESTPA Sim and Work Managers</h1>
<p>In order for the WESTPA to run the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executable, the WESTPA Sim and Work Managers need to be modified. The Sim Manager is responsible for managing the simulation and sending tasks to the Work Manager, which is responsible for executing the tasks.</p>

<p>I added the following block of code to the <code class="language-plaintext highlighter-rouge">propagate</code> function in the Sim Manager:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># If trajectory streaming is enabled submit a streaming process
</span><span class="k">if</span> <span class="n">self</span><span class="p">.</span><span class="n">do_trajectory_streaming</span><span class="p">:</span>
    <span class="n">log</span><span class="p">.</span><span class="nf">debug</span><span class="p">(</span><span class="sh">'</span><span class="s">streaming trajectory for segment block of length: {:d}</span><span class="sh">'</span><span class="p">.</span><span class="nf">format</span><span class="p">(</span><span class="nf">len</span><span class="p">(</span><span class="n">segment_block</span><span class="p">)))</span>
    <span class="n">future</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">work_manager</span><span class="p">.</span><span class="nf">submit</span><span class="p">(</span><span class="n">wm_ops</span><span class="p">.</span><span class="n">stream_trajectory</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">segment_block</span><span class="p">,))</span>
    <span class="n">futures</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
    <span class="n">stream_futures</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
</code></pre></div></div>
<p>This code runs alongside the section of code that submits the <code class="language-plaintext highlighter-rouge">propagator</code> executable to the Work Manager. The <code class="language-plaintext highlighter-rouge">wm_ops.stream_trajectory</code> operation is defined in the Work Manager and calls the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> function in the <code class="language-plaintext highlighter-rouge">ExecutablePropagator</code> class.</p>

<h1 id="issues-with-port-assignment">Issues with Port Assignment</h1>
<p>From this code, the work manager can successfully run the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executable for each segment. However, as I elaborated in my previous blog post, both the <code class="language-plaintext highlighter-rouge">propagator</code> and <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executables need to have access to the same port. Whilst in this current implementation, WESTPA successfully sends a port number to both executables using environment variables, there are some issues with the current approach. At the moment, I have not implemented code to check whether the port is free before assigning it. This is more tricky than I initially thought, but there is likely a method to do so. A more critical issue is that the port may be free at the point at which the port is assigned using WESTPA, but may be taken by another process before the molecular dynamics code starts running. If this happens, the molecular dynamics code will fail to start.</p>

<p>Multinode setups represent a further challenge, as there is nothing stopping the work manager from running the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executable on a different node to the <code class="language-plaintext highlighter-rouge">propagator</code> executable. This would mean that the two executables may not be able to communicate with each other over localhost. This may require forcing the work manager to run the <code class="language-plaintext highlighter-rouge">stream_trajectory</code> executable on the same node as the <code class="language-plaintext highlighter-rouge">propagator</code> executable, which requires some investigation.</p>

<h1 id="next-steps">Next Steps</h1>
<p>In the next week, I am going to focus on implementing the method suggested in the previous post, where a single python executable runs both the simulation and the analysis. This avoids a lot of the issues with port assignment and ensures that both processes run on the same node. I will also continue to work on the implementation within WESTPA, and think about how to handle the port assignment issues.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Week 3 exploring the integration of trajectory streaming into the WESTPA framework.]]></summary></entry><entry><title type="html">Week 1-2: First Attempt at Trajectory Streaming Using Bash Scripting</title><link href="https://jpkrowe.github.io/week1-2/" rel="alternate" type="text/html" title="Week 1-2: First Attempt at Trajectory Streaming Using Bash Scripting" /><published>2025-06-24T23:00:00+00:00</published><updated>2025-06-24T23:00:00+00:00</updated><id>https://jpkrowe.github.io/week1-2</id><content type="html" xml:base="https://jpkrowe.github.io/week1-2/"><![CDATA[<p>In the first two weeks of my GSoC project,  I focused on setting up a basic solution for streaming WESTPA trajectories. In WESTPA, simulations are run using a bash script - <code class="language-plaintext highlighter-rouge">runseg.sh</code>. A separate script is launched by the WESTPA work manager for each weighted ensemble segment. The basic idea was to modify this script to both run the simulation and a python script that would receive the trajectory data and process it in real-time. The simulation is run in the background and instructed to use the interactive molecular dynamics (IMD) protocol to stream the trajectory data over an assigned port. A basic outline of the script using GROMACS for an NaCl system is as follows:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">PORT</span><span class="o">=</span><span class="k">$((</span>WEST_CURRENT_SEG_ID <span class="o">+</span><span class="m">10000</span><span class="k">))</span>

gmx mdrun <span class="nt">-deffnm</span> seg <span class="nt">-imdwait</span> <span class="nt">-imdport</span> <span class="nv">$PORT</span> &amp;

<span class="c">#Calculate pcoord with MDAnalysis</span>
python <span class="nv">$WEST_SIM_ROOT</span>/common_files/get_distance_streaming.py <span class="nv">$PORT</span>
<span class="nb">cat </span>dist.dat <span class="o">&gt;</span> <span class="nv">$WEST_PCOORD_RETURN</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">-imdwait</code> flag tells GROMACS to wait for the IMD client to connect before starting the simulation, and the <code class="language-plaintext highlighter-rouge">-imdport</code> flag specifies the port on which the IMD client will connect. The gromacs simulation is run in the background using the <code class="language-plaintext highlighter-rouge">&amp;</code> operator, allowing the analysis script to execute while the simulation is running. In this case, the assigned port is simply calculated by adding 10000 to the current segment ID, which is unique for each segment in WESTPA. Whilst this ensures that each segment has a unique port, it is not a robust solution as it assumes that these ports are not already in use by another process.</p>

<p>An outline of the <code class="language-plaintext highlighter-rouge">get_distance_streaming.py</code> script is as follows:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">MDAnalysis</span> <span class="k">as</span> <span class="n">mda</span>
<span class="kn">from</span> <span class="n">MDAnalysis.analysis.distances</span> <span class="kn">import</span> <span class="n">self_distance_array</span>
<span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="n">imdclient.IMD</span> <span class="kn">import</span> <span class="n">IMDReader</span>
<span class="kn">import</span> <span class="n">sys</span>

<span class="n">port</span> <span class="o">=</span> <span class="nf">int</span><span class="p">(</span><span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">u</span> <span class="o">=</span> <span class="n">mda</span><span class="p">.</span><span class="nc">Universe</span><span class="p">(</span><span class="sh">'</span><span class="s">bstate.gro</span><span class="sh">'</span><span class="p">,</span> <span class="sa">f</span><span class="sh">"</span><span class="s">imd://localhost:</span><span class="si">{</span><span class="n">port</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="n">ag</span> <span class="o">=</span> <span class="n">u</span><span class="p">.</span><span class="nf">select_atoms</span><span class="p">(</span><span class="sh">'</span><span class="s">not water</span><span class="sh">'</span><span class="p">)</span>

<span class="n">dist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">ts</span> <span class="ow">in</span> <span class="n">u</span><span class="p">.</span><span class="n">trajectory</span><span class="p">:</span>
    <span class="n">dist</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="nf">self_distance_array</span><span class="p">(</span><span class="n">ag</span><span class="p">)[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">np</span><span class="p">.</span><span class="nf">savetxt</span><span class="p">(</span><span class="sh">"</span><span class="s">dist.dat</span><span class="sh">"</span><span class="p">,</span> <span class="n">np</span><span class="p">.</span><span class="nf">array</span><span class="p">(</span><span class="n">dist</span><span class="p">))</span>
</code></pre></div></div>
<p>As a client, <a href="https://github.com/Becksteinlab/imdclient">IMDClient</a> expects that the port is already open and listening for connections. In this current form, the script will likely fail as the port is not open when the script is executed. Therefore, a small modification to the <code class="language-plaintext highlighter-rouge">get_distance_streaming.py</code> script is needed to ensure that the port is open before the IMD client attempts to connect. This is shown below:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">socket</span>
<span class="kn">import</span> <span class="n">time</span>
<span class="kn">import</span> <span class="n">sys</span>

<span class="n">port_open</span> <span class="o">=</span> <span class="bp">False</span>
<span class="n">timeout</span><span class="o">=</span><span class="mf">0.2</span>
<span class="n">port</span><span class="o">=</span><span class="nf">int</span><span class="p">(</span><span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">host</span><span class="o">=</span><span class="sh">"</span><span class="s">localhost</span><span class="sh">"</span>
<span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="p">.</span><span class="nf">socket</span><span class="p">(</span><span class="n">socket</span><span class="p">.</span><span class="n">AF_INET</span><span class="p">,</span><span class="n">socket</span><span class="p">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="k">while</span> <span class="ow">not</span> <span class="n">port_open</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">sock</span><span class="p">.</span><span class="nf">connect</span><span class="p">((</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">))</span>
    <span class="k">except</span> <span class="nb">ConnectionRefusedError</span><span class="p">:</span>
        <span class="n">time</span><span class="p">.</span><span class="nf">sleep</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Port </span><span class="si">{</span><span class="n">port</span><span class="si">}</span><span class="s"> on </span><span class="si">{</span><span class="n">host</span><span class="si">}</span><span class="s"> is now open!</span><span class="sh">"</span><span class="p">)</span>
        <span class="n">port_open</span> <span class="o">=</span> <span class="bp">True</span>
</code></pre></div></div>
<p>This simple code snippet attempts to connect to the specified port every 0.2 seconds until it succeeds, indicating that the port is open and ready for connections. Once the connection is established, the script proceeds to run the IMD client and process the trajectory data.</p>

<h2 id="issues-with-this-approach-and-next-steps">Issues with this approach and next steps</h2>
<p>As mentioned above, this current setup does not smartly assign ports to segments, which could lead to the weighted ensemble simulation crashing if other processes are using the same ports. To address this, a more robust port assignment strategy is needed. The initial idea was to use WESTPA to assign ports to segments. After some investigation, this is not as straightforward as it seems, as (as far as I am aware) python does not have a robust way to get all the open ports on a system. In addition, there is no way to guarantee that the port will remain open in the time between WESTPA assigning the port and the molecular dynamics simulation connecting to it.</p>

<p>After discussion with my mentors, Oliver Beckstein, Jeremy Leung and Lawson Woods, we decided that the best approach would be one where the molecular dynamics simulation first connects to the port, and then communicates the port back to WESTPA/the analysis script. This would ensure that the analysis script and the molecular dynamics simulation are always using the same port, and that the port is open. In its current form, it is not possible to communicate information back to WESTPA when the segments are running, so we cannot use WESTPA to communicate the port to the analysis script. Therefore, it was suggested to use a python script to run both the molecular dynamics simulation and the analysis. This script would first start the molecular dynamics simulation, check which port the molecular dynamics simulation is using, and finally run the analysis script. Wrappers for GROMACS (such as <a href="https://gromacswrapper.readthedocs.io/en/latest/">GromacsWrapper</a>) can be used to launch the GROMACS simulation and retrieve the port number from the output.</p>

<p>I have also attempted to integrate this workflow further into WESTPA, by modifying <code class="language-plaintext highlighter-rouge">executable.py</code> in WESTPA propagators. The aim would be to use the WESTPA work manager to launch analysis processes alongside the simulation processes. I will discuss this in more detail in my next post.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[First two weeks developing a simple approach]]></summary></entry><entry><title type="html">Introduction to Weighted Ensemble Simulations and MDAnalysis Streaming</title><link href="https://jpkrowe.github.io/gsocprojdesc/" rel="alternate" type="text/html" title="Introduction to Weighted Ensemble Simulations and MDAnalysis Streaming" /><published>2025-05-28T23:00:00+00:00</published><updated>2025-05-28T23:00:00+00:00</updated><id>https://jpkrowe.github.io/gsocprojdesc</id><content type="html" xml:base="https://jpkrowe.github.io/gsocprojdesc/"><![CDATA[<p>As mentioned in my last post, I am thrilled to have been accepted for Google Summer of Code 2025 with MDAnalysis and WESTPA. In this post, I am going to go deeper into the details of my project, which focuses on leveraging MDAnalysis trajectory streaming to perform on-the-fly analysis of multiple trajectories generated from Weighted Ensemble simulations.</p>

<h1 id="introduction-to-weighted-ensemble-simulations">Introduction to Weighted Ensemble Simulations</h1>
<p>Weighted Ensemble simulations are a powerful technique in molecular dynamics that allow for efficient exploration of rare events and free energy landscapes. Weighted Ensemble methods are particularly appealing as they permit the calculation of kinetics and thermodynamics of complex processes without requiring the application of biasing potentials. In the Weighted Ensemble method, many short simulations are run in parallel. The simulations are run in iterations, where after each iteration, progress coordinates are calculated, and the simulations are duplicated or culled based on their progress. WESTPA (Weighted Ensemble Simulation Toolkit for Parallel Analysis) is state-of-the-art software for performing Weighted Ensemble simulations. It provides a framework for running and managing these simulations efficiently.</p>

<h1 id="the-challenge-of-analysis-overhead">The Challenge of Analysis Overhead</h1>
<p>A potential bottleneck in Weighted Ensemble simulations is the analysis step. After each iteration, the trajectory data needs to be loaded and the progress coordinates need to be calculated. Only once the progress coordinates have been calculated and sent to WESTPA can the next iteration of simulations be started. This can lead to significant delays, especially when the trajectories are short or many coordinates are calculated.</p>

<h1 id="mdanalysis-streaming-a-potential-solution">MDAnalysis Streaming: A Potential Solution</h1>
<p>MDAnalysis is a powerful library for analyzing molecular dynamics simulations. A new feature in MDAnalysis is ability to stream a trajectory as the simulation is running. This means that the trajectory data can be processed in real-time, allowing for on-the-fly analysis. This feature is particularly useful if one wants to analyse processes that occur on very short timescales. Usually, the trajectory would have to be written to disk every few steps, which can lead to very large files when the simulations are long. By analysing the trajectory in real-time, we can avoid writing large files to disk and instead process the data as it is generated. MDAnalysis streaming is based upon <a href="https://github.com/Becksteinlab/imdclient">Interactive Molecular Dynamics</a>, which sends data from the simulation engine to an external program as the simulation is running.</p>

<h2 id="application-to-weighted-ensemble-simulations">Application to Weighted Ensemble Simulations</h2>
<p>In this project, I aim to use MDAnalysis streaming to analyse the simulations as they are running. This will allow us to calculate the progress coordinates in real-time, eliminating the need to wait for the analysis step to complete before starting the next iteration of simulations. By integrating MDAnalysis streaming with WESTPA, we can significantly reduce the overhead associated with the analysis step in Weighted Ensemble simulations.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Intro to WE and MDAnalysis Streaming]]></summary></entry><entry><title type="html">Google Summer of Code 2025 with MDAnalysis and WESTPA</title><link href="https://jpkrowe.github.io/gsocintro/" rel="alternate" type="text/html" title="Google Summer of Code 2025 with MDAnalysis and WESTPA" /><published>2025-05-21T16:20:00+00:00</published><updated>2025-05-21T16:20:00+00:00</updated><id>https://jpkrowe.github.io/gsocintro</id><content type="html" xml:base="https://jpkrowe.github.io/gsocintro/"><![CDATA[<p>I am excited to announce that I have been accepted for Google Summer of Code 2025 with MDAnalysis and WESTPA. My project aims to utilise MDAnalysis trajectory streaming to analyse many trajectories from Weighted Ensemble simulations on-the-fly. This will reduce analysis overhead and decrease the time between iterations.</p>]]></content><author><name>James (Jamie) Rowe</name></author><category term="GSOC" /><category term="Molecular dynamics" /><summary type="html"><![CDATA[Google Summer of Code 2025 introduction]]></summary></entry></feed>