API

Simulation

Simulate

class raypyng.simulate.Simulate(rml=None, hide=False, ray_path=None, **kwargs)[source]

A class that takes care of performing the simulations with RAY-UI

Parameters:
  • rml (RMLFile/string, optional) – string pointing to an rml file with the beamline template, or an RMLFile class object. Defaults to None.

  • hide (bool, optional) – force hiding of GUI leftovers, xvfb needs to be installed. Defaults to False.

  • ray_path (str, optional) – the path to the RAY-UI installation folder. If None, the program will look for RAY-UI in the standard installation paths.

alignment_errors(value)[source]

Switch the alignment errors of all the optical elements in the beamline on or off.

Parameters:

value (bool, optional) – If True, the alignment errors are switched on. If False, the alignment errors are switched off.

Returns:

None

property analyze

Turn on or off the RAY-UI analysis of the results. The analysis of the results takes time, so turn it on only if needed

Returns:

True: analysis on, False: analysis off

Return type:

bool

cleanup_child_processes()[source]

Clean up all child processes initiated by this process and any specific Xvfb processes.

property efficiency

The parameters to scan, as a list of dictionaries.

For each dictionary the keys are the parameters elements of the beamline, and the values are the values to be assigned.

property exports

Get the list of files to export after the simulation is complete.

property params

The parameters to scan, as a list of dictionaries.

For each dictionary the keys are the parameters elements of the beamline, and the values are the values to be assigned.

property path

The path where to execute the simlations

Returns:

by default the path is the current path from which the program is executed

Return type:

string

property possible_exports

A list of the files that can be exported by RAY-UI

Returns:

list of the names of the possible exports for RAY-UI

Return type:

list

property possible_exports_without_analysis

A list of the files that can be exported by RAY-UI when the analysis option is turned off

Returns:

list of the names of the possible exports for RAY-UI when analysis is off

Return type:

list

property raypyng_analysis

Turn on or off the RAYPyNG analysis of the results.

Returns:

True: analysis on, False: analysis off

Return type:

bool

reflectivity(value)[source]

Switch the reflectivity of all the optical elements in the beamline on or off.

Parameters:

value (bool, optional) – If True the reflectivity is switched on, if False the reflectivity is switched off.

property repeat

The simulations can be repeated an arbitrary number of times

If the statitcs are not good enough using 2 millions of rays is suggested to repeat them instead of increasing the number of rays

Returns:

the number of repetition of the simulations, by default is 1

Return type:

int

property rml

RMLFile object instantiated in init

rml_list(recipe=None, overwrite_rml=True)[source]

Creates the folder structure and RML files needed for simulation. This method organizes simulation parameters into RML files and prepares the directory structure for simulations, which is useful for pre-simulation checks and manual adjustments.

Parameters:
  • recipe (SimulationRecipe, optional) – Recipe to use for setting up the simulation. Defaults to None.

  • overwrite_rml (bool, optional) – If True, existing RML files will be overwritten. Defaults to True.

run(recipe=None, multiprocessing=1, force=False, overwrite_rml=True, force_exit=False, remove_rawrays=False, remove_round_folders=False)[source]

Execute simulations with optional recipe, multiprocessing, and file management options.

This method orchestrates the setup and execution of simulations, managing multiprocessing, file generation, and progress tracking.

Parameters:
  • recipe (SimulationRecipe, optional) – Recipe for simulation setup. Defaults to None.

  • multiprocessing (int or str, optional) – Number of processes for parallel execution, or ‘auto’/’max’ to derive it from available CPUs and RAM. Defaults to 1.

  • force (bool, optional) – Force re-execution of simulations. Defaults to False.

  • overwrite_rml (bool, optional) – Overwrite existing RML files. Defaults to True.

  • force_exit (bool, optional) – emergency fallback that calls os._exit when the simulations are complete. Defaults to False.

  • remove_rawrays (bool, optional) – removes RawRaysIncoming and RawRaysOutgoing files, if present.

  • remove_round_folders (bool, optional) – remove the round folders after the simulations are done.

property simulation_name

A string to append to the folder where the simulations will be executed.

slope_errors(slope_errors)[source]

Switch the slope errors of all the optical elements in the beamline on or off.

Parameters:

value (bool, optional) – If True the slope errors are switched on, if False the slope errors are switched off.

property undulator_table

The undulator table, as a pandas DataFrame.

SimulationParams

class raypyng.simulate.SimulationParams(rml=None, param_list=None, **kwargs)[source]

Handles the setup and management of simulation parameters for RAY-UI simulations.

