torchspin.lft.plot#
Plots of ligand-field results: level, Tanabe-Sugano, Zeeman, angle and road-map diagrams, magnetometry (chi T, chi, mu_eff vs T; M vs B or B/T) with fits, and powder spectra.
Every function returns (fig, ax) as torchspin.levelsplot() does (ax is a
list [main, residuals] when a residual panel is drawn) and takes an optional ax to draw
into. matplotlib (torchspin’s optional plot extra) is imported inside the functions.
Units#
Ligand-field energy axes default to units='cm^-1' (torchspin.lft.units.PLOT_ENERGY_UNITS)
and accept 'MHz', 'GHz', 'K', 'eV' (any unit of torchspin.lft.units). The
unit of the data is read from the result object where it carries one (LoopResult.units,
TanabeSuganoDiagram.units, dsoxf.Solution.units) and is from_units (default
'MHz', the lft default) otherwise. Field axes are in mT (field_units='G' or 'T' on
request); magnetization plots default to tesla. Susceptibility is plotted in chi_units
('cgs': cm^3/mol, default; 'SI': m^3/mol).
Style#
Every plot is drawn inside a local matplotlib.rc_context() (the global rcParams are never
changed): Helvetica or Arial (sans-serif fallback), bold axis labels and titles, solid dark
spines of 1.2 pt, no grid. No text is drawn on top of lines, markers or other text: level and
Tanabe-Sugano labels are spread apart with leader lines (labels that cannot be placed without
overlap are left out), resonance positions are tick labels on a secondary axis, and legends go
into a corner checked to be free of data, or outside the axes.
Example ((fig, ax) is returned; the Agg backend draws without a display):
>>> import matplotlib
>>> matplotlib.use('Agg')
>>> import matplotlib.pyplot as plt
>>> import torch
>>> from torchspin import lft
>>> from torchspin.lft import plot
>>> fig, ax = plot.tanabe_sugano(lft.tanabe_sugano.tanabe_sugano(3))
>>> V = lft.crystal_field(1200.0, 2000.0, 300.0) # Cu(II), cm^-1
>>> res = lft.ddnloop.field_scan(9, torch.linspace(0, 450, 91), theta=0.0, units='cm^-1',
... zeta=830.0, k=(0.8,) * 3, V=V, pairs=[(0, 1)])
>>> fig, ax = plot.zeeman(res, mw_freq=9.5)
>>> plt.close('all')
- torchspin.lft.plot.levels(energies, *, labels=None, from_units=None, units=_u.PLOT_ENERGY_UNITS, relative=True, tol=1e-3, emax=None, parity=None, max_bars=16, title=None, fontsize=8.5, ax=None, figsize=(3.8, 4.8))[source]#
Energy-level diagram: each level a group of short horizontal bars, one bar per state.
- Parameters:
energies (array_like, Tensor, Solution or list of CubicLevel) – A 1-D tensor/array of state energies (
lft.ddn.levels,lft.dpn.levels,DsoxfSystem.levels) infrom_units; atorchspin.lft.dsoxf.Solution(its own units); or a list oftorchspin.lft.tanabe_sugano.CubicLevel(term labels and degeneracies come with them).labels (None, 'energy' or sequence of str, optional) –
'energy'labels each level with its energy; a sequence gives one string per level (or per state: the first state of a level names it). Term labels such as'4T2'are typeset (^4T_2). Labels sit right of the bars, spread apart with leader lines; those that cannot be placed without overlap are left out (the lowest levels are kept).from_units (str, optional) – Unit of plain energies; default
'MHz'(the lft default).units (str, default 'cm^-1') – Energy axis unit.
relative (bool, default True) – Put the ground level at 0.
tol (float, default 1e-3) – States within
tolcm^-1 form one level.emax (float, optional) – Upper limit of the axis, in
units.parity ({'g', 'u'}, optional) – Subscript of the term labels.
max_bars (int, default 16) – A level with more states is drawn as one bar with its degeneracy in the label.
title (str, optional)
fontsize (float, default 8.5) – Label font size.
ax (matplotlib.axes.Axes, optional) – Axes to draw into (default: a new figure).
figsize (tuple, default (3.8, 4.8)) – Size of a new figure, inches.
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Raises:
ValueError – If the energies are not 1-D, or
labelshas the wrong length.ImportError – Without matplotlib.
Examples
>>> import matplotlib >>> matplotlib.use('Agg') >>> import matplotlib.pyplot as plt >>> from torchspin import lft >>> from torchspin.lft import plot >>> e = lft.ddn.levels(9, V=lft.crystal_field(1200.0, 2000.0, 300.0), zeta=830.0, units='cm^-1') >>> fig, ax = plot.levels(e, from_units='cm^-1') >>> plt.close(fig)
- torchspin.lft.plot.tanabe_sugano(diagram, *, units=_u.PLOT_ENERGY_UNITS, ymax=None, labels=True, parents=True, title=None, fontsize=8.0, ax=None, figsize=(5.2, 5.4))[source]#
Tanabe-Sugano diagram.
Conventional axes E/B vs Dq/B (dimensionless) by default; when the diagram carries Racah B (
tanabe_sugano(..., B=...)ordiagram.at(B)) the axes are E and Dq inunits. Curves are colored by spin multiplicity (legend above the axes); the term label of every curve that ends inside the plot is placed in the right margin with a leader line (Oh labels carry the g subscript). Ground-state crossovers are dashed vertical lines.- Parameters:
diagram (TanabeSuganoDiagram) – From
torchspin.lft.tanabe_sugano.tanabe_sugano().units (str, default 'cm^-1') – Axis unit when the diagram carries B.
ymax (float, optional) – Top of the energy axis (default E/B = 70, or 70 B).
labels (bool, default True) – Draw term labels.
parents (bool, default True) – Add the free-ion parent term where a label occurs more than once, e.g. ^4T_1g(P) (
parent_terms()).title (str, optional)
fontsize (float, default 8.0)
ax (matplotlib.axes.Axes, optional)
figsize (tuple, default (5.2, 5.4))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
Examples
>>> import matplotlib >>> matplotlib.use('Agg') >>> import matplotlib.pyplot as plt >>> from torchspin import lft >>> fig, ax = lft.plot.tanabe_sugano(lft.tanabe_sugano.tanabe_sugano(3)) >>> plt.close(fig)
- torchspin.lft.plot.zeeman(result, *, states=None, units=_u.PLOT_ENERGY_UNITS, field_units='mT', mw_freq=None, offset='ground', threshold=1e-3, title=None, ax=None, figsize=(5.0, 4.0))[source]#
Zeeman diagram: energies vs field magnitude.
- Parameters:
result (LoopResult) – From
torchspin.lft.ddnloop.field_scan().states (sequence of int, optional) – Indices of the states to draw; default those within 10 mu_B B_max of the ground state somewhere in the scan (the ground manifold an EPR experiment sees).
units (str, default 'cm^-1') – Energy axis unit.
field_units ({'mT', 'G', 'T'}, default 'mT')
mw_freq (float, optional) – Microwave frequency in GHz: transitions with E_j - E_i = h nu are drawn as vertical markers (red to gray by the level-summed probability when the scan has
pairs; then only those pairs) and their fields become tick labels on the top axis.offset ('ground', float or None, default 'ground') –
'ground'puts the lowest drawn state at the first field point at 0; a number (inunits) is subtracted;Noneplots the energies as computed.threshold (float, default 1e-3) – Markers below
thresholdtimes the strongest are omitted.title (str, optional)
ax (matplotlib.axes.Axes, optional)
figsize (tuple, default (5.0, 4.0))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Raises:
ValueError – If
resultis not a scan over field magnitude.
- torchspin.lft.plot.angles(result, *, angle=None, states=None, units=_u.PLOT_ENERGY_UNITS, mw_freq=None, offset='center', threshold=1e-3, title=None, ax=None, figsize=(5.0, 4.0))[source]#
Angle (rotation) diagram: energies at fixed field vs theta or phi (degrees).
- Parameters:
result (LoopResult) – From
torchspin.lft.ddnloop.angle_scan().angle ({'theta', 'phi'}, optional) – Default: the one that varies.
offset ('center', float or None, default 'center') –
'center'subtracts the mean energy of the drawn states; a number (inunits) is subtracted;None: as computed.mw_freq (float, optional) – GHz: orientations where E_j - E_i = h nu are drawn as vertical markers and their angles become top tick labels.
states – As
zeeman().ax – As
zeeman().figsize – As
zeeman().
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Raises:
ValueError – If the field varies in the scan, or
angleis ambiguous or unknown.
See also
roadmapResonance fields vs angle.
- torchspin.lft.plot.roadmap(result, mw_freq, *, angle=None, states=None, field_units='mT', threshold=1e-3, title=None, ax=None, figsize=(5.0, 4.0))[source]#
Road map (rotation pattern): resonance fields at
mw_freqvs theta or phi.Resonances are found by interpolation along the field; with
pairsin the scan only those pairs are used and the line width follows the level-summed probability. One line color per pair (legend when there is more than one).- Parameters:
result (LoopResult) – A
torchspin.lft.ddnloop.scan()over angle x field (e.g.mesh=Truewith one theta or phi value, or angles (n, 1) broadcast against fields (m,)); the field must be the last scan axis.mw_freq (float) – Microwave frequency in GHz.
angle ({'theta', 'phi'}, optional) – Default: the one that varies.
states (sequence of int, optional) – States to consider (as
zeeman()).field_units ({'mT', 'G', 'T'}, default 'mT')
threshold (float, default 1e-3) – Markers below
thresholdtimes the strongest are dropped.ax – As
zeeman().figsize – As
zeeman().
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Raises:
ValueError – If the field is not the last, varying scan axis.
- torchspin.lft.plot.susceptibility(T, model=None, *, data=None, model_at_data=None, quantity='chiT', given='chiT', model_chi_units='SI', chi_units='cgs', residuals=None, model_label='Calc.', data_label='Obs.', title=None, ax=None, figsize=(4.6, 4.2))[source]#
chi T (default), chi or mu_eff vs T, optionally with data, a fitted curve and a residual panel.
- Parameters:
T (array_like, shape (nT,)) – Temperatures of the calculated curve, K.
model (MagResult or array_like, optional) – The calculated curve: a
torchspin.lft.ddnmag.MagResultfromlft.ddnsus.chi_T/susceptibility(one measuring field), or values (nT,).data (tuple of 2 array_like, optional) –
(T_obs, y_obs), already in the plottedquantityandchi_units.model_at_data (array_like, optional) – The model at the data temperatures (units of
model); otherwise interpolated from the curve for the residuals.quantity ({'chiT', 'chi', 'mu_eff'}, default 'chiT') – Plotted quantity (
mu_effin Bohr magnetons).given ({'chiT', 'chi'}, default 'chiT') – What
modelholds.model_chi_units ({'SI', 'cgs'}, default 'SI') – Units of
model(the ddnsus default is SI, m^3/mol).chi_units ({'cgs', 'SI'}, default 'cgs') – Plotted units: cm^3/mol or m^3/mol.
residuals (bool, optional) – Residual panel (obs - calc); default on with data and model.
model_label (str, default 'Calc.', 'Obs.')
data_label (str, default 'Calc.', 'Obs.')
title (str, optional)
ax (matplotlib.axes.Axes, optional)
figsize (tuple, default (4.6, 4.2))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes or list of Axes) –
[main, residuals]when a residual panel is drawn.
- Raises:
ValueError – For an unknown
givenorquantity, or a model with a different number of values than temperatures.
See also
fitPlot a
torchspin.lft.fit.JointFitresult directly.
Examples
>>> import matplotlib >>> matplotlib.use('Agg') >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from torchspin.lft import plot >>> T = np.linspace(2.0, 300.0, 50) >>> fig, ax = plot.susceptibility(T, np.full_like(T, 0.375), model_chi_units='cgs') >>> plt.close(fig)
- torchspin.lft.plot.magnetization(field, M, T=None, *, x='B', field_units='T', from_M_units='muB', M_units='muB', data=None, model_at_data=None, residuals=None, title=None, ax=None, figsize=(4.8, 4.2))[source]#
M vs B (
x='B') or vs B/T (x='B/T') for one or more temperatures.- Parameters:
field (array_like, shape (nB,)) – Fields in mT (as
lft.ddnmag).M (MagResult or array_like) – A
torchspin.lft.ddnmag.MagResult(its powder (nB, nT)) or values (nB,) / (nB, nT) infrom_M_units.T (array_like, shape (nT,), optional) – Temperatures in K, one curve (color) each; required for
x='B/T'.x ({'B', 'B/T'}, default 'B')
field_units ({'T', 'mT', 'G'}, default 'T') – Field axis unit.
from_M_units ({'muB', 'emu/mol', 'SI'}, default 'muB') – Units of
Mand of the plot (Bohr magnetons per ion, emu/mol, A m^2/mol).M_units ({'muB', 'emu/mol', 'SI'}, default 'muB') – Units of
Mand of the plot (Bohr magnetons per ion, emu/mol, A m^2/mol).data (tuple, optional) –
(field_obs in mT, T_obs, M_obs in M_units), markers colored by the matching temperature.model_at_data (array_like, optional) – M at the data points (
from_M_units); turns the residual panel on by default.residuals (bool, optional)
title (str, optional)
ax (matplotlib.axes.Axes, optional)
figsize (tuple, default (4.8, 4.2))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes or list of Axes) –
[main, residuals]with a residual panel.
- Raises:
ValueError – For an unknown
x,x='B/T'withoutT, or a number of curves different from the number of temperatures.
- torchspin.lft.plot.powder(result, *, mw_freq=None, field_units='mT', kind='field', from_units='MHz', units=_u.PLOT_ENERGY_UNITS, normalize=True, data=None, label=None, overlay=None, ylabel='Intensity (arb. u.)', title=None, ax=None, figsize=(5.0, 3.6))[source]#
Powder spectrum from
torchspin.lft.ddnpow,torchspin.lft.ddpowhortorchspin.lft.ddpowj.- Parameters:
result (PowderResult) – The simulation result (
ddnpowresults have the same fields).mw_freq (float, optional) – GHz; quoted in the legend.
field_units ({'mT', 'G', 'T'}, default 'mT') – Axis unit for
kind='field'.kind ({'field', 'energy', 'rf'}, default 'field') –
'field': field axis (ddnpow.simulate,ddpowh.epr,ddpowj.epr);'energy': FDMR axis (ddnpow.fdmr,ddpowh.fdmr) infrom_unitsconverted tounits;'rf': ENDOR/NMR axis in MHz (ddpowh.endor,ddpowh.nmr).from_units (str, default 'MHz') – The
unitsof the FDMR run.units (str, default 'cm^-1') – FDMR axis unit.
normalize (bool, default True) – Scale to
max(abs(y)) = 1(data too; each overlay to the main spectrum’s maximum, so relative heights are kept).data (tuple of 2 array_like, optional) –
(axis, y)in the plotted axis unit, overlaid as a dark line.label (str, optional)
overlay (list of tuple, optional) –
[(result, label), ...]: more simulations on the same axis kind, drawn dashed.ylabel (str, default 'Intensity (arb. u.)')
title (str, optional)
ax (matplotlib.axes.Axes, optional)
figsize (tuple, default (5.0, 3.6))
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes)
- Raises:
ValueError – For an unknown
kindor field unit.
Examples
>>> import matplotlib >>> matplotlib.use('Agg') >>> import matplotlib.pyplot as plt >>> import torch >>> from torchspin import SpinSystem >>> from torchspin.lft import ddpowh, plot >>> res = ddpowh.epr(SpinSystem(S=0.5, g=[2.0, 2.0, 2.2]), torch.linspace(300, 350, 101), 9.5, ... width=50.0, igloo=6) >>> fig, ax = plot.powder(res, mw_freq=9.5) >>> plt.close(fig)
- torchspin.lft.plot.fit(joint, outcome, dataset=None, *, npts=200, quantity=None, chi_units=None, x='B', field_units='T', title=None, ax=None)[source]#
Plot a
torchspin.lft.fit.JointFitresult on one magnetometry data set.Draws the data, the best-fit curve (recomputed from the model at
outcome.result.values) and the residual panel (obs - calc at the data points, exact).- Parameters:
joint (JointFit)
outcome (JointOutcome) – Result of
joint.fit().dataset (str or int, optional) – Name or index of the data set; default the first
SusceptibilityorMagnetizationblock.npts (int, default 200) – Points of the best-fit curve.
quantity (str, optional) – Susceptibility: as
susceptibility()(default the block’s).chi_units (str, optional) – Susceptibility: as
susceptibility()(default the block’s).x (str, default 'B', 'T') – Magnetization: as
magnetization().field_units (str, default 'B', 'T') – Magnetization: as
magnetization().title (str, optional)
ax (matplotlib.axes.Axes, optional)
- Returns:
fig (matplotlib.figure.Figure)
ax (list of Axes) –
[main, residuals].
- Raises:
ValueError – If there is no such data set, or it is not a Susceptibility or Magnetization block.
- torchspin.lft.plot.STYLE = {'axes.edgecolor': '#1a1a1a', 'axes.grid': False, 'axes.labelcolor': '#1a1a1a', 'axes.labelsize': 10.5, 'axes.labelweight': 'bold', 'axes.linewidth': 1.2, 'axes.titlesize': 11.0, 'axes.titleweight': 'bold', 'axes.unicode_minus': True, 'font.size': 10.0, 'legend.fontsize': 8.5, 'legend.frameon': False, 'lines.linewidth': 1.3, 'mathtext.default': 'regular', 'xtick.color': '#1a1a1a', 'xtick.direction': 'out', 'xtick.major.size': 4.0, 'xtick.major.width': 1.2, 'xtick.minor.width': 0.9, 'ytick.color': '#1a1a1a', 'ytick.direction': 'out', 'ytick.major.size': 4.0, 'ytick.major.width': 1.2, 'ytick.minor.width': 0.9}#
rcParams applied inside every plot (
font.familyis resolved to Helvetica or Arial at call time).
- torchspin.lft.plot.term_label(label, parity=None, parent=None)[source]#
Mathtext for a term or irrep label.
- Parameters:
- Returns:
str – matplotlib mathtext.
- Return type:
Examples
>>> from torchspin.lft import plot >>> plot.term_label('4T1', 'g', 'P') '$^{4}$T$_{\\mathregular{1g}}$(P)'
- torchspin.lft.plot.parent_terms(n, c_over_b, geometry='Oh')[source]#
Free-ion parent term of every Tanabe-Sugano curve of d^n.
The roots of a (2S+1)Gamma block that meet at one energy at Dq = 0 come from the free-ion terms of that spin at that energy (several when terms are degenerate, e.g. 2P and 2H of d3/d7), each contributing Gamma as often as the branching rule says. Within such a cluster the roots are ranked by <L^2> at small Dq/B (full determinant basis) and given the terms in order of L, so the labels always follow the branching rules. Where degenerate terms mix (2P/2H in a cubic field), the parent is the dominant one in this ranking, not a pure state.
- Parameters:
- Returns:
dict –
{(block label, root): parent letter}.- Raises:
RuntimeError – If the roots cannot be matched to the free-ion terms.
- Return type:
- torchspin.lft.plot.branching(L)[source]#
Multiplicity of each O irrep in the free-ion term of orbital angular momentum L.
- Parameters:
L (int) – Orbital angular momentum (S = 0, P = 1, …).
- Returns:
dict of str to int –
{irrep: multiplicity}, e.g. P -> T1, H -> E + 2 T1 + T2.- Return type:
Examples
>>> from torchspin.lft import plot >>> plot.branching(3) # F {'A2': 1, 'T1': 1, 'T2': 1}