epsproc package

Module contents

epsproc.ADMdimList(sType='stacked')[source]

Return standard list of dimensions for frame definitions, from epsproc.sphCalc.setADMs().

Parameters:sType (string, optional, default = 'stacked') – Selected ‘stacked’ or ‘unstacked’ dimensions. Set ‘sDict’ to return a dictionary of unstacked <> stacked dims mappings for use with xr.stack({dim mapping}).
Returns:list
Return type:set of dimension labels.
epsproc.AFBLMCalcLoop(matE, AKQS=<sphinx.ext.autodoc.importer._MockObject object>, eAngs=[0, 0, 0], thres=1e-06, p=0, R=0, verbose=1)[source]

Calculate inner loop for MFBLMs, based on passed set of matrix elements (Xarray).

Loop code based on Matlab code ePSproc_MFBLM.m

This works, but not very clean or efficient - should be possible to parallelize & vectorise… but this is OK for testing, benchmarking and verification purposes.

Parameters:
  • matE (Xarray) – Contains one set of matrix elements to use for calculation. Currently assumes these are a 1D list, with associated (l,m,mu) parameters, as set by mfblm().
  • AKQS (Xarray or np.array, optional, default = np.array([0,0,0,1], ndmin = 2)) – Array containing alignment parameters (axis distribution moments), $A_{Q,S}^{K}(t)$. Format is [K,Q,S,value…] if np.array. For Xarray, (K,Q,S) coords are set as multindex dimension ADM, as per epsproc.setADMs(). Default value corresponds to an isotropic axis distribution.
  • eAngs ([phi,theta,chi], optional, default = [0,0,0]) – Single set of Euler angles defining polarization geometry.
  • thres (float, optional, default = 1e-4) – Threshold value for testing significance of terms. Terms < thres will be dropped.
  • p (int, optional, default p = 0) – LF polarization term. Currently only valid for p = 0
  • R (int, optional, default R = 0) – LF polarization term (from tensor contraction). Currently only valid for p = 0
  • verbose (int, optional, default 1) –

    Verbosity level:

    • 0: Silent run.
    • 1: Print basic info.
    • 2: Print intermediate C parameter array to terminal when running.