This class is responsible for organizing simulation parameters, both independent and dependent, and generating the necessary parameter sets for conducting simulations.

rml

The RML file or the path to the RML file used as the template for simulations.

Type:

RMLFile or str

params

A list of dictionaries where each dictionary represents a set of parameters to simulate. Each key in the dictionary is a ParamElement, and its value is the parameter value(s) to simulate.

Type:

list of dict

simulation_parameters_generator()[source]

Generates a dictionary of parameters for each simulation based on the input parameter list.

Yields:

dict – A dictionary of parameters for a single simulation.

WaveHelper

Some source in RAY-UI can take as an input a file obtained by simulating the insertion device with WAVE. This class inspects the folder where the WAVES results are stored and provides a simple way to get a list of absolute paths to the simulation files.

class raypyng.wave_helper.WaveHelper(wave_folder_path, harmonics, undulator, **kwargs)[source]

Explore WAVE simulation folder and gives an easy way to convert energies into filenames

The class expects the WAVE simulations to be stored in a folder called WAVE. For instance for an undulator called ‘U49’ and harmonic=3, this filestructure is expected:

Wave ├── U49H1allrayfiles ├── U49H3allrayfiles ├── U49H5allrayfiles

Parameters:
  • wave_folder_path (str) – the path to the WAVW folder where the WAVE simulations are stored

  • harmonics (int) – the number of harmonics present.(If harmonics=2, simulations for 1st and 3rd should exist)

  • undulator (str) – the undulator name as indicated in the simulation folders

convert_energies_to_file_list(harmonic, energies)[source]

Takes the harmonic and a list of energies and returns the files location

Parameters:
  • harmonic (int) – the harmonic that you want to have

  • energies (list) – list of int, the x-ray energies

Raises:

ValueError – If an energy is not present in the WAVE simulation folder.

Returns:

list of absolute paths for each energy given as an input

Return type:

list

report_available_energies(verbose=True)[source]

Report about the availbale energies and explore the WAVE folder

Parameters:

verbose (bool, optional) – If Ture a report about the neergie is printed. Defaults to True.

VLS Grating Coefficient Calculation

This is a set of helper functions that can be used to calculate VLS gratings.

raypyng.vls_grating.calculate_vls_coeff(alpha_g_deg=89.778, beta_g_deg=85.5733, N0_lpm=2400.0, m=1, en_eV=1000.0, source_vls_distance=81.0, vls_image_distance=35.0, verbose=True)[source]

Calculate B2–B5 coefficients for a Variable Line Spacing (VLS) grating using normal incidence and diffraction angles.

The coefficients correspond to terms in the groove density expansion:

n(z) = N0 * (1 + 2*B2*z + 3*B3*z^2 + 4*B4*z^3 + 5*B5*z^4 + …)

where:
  • B2 : Cancels primary defocus

  • B3 : Cancels primary coma

  • B4 : Reduces spherical aberration

  • B5 : Cancels secondary coma

Parameters:
  • alpha_g_deg (float) – Normal incidence angle [degrees from the grating normal].

  • beta_g_deg (float) – Normal diffraction (exit) angle [degrees from the grating normal].

  • N0_lpm (float) – Central groove density [lines/mm].

  • m (int) – Diffraction order (positive for same side, negative for opposite side).

  • en_eV (float) – Photon energy [eV].

  • source_vls_distance (float) – Source-to-grating distance [m].

  • vls_image_distance (float) – Grating-to-image distance [m].

  • verbose (bool) – If True, prints a detailed recap of input parameters and results.

Returns:

  • B2 (float) – Dimensionless coefficient for defocus correction.

  • B3 (float) – Dimensionless coefficient for primary coma correction.

  • B4 (float) – Dimensionless coefficient for spherical aberration correction.

  • B5 (float) – Dimensionless coefficient for secondary coma correction.

raypyng.vls_grating.N1_to_b2(N1, k)[source]

Convert SHADOW N1 coefficient to paper b2 coefficient.

Parameters:
  • N1 (float) – SHADOW linear coefficient [lines / cm^2]

  • k (float) – Central groove density [lines / mm]

Returns:

b2 – VLS coefficient b2 [1 / m]

Return type:

float

raypyng.vls_grating.cff_for_fixed_focus(B2, en_eV, N0_lpmm, source_vls_distance_m=81.0, vls_image_distance_m=35.0, r_override=None, verbose=False)[source]

Compute the CFF (c-value) required to keep the image (focus) position fixed when scanning photon energy with a plane VLS grating.

