<jupyter_start><jupyter_text>Parallel processing with a virtual HDF5 datasetThis example demonstrates splitting up some data to be processed by several worker processes, and collecting the results back together.For this example, we'll use data from an XGM, and find the average intensity of each pulse across all the trains in the run. This doesn't actually need parallel processing: we can easily do it directly in the notebook. But the same techniques should work with much more data and more complex calculations.<jupyter_code>from extra_data import RunDirectory
import multiprocessing
import numpy as np<jupyter_output><empty_output><jupyter_text>The data that we want is separated over these seven sequence files:<jupyter_code>!ls /gpfs/exfel/exp/XMPL/201750/p700000/raw/r0002/RAW-R0034-DA01-S*.h5
run = RunDirectory('/gpfs/exfel/exp/XMPL/201750/p700000/raw/r0002/')<jupyter_output><empty_output><jupyter_text>By making a virtual dataset, we can see the shape of it, as if it was one big numpy array:<jupyter_code>vds_filename = 'xgm_vds.h5'
xgm_vds = run.get_virtual_dataset(
    'SA1_XTD2_XGM/XGM/DOOCS:output', 'data.intensityTD',
    filename=vds_filename
)
xgm_vds<jupyter_output><empty_output><jupyter_text>Let's read this into memory and calculate the means directly, to check our parallel calculations against.We can do this for this example because the calculation is simple and the data is small;it wouldn't be practical in real situations where parallelisation is useful.These data are recorded in 32-bit floats, but to minimise rounding errors we'll tell numpy to give the results as 64-bit floats. Try re-running this example with 32-bit floats to see how much the results change!<jupyter_code>simple_mean = xgm_vds[:, :40].mean(axis=0, dtype=np.float64)
simple_mean.round(4)<jupyter_output><empty_output><jupyter_text>Now, we're going to define chunks of the data for each of 4 worker processes.<jupyter_code>N_proc = 4
cuts = [int(xgm_vds.shape[0] * i / N_proc) for i in range(N_proc + 1)]
chunks = list(zip(cuts[:-1], cuts[1:]))
chunks<jupyter_output><empty_output><jupyter_text>Using `multiprocessing`This is the function we'll ask each worker process to run, adding up the data and returning a 1D numpy array.We're using default arguments as a convenient way to copy the filename and the dataset path into the worker process.<jupyter_code>def sum_chunk(chunk, filename=vds_filename, ds_name=xgm_vds.name):
    start, end = chunk
    # Reopen the file in the worker process:
    import h5py, numpy
    with h5py.File(filename, 'r') as f:
        ds = f[ds_name]
        data = ds[start:end]  # Read my chunk
    
    return data.sum(axis=0, dtype=numpy.float64)<jupyter_output><empty_output><jupyter_text>Using Python's `multiprocessing` module, we start four workers, farm the chunks out to them, and collect the results back.<jupyter_code>with multiprocessing.Pool(N_proc) as pool:
    res = pool.map(sum_chunk, chunks)<jupyter_output><empty_output><jupyter_text>`res` is now a list of 4 arrays, containing the sums from each chunk. To get the mean, we'll add these up to get a grand total, and then divide by the number of trains we have data from.<jupyter_code>multiproc_mean = (np.stack(res).sum(axis=0, dtype=np.float64)[:40] / xgm_vds.shape[0])
np.testing.assert_allclose(multiproc_mean, simple_mean)

multiproc_mean.round(4)<jupyter_output><empty_output><jupyter_text>Using SLURMWhat if we need more power? The example above is limited to one machine, but we can use SLURM to spread the work over multiple machines on the [Maxwell cluster](https://confluence.desy.de/display/IS/Maxwell).This is massive overkill for this example calculation - we'll only use one CPU core for a fraction of a second on each machine. But we could do something similar for a much bigger problem.<jupyter_code>from getpass import getuser
import h5py
import subprocess<jupyter_output><empty_output><jupyter_text>We'll write a Python script for each worker to run. Like the `sum_chunk` function above, this reads a chunk of data from the virtual dataset and sums it along the train axis. It saves the result into another HDF5 file for us to collect.<jupyter_code>%%writefile parallel_eg_worker.py
#!/gpfs/exfel/sw/software/xfel_anaconda3/1.1/bin/python
import h5py
import numpy as np
import sys

filename = sys.argv[1]
ds_name = sys.argv[2]
chunk_start = int(sys.argv[3])
chunk_end = int(sys.argv[4])
worker_idx = sys.argv[5]

with h5py.File(filename, 'r') as f:
    ds = f[ds_name]
    data = ds[chunk_start:chunk_end]  # Read my chunk

chunk_totals = data.sum(axis=0, dtype=np.float64)

with h5py.File(f'parallel_eg_result_{worker_idx}.h5', 'w') as f:
    f['chunk_totals'] = chunk_totals<jupyter_output>Writing parallel_eg_worker.py<jupyter_text>The Maxwell cluster is divided into various partitions for different groups of users. If you're running this as an external user, comment out the 'Staff' line below.<jupyter_code>partition = 'upex'   # External users
partition = 'exfel'  # Staff<jupyter_output><empty_output><jupyter_text>Now we submit 4 jobs with the `sbatch` command:<jupyter_code>for i, (start, end) in enumerate(chunks):
    cmd = ['sbatch', '-p', partition, 'parallel_eg_worker.py', vds_filename, xgm_vds.name, str(start), str(end), str(i)]
    print(subprocess.check_output(cmd))<jupyter_output>b'Submitted batch job 2631813\n'
b'Submitted batch job 2631814\n'
b'Submitted batch job 2631815\n'
b'Submitted batch job 2631816\n'<jupyter_text>We can use `squeue` to monitor the jobs running. Re-run this until all the jobs have disappeared, meaning they're finished.<jupyter_code>!squeue -u {getuser()}<jupyter_output>JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)<jupyter_text>Now, so long as all the workers succeeded, we can collect the results.If any workers failed, you'll find tracebacks in `slurm-*.out` files in the working directory.<jupyter_code>res = []

for i in range(N_proc):
    with h5py.File(f'parallel_eg_result_{i}.h5', 'r') as f:
        res.append(f['chunk_totals'][:])<jupyter_output><empty_output><jupyter_text>Now `res` is once again a list of 1D numpy arrays, representing the totals from each chunk. So we can finish the calculation as in the previous section:<jupyter_code>slurm_mean = np.stack(res).sum(axis=0)[:40] / xgm_vds.shape[0]
np.testing.assert_allclose(slurm_mean, simple_mean)

slurm_mean.round(4)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09133416458852868, 'fraction_numerical': 0.020105985037406484, 'mean_word_length': 5.581538461538462, 'pattern_counts': {'":': 0, '<': 58, '<?xml version=': 0, '>': 58, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '100968', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 2198, 'n_tokens_neox': 2080, 'n_words': 696, 'path': 'docs/parallel_example.ipynb', 'repo_name': 'trpreston5/EXtra-data', 'size': '6416'}