Returns:

  • BLMX (Xarray) – Set of B(L,M; eAngs, Eke) terms for supplied matrix elements, in an Xarray. For cases where no values are calculated (below threshold), return an array with B00 = 0 only.
  • Limitations & To Do
  • ——————–
  • * Currently set with (p,R) values passed, but only valid for (0,0) (not full sum over R terms as shown in formalism above.)
  • * Set to accept a single set of matrix elements (single E), assuming looping over E (and other parameters) elsewhere.
  • * Not explicitly parallelized here, should be done by calling function.
  • (Either via Xarray methods, or numba/dask…? http (//xarray.pydata.org/en/stable/computation.html#wrapping-custom-computation))
  • * Coded for ease, not efficiency - there will be lots of repeated ang. mom. calcs. when run over many sets of matrix elements.
  • * Scale factor currently not propagated.

class epsproc.Arrow3D(xs, ys, zs, *args, **kwargs)[source]

Bases: sphinx.ext.autodoc.importer._MockObject

Define Arrow3D plotting class

Code verbatim from StackOverflow post https://stackoverflow.com/a/22867877 Thanks to CT Zhu, https://stackoverflow.com/users/2487184/ct-zhu

draw(renderer)[source]
epsproc.BLMdimList(sType='stacked')[source]

Return standard list of dimensions for calculated BLM.

Parameters:sType (string, optional, default = 'stacked') – Selected ‘stacked’ or ‘unstacked’ dimensions. Set ‘sDict’ to return a dictionary of unstacked <> stacked dims mappings for use with xr.stack({dim mapping}).
Returns:list
Return type:set of dimension labels.
epsproc.BLMplot(BLM, thres=0.01, thresType='abs', xDim='Eke', backend='xr')[source]

Plotting routines for BLM values from Xarray. Plot line or surface plot, with various backends available.

Parameters:
  • BLM (Xarray) – Input data for plotting, dims assumed to be as per ePSproc.util.BLMdimList()
  • thres (float, optional, default 1e-2) – Value used for thresholding results, only values > thres will be included in the plot. Either abs or relative (%) value, according to thresType setting.
  • thresType (str, optional, default = 'abs') – Set to ‘abs’ or ‘pc’ for absolute threshold, or relative value (%age of max value in dataset)
  • xDim (str, optional, default = 'Eke') – Dimension to use for x-axis, also used for thresholding. Default plots (Eke, BLM) surfaces with subplots for (Euler). Change to ‘Euler’ to plot (Euler, BLM) with (Eke) subplots.
  • backend (str, optional, default = 'xr') – Plotter to use. Default is ‘xr’ for Xarray internal plotting. May be switched according to plot type in future…
epsproc.EDCSFileParse(fileName)[source]

Parse an ePS file for EDCS segments.

Parameters:fileName (str) – File to read (file in working dir, or full path)
Returns:
  • list – [lineStart, lineStop], ints for line #s found from start and end phrases.
  • list – dumpSegs, list of lines read from file.
  • Lists contain entries for each dumpIdy segment found in the file.
epsproc.EDCSSegParse(dumpSeg)[source]

Extract values from EDCS file segments.

Parameters:dumpSeg (list) – One EDCS segment, from dumpSegs[], as returned by epsproc.IO.EDCSFileParse()
Returns:
  • np.array – EDCS, array of scattering XS, [theta, Cross Section (Angstrom^2)]
  • list – attribs, list [Label, value, units]

Notes

Currently this is a bit messy, and relies on fixed EDCS format. No error checking as yet. Not yet reading all attribs.

Example

>>> EDCS, attribs = EDCSSegParse(dumpSegs[0])
epsproc.EDCSSegsParseX(dumpSegs)[source]

Extract data from ePS EDCS segments into usable form.

Parameters:dumpSegs (list) – Set of dumpIdy segments, i.e. dumpSegs, as returned by epsproc.IO.EDCSFileParse()
Returns:
  • xr.array – Xarray data array, containing cross sections. Dimensions (Eke, theta)
  • int – Number of blank segments found. (CURRENTLY not implemented.)

Example

>>> data = EDCSSegsParseX(dumpSegs)

Notes

A rather cut-down version of epsproc.IO.dumpIdySegsParseX(), no error checking currently implemented.

epsproc.EPR(QNs=None, p=None, ep=None, nonzeroFlag=True, form='2d', dlist=['l', 'lp', 'P', 'p', 'R-p', 'R'], phaseConvention='S')[source]

Define polarization tensor (LF) for 1-photon case.

Define field terms (from QM book, corrected vs. original S&U version - see beta-general-forms\_rewrite\_290917.lyx):

\[\begin{split}\begin{equation} E_{PR}(\hat{e})=[e\otimes e^{*}]_{R}^{P}=[P]^{\frac{1}{2}}\sum_{p}(-1)^{R}\left(\begin{array}{ccc} 1 & 1 & P\\ p & R-p & -R \end{array}\right)e_{p}e_{R-p}^{*} \end{equation}\end{split}\]
Parameters:
  • QNs (np.array, optional, default = None) – List of QNs [l, lp, P, m, mp, R] to compute 3j terms for. If not supplied all allowed terms for the one-photon case, l=lp=1, will be set.
  • p (list or array, optional, default = None) – Specify polarization terms p. If set to None, all allowed values for the one-photon case will be set, p=[-1,0,1]
  • ep (list or array, optional, default = None) – Relative strengths for the fields ep. If set to None, all terms will be set to unity, ep = 1
  • nonzeroFlag (bool, optional, default = True) – Drop null terms before returning values if true.
  • form (string, optional, default = '2d') – For options see ep.w3jTable()
  • phaseConvention (optional, str, default = 'S') –

    Set phase conventions:

    • ’S’ : Standard derivation.
    • ’R’ : Reduced form geometric tensor derivation.
    • ’E’ : ePolyScat, may have additional changes in numerics, e.g. conjugate Wigner D.

    See setPhaseConventions() for more details.

Examples

# Generate full EPR list with defaults >>> EPRtable = EPR()

# Return as Xarray >>> EPRtable = EPR(form = ‘xarray’)

Note

Currently not handling ep correctly! Should implement as passed Xarray for correct (p,p’) assignment.

class epsproc.Efield(Edef=None, units=None, verbose=True)[source]

Bases: object

Basic class for handling E-field generation, data and related functions.

Currently set for field creation based on Gaussian defined in time-domain. Defaults to a single (E,t) point if no parameters are supplied - this can be used with epsproc.geomFunc.EPR()

Starting to look a bit top-heavy… passing directly to Xarray might save some structural overhead here?

Define Gaussian field in the time-domain, with amplitude $E_0$, width $sigma$ and carrier frequency $omega_0$:

\[ \begin{align}\begin{aligned}E(\omega_0,t)=E_{0}e^{-(t^2/2\sigma^{2})}e^{i\omega_0 t}\\Carrier frequency in rad/s:\end{aligned}\end{align} \]
\[ \begin{align}\begin{aligned}\omega_0 = 2\pi \Omega_0\\FWHM and Gaussian width (see https://en.wikipedia.org/wiki/Gaussian_function for full definitions):\end{aligned}\end{align} \]
\[ \begin{align}\begin{aligned}FWHM = 2\sigma\sqrt{2ln2}\\Parameters ---------- If no parameters are passed, return single point with E0 = 1 For a time-dependent field, pass at least sigma.\\E0 : float, optional, default = None Set (relative) field strength. If None, set E0 = 1\\sigma : float, optional, default = None Set Gaussian width :math:\sigma, where :math:FWHM=2\sigma\sqrt{2ln2}\\t : array, optional, default = None Set time axis for E-field. If None, defaults to np.arange(-(5*sigma), 5*sigma, self.dt), and self.dt = 0.01*sigma\\dt : float, optional, default = None Set time-step. Default will set from t-axis, or self.dt = 0.01*sigma if sigma only passed. Pass here to override.\\l0 : float, optional, default = None Central wavelength in wavelength working units. If supplied this will be used to set f0 and w0.\\f0, w0 : float, optional, default = None Carrier frequency in freq. units, and :math:\omega_0 in (rad/s). If only f0 supplied, w0 will be calculated. If f0 and w0 supplied, w0 will be used directly. If None, this will be ignored.\\units : dictionary, optional, default = None Set units. If not passed, default dict will be created with units (THz, nm, fs) set.\\ TODO: - best way to handle unit conversions? Did some of this for FROG code already? Yes, see python est_codes\E_fields_redux_231118_class.py - Consider other structures here, dataclass or namedtuple? https://stackoverflow.com/questions/354883/how-do-i-return-multiple-values-from-a-function - Xarray conversion? Use Xarray directly in class? - Bug with FFT/iFFT code? If shift=True and ishift=True then get extra freq components on iFFT - must be bug in axis assignment/conversion? OK if shift = False.\end{aligned}\end{align} \]
ECalc()[source]
EFFT()[source]
EiFFT(Emod=None, Ninput=None, comment='')[source]
FWHMGau()[source]
Gau()[source]
calcSpectrogram(signal=None, gate=None, fType='blind', N=None, verbose=False)[source]
chirp(A, resetPhase=False, comment=None)[source]

Add quadratic phase (chirp) in spectral domain. Requires an E-field object, and chirp parameter A.

TODO: check Diels for nomenclature here.

fConv()[source]

Convert freq. domain axis to lenght & energy units. and set fields.

finst()[source]

Calculate f(t) as instantaneous freq.

phaseMask(domain=None, thres=None)[source]

Mask pulse phase away from main features. Should convert to use masked arrays for reversibility, or just return a mask (currently overwrites Ef).

plot(plotType='phaseUW', Nplot=None, domainList=None, thres=0.01)[source]

Basic plot with Matplotlib

plotSpectrogram()[source]

VERY basic spectrogram plotter from old code - for quick testing only.

TODO: fix axes for with/withou fft shift.

BETTER: use plotSpectrogramHV() instead, this uses full axes as set.

plotSpectrogramHV(N=None)[source]
printDef()[source]
removePhase(domain=None)[source]

Remove imaginary field terms (reset phase).

setEf()[source]

Calculate pulse properties and E-fields based on Edef.

setPhase(phaseVec=None, domain=None)[source]

Set imaginary field terms (set phase) for specified domain & recalculated FFT.

toXarrayDS(N=None)[source]
epsproc.MFBLMCalcLoop(matE, eAngs=[0, 0, 0], thres=1e-06, p=0, R=0, verbose=1)[source]

Calculate inner loop for MFBLMs, based on passed set of matrix elements (Xarray).

Loop code based on Matlab code ePSproc_MFBLM.m

This works, but not very clean or efficient - should be possible to parallelize & vectorise… but this is OK for testing, benchmarking and verification purposes.

Parameters:
  • matE (Xarray) – Contains one set of matrix elements to use for calculation. Currently assumes these are a 1D list, with associated (l,m,mu) parameters, as set by epsproc.MFBLM.mfblm().
  • eAngs ([phi,theta,chi], optional, default = [0,0,0]) – Single set of Euler angles defining polarization geometry.
  • thres (float, optional, default = 1e-4) – Threshold value for testing significance of terms. Terms < thres will be dropped.
  • p (int, optional, default p = 0) – LF polarization term. Currently only valid for p = 0
  • R (int, optional, default R = 0) – LF polarization term (from tensor contraction). Currently only valid for p = 0
  • verbose (int, optional, default 1) –

    Verbosity level:

    • 0: Silent run.
    • 1: Print basic info.
    • 2: Print intermediate C parameter array to terminal when running.
Returns:

  • BLMX (Xarray) – Set of B(L,M; eAngs, Eke) terms for supplied matrix elements, in an Xarray. For cases where no values are calculated (below threshold), return an array with B00 = 0 only.
  • Limitations & To Do
  • ——————–
  • * Currently set with (p,R) values passed, but only valid for (0,0) (not full sum over R terms as shown in formalism above.)
  • * Set to accept a single set of matrix elements (single E), assuming looping over E (and other parameters) elsewhere.
  • * Not explicitly parallelized here, should be done by calling function.
  • (Either via Xarray methods, or numba/dask…? http (//xarray.pydata.org/en/stable/computation.html#wrapping-custom-computation))
  • * Coded for ease, not efficiency - there will be lots of repeated ang. mom. calcs. when run over many sets of matrix elements.
  • .. rst-class:: strike
  • * Scale factor currently not propagated.
  • * (SF now propagated via Xarrays and implemented in main calling function )

epsproc.MFproj(QNs=None, RX=None, nonzeroFlag=True, form='2d', dlist=['l', 'lp', 'P', 'mu', 'mup', 'Rp', 'R'], phaseConvention='S')[source]

Define MF projection term, \(\Lambda_{R',R}(R_{\hat{n}})\):

\[\begin{split}\begin{equation} \Lambda_{R',R}(R_{\hat{n}})=(-1)^{(R')}\left(\begin{array}{ccc} 1 & 1 & P\\ \mu & -\mu' & R' \end{array}\right)D_{-R',-R}^{P}(R_{\hat{n}}) \end{equation}\end{split}\]

Then…

\[\begin{eqnarray} \beta_{L,-M}^{\mu_{i},\mu_{f}} & = & \sum_{P,R',R}{\color{red}E_{P-R}(\hat{e};\mu_{0})}\sum_{l,m,\mu}\sum_{l',m',\mu'}(-1)^{(\mu'-\mu_{0})}{\color{red}\Lambda_{R',R}(R_{\hat{n}};\mu,P,R,R')B_{L,-M}(l,l',m,m')}I_{l,m,\mu}^{p_{i}\mu_{i},p_{f}\mu_{f}}(E)I_{l',m',\mu'}^{p_{i}\mu_{i},p_{f}\mu_{f}*}(E) \end{eqnarray}\]
Parameters:phaseConvention (optional, str, default = 'S') – Set phase conventions: - ‘S’ : Standard derivation. - ‘R’ : Reduced form geometric tensor derivation. - ‘E’ : ePolyScat, conjugate Wigner D. See setPhaseConventions() for more details.

Notes

This is very similar to \(E_{PR}\) term.

Examples

>>> lTerm, lambdaTable, lambdaD, QNs = MFproj(form = 'xarray')
epsproc.TKQarrayRot(TKQ, eAngs)[source]

Frame rotation for multipoles $T_{K,Q}$.

Basic frame rotation code, see https://github.com/phockett/Quantum-Metrology-with-Photoelectrons/blob/master/Alignment/Alignment-1.ipynb for examples.

Parameters:
  • TKQ (np.array) – Values defining the initial distribution, [K,Q,TKQ]
  • eAngs (list or np.array) – List of Euler angles (theta,phi,chi) defining rotated frame.
Returns:

  • TKQRot (np.array) – Multipoles $T’_{K,Q}$ in rotated frame, as an np.array [K,Q,TKQ].
  • TODO (redo with Moble’s functions, and Xarray input & output.)
  • Formalism
  • ———-
  • For the state multipoles, frame rotations are fairly straightforward
  • (Eqn. 4.41 in Blum)
  • .. math:: – begin{equation} leftlangle T(J’,J)_{KQ}^{dagger}rightrangle =sum_{q}leftlangle T(J’,J)_{Kq}^{dagger}rightrangle D(Omega)_{qQ}^{K*} end{equation}
  • Where $D(Omega)_{qQ}^{K}$ is a Wigner rotation operator, for a*
  • rotation defined by a set of Euler angles $Omega={theta,phi,chi}$.
  • Hence the multipoles transform, as expected, as irreducible tensors,
  • i.e. components $q$ are mixed by rotation, but terms of different
  • rank $K$ are not.

epsproc.TKQarrayRotX(TKQin, RX, form=2)[source]

Frame rotation for multipoles $T_{K,Q}$.

Basic frame rotation code, see https://github.com/phockett/Quantum-Metrology-with-Photoelectrons/blob/master/Alignment/Alignment-1.ipynb for examples.

Parameters:
  • TKQin (Xarray) – Values defining the initial distribution, [K,Q,TKQ]. Other dimensions will be propagated.
  • RX (Xarray defining frame rotations, from epsproc.setPolGeoms()) – List of Euler angles (theta,phi,chi) and corresponding quaternions defining rotated frame.
Returns:

TKQRot – Multipoles $T’_{K,Q}$ in rotated frame, as an np.array [K,Q,TKQ].

Return type:

Xarray

For the state multipoles, frame rotations are fairly straightforward (Eqn. 4.41 in Blum):

\[\begin{equation} \left\langle T(J',J)_{KQ}^{\dagger}\right\rangle =\sum_{q}\left\langle T(J',J)_{Kq}^{\dagger}\right\rangle D(\Omega)_{qQ}^{K*} \end{equation}\]

Where $D(Omega)_{qQ}^{K*}$ is a Wigner rotation operator, for a rotation defined by a set of Euler angles $Omega={theta,phi,chi}$. Hence the multipoles transform, as expected, as irreducible tensors, i.e. components $q$ are mixed by rotation, but terms of different rank $K$ are not.

Examples

>>> vFlag = 2
>>> RX = ep.setPolGeoms(vFlag = vFlag)  # Package version
>>> RX
>>> testADMX = ep.setADMs(ADMs=[[0,0,0,1],[2,0,0,0.5]])
>>> testADMX
>>> testADMrot, wDX, wDXre = TKQarrayRotX(testADMX, RX)
>>> testADMrot
>>> testADMrot.attrs['dataType'] = 'ADM'
>>> sph, _ = sphFromBLMPlot(testADMrot, facetDim = 'Euler', plotFlag = True)
epsproc.Wigner3jCached[source]

Wrapper for 3j caching with functools.lru_cache

epsproc.Wigner3jCached[source]

Wrapper for 3j caching with functools.lru_cache

epsproc.Wigner3jQNs(QNs)[source]
epsproc.Wigner_D_element_Cached[source]

Wrapper for WignerD caching with functools.lru_cache

epsproc.Wigner_D_element_Cached[source]

Wrapper for WignerD caching with functools.lru_cache

epsproc.afblm(daIn, selDims={'Type': 'L'}, AKQS=<sphinx.ext.autodoc.importer._MockObject object>, eAngs=[0, 0, 0], thres=0.0001, sumDims=('l', 'm', 'mu', 'Cont', 'Targ', 'Total', 'it'), SFflag=True, verbose=1)[source]

Calculate MFBLMs for a range of (E, sym) cases. Default is to calculated for all symmetries at each energy.

Parameters:
  • da (Xarray) – Contains matrix elements to use for calculation. Matrix elements will be sorted by energy and BLMs calculated for each set.
  • selDims (dict, optional, default = {'Type':'L'}) – Additional sub-selection to be applied to matrix elements before BLM calculation. Default selects just length gauge results.
  • eAngs ([phi,theta,chi], optional, default = [0,0,0]) – Single set of Euler angles defining polarization geometry.
  • thres (float, optional, default = 1e-4) – Threshold value for testing significance of terms. Terms < thres will be dropped.
  • sumDims (tuple, optional, default = ('l','m','mu','Cont','Targ','Total','it')) – Defines which terms are summed over (coherent) in the MFBLM calculation. (These are used to flatten the Xarray before calculation.) Default includes sum over (l,m), symmetries and degeneracies (but not energies).
  • SFflag (bool, default = True) – Normalise by scale factor to give X-sections (B00) in Mb
  • verbose (int, optional, default 1) –

    Verbosity level:

    • 0: Silent run.
    • 1: Print basic info.
    • 2: Print intermediate C parameter array to terminal when running.
Returns:

  • Xarray – Calculation results BLM, dims (Euler, Eke, l,m). Some global attributes are also appended.
  • Limitations
  • ———–
  • Currently set to loop calcualtions over energy only, and all symmetries.
  • Pass single {‘Cont’ (‘sym’} to calculated for only one symmetry group.)
  • TODO (In future this will be more elegant.)
  • TODO (Setting selDims in output structure needs more thought for netCDF save compatibility.)

epsproc.afblmXprod(matEin, QNs=None, AKQS=None, EPRX=None, p=[0], BLMtable=None, lambdaTerm=None, RX=None, eulerAngs=None, thres=0.01, thresDims='Eke', selDims={'Type': 'L', 'it': 1}, sumDims=['mu', 'mup', 'l', 'lp', 'm', 'mp', 'S-Rp'], sumDimsPol=['P', 'R', 'Rp', 'p'], symSum=True, SFflag=False, SFflagRenorm=False, BLMRenorm=1, squeeze=False, phaseConvention='S')[source]

Implement \(\beta_{LM}^{AF}\) calculation as product of tensors.

\[\begin{eqnarray} \beta_{L,-M}^{\mu_{i},\mu_{f}} & =(-1)^{M} & \sum_{P,R',R}{[P]^{\frac{1}{2}}}{E_{P-R}(\hat{e};\mu_{0})}\sum_{l,m,\mu}\sum_{l',m',\mu'}(-1)^{(\mu'-\mu_{0})}{\Lambda_{R'}(\mu,P,R')B_{L,-M}(l,l',m,m')}I_{l,m,\mu}^{p_{i}\mu_{i},p_{f}\mu_{f}}(E)I_{l',m',\mu'}^{p_{i}\mu_{i},p_{f}\mu_{f}*}(E)\sum_{K,Q,S}\Delta_{L,M}(K,Q,S)A_{Q,S}^{K}(t) \end{eqnarray}\]

Where each component is defined by fns. in :py:module:`epsproc.geomFunc.geomCalc` module.

10/09/20 Verified (but messy) version, with updated defaults.

01/09/20 Verified (but messy) version, including correct renormalisation routines.

15/06/20 In progress! Using mfblmXprod() as template, with just modified lambda term, and new alignment term, to change.

Dev code:
geometric_method_dev_pt3_AFBLM_090620.ipynb http://localhost:8888/lab/tree/dev/ePSproc/geometric_method_dev_Betas_090320.ipynb D:codeePSprocpython_devePSproc_MFBLM_Numba_dev_tests_120220.PY

TOTAL MESS AT THE MOMENT>>?>>>>?DFdas<>r ty

Parameters:phaseConvention (optional, str, default = 'S') – Set phase conventions with epsproc.geomCalc.setPhaseConventions(). To use preset phase conventions, pass existing dictionary.

Notes

Cross-section outputs now set as:

  • XSraw = direct AF calculation output.
  • XSrescaled = XSraw * SF * sqrt(4pi)
  • XSiso = direct sum over matrix elements

Where XSrescaled == XSiso == ePS GetCro output for isotropic distribution.

epsproc.arraySort2D(a, col)[source]

Sort np.array a by specified column col. From https://thispointer.com/sorting-2d-numpy-array-by-column-or-row-in-python/

epsproc.betaTerm(QNs=None, Lmin=0, Lmax=10, nonzeroFlag=True, form='2d', dlist=['l', 'lp', 'L', 'm', 'mp', 'M'], phaseConvention='S')[source]

Define BLM coupling tensor

Define field terms (from QM book, corrected vs. original S&U version - see beta-general-forms\_rewrite\_290917.lyx):

\[\begin{split}\begin{equation} B_{L,M}=(-1)^{m}\left(\frac{(2l+1)(2l'+1)(2L+1)}{4\pi}\right)^{1/2}\left(\begin{array}{ccc} l & l' & L\\ 0 & 0 & 0 \end{array}\right)\left(\begin{array}{ccc} l & l' & L\\ -m & m' & M \end{array}\right) \end{equation}\end{split}\]
Parameters:
  • QNs (np.array, optional, default = None) – List of QNs [l, lp, L, m, mp, M] to compute 3j terms for. If not supplied all allowed terms for {Lmin, Lmax} will be set. (If supplied, values for Lmin, Lmax and mFlag are not used.)
  • Lmax (Lmin,) – Integer values for Lmin and Lmax respectively.
  • mFlag (bool, optional, default = True) – m, mp take all values -l…+l if mFlag=True, or =0 only if mFlag=False
  • nonzeroFlag (bool, optional, default = True) – Drop null terms before returning values if true.
  • form (string, optional, default = '2d') – For options see ep.w3jTable()
  • dlist (list of labels, optional, default ['l','lp','L','m','mp','M']) – Used to label array for Xarray output case.
  • phaseConvention (optional, str, default = 'S') – Set phase conventions: - ‘S’ : Standard derivation. - ‘R’ : Reduced form geometric tensor derivation. - ‘E’ : ePolyScat, may have additional changes in numerics, e.g. conjugate Wigner D. See setPhaseConventions() for more details.

Examples

>>> Lmax = 2
>>> BLMtable = betaTerm(Lmax = Lmax, form = 'xds')
>>> BLMtable = betaTerm(Lmax = Lmax, form = 'xdaLM')
epsproc.blmXarray(BLM, Eke)[source]

Create Xarray from BLM list, format BLM = [L, M, Beta], at a single energy Eke.

Array sorting only valid for 2D BLM array, for B00=0 case pass BLM = None.

epsproc.blmXarray(BLM, Eke)[source]

Create Xarray from BLM list, format BLM = [L, M, Beta], at a single energy Eke.

Array sorting only valid for 2D BLM array, for B00=0 case pass BLM = None.

epsproc.conv_ev_atm(data, to='ev')[source]

Convert eV <> Hartree (atomic units)

Parameters:
  • data (int, float, np.array) – Values to convert.
  • to (str, default = 'ev') –
    • ‘ev’ to convert H > eV
    • ’H’ to convert eV > H
Returns:

Return type:

data converted in converted units.

epsproc.conv_ev_nm(data)[source]

Convert E(eV) <> nu(nm).

epsproc.dataGroupSel(data, dInd)[source]
epsproc.dataTypesList()[source]

Return a dict of allowed dataTypes, corresponding to epsproc processed data.

Each dataType lists ‘source’, ‘desc’ and ‘recordType’ fields.

  • ‘source’ fields correspond to ePS functions which get or generate the data.
  • ‘desc’ brief description of the dataType.
  • ‘recordType’ gives the required segment in ePS files (and associated parser). If the segment is not present in the source file, then the dataType will not be available.

TODO: best choice of data structure here? Currently nested dictionary.

epsproc.deltaLMKQS(EPRX, AKQS, phaseConvention='S')[source]

Calculate aligned-frame “alignment” term:

\[\begin{equation} \sum_{K,Q,S}\Delta_{L,M}(K,Q,S)A_{Q,S}^{K}(t) \end{equation}\]
\[\begin{split}\begin{equation} \Delta_{L,M}(K,Q,S)=(2K+1)^{1/2}(-1)^{K+Q}\left(\begin{array}{ccc} P & K & L\\ R & -Q & -M \end{array}\right)\left(\begin{array}{ccc} P & K & L\\ R' & -S & S-R' \end{array}\right) \end{equation}\end{split}\]

15/06/20 IN PROGRESS

Parameters:
  • EPRX (Xarray) – Polarization terms in an Xarray, as set by epsproc.geomCalc.EPR()
  • AKQS (Xarray) – Alignement terms in an Xarray, as set by epsproc.setADMs()
Returns:

  • AFterm (Xarray) – Full term, including multiplication and sum over (K,Q,S) (note S-Rp term is retained).
  • DeltaKQS (Xarray) – Alignment term \(\Delta_{L,M}(K,Q,S)\).
  • To do
  • —–
  • - Add optional inputs.
  • - Add error checks.
  • See other similar functions for schemes.

epsproc.dumpIdyFileParse(fileName)[source]

Parse an ePS file for dumpIdy segments.

Parameters:fileName (str) – File to read (file in working dir, or full path)
Returns:
  • list – [lineStart, lineStop], ints for line #s found from start and end phrases.
  • list – dumpSegs, list of lines read from file.
  • Lists contain entries for each dumpIdy segment found in the file.
epsproc.dumpIdySegParse(dumpSeg)[source]

Extract values from dumpIdy file segments.

Parameters:dumpSeg (list) – One dumpIdy segment, from dumpSegs[], as returned by epsproc.IO.dumpIdyFileParse()
Returns:
  • np.array – rawIdy, array of matrix elements, [m,l,mu,ip,it,Re,Im]
  • list – attribs, list [Label, value, units]

Notes

Currently this is a bit messy, and relies on fixed DumpIDY format. No error checking as yet. Not yet reading all attribs.

Example

>>> matEle, attribs = dumpIdySegParse(dumpSegs[0])
epsproc.dumpIdySegsParseX(dumpSegs, ekeListUn, symSegs)[source]

Extract data from ePS dumpIdy segments into usable form.

Parameters:
Returns:

  • xr.array – Xarray data array, containing matrix elements etc. Dimensions (LM, Eke, Sym, mu, it, Type)
  • int – Number of blank segments found.

Example

>>> data = dumpIdySegsParseX(dumpSegs)
epsproc.eulerDimList(sType='stacked')[source]

Return standard list of dimensions for frame definitions, from epsproc.sphCalc.setPolGeoms().

Parameters:sType (string, optional, default = 'stacked') – Selected ‘stacked’ or ‘unstacked’ dimensions. Set ‘sDict’ to return a dictionary of unstacked <> stacked dims mappings for use with xr.stack({dim mapping}).
Returns:list
Return type:set of dimension labels.
epsproc.fileParse(fileName, startPhrase=None, endPhrase=None, comment=None, verbose=False)[source]

Parse a file, return segment(s) from startPhrase:endPhase, excluding comments.

Parameters:
  • fileName (str) – File to read (file in working dir, or full path)
  • startPhrase (str, optional) – Phrase denoting start of section to read. Default = None
  • endPhase (str or list, optional) – Phrase denoting end of section to read. Default = None
  • comment (str, optional) – Phrase denoting comment lines, which are skipped. Default = None
Returns:

  • list – [lineStart, lineStop], ints for line #s found from start and end phrases.
  • list – segments, list of lines read from file.
  • All lists can contain multiple entries, if more than one segment matches the search criteria.

epsproc.genKQSterms(Kmin=0, Kmax=2, mFlag=True)[source]
epsproc.genKQStermsFromTensors(EPR, AKQS, uniqueFlag=True, phaseConvention='S')[source]

Generate all QNs for \(\Delta_{L,M}(K,Q,S)\) from existing tensors (Xarrays) \(E_{P,R}\) and \(A^K_{Q,S}\).

Cf. epsproc.geomFunc.genllpMatE(), code adapted from there.

Parameters:
  • matE (Xarray) – Xarray containing matrix elements, with QNs (l,m), as created by readMatEle()
  • uniqueFlag (bool, default = True) – Check for duplicates and remove (can occur with some forms of matrix elements).
  • mFlag (bool, optional, default = True) – m, mp take all passed values if mFlag=True, or =0 only if mFlag=False
  • phaseConvention (optional, str, default = 'S') – Set phase conventions with epsproc.geomCalc.setPhaseConventions(). To use preset phase conventions, pass existing dictionary. If matE.attrs[‘phaseCons’] is already set, this will be used instead of passed args.
Returns:

  • QNs1, QNs2 (two 2D np.arrays) – Values take all allowed combinations [‘P’,’K’,’L’,’R’,’Q’,’M’] and [‘P’,’K’,’L’,’Rp’,’S’,’S-Rp’] from supplied matE. Note phase conventions not applied to QN lists as yet.
  • To do
  • —–
  • - Implement output options (see dev. function w3jTable).

epsproc.genLM(Lmax)[source]

Return array of (L,M) up to supplied Lmax

TODO: add return type options, include conversion to SHtools types.

epsproc.genllL(Lmin=0, Lmax=10, mFlag=True)[source]

Generate quantum numbers for angular momentum contractions (l, lp, L)

Parameters:
  • Lmax (Lmin,) – Integer values for Lmin and Lmax respectively.
  • mFlag (bool, optional, default = True) – m, mp take all values -l…+l if mFlag=True, or =0 only if mFlag=False
Returns:

QNs – Values take all allowed combinations [‘l’,’lp’,’L’,’m’,’mp’,’M’] up to l=lp=Lmax, one set per row.

Return type:

2D np.array

Examples

>>> # Calculate up to Lmax = 2
>>> QNs = genllL(Lmax=2)
>>> # Use with w3jTable function to calculate Wigner 3j terms
>>> w3j = w3jTable(QNs = QNs)
  • Implement output options (see dev. function w3jTable).
epsproc.genllLList(Llist, uniqueFlag=True, mFlag=True)[source]

Generate quantum numbers for angular momentum contractions (l, lp, L) from a passed list, (m, mp, M)=0 or all allowed terms.

Parameters:
  • Llist (list) – Values [l, lp, L] to use for calculations.
  • uniqueFlag (bool, optional, default = True) – Drop duplicate [l,lp,L] sets from list.
  • mFlag (bool, optional, default = True) – m, mp take all values -l…+l if mFlag=True, or =0 only if mFlag=False
Returns:

QNs – Values take all allowed combinations [‘l’,’lp’,’L’,’m’,’mp’,’M’] up to l=lp=Lmax, one set per row.

Return type:

2D np.array

Examples

>>> # Set from an array
>>> QNs = genllLList(np.array([[1,1,2],[1,3,2],[1,1,2]]), mFlag = True)
>>> # Use with w3jTable function to calculate Wigner 3j terms
>>> w3j = w3jTable(QNs = QNs)
  • Implement output options (see dev. function w3jTable).
epsproc.genllpMatE(matE, uniqueFlag=True, mFlag=True, phaseConvention='S')[source]

Generate quantum numbers for angular momentum contractions (l, lp, L, m, mp, M) from sets of matrix elements.

Parameters:
  • matE (Xarray) – Xarray containing matrix elements, with QNs (l,m), as created by readMatEle()
  • uniqueFlag (bool, default = True) – Check for duplicates and remove (can occur with some forms of matrix elements).
  • mFlag (bool, optional, default = True) – m, mp take all passed values if mFlag=True, or =0 only if mFlag=False
  • phaseConvention (optional, str, default = 'S') – Set phase conventions with epsproc.geomCalc.setPhaseConventions(). To use preset phase conventions, pass existing dictionary. If matE.attrs[‘phaseCons’] is already set, this will be used instead of passed args.
Returns:

QNs – Values take all allowed combinations [‘l’,’lp’,’L’,’m’,’mp’,’M’] from supplied matE

Return type:

2D np.array

Examples

>>> # From demo matrix elements
>>> dataFile = os.path.join(dataPath, 'n2_3sg_0.1-50.1eV_A2.inp.out')  # Set for sample N2 data for testing
>>> # Scan data file
>>> dataSet = ep.readMatEle(fileIn = dataFile)
>>> QNs = genllpMatE(dataSet[0])
>>> # Use with w3jTable function to calculate Wigner 3j terms
>>> w3j = w3jTable(QNs = QNs)
  • Implement output options (see dev. function w3jTable).
epsproc.getCroFileParse(fileName)[source]

Parse an ePS file for GetCro/CrossSection segments.

Parameters:fileName (str) – File to read (file in working dir, or full path)
Returns:
  • list – [lineStart, lineStop], ints for line #s found from start and end phrases.
  • list – dumpSegs, list of lines read from file.
  • Lists contain entries for each dumpIdy segment found in the file.
epsproc.getCroSegParse(dumpSeg)[source]

Extract values from GetCro/CrossSection file segments.

Parameters:dumpSeg (list) – One CrossSection segment, from dumpSegs[], as returned by epsproc.IO.getCroFileParse()
Returns:
  • np.array – CrossSections, table of results vs. energy.
  • list – attribs, list [Label, value, units]

Notes

Currently this is a bit messy, and relies on fixed CrossSection output format. No error checking as yet. Not yet reading all attribs.

Example

>>> XS, attribs = getCroSegParse(dumpSegs[0])
epsproc.getCroSegsParseX(dumpSegs, symSegs, ekeList)[source]

Extract data from ePS getCro/CrossSecion segments into usable form.

Parameters:dumpSegs (list) – Set of dumpIdy segments, i.e. dumpSegs, as returned by epsproc.IO.getCroFileParse()
Returns:
  • xr.array – Xarray data array, containing cross sections. Dimensions (Eke, theta)
  • int – Number of blank segments found. (CURRENTLY not implemented.)

Example

>>> data = getCroSegsParseX(dumpSegs)

Notes

A rather cut-down version of epsproc.IO.dumpIdySegsParseX(), no error checking currently implemented.

epsproc.getFiles(fileIn=None, fileBase=None, fType='.out', verbose=True)[source]

Read ePS file(s) and return results as Xarray data structures. File endings specified by fType, default .out.

Parameters:
  • fileIn (str, list of strs, optional.) – File(s) to read (file in working dir, or full path). Defaults to current working dir if only a file name is supplied. For consistent results, pass raw strings, e.g. fileIn = r"C:\share\code\ePSproc\python_dev\no2_demo_ePS.out"
  • fileBase (str, optional.) – Dir to scan for files. Currently only accepts a single dir. Defaults to current working dir if no other parameters are passed.
  • fType (str, optional) – File ending for ePS output files, default ‘.out’
  • verbose (bool, optional) – Print output details, default True.
Returns:

List of Xarray data arrays, containing matrix elements etc. from each file scanned.

Return type:

list

epsproc.headerFileParse(fileName, verbose=True)[source]

Parse an ePS file for header & input job info.

Parameters:
  • fileName (str) – File to read (file in working dir, or full path)
  • verbose (bool, default True) – Print job info from file header if true.
Returns:

  • jobInfo (dict) – Dictionary generated from job details.
  • TO DO
  • —–
  • - Tidy up methods - maybe with parseDigits?
  • - Tidy up dict output.

epsproc.jobSummary(jobInfo=None, molInfo=None, tolConv=0.01)[source]

Print some jobInfo stuff & plot molecular structure. (Currently very basic.)

Parameters:
  • jobInfo (dict, default = None) – Dictionary of job data, as generated by :py:function:`epsproc.IO.headerFileParse()` from source ePS output file.
  • molInfo (dict, default = None) – Dictionary of molecule data, as generated by epsproc.IO.molInfoParse() from source ePS output file.
  • tolConv (float, default = 1e-2) – Used to check for convergence in ExpOrb outputs, which defines single-center expansion of orbitals.
Returns:

Job info

Return type:

list

epsproc.lmPlot(data, pType='a', thres=0.01, thresType='abs', SFflag=True, logFlag=False, eulerGroup=True, selDims=None, sumDims=None, plotDims=None, squeeze=True, fillna=False, xDim='Eke', backend='sns', cmap=None, figsize=None, verbose=False, mMax=10)[source]

Plotting routine for ePS matrix elements & BLMs.

First pass - based on new codes + util functions from sphPlot.py, and matE sorting codes.

Parameters:
  • data (Xarray, data to plot.) – Should work for any Xarray, but optimised for dataTypes: - matE, matrix elements - BLM paramters - ADMs
  • pType (char, optional, default 'a' (abs values)) – Set (data) type to plot. See plotTypeSelector().
  • thres (float, optional, default 1e-2) – Value used for thresholding results, only values > thres will be included in the plot. Either abs or relative (%) value, according to thresType setting.
  • thresType (str, optional, default = 'abs') – Set to ‘abs’ or ‘pc’ for absolute threshold, or relative value (%age of max value in dataset)
  • SFflag (bool, optional, default = True) – For dataType = matE: Multiply by E-dependent scale factor. For dataType = BLM: Multiply by cross-section (XS) (I.e. if False, normalised BLMs are plotted, with B00 = 1)
  • logFlag (bool, optional, default = False) – Plot values on log10 scale.
  • eulerGroup (bool, optional, default = True) – Group Euler angles by set and use labels (currenly a bit flakey…)
  • selDims (dict, optional, default = {'Type':'L'}) – Dimensions to select from input Xarray.
  • sumDims (tuple, optional, default = None) – Dimensions to sum over from the input Xarray.
  • plotDims (tuple, optional, default = None) – Dimensions to stack for plotting, also controls order of stacking (hence sorting and plotting). Default case plots all dims not included in (xDim, sumDims, selDims). E.g. for matrix elements this will be (‘l’,’m’,’mu’,’Cont’,’Targ’,’Total’,’it’,’Type’) TO DO: auto generation for different dataType, also based on selDims and sumDims selections. 11/03/20: partially fixed, now add any missing dims to plot automatically. NOTE: this currently fails for ‘Labels’ case, not sure why.
  • squeeze (bool, optional, default = True) – Drop singleton dimensions from plot.
  • fillna (bool, optional, default = False) – Fill NaN values with 0 if True.
  • xDim (str, optional, default = 'Eke') – Dimension to use for x-axis, also used for thresholding. Default plots (Eke, LM) surfaces. NOTE: if xDim is a MultiIndex, pass as a dictionary mapping, otherwise it may be unstacked during data prep. E.g. for plotting stacked (L,M), set xDim = {‘LM’:[‘L’,’M’]} NOTE: this is currently also passed to matEleSelector(), so stacked dims must exist in inital Xarray. THIS SHOULD BE FIXED, since it’s a pain.
  • backend (str, optional, default = 'sns') – Plotter to use. Default is ‘sns’ for Seaborn clustermap plot. Set to ‘xr’ for Xarray internal plotting (not all passed args will be used in this case). May be switched according to plot type in future…
  • cmap (str, optional, default = None) – Cmap option to pass to sns clustermap plot.
  • figsize (tuple, optional, default None) – Tuple for Seaborn figure size (ratio), e.g. figsize = (15,5). Useful for setting a long axis explicitly in cases with large dimensional disparity. Default results in a square (ish) aspect.
  • verbose (bool, optional, default False) – Print debug info.
  • mMax (int, optional, default = 10) – Used as default for m colour mapping, in cases where coords are not parsed. TODO: fix this, it’s ugly.
Returns:

  • daPlot (Xarray) – Data subset as plotted.
  • legendList (list) – Labels & colour maps
  • g (figure object)

Notes

  • Improved dim handling, maybe use epsproc.util.matEdimList() (and related functions) to avoid hard-coding multiple cases here.
    • Partially implemented in dimMap.
    • Currently throws an error for None in symmetry plotting cases for unrecognised dataType. TO FIX!
  • Improved handling of sets of polarization geometries (angles).
  • CONSOLIDATE stacked/unstacked dim handling. At the moment some functions use stacked, some unstacked, which is leading to annoying bugs.
  • 27/02/20 - handling for MultiIndex cases for Wigner 3j type data (function of (l,lp,L,m,mp,M))
    • Fixed issue with conversion to Pandas table - should now handle dims better.
    • Improved multidim dropna() using Xarray version (previously used Pandas version).
    • Added xDim as dict mapping capability.
  • 05/12/19 - debug
  • 29/11/19 - initial version.

Examples

(See https://github.com/phockett/ePSproc/blob/master/epsproc/tests/ePSproc_demo_matE_plotting_Nov2019.ipynb)

epsproc.lmSymSummary(data)[source]

Display summary info data tables.

Works nicely in a notebook cell, with Pandas formatted table… but not from function?

For a more sophisticated Pandas conversion, see epsproc.util.conversion.multiDimXrToPD()

epsproc.matEdimList(sType='stacked')[source]

Return standard list of dimensions for matrix elements.

Parameters:sType (string, optional, default = 'stacked') – Selected ‘stacked’ or ‘unstacked’ dimensions. Set ‘sDict’ to return a dictionary of unstacked <> stacked dims mappings for use with xr.stack({dim mapping}).
Returns:list
Return type:set of dimension labels.
epsproc.matEleGroupDim(data, dimGroups=[3, 4, 2])[source]

Group ePS matrix elements by redundant labels.

Default is to group by [‘ip’, ‘it’, ‘mu’] terms, all have only a few values.

TODO: better ways to do this? Shoud be possible at Xarray level.

Parameters:data (list) – Sections from dumpIdy segment, as created in dumpIdySegsParseX() Ordering is [labels, matElements, attribs].
epsproc.matEleGroupDimX(daIn)[source]

Group ePS matrix elements by redundant labels (Xarray version).

Group by [‘ip’, ‘it’, ‘mu’] terms, all have only a few values. Rename ‘ip’:1,2 as ‘Type’:’L’,’V’

TODO: better ways to do this? Via Stack/Unstack? http://xarray.pydata.org/en/stable/api.html#id16 See also tests in funcTests_210819.py for more versions/tests.

Parameters:data (Xarray) – Data array with matrix elements to be split and recombined by dims.
Returns:data – Data array with reordered matrix elements (dimensions).
Return type:Xarray
epsproc.matEleGroupDimXnested(da)[source]

Group ePS matrix elements by redundant labels (Xarray version).

Group by [‘ip’, ‘it’, ‘mu’] terms, all have only a few values.

TODO: better ways to do this? See also tests in funcTests_210819.py for more versions/tests.

Parameters:data (Xarray) – Data array with matrix elements to be split and recombined by dims.
epsproc.matEleSelector(da, thres=None, inds=None, dims=None, sq=False, drop=True)[source]

Select & threshold raw matrix elements in an Xarray

Parameters:
  • da (Xarray) – Set of matrix elements to sub-select
  • thres (float, optional, default None) – Threshold value for abs(matElement), keep only elements > thres. This is element-wise.
  • inds (dict, optional, default None) – Dicitonary of additional selection criteria, in name:value format. These correspond to parameter dimensions in the Xarray structure. E.g. inds = {‘Type’:’L’,’Cont’:’A2’}
  • dims (str or list of strs, dimensions to look for max & threshold, default None) – Set for dimension-wise thresholding. If set, this is used instead of element-wise thresholding. List of dimensions, which will be checked vs. threshold for max value, according to abs(dim.max) > threshold This allows for consistent selection of continuous parameters over a dimension, by a threshold.
  • sq (bool, optional, default False) – Squeeze output singleton dimensions.
  • drop (bool, optional, default True) – Passed to da.where() for thresholding, drop coord labels for values below threshold.
Returns:

Xarray structure of selected matrix elements. Note that Nans are dropped if possible.

Return type:

daOut

Example

>>> daOut = matEleSelector(da, inds = {'Type':'L','Cont':'A2'})
epsproc.mfblm(daIn, selDims={'Type': 'L'}, eAngs=[0, 0, 0], thres=0.0001, sumDims=('l', 'm', 'mu', 'Cont', 'Targ', 'Total', 'it'), SFflag=True, verbose=1)[source]

Calculate MFBLMs for a range of (E, sym) cases. Default is to calculated for all symmetries at each energy.

Parameters:
  • da (Xarray) – Contains matrix elements to use for calculation. Matrix elements will be sorted by energy and BLMs calculated for each set.
  • selDims (dict, optional, default = {'Type':'L'}) – Additional sub-selection to be applied to matrix elements before BLM calculation. Default selects just length gauge results.
  • eAngs ([phi,theta,chi], optional, default = [0,0,0]) – Single set of Euler angles defining polarization geometry.
  • thres (float, optional, default = 1e-4) – Threshold value for testing significance of terms. Terms < thres will be dropped.
  • sumDims (tuple, optional, default = ('l','m','mu','Cont','Targ','Total','it')) – Defines which terms are summed over (coherent) in the MFBLM calculation. (These are used to flatten the Xarray before calculation.) Default includes sum over (l,m), symmetries and degeneracies (but not energies).
  • SFflag (bool, default = True) – Normalise by scale factor to give X-sections (B00) in Mb
  • verbose (int, optional, default 1) –

    Verbosity level:

    • 0: Silent run.
    • 1: Print basic info.
    • 2: Print intermediate C parameter array to terminal when running.
Returns:

  • Xarray – Calculation results BLM, dims (Euler, Eke, l,m). Some global attributes are also appended.
  • Limitations
  • ———–
  • Currently set to loop calcualtions over energy only, and all symmetries.
  • Pass single {‘Cont’ (‘sym’} to calculated for only one symmetry group.)
  • TODO (In future this will be more elegant.)
  • TODO (Setting selDims in output structure needs more thought for netCDF save compatibility.)

epsproc.mfblmEuler(da, selDims={'Type': 'L'}, eAngs=[0, 0, 0], thres=0.0001, sumDims=('l', 'm', 'mu', 'Cont', 'Targ', 'Total', 'it'), SFflag=True, verbose=1)[source]

Wrapper for epsproc.MFBLM.mfblm() for a set of Euler angles. All other parameters are simply passed to mfblm(). Calculate MFBLMs for a range of (E, sym) cases. Default is to calculated for all symmetries at each energy.

Parameters:
  • da (Xarray) – Contains matrix elements to use for calculation. Matrix elements will be sorted by energy and BLMs calculated for each set.
  • selDims (dict, optional, default = {'Type':'L'}) – Additional sub-selection to be applied to matrix elements before BLM calculation. Default selects just length gauge results.
  • eAngs ([phi,theta,chi], optional, default = [0,0,0]) – Set of Euler angles defining polarization geometry. List or np.array, dims(N, 3). Basic Xarray support also in place, as generated by epsproc.sphCalc.setPolGeoms()
  • thres (float, optional, default = 1e-4) – Threshold value for testing significance of terms. Terms < thres will be dropped.
  • sumDims (tuple, optional, default = ('l','m','mu','Cont','Targ','Total','it')) – Defines which terms are summed over (coherent) in the MFBLM calculation. (These are used to flatten the Xarray before calculation.) Default includes sum over (l,m), symmetries and degeneracies (but not energies).
  • SFflag (bool, default = True) – Normalise by scale factor to give X-sections (B00) in Mb
  • verbose (int, optional, default 1) –

    Verbosity level:

    • 0: Silent run.
    • 1: Print basic info.
    • 2: Print intermediate C parameter array to terminal when running.
Returns:

  • Xarray – Calculation results BLM, dims (Euler(P,T,C), Eke, BLM(l,m)) - as per epsproc.util.BLMdimList(). Some global attributes are also appended.
  • Limitations
  • ———–
  • Currently set to loop calcualtions over energy only, and all symmetries.
  • Pass single {‘Cont’ (‘sym’} to calculated for only one symmetry group.)
  • TODO (In future this will be more elegant.)
  • TODO (Setting selDims in output structure needs more thought for netCDF save compatibility.)

epsproc.mfblmXprod(matEin, QNs=None, EPRX=None, p=[0], lambdaTerm=None, BLMtable=None, thres=0.01, thresDims='Eke', selDims={'Type': 'L', 'it': 1}, sumDims=['mu', 'mup', 'l', 'lp', 'm', 'mp'], sumDimsPol=['P', 'R', 'Rp', 'p'], symSum=True, SFflag=True)[source]
epsproc.mfblmXprod(matEin, QNs=None, EPRX=None, p=[0], lambdaTerm=None, BLMtable=None, thres=0.01, thresDims='Eke', selDims={'Type': 'L', 'it': 1}, sumDims=['mu', 'mup', 'l', 'lp', 'm', 'mp'], sumDimsPol=['P', 'R', 'Rp', 'p'], symSum=True, SFflag=True)[source]
epsproc.mfpad(dataIn, thres=0.01, inds={'Type': 'L', 'it': 1}, res=50, R=None, p=0)[source]
Parameters:
  • dataIn (Xarray) – Contains set(s) of matrix elements to use, as output by epsproc.readMatEle().
  • thres (float, optional, default 1e-2) – Threshold value for matrix elements to use in calculation.
  • ind (dictionary, optional.) – Used for sub-selection of matrix elements from Xarrays. Default set for length gauage, single it component only, inds = {‘Type’:’L’,’it’:’1’}.
  • res (int, optional, default 50) – Resolution for output (theta,phi) grids.
  • R (list of Euler angles or quaternions, optional.) – Define LF > MF polarization geometry/rotations. For default case (R = None), 3 geometries are calculated, corresponding to z-pol, x-pol and y-pol cases. Defined by Euler angles (p,t,c) = [0 0 0] for z-pol, [0 pi/2 0] for x-pol, [pi/2 pi/2 0] for y-pol.
  • p (int, optional.) – Defines LF polarization state, p = -1…1, default p = 0 (linearly pol light along z-axis). TODO: add summation over p for multiple pol states in LF.
Returns:

  • Ta – Xarray (theta, phi, E, Sym) of MFPADs, summed over (l,m)
  • Tlm – Xarray (theta, phi, E, Sym, lm) of MFPAD components, expanded over all (l,m)

epsproc.molInfoParse(fileName, verbose=True)[source]

Parse an ePS file for input molecule info.

Parameters:
  • fileName (str) – File to read (file in working dir, or full path)
  • verbose (bool, default True) – Print job info from file header if true.
Returns:

molInfo – Dictionary with atom & orbital details.

Return type:

dict

Notes

Only tested for Molden input (MoldenCnv2006).

epsproc.molPlot(molInfo)[source]

Basic 3D scatter plot from molInfo data.

epsproc.multiDimXrToPD(da, colDims=None, rowDims=None, thres=None, squeeze=True, dropna=True, fillna=False, verbose=False)[source]

Convert multidim Xarray to stacked Pandas 2D array, (rowDims, colDims)

Parameters:
  • da (Xarray) – Array for conversion.
  • colDims (list of dims for columns, default = None) –
  • rowDims (list of dims for rows, default = None) –
  • NOTE (if xDim is a MultiIndex, pass as a dictionary mapping, otherwise it may be unstacked during data prep.) –
  • full control over dim stack ordering, specifiy both colDims and rowDims (For) –
  • NOTE
  • for plotting stacked (L,M), set xDim = {'LM' (E.g.) –
  • thres (float, optional, default = None) – Threshold values in output (pd table only) TODO: generalise this and use matEleSelector() for input?
  • squeeze (bool, optional, default = True) – Drop singleton dimensions.
  • dropna (bool, optional, default = True) – Drop all NaN dimensions from output pd data frame (columnwise and rowise).
  • fillna (bool, optional, default = False) – Fill any NaN values with 0.0. Useful for plotting/making data contiguous.
Returns:

  • daRestackpd (pandas data frame (2D) with sorted data.)
  • daRestack (Xarray with restacked data.)

Restack Xarray by specified dims, including basic dims checking, then use da.to_pandas().

12/03/20 Function adapted from lmPlot() code.

Note

This might casue epsproc.lmPlot() to fail for singleton x-dimensions if squeeze = True. TO do: add work-around, see lines 114-122.

epsproc.parseLineDigits(testLine)[source]

Use regular expressions to extract digits from a string. https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python

epsproc.plotTypeSelector(dataPlot, pType='a', axisUW='Eke', returnDict=False)[source]

Set plotting data type.

Parameters:
  • dataPlot (np.array, Xarray) – Data for plotting, output converted to type defined by pType.
  • pType (char, optional, default 'a') –

    Set type of plot.

    • ’a’ (abs) = np.abs(dataPlot)
    • ’a2’ (abs^2) = np.abs(dataPlot**2)
    • ’r’ (real) = np.real(dataPlot)
    • ’i’ (imag) = np.imag(dataPlot)
    • ’p’ (product) = dataPlot * np.conj(dataPlot)
    • ’phase’ = np.angle(dataPlot)
    • ’phaseUW’ = np.unwrap(np.angle(dataPlot), axis = axisUW)
  • axisUW (str, optional, default 'Eke') – Axis to use for phase unwrapping (for pType = ‘phaseUW’). Axis name must be in passed Xarray.
  • returnDict (optional, default = False) – If true, return dictionary of types & methods instead of data array.
Returns:

  • dataPlot (Xarray or np.array) – Input data structure converted to pType.
  • pTypeDict (dictionary) – Structure of valid types, formula and functions.

epsproc.readMatEle(fileIn=None, fileBase=None, fType='.out', recordType='DumpIdy')[source]

Read ePS file(s) and return results as Xarray data structures. File endings specified by fType, default *.out.

Parameters:
  • fileIn (str, list of strs, optional.) – File(s) to read (file in working dir, or full path). Defaults to current working dir if only a file name is supplied. For consistent results, pass raw strings, e.g. fileIn = r"C:\share\code\ePSproc\python_dev\no2_demo_ePS.out"
  • fileBase (str, optional.) – Dir to scan for files. Currently only accepts a single dir. Defaults to current working dir if no other parameters are passed.
  • fType (str, optional) – File ending for ePS output files, default ‘.out’
  • recordType (str, optional, default 'DumpIdy') – Type of record to scan for, currently set for ‘DumpIdy’, ‘EDCS’ or ‘CrossSection’. For a full list of descriptions, types and sources, run: >>> epsproc.util.dataTypesList()
Returns:

  • list – List of Xarray data arrays, containing matrix elements etc. from each file scanned.
  • To do
  • —–
  • - Change to pathlib paths.

Examples

>>> dataSet = readMatEle()  # Scan current dir
>>> fileIn = r'C:\share\code\ePSproc\python_dev\no2_demo_ePS.out'
>>> dataSet = readMatEle(fileIn)  # Scan single file
>>> dataSet = readMatEle(fileBase = r'C:\share\code\ePSproc\python_dev') # Scan dir

Note

  • Files are scanned for matrix element output flagged by “DumpIdy” headers.
  • Each segment found is parsed for attributes and data (set of matrix elements).
  • Matrix elements and attributes are combined and output as an Xarray array.
epsproc.readOrb3D(fileIn=None, fileBase=None, fType='_Orb.dat', verbose=True)[source]

Read ePS 3D data file(s) and return results. File endings specified by fType, default *_Orb.dat.

fileIn : str, list of strs, optional.
File(s) to read (file in working dir, or full path). Defaults to current working dir if only a file name is supplied. For consistent results, pass raw strings, e.g. fileIn = r”C:sharecodeePSprocpython_dev

o2_demo_ePS.out”

fileBase : str, optional.
Dir to scan for files. Currently only accepts a single dir. Defaults to current working dir if no other parameters are passed.
fType : str, optional
File ending for ePS output files, default ‘_Orb.dat’
verbose : bool, optional
Print output details, default True.
list
List of data arrays, containing matrix elements etc. from each file scanned.

# TODO: Change output to Xarray?

>>> dataSet = readOrb3D()  # Scan current dir
>>> fileIn = r'C:\share\code\ePSproc\python_dev\DABCOSA2PPCA2PP_10.5eV_Orb.dat'
>>> dataSet = readOrb3D(fileIn)  # Scan single file
>>> dataSet = readOrb3D(fileBase = r'C:\share\code\ePSproc\python_dev') # Scan dir
epsproc.readOrbCoords(f, headerLines)[source]
epsproc.readOrbData(f, headerLines)[source]
epsproc.readOrbElements(f, n)[source]
epsproc.readOrbHeader(f)[source]
epsproc.readXarray(fileName, filePath=None, engine='scipy')[source]

Read file from netCDF format via Xarray method.

Parameters:
  • fileName (str) – File to read.
  • filePath (str, optional, default = None) – Full path to file. If set to None (default) the file will be written in the current working directory (as returned by os.getcwd()).
Returns:

Data from file. May be in serialized format.

Return type:

Xarray

Notes

The default option for Xarray is to use Scipy netCDF writer, which does not support complex datatypes. In this case, the data array is written as a dataset with a real and imag component.

Multi-level indexing is also not supported, and must be serialized first. Ugh.

TODO: generalize multi-level indexing here.

epsproc.remapllpL(dataIn, QNs, form='dict', method='sel', dlist=['l', 'lp', 'L', 'm', 'mp', 'M'], verbose=0)[source]

Remap Wigner 3j table, with QNs (l,lp,L,m,mp,M) > tensor forms.

Tensors are stored by (l,lp,L) triples, with corresponding arrays [m,mp,M], as a dictionary, or Xarray dataarray or dataset.

Parameters:
  • dataIn (np.array) – Array of data values corresponding to rows (coords) in QNs.
  • QNs (np.array) – List of QNs [l, lp, L, m, mp, M] to compute 3j terms for. If not supplied all allowed terms for {Lmin, Lmax} will be set. (If supplied, values for Lmin, Lmax and mFlag are not used.)
  • form (str, optional, default = 'dict') – Type of output structure. - ‘dict’ : dictionary with keys (l,lp,L), coordinate tables - ‘3d’ : dictionary with keys (l,lp,L), 3D arrays indexed by [l+m, lp+mp, L+M]; this case also sets (0,0,0) term as ‘w3j0’. - ‘xdaLM’ : Xarray dataarray, with stacked dims [‘lSet’,’mSet’] - ‘xds’ : Xarray dataset, with one array per (l,lp,L) - ‘xdalist’ : List of Xarray dataarrays, one per (l,lp,L)
  • method (str, optional, default = 'sel') – Method for selection from input array. - ‘sel’ : use full selection routine, epsproc.selQNsRow(), should be most robust. - ‘n’ : sort based on np.unique reindexing. Should be faster, but possibly not robust…?
  • dlist (list, optional, default = ['l','lp','L','m','mp','M']) – Full list of dimension names to use/set.
Returns:

w3j – Wigner3j(l,lp,L,m,mp,M) values corresponding to rows (coords) in QNs, type according to input form. Data structure sorted by (l,lp,L) triples.

Return type:

Xarray, dictionary

epsproc.scatEngFileParse(fileName)[source]

Parse an ePS file for ScatEng list.

Parameters:fileName (str) – File to read (file in working dir, or full path)
Returns:
  • list – ekeList, np array of energies set in the ePS file.
  • Lists contain entries for each dumpIdy segment found in the file.
epsproc.selQNsRow(QNs, QNmask, fields=None, verbose=1)[source]

Basic routine for selecting/filtering valid rows from an input array of QNs.

This is similar to methods used in Matlab version, but likely rather slow.

Parameters:
  • QNs (np.array) – Values to be filtered.
  • QNmask (list or np.array) – Values to be matched. Must be same dims as QNs, unless fields is also set. If set to None field will be skipped (i.e. match all values)
  • fields (list or np.array, optional, default = None) – Which fields to match in QNs.
  • verbose (int, optional, default = 1) – Print info to terminal.
Returns:

  • QNs[boolMask] (np.array of selected values.)
  • boolMask (np.array corresponding to selected values.)

Examples

>>> QNsMask, mask = selQNsRow(QNs,[None, None, None, 0, 0, 0], verbose = False)
>>> # With fields
>>> QNsMask, mask = selQNsRow(QNs,[0, 0, 0], fields = [3,4,5], verbose = False)
epsproc.setADMs(ADMs=[0, 0, 0, 1], KQSLabels=None, t=None, addS=False)[source]

Create Xarray from ADMs, or create default case ADM(K,Q,S) = [0,0,0,1].

Parameters:
  • ADMs (list or np.array, default = [0,0,0,1]) – Set of ADMs = [K, Q, S, ADM]. If multiple ADMs are provided per (K,Q,S) index, they are set to the t axis (if provided), or indexed numerically.
  • KQSLabels (list or np.array, optional, default = None) – If passed, assume ADMs are unabelled, and use (K,Q,S) indicies provided here.
  • t (list or np.array, optional, default = None) – If passed, use for dimension defining ADM sets (usually time). Defaults to numerical label if not passed, t = np.arange(0,ADMs.shape[1])
  • addS (bool, default = False) – If set, append S = 0 to ADMs. This allows for passing of [K,Q,ADM] type values (e.g. for symmetric top case)
Returns:

ADMX – ADMs in Xarray format, dims as per epsproc.utils.ADMdimList()

Return type:

Xarray

Examples

>>> # Default case
>>> ADMX = setADMs()
>>> ADMX
>>> # With full N2 rotational wavepacket ADM set from demo data (ePSproc\datalignment), where modPath defines root...
>>> # Load ADMs for N2
>>> from scipy.io import loadmat
>>> ADMdataFile = os.path.join(modPath, 'data', 'alignment', 'N2_ADM_VM_290816.mat')
>>> ADMs = loadmat(ADMdataFile)
>>> ADMX = setADMs(ADMs = ADMs['ADM'], KQSLabels = ADMs['ADMlist'], addS = True)
>>> ADMX
epsproc.setPhaseConventions(phaseConvention='S', typeList=False)[source]

Set phase convention/choices for geometric functions.

20/03/20 - first attempt. Aim to centralise all phase choices here to keep things clean and easy to debug/change.

Set as dictionary for each term, to be appended to results Xarray.

Parameters:
  • phaseConvention (optional, str, default = 'S') – Set phase conventions: - ‘S’ : Standard derivation. - ‘R’ : Reduced form geometric tensor derivation. - ‘E’ : ePolyScat, may have additional changes in numerics, e.g. conjugate Wigner D. If a dict of phaseConventions is passed they will simply be returned - this is for transparency/consistency over multiple fns which call setPhaseConventions()… although may be an issue in some cases.
  • typeList (optional, bool, default = False) – If true, return list of supported options instead of list of phase choices.

Note

If a dict of phaseConventions is passed they will simply be returned - this is for transparency/consistency over multiple fns which call setPhaseConventions()… although may be an issue in some cases.

epsproc.setPhaseConventions(phaseConvention='S', typeList=False)[source]

Set phase convention/choices for geometric functions.

20/03/20 - first attempt. Aim to centralise all phase choices here to keep things clean and easy to debug/change.

Set as dictionary for each term, to be appended to results Xarray.

Parameters:
  • phaseConvention (optional, str, default = 'S') – Set phase conventions: - ‘S’ : Standard derivation. - ‘R’ : Reduced form geometric tensor derivation. - ‘E’ : ePolyScat, may have additional changes in numerics, e.g. conjugate Wigner D. If a dict of phaseConventions is passed they will simply be returned - this is for transparency/consistency over multiple fns which call setPhaseConventions()… although may be an issue in some cases.
  • typeList (optional, bool, default = False) – If true, return list of supported options instead of list of phase choices.

Note

If a dict of phaseConventions is passed they will simply be returned - this is for transparency/consistency over multiple fns which call setPhaseConventions()… although may be an issue in some cases.

epsproc.setPolGeoms(eulerAngs=None, quat=None, labels=None, vFlag=2)[source]

Generate Xarray containing polarization geometries as Euler angles and corresponding quaternions.

Define LF > MF polarization geometry/rotations. Provide either eulerAngs or quaternions, but not both (supplied quaternions only will be used in this case).

For default case (eulerAngs = None, quat = None), 3 geometries are calculated, corresponding to z-pol, x-pol and y-pol cases. Defined by Euler angles: (p,t,c) = [0 0 0] for z-pol, (p,t,c) = [0 pi/2 0] for x-pol, (p,t,c) = [pi/2 pi/2 0] for y-pol.

Parameters:
  • eulerAngs (list or np.array of Euler angles (p(hi), t(heta), c(hi)), optional.) – List or array [p,t,c…], shape (Nx3). List or array including set labels, [label,p,t,c…], shape (Nx4)
  • quat (list or np.array of quaternions, optional.) –
  • labels (list of labels, one per set of angles. Optional.) – If not set, states will be labelled numerically.
  • vFlag (version of routine to use, optional, default = 2) – Options: - 1, use labels as sub-dimensional coord. - 2, set labels as non-dimensional coord.
Returns:

  • RX (Xarray of quaternions, with Euler angles as dimensional params.)
  • To do
  • —–
  • - Better label handling, as dictionary? With mixed-type array may get issues later. – (sf.quaternion doesn’t seem to have an issue however.)
  • - Xarray MultiIndex with mixed types? – Tested with pd - not supported: >>> eulerInd = pd.MultiIndex.from_arrays([eulerAngs[:,0].T, eulerAngs[:,1:].T.astype(‘float’)], names = [‘Label’,’P’,’T’,’C’]) # Gives error: # NotImplementedError: > 1 ndim Categorical are not supported at this time

Examples

>>> # Defaults
>>> RXdefault = setPolGeoms()
>>> print(RXdefault)
>>> # Pass Eulers, no labels
>>> pRot = [1.666, 0, np.pi/2]
>>> tRot = [0, np.pi/2, np.pi/2]
>>> cRot = [-1.5, 0, 0]
>>> eulerAngs = np.array([pRot, tRot, cRot]).T
>>> RXePass = setPolGeoms(eulerAngs = eulerAngs)
>>> print(RXePass)
>>> # Pass labels separately
>>> RXePass = setPolGeoms(eulerAngs = eulerAngs, labels = ['1','23','ff'])
>>> print(RXePass)
>>> # Pass Eulers with existing labels
>>> labels = ['A','B','C']
>>> eulerAngs = np.array([labels, pRot, tRot, cRot]).T
>>> RXePass = setPolGeoms(eulerAngs = eulerAngs)
>>> print(RXePass)
>>> # Pass Quaternions and labels
>>> RXqPass = setPolGeoms(quat = RXePass, labels = labels)
>>> print(RXqPass)
>>> # Pass both - only quaternions will be used in this case, and warning displayed.
>>> RXqeTest = setPolGeoms(eulerAngs = eulerAngs, quat = RXePass, labels = labels)
>>> print(RXqeTest)
epsproc.sphCalc(Lmax, Lmin=0, res=None, angs=None, XFlag=True, fnType='sph', convention='phys')[source]

Calculate set of spherical harmonics Ylm(theta,phi) on a grid.

Parameters:
  • Lmax (int) – Maximum L for the set. Ylm calculated for Lmin:Lmax, all m.
  • Lmin (int, optional, default 0) – Min L for the set. Ylm calculated for Lmin:Lmax, all m.
  • res (int, optional, default None) – (Theta, Phi) grid resolution, outputs will be of dim [res,res].
  • angs (list of 2D np.arrays, [thetea, phi], optional, default None) – If passed, use these grids for calculation
  • XFlag (bool, optional, default True) – Flag for output. If true, output is Xarray. If false, np.arrays
  • fnType (str, optional, default = 'sph') – Currently can set to ‘sph’ for SciPy spherical harmonics, or ‘lg’ for SciPy Legendre polynomials. More backends to follow.

Note that either res OR angs needs to be passed.

  • if XFlag -
YlmX
3D Xarray, dims (lm,theta,phi)
  • else -
Ylm, lm
3D np.array of values, dims (lm,theta,phi), plus list of lm pairs
Currently set for scipy.special.sph_harm as calculation routine. Note (theta, phi) definition, and normalisation.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sph_harm.html

Example

>>> YlmX = sphCalc(2, res = 50)
epsproc.sphCalc(Lmax, Lmin=0, res=None, angs=None, XFlag=True, fnType='sph', convention='phys')[source]

Calculate set of spherical harmonics Ylm(theta,phi) on a grid.

Parameters:
  • Lmax (int) – Maximum L for the set. Ylm calculated for Lmin:Lmax, all m.
  • Lmin (int, optional, default 0) – Min L for the set. Ylm calculated for Lmin:Lmax, all m.
  • res (int, optional, default None) – (Theta, Phi) grid resolution, outputs will be of dim [res,res].
  • angs (list of 2D np.arrays, [thetea, phi], optional, default None) – If passed, use these grids for calculation
  • XFlag (bool, optional, default True) – Flag for output. If true, output is Xarray. If false, np.arrays
  • fnType (str, optional, default = 'sph') – Currently can set to ‘sph’ for SciPy spherical harmonics, or ‘lg’ for SciPy Legendre polynomials. More backends to follow.

Note that either res OR angs needs to be passed.

  • if XFlag -
YlmX
3D Xarray, dims (lm,theta,phi)
  • else -
Ylm, lm
3D np.array of values, dims (lm,theta,phi), plus list of lm pairs
Currently set for scipy.special.sph_harm as calculation routine. Note (theta, phi) definition, and normalisation.
https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sph_harm.html

Example

>>> YlmX = sphCalc(2, res = 50)
epsproc.sphFromBLMPlot(BLMXin, res=50, pType='r', plotFlag=False, facetDim=None, backend='mpl', fnType=None)[source]

Calculate spherical harmonic expansions from BLM parameters and plot.

Surfaces calculated as:

\[I(\theta,\phi)=\sum_{L,M}\beta_{L,M}Y_{L,M}(\theta,\phi)\]
Parameters:
  • dataIn (Xarray) – Input set of BLM parameters, or other (L,M) exapansion dataType.
  • res (int, optional, default 50) – Resolution for output (theta,phi) grids.
  • pType (char, optional, default 'r' (real part)) – Set (data) type to plot. See plotTypeSelector().
  • plotFlag (bool, optional, default False) – Set plotting True/False. Note that this will plot for all facetDim.
  • facetDim (str, optional, default None) – Dimension to use for subplots. Currently set for a single dimension only. For matplotlib backend: one figure per surface. For plotly backend: subplots per surface.
  • backend (str, optional, default 'mpl' (matplotlib)) – Set backend used for plotting. See sphSumPlotX() for details.
  • fnType (str, optional, default = 'sph') – Set function for expansion parameters, default is YLM from scipy.special.sph_harm. See ep.sphCalc() for details.
Returns:

  • Xarray – Xarray containing the calcualted surfaces I(theta,phi,…)
  • fig – List of figure handles.

epsproc.sphPlotHV(dataIn)[source]
epsproc.sphPlotMPL(dataPlot, theta, phi, convention='phys')[source]

Plot spherical polar function (R,theta,phi) to a Cartesian grid, using Matplotlib.

Parameters:
  • dataPlot (np.array or Xarray) – Values to plot, single surface only, with dims (theta,phi).
  • phi (theta,) – Angles defining spherical polar grid, 2D arrays.
Returns:

Handle to matplotlib figure.

Return type:

fig

epsproc.sphPlotPL(dataPlot, theta, phi, facetDim='Eke', rc=None)[source]

Plot spherical polar function (R,theta,phi) to a Cartesian grid, using Plotly.

Parameters:
  • dataPlot (np.array or Xarray) – Values to plot, single surface only, with dims (theta,phi).
  • phi (theta,) – Angles defining spherical polar grid, 2D arrays.
  • facetDim (str, default 'Eke') – Dimension to use for faceting (subplots), currently set for single dim only.
Returns:

Handle to figure.

Return type:

fig

epsproc.sphSumPlotX(dataIn, pType='a', facetDim='Eke', backend='mpl', convention='phys')[source]

Plot sum of spherical harmonics from an Xarray.

Parameters:
  • dataIn (Xarray) –

    Input structure can be

    • Set of precalculated Ylms, dims (theta,phi) or (theta,phi,LM).
    • Set of precalculated mfpads, dims (theta,phi), (theta,phi,LM) or (theta,phi,LM,facetDim).
    • If (LM) dimension is present, it is summed over before plotting.
    • If facetDim is present this is used for subplots, currently only one facetDim is supported here.
  • pType (char, optional, default 'a' (abs value)) – Set (data) type of plot. See plotTypeSelector().
  • facetDim (str, optional, default Eke) –

    Dimension to use for subplots.

    • Currently set for a single dimension only.
    • For matplotlib backend: one figure per surface.
    • For plotly backend: subplots per surface.
  • backend (str, optional, default 'mpl') –

    Set backend used for plotting.

    • mpl matplotlib: basic 3D plotting, one figure per surface.
    • pl plotly: fancier 3D plotting, interactive in Jupyter but may fail at console.
      Subplots for surfaces.
    • hv holoviews: fancier plotting with additional back-end options.
      Can facet on specific data types.
Returns:

List of figure handles.

Return type:

fig

Examples

>>> YlmX = sphCalc(2, res = 50)
>>> sphSumPlotX(YlmX)

Note

Pretty basic functionality here, should add more colour mapping options and multiple plots, alternative back-ends, support for more dimensions etc.

epsproc.sphToCart(R, theta, phi, convention='phys')[source]

Convert spherical polar coords \((R,\theta,\phi)\) to Cartesian \((X,Y,Z)\).

Parameters:
  • theta, phi (R,) – Spherical polar coords \((R,\theta,\phi)\).
  • convention (str, optional, default = 'phys') – Specify choice of Spherical Polar coordinate system, ‘phys’ or ‘maths’ (see note below).
Returns:

X, Y, Z – Cartesian coords \((X,Y,Z)\).

Return type:

np.arrays

Conversion defined with the usual physics convention , where:

  • \(R\) is the radial distance from the origin
  • \(\theta\) is the polar angle (defined relative to the z-axis), \(0\leq\theta\leq\pi\)
  • \(\phi\) is the azimuthal angle (defined relative to the x-axis), \(0\leq\theta\leq2\pi\)
  • \(X = R * np.sin(phi) * np.cos(theta)\)
  • \(Y = R * np.sin(phi) * np.sin(theta)\)
  • \(Z = R * np.cos(phi)\)

Specify convention = ‘maths’ to use alternative definition with theta and phi swapped.

epsproc.stringRepMap(string, replacements, ignore_case=False)[source]

Given a string and a replacement map, it returns the replaced string. :param str string: string to execute replacements on :param dict replacements: replacement dictionary {value to find: value to replace} :param bool ignore_case: whether the match should be case insensitive :rtype: str

CODE from: https://gist.github.com/bgusach/a967e0587d6e01e889fd1d776c5f3729 https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string … more or less verbatim.

Thanks to bgusach for the Gist.

epsproc.symFileParse(fileName)[source]

Parse an ePS file for scattering symmetries.

Parameters:fileName (str) – File to read (file in working dir, or full path)
Returns:
  • list – symSegs, raw lines from the ePS file.
  • Lists contain entries for each ScatSym setting found in file header (job input).
epsproc.symListGen(data)[source]
epsproc.w3jTable(Lmin=0, Lmax=10, QNs=None, mFlag=True, nonzeroFlag=False, form='2d', dlist=['l', 'lp', 'L', 'm', 'mp', 'M'], backend='par', verbose=0)[source]

Calculate/tabulate all wigner 3j terms for a given problem/set of QNs.

\[\begin{split}\begin{equation} \begin{array}{ccc} l & l' & L\\ m & m' & M \end{array} \end{equation}\end{split}\]

Where l, l’ take values Lmin…Lmax (default 0…10). \(\l-lp\<=L<=l+lp\) m, mp take values -l…+l if mFlag=True, or =0 only if mFlag=False

Parameters:
  • Lmax (Lmin,) – Integer values for Lmin and Lmax respectively.
  • QNs (np.array, optional, default = None) – List of QNs [l, lp, L, m, mp, M] to compute 3j terms for. If not supplied all allowed terms for {Lmin, Lmax} will be set. (If supplied, values for Lmin, Lmax and mFlag are not used.)
  • mFlag (bool, optional, default = True) – m, mp take all values -l…+l if mFlag=True, or =0 only if mFlag=False
  • nonzeroFlag (bool, optional, default = False) – Drop null terms before returning values if true.
  • form (string, optional, default = '2d') –
    Defines return format. Options are:
    • 2d, return 2D np.array, rows [l, lp, L, m, mp, M, 3j]
    • xarray, return xarray
      This is nice for easy selection/indexing, but may be problematic for large Lmax if unstacked (essentailly similar to nd case).
    • nd, return ND np.array, dims indexed as [l, lp, L, l+m, lp+mp, L+M], with values 3j.
      This is suitable for direct indexing, but will have a lot of zero entries and may be large.
    • ndsparse, return ND sparse array, dims indexed as [l, lp, L, l+m, lp+mp, L+M], with values 3j.
    Additional options are set via remapllpL(). This additionally sorts values by (l,lp,L) triples, which is useful in some cases.
    • ’dict’ : dictionary with keys (l,lp,L), coordinate tables
    • ’3d’ : dictionary with keys (l,lp,L), 3D arrays indexed by [l+m, lp+mp, L+M]; this case also sets (0,0,0) term as ‘w3j0’.
    • ’xdaLM’ : Xarray dataarray, with stacked dims [‘lSet’,’mSet’]
    • ’xds’ : Xarray dataset, with one array per (l,lp,L)
    • ’xdalist’ : List of Xarray dataarrays, one per (l,lp,L)
  • dlist (list of labels, optional, default ['l','lp','L','m','mp','M']) – Used to label array for Xarray output case.
  • backend (str, optional, default = 'par') – See Implementation note below.
Returns:

w3j – Wigner3j(l,lp,L,m,mp,M) values corresponding to rows (coords) in QNs, type according to input form.

Return type:

np.array, Xarray, dictionary

Currently set to run:
  • ‘vec’: w3jguVecCPU(), which uses sf.Wigner3j on the back-end, with additional vectorisation over supplied QNs via Numba’s @guvectorize.
  • ‘par’: w3jprange(), which uses sf.Wigner3j on the back-end, with parallelization over QNs via Numba’s @njit with a prange loop.
epsproc.w3jguVecCPU(QNs, w3j_QNs)[source]

Wrapper for 3j with vectorization via @numba.guvectorize([“void(int32[:,:], float64[:])”], ‘(n,m)->(n)’, target = ‘parallel’).

Parameters:
  • QNs (np.array) – Array of QNs to calculated Wigner 3j terms for, columns [l,lp,L,m,mp,M].
  • w3j_QNs (np.array) – Empty array to hold results (no return from @guvectorize). Create as w3j_QNs = np.zeros(QNs.shape[0])
epsproc.w3jprange(QNs)[source]

Wrapper for 3j with @numba.njit(parallel=True), using prange parallel loop.

In testing (Feb 2020) on an AMD Threadripper 1950X (16 core) this was (usually) fastest case, and beat vectorised version.

Parameters:QNs (np.array) – Array of QNs to calculated Wigner 3j terms for, columns [l,lp,L,m,mp,M].
Returns:w3j_QNs – Array of Wigner 3j results, one per row of input QNs.
Return type:np.array
epsproc.wDcalc(Lrange=[0, 1], Nangs=None, eAngs=None, R=None, XFlag=True, QNs=None, dlist=['lp', 'mu', 'mu0'], eNames=['P', 'T', 'C'], conjFlag=False)[source]

Calculate set of Wigner D functions D(l,m,mp; R) on a grid.

Parameters:
  • Lrange (list, optional, default [0, 1]) – Range of L to calculate parameters for. If len(Lrange) == 2 assumed to be of form [Lmin, Lmax], otherwise list is used directly. For a given l, all (m, mp) combinations are calculated.
  • QNs (np.array, optional, default = None) – List of QNs [l,m,mp] to compute Wigner D terms for. If supplied, use this instead of Lrange setting.
  • for setting angles (use one only) (Options) –
  • Nangs (int, optional, default None) – If passed, use this to define Euler angles sampled. Ranges will be set as (theta, phi, chi) = (0:pi, 0:pi/2, 0:pi) in Nangs steps.
  • eAngs (np.array, optional, default None) – If passed, use this to define Euler angles sampled. Array of angles, [theta,phi,chi], in radians
  • R (np.array, optional, default None) – If passed, use this to define Euler angles sampled. Array of quaternions, as given by quaternion.from_euler_angles(eAngs).
XFlag : bool, optional, default True
Flag for output. If true, output is Xarray. If false, np.arrays
dlist : list, optional, default [‘lp’,’mu’,’mu0’]
Labels for Xarray QN dims.
eNames : list, optional, default [‘P’,’T’,’C’]
Labels for Xarray Euler dims.
conjFlag : bool, optional, default = False
If true, return complex conjuage values.
  • if XFlag -
wDX
Xarray, dims (lmmp,Euler)
  • else -
wD, R, lmmp
np.arrays of values, dims (lmmp,Euler), plus list of angles and lmmp sets.
Uses Moble's spherical_functions package for wigner D function.
https://github.com/moble/spherical_functions
Moble's quaternion package for angles and conversions.
https://github.com/moble/quaternion
For testing, see https://epsproc.readthedocs.io/en/latest/tests/Spherical_function_testing_Aug_2019.html

Examples

>>> wDX1 = wDcalc(eAngs = np.array([0,0,0]))
>>> wDX2 = wDcalc(Nangs = 10)
epsproc.writeOrb3Dvtk(dataSet)[source]

Write ePS 3D data file(s) to vtk format. This can be opened in, e.g., Paraview.

Parameters:
  • dataSet (list) – List of data arrays, containing matrix elements etc. from each file scanned. Assumes format as output by readOrb3D(), [fileName, headerLines, coords, data]
  • TODO (#) –
Returns:

List of output files.

Return type:

list

epsproc.writeXarray(dataIn, fileName=None, filePath=None, engine='h5netcdf')[source]

Write file to netCDF format via Xarray method.

Parameters:
  • dataIn (Xarray) – Data array to write to disk.
  • fileName (str, optional, default = None) – Filename to use. If set to None (default) the file will be written with a datastamp.
  • filePath (str, optional, default = None) – Full path to file. If set to None (default) the file will be written in the current working directory (as returned by os.getcwd()).
  • engine (str, optional, default = 'h5netcdf') – netCDF engine for Xarray to_netcdf method. Some libraries may not support multidim data formats.
Returns:

Indicates save type and file path.

Return type:

str

Notes

The default option for Xarray is to use Scipy netCDF writer, which does not support complex datatypes. In this case, the data array is written as a dataset with a real and imag component.

TODO: implement try/except to handle various cases here, and test other netCDF writers (see http://xarray.pydata.org/en/stable/io.html#netcdf).

Multi-level indexing is also not supported, and must be serialized first. Ugh.