This function determines the value of the included-angle parameter

c = cos(beta) / cos(alpha)

such that the defocus term of the optical path function vanishes (M_20 = 0). Physically, this enforces that the focal plane (e.g. exit slit, detector) remains at a fixed longitudinal position while the photon energy is varied.

The calculation implements the closed-form solution derived by Reininger & de Castro (NIM A 538, 2005) for plane variable-line-spacing (VLS) gratings. It is applicable to both:

  • collimated-beam geometries (r = rB / rA = 0), as used in the SRC beamline,

  • finite-distance geometries (r > 0), as used in LNLS-type designs.

In practice, this function answers the question:

“How must the CFF be adjusted as a function of photon energy

so that the focus does not move?”

Parameters:
  • B2 (float) – VLS defocus coefficient in units of 1/mm. This corresponds to the quadratic term in the groove-density expansion.

  • en_eV (float) – Photon energy in electron-volts.

  • N0_lpmm (float) – Central groove density of the grating in lines/mm.

  • source_vls_distance_m (float, optional) – Distance from source (or virtual source) to the grating, in meters. Used only if r_override is None.

  • vls_image_distance_m (float, optional) – Distance from the grating to the image plane (exit slit), in meters.

  • r_override (float, optional) – If provided, explicitly sets r = rB / rA. Use r_override = 0.0 for collimated-beam operation.

  • verbose (bool, optional) – If True, print intermediate optical quantities for diagnostics.

Returns:

The physically valid CFF (c > 1) that maintains a fixed focus position. Returns NaN if no real solution exists for the given parameters.

Return type:

float

Notes

  • The function automatically selects the physical algebraic branch corresponding to beta > alpha (c > 1).

  • All internal calculations are performed in SI units.

  • The returned CFF is dimensionless.

Recipes

Resolving Power

class raypyng.recipes.ResolvingPower(energy_range, exported_object, /, *args, source=None, sim_folder=None)[source]

Recipe for resolving power simulations.

The eflectivity is automatically switched off for all elements, the source if automatically recognized.

Parameters:
  • energy_range (np.array, list) – the energies to simulate in eV

  • exported_object (ObjectElement) – the object to export

  • source (ObjectElement, optional) – the source object. If None is provided, an automatic recogniton of the source will be tried. Defaults to None.

  • sim_folder (str, optional) – the name of the simulation folder. If None, the rml filename will be used. Defaults to None.

Flux

class raypyng.recipes.Flux(energy_range, exported_object, /, *args, source=None, sim_folder=None)[source]

Recipe for flux simulations.

The reflectivity is automatically switched on for all elements, and the source is automatically identified.

Parameters:
  • energy_range (np.array, list) – the energies to simulate in eV

  • exported_object (ObjectElement) – the object to export

  • source (ObjectElement, optional) – the source object. If None is provided, an automatic recogniton of the source will be tried. Defaults to None.

  • sim_folder (str, optional) – the name of the simulation folder. If None, the rml filename will be used. Defaults to None.

Process simulation files

PostProcess rays analyzed by raypyng

class raypyng.postprocessing.PostProcess[source]

class to post-process the data.

It works only if the exported data are RawRaysOutgoing

cleanup(dir_path=None, repeat=1, exp_elements=None, exported_file_type=None)[source]

Reads all the results of the postprocessing process and summarize them in a single file for each exported object.

This functions reads all the temporary files created by self.postprocess_RawRays() saves one file for each exported element in dir_path, and deletes the temporary files. If more than one round of simulations was done, the values are averaged.

Parameters:
  • dir_path (str, optional) – The path to the folder to cleanup. Defaults to None.

  • repeat (int, optional) – number of rounds of simulations. Defaults to 1.

  • exp_elements (list, optional) – the exported elements names as str. Defaults to None.

extract_bw_from_source(rml_filename)[source]

Extract photon energy from rml file, find source automatically

Parameters:

rml_filename (str) – the rml file to use to extract the photon flux

Returns:

the photon energy

Return type:

str

extract_energy_from_source(rml_filename)[source]

Extract photon energy from rml file, find source automatically

Parameters:

rml_filename (str) – the rml file to use to extract the photon flux

Returns:

the photon energy

Return type:

str

extract_nrays_from_source(rml_filename)[source]

Extract photon flux from rml file, find source automatically

Parameters:

rml_filename (str) – the rml file to use to extract the photon flux

Returns:

the photon flux

Return type:

str

