opal.analysis package
Notebooks
opal.analysis.FieldAnalysis module
- class opal.analysis.FieldAnalysis.FieldAnalysis[source]
Bases:
object
- max(var, step=0)[source]
Get the maximum value of a variable.
- Parameters:
var (str) – variable name
step (int, optional) – time step
- Returns:
the maximum value of the given variable
- Return type:
numpy.float64
opal.analysis.H5Statistics module
- class opal.analysis.H5Statistics.H5Statistics[source]
Bases:
Statistics
- _halo_2d_ellipsoidal_beam(q, p)[source]
Compute the 2D halo
Compute the 2D halo in horizontal, vertical or longitudinal direction according to
\[\begin{split}\begin{align} H_i & = \frac{\sqrt{3}}{2} \frac{\sqrt{A}}{B} - \frac{15}{7} \\ A & = {<}q^4{>}{<}p^4{>} + 3 {<}q^2p^2{>}^2 - 4 {<}qp^3{>} {<}q^3p{>} \\ B & = {<}q^2{>}{<}p^2{>} - {<}qp{>}^2 \end{align}\end{split}\]with coordinate q and momentum p.
- Parameters:
q (array_like) – coordinate data
p (array_like) – momentum data
- Returns:
halo
- Return type:
float
References
https://journals.aps.org/prab/abstract/10.1103/PhysRevSTAB.5.124202
- _select(data, attrval, val)[source]
Take a slice from the array
- Parameters:
data (array_like) – Container to extract data from
attrval (array_like) – Data to compare with in extraction value
val (int or float) – Value for extraction comparison
- Returns:
Slice of data
- Return type:
array_like
- _selectBunch(data, bunch, step)[source]
Take a bunch slice from the array
- Parameters:
data (array_like) – The data where to extract
bunch (int) – Bunch to select
step (int) – Step in H5 file
- Returns:
Slice of data
- Return type:
array_like
- find_beams(var, **kwargs)[source]
Compute the starting and end points of a beam via a histogram.
The purpose of this script is to distinguish bunches of a multi-bunch simulation.
- Parameters:
var (str) – The variable
step (int, optional) – Step in H5 file (default: 0)
bins (int, optional) – Number of bins for histogram (default: 0)
Wn (float, optional) – Critical frequency for lowpass filter (default: 0.15) (see https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.butter.html)
- Returns:
peaks (ndarray) – Indices of minima locations
hist (array) – The values of the corresponding numpy histogram.
bin_edges (array of dtype float) – Return the bin edges
(length(hist)+1)
.
- gaussian_kde(var, **kwargs)[source]
Representation of a kernel-density estimate using Gaussian kernels.
- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
scipy kernel density estimator
- Return type:
scipy.stats.gaussian_kde
Notes
23. March 2018 https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html
- halo_2d_ellipsoidal_beam(var, **kwargs)[source]
Compute the 2D halo for a ellipsoidal beam
Compute the 2D halo in horizontal, vertical or longitudinal direction according to
\[\begin{split}\begin{align} H_i & = \frac{\sqrt{3}} {2} \frac{\sqrt{A}} {B} - \frac{15}{7} \\ A & = {<}q^4{>}{<}p^4{>} + 3 {<}q^2p^2{>}^2 - 4 {<}qp^3{>} {<}q^3p{>} \\ B & = {<}q^2{>}{<}p^2{>} - {<}qp{>}^2 \end{align}\end{split}\]with coordinate q and momentum p. Specify either the ‘step’ or ‘turn’ (probes only).
- Parameters:
var (str) – The direction ‘x’, ‘y’, ‘z’
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
halo
- Return type:
float
References
https://journals.aps.org/prab/abstract/10.1103/PhysRevSTAB.5.124202
- halo_continuous_beam(var, **kwargs)[source]
Compute the halo for a continuous beam.
Compute the halo in horizontal or vertical direction according to
\[h_x = \frac{{<}x^4{>}} {{<}x^2{>}^2} - 2\]- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
halo
- Return type:
float
References
T. P. Wangler, Los Alamos National Laboratory, Los Alamos, NM 87545, K. R. Crandall, TechSource, Santa Fe, NM 87594-1057, BEAM HALO IN PROTON LINAC BEAMS, XX International Linac Conference, Monterey, California
- halo_ellipsoidal_beam(var, **kwargs)[source]
Compute the halo for a ellipsoidal beam
Compute the halo in horizontal, vertical or longitudinal direction according to
\[h_x = \frac{{<}x^4{>}} {{<}x^2{>}^2} - \frac{15}{7}\]- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
halo
- Return type:
float
References
T. P. Wangler, Los Alamos National Laboratory, Los Alamos, NM 87545, K. R. Crandall, TechSource, Santa Fe, NM 87594-1057, BEAM HALO IN PROTON LINAC BEAMS, XX International Linac Conference, Monterey, California
- histogram(var, bins, **kwargs)[source]
Compute a histogram of a dataset
- Parameters:
var (str) – The variable
bins (int or str) – Binning type or nr of bins (see https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html)
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
density (bool, optional) – Normalize such that integral over range is 1 (default: True).
- Returns:
numpy.histogram (array) – The values of the histogram. See density and weights for a description of the possible semantics.
bin_edges (array of dtype float) – Return the bin edges
(length(hist)+1)
.
Notes
See https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html
- kurtosis(var, **kwargs)[source]
Compute the kurtosis (Fisher or Pearson) of a dataset.
Kurtosis is the fourth central moment divided by the square of the variance. Fisher’s definition is used, i.e. 3.0 is subtracted from the result to give 0.0 for a normal distribution.
- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
kurtosis
- Return type:
float
Notes
23. March 2018 https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html
- mean(var, **kwargs)[source]
Calculate the arithmetic mean.
- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
arithmetic mean
- Return type:
float
- moment(var, k, **kwargs)[source]
Calculate the k-th central moment.
- Parameters:
var (str) – The variable to compute k-th central moment
k (int) – The moment number, k = 1 is central mean
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
k-th central moment
- Return type:
float
Notes
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.moment.html
- projected_emittance(dim, **kwargs)[source]
Compute the projected emittance
It shifts the coordinates by their mean value such that the bunch is centered around zero.
\[\varepsilon = \sqrt{ {<}coords^2{>}{<}momenta^2{>} - {<}coords*momenta{>}^2 }\]- Parameters:
dim (str) – the dimension ‘x’, ‘y’ or ‘z’
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
the projected emittance
- Return type:
float
- radial_halo_2d_ellipsoidal_beam(azimuth, **kwargs)[source]
Compute the 2D radial halo for a ellipsoidal beam
Compute the 2D radial halo according to
\[\begin{split}\begin{align} H_i & = \frac{\sqrt{3}}{2} \frac{\sqrt{A}}{B} - \frac{15}{7} \\ A & = {<}r^4{>}{<}p^4{>} + 3 {<}r^2p^2{>}^2 - 4 {<}rp^3{>} {<}r^3p{>} \\ B & = {<}r^2{>}{<}p^2{>} - {<}rp{>}^2 \end{align}\end{split}\]with radius r and radial momentum p.
- Parameters:
azimuth (float) – Azimuth for radial halo only (in degree)
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
halo
- Return type:
float
References
https://journals.aps.org/prab/abstract/10.1103/PhysRevSTAB.5.124202
- radial_halo_ellipsoidal_beam(**kwargs)[source]
Compute the radial halo for a ellipsoidal beam
Compute the halo in radial direction according to
\[h_r = \frac{{<}r^4{>}} {{<}r^2{>}^2} - \frac{15}{7}\]- Parameters:
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
halo
- Return type:
float
References
T. P. Wangler, Los Alamos National Laboratory, Los Alamos, NM 87545, K. R. Crandall, TechSource, Santa Fe, NM 87594-1057, BEAM HALO IN PROTON LINAC BEAMS, XX International Linac Conference, Monterey, California
- radial_moment(k, **kwargs)[source]
Calculate the k-th central radial moment.
- Parameters:
k (int) – The moment number, k = 1 is central mean
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
k-th central radial moment
- Return type:
float
Notes
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.moment.html
- radial_projected_emittance(azimuth, **kwargs)[source]
Compute the radial projected emittance
It shifts the coordinates by their mean value such that the bunch is centered around zero.
\[\varepsilon = \sqrt{ {<}r^2{>}{<}p_r^2{>} - {<}r*p_r{>}^2 }\]- Parameters:
azimuth (float) – Azimuth angle (in degree)
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
the projected emittance
- Return type:
float
- rotate(y, theta)[source]
Rotate the coordinates (x, y) by theta (degree)
- Parameters:
x (dask.array) – x-data
y (dask.array) – y-data
theta (float) – The angle in degree
- Returns:
rx (dask.array) – rotated coordinates x
ry (dask.array) – rotated coordinates y
Notes
\[\begin{split}\begin{align} R(\theta) & = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix} \\ \begin{bmatrix} rx & ry \end{bmatrix} & = R(\theta) * \begin{bmatrix} x & y \end{bmatrix} \end{align}\end{split}\]References
- selectData(var, **kwargs)[source]
Select subset of data
Given a H5 dataset, select a subset using the attributes step (or turn) and bunch.
- Parameters:
var (str) – Variable name
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
Data array
- Return type:
array_like
- skew(var, **kwargs)[source]
Calculate the skewness.
- Parameters:
var (str) – The variable
bunch (int, optional) – Bunch to select (default: -1, which means all particles)
step (int, optional) – Step in H5 file (default: 0)
turn (int, optional) – Turn of dataset (default: None, which implies no specific turn selection) (probe H5 files only)
- Returns:
skewness
- Return type:
float
Notes
23. March 2018 https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
opal.analysis.OptimizerAnalysis module
- class opal.analysis.OptimizerAnalysis.OptimizerAnalysis[source]
Bases:
object
- find(function, opt=0)[source]
Find the individual according to the given function in the Pareto file.
- Parameters:
function (callable) – A function that takes all objectives of 2 individuals as values of 2 lists as argument and returns the better individual. The objectives are considered alphabetically ordered
opt (int, optional) – Number of Pareto file
- Returns:
The ID of best individual that fulfills the custom function.
- Return type:
int
- find_minimum(exclude=[], constraints={})[source]
Find the invidual with minimum sum of all objectives over all generations.
It is possible to exclude some objectives with the list exclude.
It is possible to give constraints on objectives as a dictionary, e.g. { “DPEAK_1_16”: 4.0 } means only individuals that have a “DPEAK_1_16” objective with a value <= 4.
- Parameters:
exclude (list, optional) – Objectives that should be excluded
constraints (dict, optional) – Constraints on objectives
- Returns:
float – Sum of objectives
int – Generation
int – Individual ID
- print_individual(ind, gen=1, opt=0, pareto=False)[source]
Print the values of the design variables and objectives of an individual.
If pareto = True, gen is not considered.
- Parameters:
ind (int) – Individual identity number
gen (int, optional) – Generation, default: 1
opt (int, optional) – Optimizer, default: 0
pareto (bool, optional) – Load pareto file (default: False)
opal.analysis.SamplerStatistics module
- class opal.analysis.SamplerStatistics.SamplerStatistics[source]
Bases:
object
- find_matches(ids1, ids2, **kwargs)[source]
Compare two lists
Compare two lists with indices ids1 and ids2 in order to check if they are independent (i.e. not many matches).
- Parameters:
ids1 (list) – Indices of 1st sample set
ids2 (list) – Indices of 2nd sample set
matches (bool, optional) – If true, the input values of the matches are returned as well, (default: False)
- Returns:
int – Number of matches
list – Values of matched input (only if matches is True)
opal.analysis.Statistics module
- class opal.analysis.Statistics.Statistics[source]
Bases:
object
Base class for all statistic functions on datasets.
It also provides functions on plain data.
- gaussian_kde(data)[source]
Calculate the kernel density estimator directly on data.
- Parameters:
data (array_like) – Plain data
- Returns:
scipy kernel density estimator
- Return type:
scipy.stats.gaussian_kde
- histogram(data, **kwargs)[source]
Compute a histogram of a dataset
- Parameters:
data (array_like) – Plain data
bins (int or str, optional) – Binning type or nr of bins (default: ‘sturges’) (see https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html)
density (bool, optional) – Normalize such that integral over range is 1 (default: True).
- Returns:
numpy.histogram (array) – The values of the histogram. See density and weights for a description of the possible semantics.
bin_edges (array of dtype float) – Return the bin edges
(length(hist)+1)
.
Notes
See https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.histogram.html
- kurtosis(data)[source]
Compute the kurtosis (Fisher or Pearson) directly on data.
- Parameters:
data (array_like) – Plain data
- Returns:
kurtosis
- Return type:
float
- mean(data)[source]
Calculate the arithmetic mean directly on data.
- Parameters:
data (array_like) – Plain data
- Returns:
arithmetic mean
- Return type:
float
opal.analysis.StdOpalOutputAnalysis module
opal.analysis.TrackOrbitAnalysis module
- class opal.analysis.TrackOrbitAnalysis.TrackOrbitAnalysis[source]
Bases:
object
- calcTurnSeparation(nsteps=-1, angle=0.0)[source]
Calculate turn separation from OPAL xxx–trackOrbit.dat file
- Parameters:
nsteps (int) – Number of steps per turn
angle (float) – Angle of reference line in radians
- Returns:
float – Turn separation
float – Energy
float – Radial angle phi_r
float – Radius
Examples
Check Cyclotron.ipynb in the opal/test directory
opal.analysis.cyclotron module
- opal.analysis.cyclotron.calcCenteringExtraction(radius, turnCorrection=1.35, phaseCorrection=0.0, amplitudeCorrection=1)[source]
Calculate betatron tune values and zentrierung
Based on Fortran routine from Martin Humbel “Bestimmung der horizontalen Betatronschwingungsgroessen R0, DR, A und B mit der Methode der Normalengleichung”
- Parameters:
radius (array_like) – Radii of turns
turnCorrection (float, optional) – Betatron oscillations per turn (tune), default value (1.35) based on PSI Ring
phaseCorrection (float, optional) – Phase correction for betatron calculation in grad (radial angle between measurement and extraction, default: 0)
amplitudeCorrection (float, optional) – Amplitude correction for betatron calculation (default: 1)
- Returns:
The centering values
- Return type:
array
Examples
Check Cyclotron.ipynb in the opal/test directory
- opal.analysis.cyclotron.detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising', kpsh=False, valley=False, show=False, ax=None)[source]
Detect peaks in data based on their amplitude and other features.
- Parameters:
x (array_like) – 1D data.
mph (None or number, optional) – Detect peaks that are greater than minimum peak height (default: None).
mpd (int, optional) – detect peaks that are at least separated by minimum peak distance (in number of data, default = 1).
threshold (int, optional) – Detect peaks (valleys) that are greater (smaller) than threshold in relation to their immediate neighbors (default = 0).
edge (None or str) – {None, ‘rising’, ‘falling’, ‘both’}, optional (default = ‘rising’) for a flat peak, keep only the rising edge (‘rising’), only the falling edge (‘falling’), both edges (‘both’), or don’t detect a flat peak (None).
kpsh (bool, optional) – keep peaks with same height even if they are closer than mpd (default = False).
valley (bool, optional) – If True, detect valleys (local minima) instead of peaks.
show (bool, optional) – If True, plot data in matplotlib figure.
ax (matplotlib.axes.Axes instance, optional) –
- Returns:
ind – indices of the peaks in x.
- Return type:
array_like
Notes
The detection of valleys instead of peaks is performed internally by simply negating the data: ind_valleys = detect_peaks(-x)
The function can handle NaN’s
See this IPython Notebook [1].
References
Examples
>>> from detect_peaks import detect_peaks >>> x = np.random.randn(100) >>> x[60:81] = np.nan >>> # detect all peaks and plot data >>> ind = detect_peaks(x, show=True) >>> print(ind)
>>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5 >>> # set minimum peak height = 0 and minimum peak distance = 20 >>> detect_peaks(x, mph=0, mpd=20, show=True)
>>> x = [0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0] >>> # set minimum peak distance = 2 >>> detect_peaks(x, mpd=2, show=True)
>>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5 >>> # detection of valleys instead of peaks >>> detect_peaks(x, mph=0, mpd=20, valley=True, show=True)
>>> x = [0, 1, 1, 0, 1, 1, 0] >>> # detect both edges >>> detect_peaks(x, edge='both', show=True)
>>> x = [-2, 1, -2, 2, 1, 1, 3, 0] >>> # set threshold = 2 >>> detect_peaks(x, threshold = 2, show=True)
- opal.analysis.cyclotron.eval_radial_momentum(px, py, theta)[source]
Evaluate the radial momentum
- Parameters:
px (float or array) – Data of momentum in x
py (float or array) – Data of momentum in y
theta (float) – Azimuthal angle (in radian)
- Returns:
Radial momentum
- Return type:
float
Notes
\[\begin{split}\begin{align} x & = r \sin(\theta) \\ y & = r \cos(\theta) \\ r & = \sqrt(x^2 + y^2) \\ \frac{dr}{dt} & = \frac{dr}{dx} \frac{dx}{dt} + \frac{dr}{dy} \frac{dy}{dt} \\ \frac{dr}{dt} & \sim \textrm{radial momentum}~p_r \\ \frac{dx}{dt} & \sim \textrm{horizontal momentum}~p_x \\ \frac{dy}{dt} & \sim \textrm{longitudinal momentum}~p_y \\ \frac{dr}{dx} & = \frac{1}{2 r} * 2 * x = \frac{x}{r} = \cos(\theta) \\ \frac{dr}{dy} & = \frac{1}{2 r} * 2 * y = \frac{y}{r} = \sin(\theta) \\ \rightarrow p_r & = p_x \cos(\theta) + p_y \sin(\theta) \end{align}\end{split}\]
opal.analysis.pareto_fronts module
- opal.analysis.pareto_fronts.delete_repeats(x, y, z=0)[source]
Delete repeated pareto front values, if any.
- Parameters:
x (array_like) – 1D array of first objective values
y (array_like) – 1D array of second objective values
z (array_like, optional) – ND array of second design variables
- Return type:
df (pandas db) database with out repeats
- opal.analysis.pareto_fronts.get_all_data_db(dbpath)[source]
Get objectives and design variables
Get all objectives and design variables from every generation in an optimzation database. Databases are made using OPAL output from json files or stat files. Functions to make databases can be found in mldb.py.
- Parameters:
db (str) – Path to pickle file containing database made with mldb.py
- Returns:
data – Dictonary containing all objectives and design values in optimization database.
- Return type:
dict
- opal.analysis.pareto_fronts.pareto_pts(x, y)[source]
Find Pareto points
Find Pareto points for 2 objectives, given all data recorded by optimization run. These points are calculated independent of generation. i.e. best points from all generations are found and saved.
- Parameters:
x (array_like) – 1D array of first objective values
y (array_like) – 1D array of second objective values
dvars (array_like, optional) – ND array of design variables
- Returns:
pfdict – Dictionary that holds pareto front values and corresponding design values
- Return type:
dict