shadow4.tools package
Submodules
shadow4.tools.arrayofvectors module
Operations on arrays of 3D vectors with shape (n_vectors, 3).
Each function operates element-wise over a batch of vectors so that an entire
ray bundle can be transformed in a single NumPy call. All inputs and outputs
follow the convention v[n_vectors, 3] unless otherwise stated.
- shadow4.tools.arrayofvectors.vector_add_scalar(u, k)[source]
Calculate the sum of a vector and a scalar constant.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
k (numpy array shape (n_vectors)) – scalar values to be added.
- Returns:
Result vector.
- Return type:
numpy array shape (n_vectors)
- shadow4.tools.arrayofvectors.vector_cross(u, v)[source]
Calculate the vector cross product.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
v (numpy array shape (n_vectors,3)) – input vector 2.
- Returns:
Result vector.
- Return type:
numpy array shape (n_vectors,3)
- shadow4.tools.arrayofvectors.vector_default_efields(DIREC, pol_deg=1.0)[source]
Creates two unitary vectors pointing on a sigma and pi-polarization directions. They are perpendicular to the incident direction, and the sum of the squarred moduli is one.
- Parameters:
DIREC (numpy array of 3D vectors, shape: (n_vectors,3)) – The vector with the direction.
pol_deg (numpy array shape: (n_vectors)) – The polarization degree as defined in SHADOW.
- Returns:
(E_S, E_P): the 3D vectors, shape: (n_vectors,3) for the S and P polarizations.
- Return type:
tuple
- shadow4.tools.arrayofvectors.vector_diff(u, v)[source]
Calculate the difference of two vectors u - v.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
v (numpy array shape (n_vectors,3)) – input vector 2.
- Returns:
Result vector.
- Return type:
numpy array shape (n_vectors,3)
- shadow4.tools.arrayofvectors.vector_dot(u, v)[source]
Calculate the dot product of two vectors.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
v (numpy array shape (n_vectors,3)) – input vector 2.
- Returns:
Result dot product vector.
- Return type:
numpy array shape (n_vectors)
- shadow4.tools.arrayofvectors.vector_modulus(u)[source]
Calculates the modulus of a vector array.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
- Returns:
Result vector modulus.
- Return type:
numpy array shape (n_vectors)
- shadow4.tools.arrayofvectors.vector_modulus_square(u)[source]
Calculates the modulus of a vector array to the power 2.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
- Returns:
Result vector modulus to the power 2.
- Return type:
numpy array shape (n_vectors)
- shadow4.tools.arrayofvectors.vector_multiply_scalar(u, k)[source]
Calculate the product of a vector by a scalar.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector 1.
k (numpy array shape (n_vectors)) – scalar values to multiply by.
- Returns:
Result vector.
- Return type:
numpy array shape (n_vectors)
- shadow4.tools.arrayofvectors.vector_norm(u)[source]
Calculate the normalized vector.
- Parameters:
u (numpy array shape (n_vectors,3)) – input vector.
- Returns:
Result vector.
- Return type:
numpy array shape (n_vectors,3)
- shadow4.tools.arrayofvectors.vector_reflection(v1, normal)[source]
Calculate the reflection of a vector (ray) on a surface.
- Parameters:
v1 (array of 3D vectors, shape: (n_vectors,3)) – Incident unit vector.
normal (array of 3D vectors, shape: (n_vectors,3)) – Normal unit vector at the interface.
- Returns:
The unitary vector along the reflected direction with shape (n_vectors,3).
- Return type:
numpy array
- shadow4.tools.arrayofvectors.vector_refraction(vin, normal, n1, n2, sgn=1, do_check=0)[source]
Calculate the refraction (transmission) vector using Snell’s Law in vector form.
- Parameters:
vin (array of 3D vectors, shape: (n_vectors,3)) – Incident unit vector.
normal (array of 3D vectors, shape: (n_vectors,3)) – Normal unit vector at the interface.
n1 (numpy array) – The refraction index of the incident mediuma (n_vectors)
n2 (numpy array) – The refraction index of the object transmission (n_vectors).
sgn (numpy array) – +1 or -1 to play and adjust the directions.
do_check (int) – A flag to display incident and refracted angles.
- Returns:
numpy array – The unitary vector along the refracted direction with shape (n_vectors,3).
Reference
———
For a detailed explanation of the vector form of Snell’s Law, see
https (//www.starkeffects.com/snells-law-vector.shtml)
- shadow4.tools.arrayofvectors.vector_rotate_around_axis(u, rotation_axis, angle)[source]
Rotates the vector around an axis. It uses the Rodrigues formula [rf]
- Parameters:
rotation_axis (numpy array of 3D vectors, shape: (n_vectors,3)) – Vector specifying the rotation axis (not necessarily unit vector).
angle (float) – Rotation angle in radiants.
- Returns:
Rotated vector as a new vector.
- Return type:
Vector instance
References
- shadow4.tools.arrayofvectors.vector_scattering(K_IN, H, NORMAL)[source]
Calculate the scattering of a wavevector.
Method:
- Parameters:
K_IN (numpy array of 3D vectors, shape: (n_vectors,3)) – Incident wavevector (modulus is 2 pi / wavelength) in cm**-1.
H (numpy array of 3D vectors, shape: (n_vectors,3)) – The diffraction vector.
NORMAL (numpy array of 3D vectors, shape: (n_vectors,3)) – The normal vector.
- Returns:
The diffracted wavevector with shape (n_vectors,3).
- Return type:
numpy array
shadow4.tools.beamline_tools module
Tools (functions) to operate with the beamline (instance of S4Beamline).
- shadow4.tools.beamline_tools.beamline_get_beam_at_element(beamline, index)[source]
retrieve (and calculate if necessary) the beam after a given beamline element.
- Parameters:
beamline (instance of S4Beamline) – The beamline.
index (int) – The index of the beamline element at which the beam is extracted.
- Returns:
The beam at the index beamline element (at its image position).
- Return type:
instance of S4Beam
- shadow4.tools.beamline_tools.beamline_get_last_beam(beamline)[source]
retrieve (and calculate if necessary) the beam at the final image position (after the last element).
- Parameters:
beamline (instance of S4Beamline) – The beamline.
- Returns:
The beam at the final image position.
- Return type:
instance of S4Beam
- shadow4.tools.beamline_tools.beamline_get_source_beam(beamline)[source]
retrieve (and calculate if necessary) the beam at the source position.
- Parameters:
beamline (instance of S4Beamline) – The beamline.
- Returns:
The beam at the source position.
- Return type:
instance of S4Beam
- shadow4.tools.beamline_tools.flux_summary(beamline, spectrum_energy=None, spectrum_flux=None, e_min=None, e_max=None, nbins=102)[source]
Retrieve a summary of the absolute flux and power.
- Parameters:
beamline (instance of S4Beamline) – The beamline.
spectrum_energy (None or numpy array) – The external spectrum abscissa values in eV. If defined as None, it is obtained from S4LightSource.calculate_spectrum()
spectrum_flux (None or numpy array) – The external spectrum ordinate values in ph/s/0.1%bw. If defined as None, it is obtained from S4LightSource.calculate_spectrum()
e_min (None or float) – The minimum photon energy in eV. If defined as None, the minimum energy of the photon beam is used.
e_max (None or float) – The maximum photon energy in eV. If defined as None, the maximum energy of the photon beam is used.
nbins (int, optional) – Number of beam for the histogram calculations.
- Returns:
A text with the informations.
- Return type:
str
- shadow4.tools.beamline_tools.focnew(beamline=None, beam=None, nolost=1, mode=0, center=[0.0, 0.0])[source]
FocNew tool that finds the best focus looking at the evolution of the beam calculated after the standard deviation of some beam variables.
It locates the waist of the beam by minimizing the variance in real space with respect to the optical axis in the X, Z planes and for the circle of least confusion. For many purposes, the focus can be defined as the position where the beam spread is minimum. Thus we have to find the minimum of the variance. If x_i is the coordinate-vector of the i-th ray, and v_i is its direction vector then the variance will be: var_x(t) = (1/N) Sum[(x_i + v_i t)^2]. Expanding the sum, and taking the derivative equal to zero we obtain “t”, or location of the beast focus: t = Sum[x_i v_i] / Sum[v_i^2].
The user may also choose a center of the distribution other than the optical axis. This utility is very important in the study of monochromators and spectrographs, since it allows the user to verify the real location of the focal position.
- Parameters:
beamline (instance of S4beamline or None, optional) – The beamline instance. Note that either beamline or beam should be defined.
beam (instance of S4Beam or None) – The beam instance. Note that either beamline or beam should be defined.
nolost (int, optional) –
0=uses all rays,
1=uses only good rays (non-lost rays),
2=uses only lost rays.
mode (int, optional) – A flag to define the center: * 0 = center at origin, * 1 = Center at barycenter (coordinate mean), * 2 = External center.
center (list or tuple, optional) – The (x,z) coordinates of the center. Used if mode=2.
- Returns:
A dictionary (ticket) with the calculation results: * ticket[‘nolost’] # input flag * ticket[‘mode’] # input flag * ticket[‘center_at’] # text of mode: ‘Origin’,’Baricenter’ or ‘External’ * ticket[‘AX’] # * ticket[‘AZ’] # focnew coefficients (to be used by focnew_scan) * ticket[‘AT’] # / * ticket[‘x_waist’] # position of waist X * ticket[‘z_waist’] # position of waist Z * ticket[‘t_waist’] # position of waist T (averaged) * ticket[‘text’] = txt # a text with focnew info
- Return type:
dict
Notes
One must be careful in using FOCNEW and verify with PLOTXY that the calculations are correct. This is because with strongly asymmetric or multimodel distribution the standard deviation is not a good measure of the image “size”. Also, if the beam are not Gaussian, the relation between the FWHM and sigma is not defined (It is FWHM=2.355 sigma for beams that follow Gaussian distributions).
- shadow4.tools.beamline_tools.focnew_scan(A, x)[source]
Scans the RMS of the beam size along the optical axis using the focnew coefficients.
- Parameters:
A (numpy array or list or tuple) – array of 6 coefficients as a result of S4beam.focnew_coeffs().
x (numpy array) – the abscissas array.
- Returns:
the array with RMS values.
- Return type:
numpy array
- shadow4.tools.beamline_tools.focnew_scan_full_beamline(beamline, npoints=10)[source]
Scans the RMS of the beam size along the optical axis of the complete beamline.
- Parameters:
beamline (instance of S4beamline or None, optional) – The beamline instance. Note that either beamline or beam should be defined.
npoints (int, optional) – The number of points along the scanned p or q at each element.
- Returns:
dict
A dictionary with the data. Keys are –
x,y,z: the position (y) and RMS sizes in x and z (in m).
list_oes: a list with the position of the elements (in m).
list_screens: a list with the positions of the image screems (in m).
- list_y, list_x, list_z, list_x_label, list_z_label: lists where each element crresponds to a segment
(p or q) of an element. The Horizontal and Vertical values are separated. y in m, x and z in um.
yy_multi, xz_multi, tt_multi: similar to the previous case, but the list concatenates elements in H and V.
shadow4.tools.graphics module
Matplotlib-based plotting tools for shadow4 beam data.
Provides histo1() (1D histogram) and plotxy() (2D scatter/histogram)
as the main public interface, mirroring the classic Shadow3 ShadowTools API.
Column numbers follow the shadow4 convention (1-indexed, columns 1–33).
- exception shadow4.tools.graphics.ArgsError(value)[source]
Bases:
ExceptionRaised when a plotting function receives an invalid argument.
- shadow4.tools.graphics.Histo1_CheckArg(beam, col, xrange, yrange, nbins, nolost, ref, write, title, xtitle, ytitle, calfwhm, noplot)[source]
- class shadow4.tools.graphics.Histo1_Ticket[source]
Bases:
objectContainer for the output of a 1D histogram plot.
- exception shadow4.tools.graphics.NoValueSelectedError(value)[source]
Bases:
ExceptionRaised when no value is selected from a data set.
- shadow4.tools.graphics.histo1(beam, col, notitle=0, nofwhm=0, bar=0, **kwargs)[source]
Plot the 1D histogram of a beam column using matplotlib.
- Parameters:
beam (S4Beam) – The beam instance to histogram.
col (int) – Shadow column number (1-indexed, 1–33).
notitle (int, optional) – Set to 1 to suppress the plot title.
nofwhm (int, optional) – Set to 1 to suppress the FWHM annotation.
bar (int, optional) – 1 for a bar plot, 0 (default) for a line plot.
**kwargs – Additional keyword arguments forwarded to
S4Beam.histo1().
- Returns:
The ticket dictionary returned by
S4Beam.histo1().- Return type:
dict
- shadow4.tools.graphics.plotxy(beam, col_h, col_v, nofwhm=1, title='', **kwargs)[source]
Plot a 2D scatter/histogram of two beam columns using matplotlib.
- Parameters:
beam (S4Beam or dict) – The beam instance, or a pre-computed ticket dictionary from
S4Beam.histo2()(in which casecol_handcol_vare ignored and read from the dictionary).col_h (int) – Shadow column number for the horizontal axis (1-indexed, 1–33).
col_v (int) – Shadow column number for the vertical axis (1-indexed, 1–33).
nofwhm (int, optional) – Set to 0 to annotate FWHM values on the marginal histograms (default 1 suppresses the annotation).
title (str, optional) – Plot title. Defaults to
"plotxy".**kwargs – Additional keyword arguments forwarded to
S4Beam.histo2().
- Returns:
The ticket dictionary returned by
S4Beam.histo2().- Return type:
dict
- shadow4.tools.graphics.plotxy_CheckArg(beam, cols1, cols2, nbins, nbins_h, level, xrange, yrange, nolost, title, xtitle, ytitle, noplot, calfwhm, contour)[source]
shadow4.tools.logger module
Logging verbosity helpers for shadow4.
The module wraps Python’s standard logging root logger with a simple
two-level interface (verbose / debug) so that the rest of shadow4 does not
need to import logging directly.
Default level is WARNING, meaning neither is_verbose() nor
is_debug() returns True until explicitly enabled.
Example usage:
from shadow4.tools.logger import set_verbose, printlog
set_verbose(1)
printlog("ray tracing started") # emits at INFO level
- shadow4.tools.logger.printlog(*args)[source]
Emit a message at INFO level via the root logger.
- Parameters:
*args – Passed directly to
logging.info().
shadow4.tools.srw module
Optional SRW (Synchrotron Radiation Workshop) import helper.
Attempts to import SRW in the following order:
srwpy(OASYS 2.0, SRW 4)srwlib(SRW 3, standalone)oasys_srw(OASYS 1.x)
Sets the module-level flag SRW_INSTALLED = False if none of the above
is available, so callers can guard SRW-dependent code with:
from shadow4.tools.srw import SRW_INSTALLED
if SRW_INSTALLED:
...