postprocess_RawRays(exported_element=None, exported_object=None, dir_path=None, sim_number=None, rml_filename=None, suffix=None, remove_rawrays=False, undulator_table=None, efficiency=None)[source]

PostProcess routine of the RawRaysOutgoing extracted files.

The method looks in the folder dir_path for a file with the filename:

filename = os.path.join(dir_path, sim_number + exported_element + '-' + exported_object + '.csv')

For each file, it calculates the number of rays, bandwidth, horizontal and vertical focus size. It saves the results in an array formatted as:

[n_rays, bandwidth, hor_focus, vert_focus]

The array is then saved to:

os.path.join(dir_path, sim_number + exported_element + '_analyzed_rays.npy')

Parameters:
  • exported_element (list, optional) – List of exported element names as strings. Defaults to None.

  • exported_object (str, optional) – The exported object, tested only with RawRaysOutgoing. Defaults to None.

  • dir_path (str, optional) – Folder where the file to process is located. Defaults to None.

  • sim_number (str, optional) – Prefix of the file, typically the simulation number with a prepended _, e.g., 0_. Defaults to None.

  • rml_filename (str)

  • suffix (str)

  • remove_rawrays (bool)

PostProcess rays analyzed by RAY-UI

class raypyng.postprocessing.PostProcessAnalyzed[source]

class to analyze the data exported by RAY-UI

moving_average(x, w)[source]

Computes the morivng average with window w on the array x

Parameters:
  • x (array) – the array to average

  • w (int) – the window for the moving average

Returns:

the x array once the moving average was applied

Return type:

np.array

retrieve_bw_and_focusSize(folder_name, oe, nsimulations, rounds)[source]

Extract the bandwidth and focus size from ScalarBeamProperties of an object.

Parameters:
  • folder_name (str) – the path to the folder where the simulations are

  • oe (str) – the optical element name

  • nsimulations (int) – the number of simulations

  • rounds (int) – the number of rounds of simulations

Returns:

the bandwidth foc_x np.array: the horizontal focus foc_y np.array: the vertical focus

Return type:

bw np.array

retrieve_flux_beamline(folder_name, source, oe, nsimulations, rounds=1, current=0.3)[source]

Extract the flux from ScalarBeamProperties and from ScalarElementProperties.

This function takes as arguments the name of the simulation folder, the exported objet in RAY-UI and there number of simulations and returns the flux at the optical element in percentage and in number of photons, and the flux produced by the dipole. It requires ScalarBeamProperties to be exported for the desired optical element, if the source is a dipole it requires ScalarElementProperties to be exported for the Dipole

Parameters:
  • folder_name (str) – the path to the folder where the simulations are

  • source (str) – the source name

  • oe (str) – the optical element name

  • nsimulations (int) – the number of simulations

  • rounds (int) – the number of rounds of simulations

  • current (float, optional) – the ring current in Ampere. Defaults to 0.3.

Returns:

photon_flux (np.array)the photon flux at the optical element

flux_percent (np.array) : the photon flux in percentage relative to the source source_Photon_flux (np.array) : the photon flux of the source

else:

flux_percent (np.array) : the photon flux in percentage relative to the source

Return type:

if the source is a Dipole

RayProperties

class raypyng.postprocessing.RayProperties(input=None, filename=None, undulator_table=None)[source]
concat(other)[source]

Concatenates another RayProperties object to current.

save(filename)[source]

Save current object into a CSV file.

RAY-UI API

RayUIRunner

class raypyng.runner.RayUIRunner(ray_path=None, ray_binary='rayui.sh', background=True, hide=False)[source]

RayUIRunner class implements all logic to start a RayUI process, load and rml file, trace and export.

Parameters:
  • ray_path (str, optional) – the path to the RAY-UI installation folder. Defaults to config.ray_path, that will look for the ray_path in the standard installation folders.

  • ray_binary (_type_, optional) – the binary file of RAY-UI. Defaults to “rayui.sh”.

  • background (bool, optional) – activate background mode. Defaults to True.

  • hide (bool, optional) – Hide the RAY-UI graphical instances. Available only if xvfb is installed. Defaults to False.

property isrunning

Check weather a process is running and rerutn a boolean

Returns:

returns True if the process is running, otherwise False

Return type:

bool

kill()[source]

kill a RAY-UI process

property pid

Get process id of the RayUI process

Returns:

PID of the process if it running, None otherwise

Return type:

int

run()[source]

Open one instance of RAY-UI using subprocess

Raises:

RayPyRunnerError – if the RAY-UI executable is not found raise an error

RayUIAPI

class raypyng.runner.RayUIAPI(runner=None)[source]

RayUIAPI class implements (hopefully all) command interface of the RAY-UI

Parameters:

runner (RayUIRunner)

export(objects, parameters, export_path, data_prefix, **kwargs)[source]

Export simulation results from RAY-UI.

Parameters:
  • objects (str) – string with objects list, e.g. “Dipole,DetectorAtFocus”

  • parameters (str) – stromg with parameters to export,

  • "ScalarBeamProperties (e.g.)

  • ScalarElementProperties"

  • export_path (str) – path where to save the data

  • data_prefix (str) – prefix for the putput files

load(rml_path, **kwargs)[source]

Load an rml file

Parameters:

rml_path (str) – path to the rml file

quit()[source]

quit RAY-UI if it is running

save(rml_path, **kwargs)[source]

Save an rml file

Parameters:

rml_path (path) – path to save the rml file

trace(analyze=True, **kwargs)[source]

Trace an rml file (must have been loaded before).

Parameters:

analyze (bool, optional) – If True RAY-UI will perform analysis of the rays. Defaults to True.

RML

RMLFile

class raypyng.rml.RMLFile(filename=None, /, template=None)[source]

Read/Write wrapper for the Ray RML files

Parameters:
  • filename (str, optional) – path to rml file. Defaults to None.

  • template (str, optional) – path to rml file to use as template. Defaults to None.

read(file=None)[source]

Read rml file

Parameters:

file (str, optional) – file name to read. If set to None will use template file name defined during initilizatino of the class. Defaults to None.

write(file=None)[source]

Write the rml to file

Parameters:

file (str, optional) – filename . Defaults to None.

BeamlineElement

class raypyng.rml.BeamlineElement(name, attributes, **kwargs)[source]
Parameters:
  • name (str)

  • attributes (dict)

add_cdata(cdata)

Store cdata

add_child(element)

Store child elements.

get_attribute(key)

Get attributes by key

get_elements(name=None)

Find a child element by name

get_full_path()

Returns the full path of the xml object

Returns:

path of the xml object

Return type:

str

resolvable_name()

Returns the name of the objects, removing lab.beamline.

Returns:

name of the object

Return type:

str

ObjectElement

class raypyng.rml.ObjectElement(name, attributes, **kwargs)[source]
Parameters:
  • name (str)

  • attributes (dict)

add_cdata(cdata)

Store cdata

add_child(element)

Store child elements.

get_attribute(key)

Get attributes by key

get_elements(name=None)

Find a child element by name

get_full_path()

Returns the full path of the xml object

Returns:

path of the xml object

Return type:

str

resolvable_name()

Returns the name of the objects, removing lab.beamline.

Returns:

name of the object

Return type:

str

ParamElement

class raypyng.rml.ParamElement(name, attributes, **kwargs)[source]
Parameters:
  • name (str)

  • attributes (dict)

add_cdata(cdata)

Store cdata

add_child(element)

Store child elements.

get_attribute(key)

Get attributes by key

get_elements(name=None)

Find a child element by name

get_full_path()

Returns the full path of the xml object

Returns:

path of the xml object

Return type:

str

resolvable_name()

Returns the name of the objects, removing lab.beamline.

Returns:

name of the object

Return type:

str

Dipole

Based on srxraylib

class raypyng.dipole_flux.Dipole(bending_radius_m=None, magnetic_field_T=None, beam_energy_GeV=2.5, current_A=0.1)[source]

Synchrotron dipole radiation spectrum calculator.

calculate_spectrum(photon_energy_array, hdiv=1)[source]

Calculates the photon flux spectrum for the dipole source.

Parameters:
  • photon_energy_array (np.ndarray) – Photon energies in eV.

  • hdiv (float or array-like) – Horizontal divergence in mrad. Can be a scalar (applied uniformly) or an array matching the photon energy array.

Returns:

Array of photon fluxes for each dipole case.

Return type:

np.ndarray

plot_spectrum(show=True, save_path=None, xscale='log', yscale='log')[source]

Plots the dipole radiation spectrum for all cases.

Parameters:
  • show (bool) – If True, display the plot using plt.show().

  • save_path (str, optional) – Path to save the figure (e.g., ‘plot.png’).

  • xscale (str) – X-axis scale, usually ‘log’ or ‘linear’.

  • yscale (str) – Y-axis scale, usually ‘log’ or ‘linear’.

Returns:

(matplotlib.figure.Figure, matplotlib.axes._subplots.AxesSubplot)

Return type:

tuple