pysme package#
Subpackages#
- pysme.gui package
- Submodules
- pysme.gui.plot_colors module
- pysme.gui.plot_plotly module
FinalPlotFinalPlot.add()FinalPlot.create_mask_points()FinalPlot.create_plot()FinalPlot.on_toggle_click()FinalPlot.save()FinalPlot.selection_fn()FinalPlot.set_mask_bad()FinalPlot.set_mask_continuum()FinalPlot.set_mask_good()FinalPlot.set_mask_line()FinalPlot.set_mask_type()FinalPlot.shift_mask()FinalPlot.show()
FitPlot
- pysme.gui.plot_pyplot module
- Module contents
Submodules#
pysme.abund module#
Elemental abundance data handling module
- class pysme.abund.Abund(monh=0, pattern='solar', type='sme', citation_info='\n@article{loss2003atomic,\n title={Atomic weights of the elements 2001 (IUPAC Technical Report)},\n author={Loss, RD},\n journal={Pure and Applied Chemistry},\n volume={75},\n number={8},\n pages={1107--1122},\n year={2003},\n publisher={De Gruyter}\n}\n')[source]#
Bases:
IPersistElemental abundance data and methods. Valid abundance pattern types are:
- ‘sme’ - For hydrogen, the abundance value is the fraction of all
nuclei that are hydrogen, including all ionization states and treating molecules as constituent atoms. For the other elements, the abundance values are log10 of the fraction of nuclei of each element in any form relative to the total for all elements in any form. For the Sun, the abundance values of H, He, and Li are approximately 0.92, -1.11, and -11.0.
- ‘n/nTot’ - Abundance values are the fraction of nuclei
of each element in any form relative to the total for all elements in any form. For the Sun, the abundance values of H, He, and Li are approximately 0.92, 0.078, and 1.03e-11.
- ‘n/nH’ - Abundance values are the fraction of nuclei
of each element in any form relative to the number of hydrogen nuclei in any form. For the Sun, the abundance values of H, He, and Li are approximately 1, 0.085, and 1.12e-11.
- ‘H=12’ - Abundance values are log10 of the fraction of nuclei of
each element in any form relative to the number of hydrogen in any form plus an offset of 12. For the Sun, the nuclei abundance values of H, He, and Li are approximately 12, 10.9, and 1.05.
- static fromtype(pattern, fromtype, raw=False)[source]#
Return a copy of the input abundance pattern, transformed from the input type to the ‘H=12’ type. Valid abundance pattern types are ‘sme’, ‘n/nTot’, ‘n/nH’, ‘n/nFe’, and ‘H=12’.
- get_pattern(type=None, raw=False)[source]#
Transform the specified abundance pattern from type used internally by SME to the requested type. Valid abundance pattern types are: ‘sme’, ‘n/nTot’, ‘n/nH’, ‘H=12’
- Parameters:
type (str) – The pattern format to retrieve the pattern as. Defaults to the original input format.
raw (bool) – If True will return the pattern as a numpy array, with indices as defined in elem dict. Otherwise the return value is a dictionary, with the elements as keys.
- set_pattern_by_name(pattern_name)[source]#
Set the abundance pattern to one of the predefined options
- Parameters:
pattern_name (str) – Name of the predefined option to use. One of: ‘grevesse2007’, ‘asplund2009’, ‘asplund2021’, ‘asplund2005’, ‘lodders2003’, ‘anders1989’, ‘grevesse1996’, ‘grevesse1998’, ,’lodders2010’, ‘empty’
- Raises:
ValueError – If an undefined pattern_name was given
- static totype(pattern, totype, raw=False, copy=True, X=None)[source]#
Return a copy of the input abundance pattern, transformed from the ‘H=12’ type to the output type. Valid abundance pattern types are ‘sme’, ‘kurucz’, ‘n/nTot’, ‘n/nH’, and ‘H=12’.
- update_pattern(updates)[source]#
Update the abundance pattern for several elements at once
The abundance is first converted into the initially specified format, before being converted back to the internal format
- Parameters:
updates (dict{str:float}) – the elements to update
- Raises:
KeyError – If any of the element keys is not valid
- property A#
Mutable mapping view of abundances used in synthesis (H=12 scale).
- property elem#
Return the standard abbreviation for each element. Use property so user will not redefine elements.
- property elem_dict#
Return the position of each element in the raw array
- property monh#
Metallicity, the logarithmic offset added to the abundance pattern for all elements except hydrogen and helium.
- Type:
float
- property pattern#
Mutable mapping view of the current internal abundance pattern.
- property reference#
Read-only mapping view of the fixed abundance reference pattern.
- property xh#
Mutable mapping view of [X/H] relative to the reference pattern.
- property xm#
Mutable mapping view of [X/M]_PySME relative to the reference pattern.
pysme.atmosphere module#
pysme.broadening module#
- pysme.broadening.apply_broadening(ipres, x_seg, y_seg, type='gauss', sme=None)[source]#
Broaden a spectrum by instrument resolution, with a given broadening type
- Parameters:
ipres (float) – instrument resolution
x_seg (array (npoints,)) – x values (wavelength) of the spectrum to broaden
y_seg (array (npoints,)) – y values (intensities) of the spectrum to broaden
type ({str, None}, optional) – broadening type to apply. Options are “gauss”, “sinc”, “table”, None. If None, will try to use sme.iptype to determine type. “table” requires keyword sme to be passed as well. See functions the respective for details. (default: “gauss”)
sme (SME_Struct, optional) – sme structure with instrument profile data, required only for type=”table” or type=None (default: None)
- Raises:
AttributeError – if type requires SME_Struct, but its missing passed type not recognized
- Returns:
y_seg – broadened intensity spectrum
- Return type:
array (npoints,)
- pysme.broadening.gaussbroad(w, s, hwhm)[source]#
Smooths a spectrum by convolution with a gaussian of specified hwhm.
- Parameters:
w (array[n]) – wavelength scale of spectrum to be smoothed
s (array[n]) – spectrum to be smoothed
hwhm (float) – half width at half maximum of smoothing gaussian.
- Returns:
sout – the gaussian-smoothed spectrum.
- Return type:
array[n]
- pysme.broadening.sincbroad(w, s, hwhm)[source]#
Smooths a spectrum by convolution with a sinc function of specified hwhm.
- Parameters:
w (array of size (n,)) – wavelength scale of spectrum to be smoothed
s (array of size (n,)) – spectrum to be smoothed
hwhm (float) – half width at half maximum of smoothing gaussian.
- Returns:
sout – the sinc-smoothed spectrum.
- Return type:
array of size (n,)
- pysme.broadening.tablebroad(w, s, xip, yip)[source]#
Convolves a spectrum with an arbitrary instrumental profile.
- Parameters:
w (array of size (n,)) – wavelength scale of spectrum to be smoothed
s (array of size (n,)) – spectrum to be smoothed
xip (array of size (m,)) – x points of the instrument profile
yip (array of size (m,)) – y points of the instrument profile
- Returns:
sout – the smoothed spectrum.
- Return type:
array[n]
pysme.config module#
Handle the Json configuration file At the moment it is only used for the LargeFileStorage
pysme.continuum_and_radial_velocity module#
Determine continuum based on continuum mask and fit best radial velocity to observation
- class pysme.continuum_and_radial_velocity.ContinuumNormalizationMask[source]#
Bases:
ContinuumNormalizationAbstract- get_continuum_mask(wave, synth, linelist, threshold=0.1, mask=None)[source]#
Use the effective wavelength range of the lines, to find wavelength points that should be unaffected by lines However one usually has to ignore the weak lines, as most points are affected by one line or another Therefore keep increasing the threshold until enough lines have been found (>10%)
- Parameters:
wave (array of size (n,)) – wavelength points
linelist (LineList) – LineList object that was input into the Radiative Transfer
threshold (float, optional) – starting threshold, lines with depth below this value are ignored the actual threshold is increased until enough points are found (default: 0.1)
- Returns:
mask – True for points between lines and False for points within lines
- Return type:
array(bool) of size (n,)
- class pysme.continuum_and_radial_velocity.ContinuumNormalizationMatchLines[source]#
Bases:
ContinuumNormalizationMatch
- class pysme.continuum_and_radial_velocity.ContinuumNormalizationMatchMask[source]#
Bases:
ContinuumNormalizationMatch
- class pysme.continuum_and_radial_velocity.ContinuumNormalizationSplineMask[source]#
Bases:
ContinuumNormalizationSpline
- pysme.continuum_and_radial_velocity.apply_continuum(wave, smod, cwave, cscale, cscale_type, segments, copy=False)[source]#
Apply continuum to the spectra according to cscale.
- pysme.continuum_and_radial_velocity.apply_radial_velocity(wave, wmod, smod, vrad, segments, copy=False)[source]#
- pysme.continuum_and_radial_velocity.apply_radial_velocity_and_continuum(wave, wmod, smod, vrad, cscale, cscale_type, segments, copy=False)[source]#
Apply the radial velocity and continuum corrections to a syntheic spectrum to match the observation
- Parameters:
wave (array) – final wavelength array of the observation
wmod (array) – wavelength array of the synthethic spectrum
smod (array) – flux array of the synthetic spectrum
vrad (array, None) – radial velocities in km/s for each segment
cscale (array, None) – continnum scales for each segment, exact meaning depends on cscale_type
cscale_type (str) – defines the continuum correction behaviour
segments (array) – the segments to apply the correction to
- Returns:
smod – the corrected synthetic spectrum
- Return type:
array
- pysme.continuum_and_radial_velocity.cross_correlate_segment(x_obs, y_obs, x_syn, y_syn, mask, mask_wider, rv_bounds)[source]#
- pysme.continuum_and_radial_velocity.determine_radial_velocity(sme, x_syn, y_syn, segment, cscale=None, whole=False, least_squares_kwargs=None)[source]#
Calculate radial velocity by using cross correlation and least-squares between observation and synthetic spectrum
- Parameters:
sme (SME_Struct) – sme structure with observed spectrum and flags
segment (int) – which wavelength segment to handle, -1 if its using the whole spectrum
cscale (array of size (ndeg,)) – continuum coefficients, as determined by e.g. determine_continuum
x_syn (array of size (n,)) – wavelength of the synthetic spectrum
y_syn (array of size (n,)) – intensity of the synthetic spectrum
- Raises:
ValueError – if sme.vrad_flag is not recognized
- Returns:
rvel – best fit radial velocity for this segment/whole spectrum or None if no observation is present
- Return type:
float
- pysme.continuum_and_radial_velocity.match_rv_continuum(sme, segments, x_syn, y_syn)[source]#
Match both the continuum and the radial velocity of observed/synthetic spectrum
Note that the parameterization of the continuum is different to old SME !!!
- Parameters:
sme (SME_Struct) – input sme structure with all the parameters
segment (int) – index of the wavelength segment to match, or -1 when dealing with the whole spectrum
x_syn (array of size (n,)) – wavelength of the synthetic spectrum
y_syn (array of size (n,)) – intensitz of the synthetic spectrum
- Returns:
rvel (float) – new radial velocity
cscale (array of size (ndeg + 1,)) – new continuum coefficients
pysme.cwrapper module#
Wrapper for IDL style C libary code
{return_type} {func_name}(int argv, void *argc[]);
with argv - number of parameters and argc - list of pointers to those parameters
- class pysme.cwrapper.GlobalState[source]#
Bases:
Structure- ABUND#
Structure/Union member
- ACOOL#
Structure/Union member
- AH2P#
Structure/Union member
- AHE1#
Structure/Union member
- AHE2#
Structure/Union member
- AHEMIN#
Structure/Union member
- AHMIN#
Structure/Union member
- AHOT#
Structure/Union member
- AHYD#
Structure/Union member
- ALMAX#
Structure/Union member
- ALUKE#
Structure/Union member
- ANSTEE#
Structure/Union member
- ATOTAL#
Structure/Union member
- AUTOION#
Structure/Union member
- AVOIGT#
Structure/Union member
- BNLTE_low#
Structure/Union member
- BNLTE_upp#
Structure/Union member
- BNU#
Structure/Union member
- COPBLU#
Structure/Union member
- COPRED#
Structure/Union member
- COPSTD#
Structure/Union member
- EHVKT#
Structure/Union member
- ENL4#
Structure/Union member
- ENU4#
Structure/Union member
- EXCIT#
Structure/Union member
- EXCUP#
Structure/Union member
- FRACT#
Structure/Union member
- FREQ#
Structure/Union member
- FREQLG#
Structure/Union member
- GAMQST#
Structure/Union member
- GAMRAD#
Structure/Union member
- GAMVW#
Structure/Union member
- GF#
Structure/Union member
- GRAV#
Structure/Union member
- H1FRACT#
Structure/Union member
- H2molFRACT#
Structure/Union member
- HE1FRACT#
Structure/Union member
- HKT#
Structure/Union member
- IDLHEL#
Structure/Union member
- IFOP#
Structure/Union member
- INDX_C#
Structure/Union member
- ION#
Structure/Union member
- IXAL1#
Structure/Union member
- IXC1#
Structure/Union member
- IXCA1#
Structure/Union member
- IXCA2#
Structure/Union member
- IXCH#
Structure/Union member
- IXFE1#
Structure/Union member
- IXH1#
Structure/Union member
- IXH2#
Structure/Union member
- IXH2mol#
Structure/Union member
- IXH2pl#
Structure/Union member
- IXHE1#
Structure/Union member
- IXHE2#
Structure/Union member
- IXHE3#
Structure/Union member
- IXHMIN#
Structure/Union member
- IXMG1#
Structure/Union member
- IXMG2#
Structure/Union member
- IXN1#
Structure/Union member
- IXNH#
Structure/Union member
- IXO1#
Structure/Union member
- IXOH#
Structure/Union member
- IXSI1#
Structure/Union member
- IXSI2#
Structure/Union member
- LINEOP#
Structure/Union member
- LTE_b#
Structure/Union member
- MARK#
Structure/Union member
- MOLWEIGHT#
Structure/Union member
- MOTYPE#
Structure/Union member
- NLINES#
Structure/Union member
- NRHOX#
Structure/Union member
- NRHOX_allocated#
Structure/Union member
- NWAVE_C#
Structure/Union member
- N_SPLIST#
Structure/Union member
- NumberSpectralSegments#
Structure/Union member
- PARTITION_FUNCTIONS#
Structure/Union member
- PATH#
Structure/Union member
- PATHLEN#
Structure/Union member
- POTION#
Structure/Union member
- RADIUS#
Structure/Union member
- RAD_ATMO#
Structure/Union member
- RHO#
Structure/Union member
- RHOX#
Structure/Union member
- RHO_eos#
Structure/Union member
- SIGEL#
Structure/Union member
- SIGH#
Structure/Union member
- SIGH2#
Structure/Union member
- SIGHE#
Structure/Union member
- SPINDEX#
Structure/Union member
- SPLIST#
Structure/Union member
- STIM#
Structure/Union member
- T#
Structure/Union member
- TEFF#
Structure/Union member
- TK#
Structure/Union member
- TKEV#
Structure/Union member
- TLOG#
Structure/Union member
- VTURB#
Structure/Union member
- VVOIGT#
Structure/Union member
- VW_SCALE#
Structure/Union member
- WFIRST#
Structure/Union member
- WLAST#
Structure/Union member
- WLCENT#
Structure/Union member
- WLSTD#
Structure/Union member
- Wlim_left#
Structure/Union member
- Wlim_right#
Structure/Union member
- XMASS#
Structure/Union member
- XNA#
Structure/Union member
- XNA_eos#
Structure/Union member
- XNE#
Structure/Union member
- XNE_eos#
Structure/Union member
- YABUND#
Structure/Union member
- allocated_NLTE_lines#
Structure/Union member
- change_byte_order#
Structure/Union member
- debug_print#
Structure/Union member
- flagABUND#
Structure/Union member
- flagCONTIN#
Structure/Union member
- flagH2broad#
Structure/Union member
- flagIONIZ#
Structure/Union member
- flagLINELIST#
Structure/Union member
- flagMODEL#
Structure/Union member
- flagNLTE#
Structure/Union member
- flagWLRANGE#
Structure/Union member
- initNLTE#
Structure/Union member
- lineOPACITIES#
Structure/Union member
- result#
Structure/Union member
- spname#
Structure/Union member
- class pysme.cwrapper.IDL_DLL(*args, **kwargs)[source]#
Bases:
object- call(name, *args, raise_error=True, raise_warning=False, **kwargs)[source]#
run idl_call_external and check for errors in the output
- Parameters:
name (str) – name of the external C function to call
args – parameters for the function
kwargs – keywords for the function
- Raises:
ValueError – If the returned string is not empty, it means an error occured in the C library
- class pysme.cwrapper.IDL_String[source]#
Bases:
StructureIDL strings are actually structures like this one, for correct passing of values we need to define this structure NOTE: the definition might have changed with IDL version, so make sure to use the same one as in the C code
- s#
Structure/Union member
- slen#
Structure/Union member
- stype#
Structure/Union member
- pysme.cwrapper.get_dtype(type)[source]#
Get the ctypes dtype appropiate for the passed type string
- Parameters:
type (str) – One of ‘int’, ‘short’, ‘long’, ‘float’, ‘double’, ‘unicode’ or one of the first letters ‘islfdu’
- Returns:
type – corresponding ctypes type
- Return type:
class
- pysme.cwrapper.get_typenames(arg)[source]#
Return internal typename based on the type of the argument strings -> “unicode” floating points -> “double” integers -> “int”
- pysme.cwrapper.idl_call_external(funcname, *args, restype='str', type=None, lib=None, state=None)[source]#
Call an external C library (here the SME lib) function that uses the IDL type interface i.e. restype func(int n, void *args[]), where n is the number of arguments, and args is a list of pointers to the arguments
Input arrays will be converted to the required datatype for the C function (see type keyword), and any changes to input arrays will be written back if possible. Input arrays that are already in the correct datatype will not be copied (and the values can therefore change in the C call)
Note that all strings are converted into IDL_String objects, even those that are in arrays
- Parameters:
funcname (str) – Name of the function to call in the library
restype (str, optional) – expected type of the return value (default: “str”)
type (str, list(str), optional) – type of the input parameters, will default to int/double for all integer/floating point values. Accepted values are (‘short’, ‘int’, ‘long’, ‘float’, ‘double’, ‘unicode’) or their respective first letters. This means one can use a string as shorthand, e.g. “iidds”
- Returns:
value – return value of the function call
- Return type:
restype
pysme.echelle module#
Contains functions to read and modify echelle structures, just as in reduce
Mostly for compatibility reasons
- pysme.echelle.calc_1dpolynomials(ncol, poly)[source]#
Expand a set of 1d polynomials (one per order) seperately
- Parameters:
ncol (int) – number of columns
poly (array[nord, degree]) – polynomial coefficients
- Returns:
poly – expanded polynomials
- Return type:
array[nord, ncol]
- pysme.echelle.calc_2dpolynomial(solution2d)[source]#
Expand a 2d polynomial, where the data is given in a REDUCE make_wave format Note that the coefficients are for order/100 and column/1000 respectively, where the order is counted from order base up
- Parameters:
solution2d (array) – data in a REDUCE make_wave format: 0: version 1: number of columns 2: number of orders 3: order base, i.e. 0th order number 4-6: empty 7: number of cross coefficients 8: number of column only coefficients 9: number of order only coefficients 10: coefficient - constant 11-x: column coefficients x-y : order coefficients z- : cross coefficients (xy, xy2, x2y, x2y2, xy3, x3y), with x = orders, y = columns
- Returns:
poly – expanded polynomial
- Return type:
array[nord, ncol]
- pysme.echelle.expand_polynomial(ncol, poly)[source]#
Checks if and how to expand data poly, then expands the data if necessary
- Parameters:
ncol (int) – number of columns in the image
poly (array[nord, ...]) – polynomial coefficients to expand, or already expanded data
- Returns:
poly – expanded data
- Return type:
array[nord, ncol]
- pysme.echelle.read(fname, extension=1, raw=False, continuum_normalization=True, barycentric_correction=True, radial_velociy_correction=True)[source]#
Read data from an echelle file Expand wavelength and continuum polynomials Apply barycentric/radial velocity correction Apply continuum normalization
Will load any fields in the binary table, however special attention is given only to specific names: “SPEC” : Spectrum “SIG” : Sigma, i.e. (absolute) uncertainty “CONT” : Continuum “WAVE” : Wavelength solution “COLUMNS” : Column range
- Parameters:
fname (str) – filename to load
extension (int, optional) – fits extension of the data within the file (default: 1)
raw (bool, optional) – if true apply no corrections to the data (default: False)
continuum_normalization (bool, optional) – apply continuum normalization (default: True)
barycentric_correction (bool, optional) – apply barycentric correction (default: True)
radial_velociy_correction (bool, optional) – apply radial velocity correction (default: True)
- Returns:
ech – Echelle structure, with data contained in attributes
- Return type:
obj
- pysme.echelle.save(fname, header, **kwargs)[source]#
Save data in an Echelle fits, i.e. a fits file with a Binary Table in Extension 1
The data is passed in kwargs, with the name of the binary table column as the key Floating point data is saved as float32 (E), Integer data as int16 (I)
- Parameters:
fname (str) – filename
header (fits.header) – FITS header
**kwargs (array[]) – data to be saved in the file
pysme.iliffe_vector module#
- class pysme.iliffe_vector.Iliffe_vector(values, offsets=None, dtype=None)[source]#
Bases:
NDArrayOperatorsMixin,MultipleDataExtensionIlliffe vectors are multidimensional (here 2D) but not necessarily rectangular Instead the index is a pointer to segments of a 1D array with varying sizes
- property dtype#
- property ndim#
- property nseg#
- property segments#
- property shape#
- property size#
- property sizes#
pysme.large_file_storage module#
System to store large data files on a server Load them whem required by the user Update the pointer file on github when new datafiles become available
Pro: Versioning is effectively done by Git Con: Need to run server
- class pysme.large_file_storage.LargeFileStorage(server, pointers, storage)[source]#
Bases:
objectDownload large data files from data server when needed New versions of the datafiles are indicated in a ‘pointer’ file that includes the hash of the newest version of the files
- Raises:
FileNotFoundError – If the datafiles can’t be located anywhere
- get(key)[source]#
Request a datafile from the LargeFileStorage Assures that tracked files are at the specified version And downloads data from the server if necessary
- Parameters:
key (str) – Name of the requested datafile
- Raises:
FileNotFoundError – If the requested datafile can not be found anywhere
- Returns:
fullpath – Absolute path to the datafile
- Return type:
str
- get_urls(key)[source]#
Return ordered candidate URLs/URIs for a tracked key.
For tracked files: - pointer value may be a string or a list of strings - each pointer string may be a full URI (http/https/file) or relative path - relative paths are combined with every configured mirror server in order
- move_to_cache(fname, key=None)[source]#
Move currently used files into cache directory and use symlinks instead, just as if downloaded from a server
- pointers#
points from a filename to the current newest object id, usually a hash
- Type:
dict(fname
- Type:
hash)
- server#
legacy single-server alias (first mirror)
- Type:
str
- servers#
ordered mirrors to try
- Type:
list[str]
pysme.linelist module#
pysme.nlte module#
NLTE module of SME reads and interpolates departure coefficients from library files
- class pysme.nlte.DirectAccessFile(filename)[source]#
Bases:
objectThis function reads a single record from binary file that has the following structure: Version string - 64 byte long # of directory bocks - short int directory block length - short int # of used directory blocks - short int 1st directory block key - string of up to 256 characters padded with ‘ ‘ datatype - 32-bit int 23-element array returned by SIZE pointer - 64-bit int pointer to the beginning of the record
2nd directory block … last directory block 1st data record … last data record
- static get_typecode(dt)[source]#
relevant IDL typecodes and corresponding Numpy Codes Most specify a byte size, but not all
- class pysme.nlte.Grid(sme, elem, lfs_nlte, selection='energy', solar=None, abund_format='Fe=12', min_energy_diff=None)[source]#
Bases:
objectNLTE Grid class that handles all NLTE data reading and interpolation
- interpolate(rabund, teff, logg, monh, atmo)[source]#
interpolate nlte coefficients on the model grid
- Parameters:
rabund (float) – relative (to solar) abundance of the element
teff (float) – temperature in Kelvin
logg (float) – surface gravity in log(cgs)
monh (float) – Metallicity in H=12
- Returns:
subgrid – interpolated grid values
- Return type:
array (ndepth, nlines)
- read_grid(rabund, teff, logg, monh)[source]#
Read the NLTE coefficients from the nlte_grid files for the given element The class will cache subgrid_size points around the target values as well
- Parameters:
rabund (float) – relative (to solar) abundance of the element
teff (float) – temperature in Kelvin
logg (float) – surface gravity in log(cgs)
monh (float) – Metallicity in H=12
- Returns:
nlte_grid (dict) – collection of nlte coefficient data (memmapped)
linerefs (array (nlines,)) – linelevel descriptions (Energy level terms)
lineindices (array (nlines,)) – indices of the used lines in the linelist
- select_levels(conf, term, species, rotnum)[source]#
Match our NLTE terms to transitions in the vald3-format linelist.
Level descriptions in the vald3 long format look like this: ‘LS 2p6.3s 2S’ ‘LS 2p6.3p 2P*’ These are stored in line_term_low and line_term_upp. The array line_extra has dimensions [3 x nlines]. It stores J_low, E_up, J_up The sme.atomic array stores: 0) atomic number, 1) ionization state, 2) wavelength (in A), 3) excitation energy of lower level (in eV), 4) log(gf), 5) radiative, 6) Stark, 7) and van der Waals damping parameters
- Parameters:
conf (array of shape (nl,)) – electronic configuration (for identification), e.g., 2p6.5s
term (array of shape (nl,)) – term designations (for identification), e.g., a5F
species (array of shape (nl,)) – Element and ion for each atomic level (for identification), e.g. Na 1.
rotnum (array of shape (nl,)) – rotational number J of atomic state (for identification).
- Returns:
lineindices (array of shape (nl,)) – Indices of the used lines in the linelist
linerefs (array of shape (2, nlines,)) – Cross references for the lower and upper level in each transition, to their indices in the list of atomic levels. Missing levels use indices of -1.
iused (array of shape (nl,)) – Indices used in the subgrid
- abund_format#
Solar Abundance of the element
- Type:
float
- bgrid#
NLTE data array
- Type:
array
- citation_info#
citations in bibtex format, if known
- Type:
str
- depth#
Depth points of the NLTE data
- Type:
array
- depth_name#
Which parameter is used as the depth axis
- Type:
str
- directory#
The NLTE data file
- Type:
- elem#
Element of the NLTE grid
- Type:
str
- fname#
complete filename of the NLTE grid data file
- Type:
str
- grid_name#
Name of the grid
- Type:
str
- iused#
Indices of the lines in the bgrid
- Type:
array
- limits#
upper and lower parameters covered by the grid
- Type:
dict
- lineindices#
Indices of the lines in the LineList
- Type:
array
- linerefs#
Indices of the lines in the NLTE data
- Type:
array
- min_energy_diff#
Minimum difference between energy levels to match, only relevant for selection==’energy’
- Type:
float
- selection#
Selection algorithm to match lines in grid with linelist
- Type:
{“levels”, “energy”}
- subgrid_size#
number of points in the grid to cache for each parameter, order; abund, teff, logg, monh
- Type:
list(int)
- class pysme.nlte.NLTE(**kwargs)[source]#
Bases:
Collection- get_grid(sme, elem, lfs_nlte)[source]#
Read and interpolate the NLTE grid for the current element and parameters
- remove_nlte(element)[source]#
Remove an element from the NLTE calculations
- Parameters:
element (str) – Abbreviation of the element to remove from NLTE
- set_nlte(element, grid=None)[source]#
Add an element to the NLTE calculations
- Parameters:
element (str) – The abbreviation of the element to add to the NLTE calculations
grid (str, optional) – Filename of the NLTE data grid to use for this element the file must be in nlte_grids directory Defaults to a set of “known” files for some elements
- update_coefficients(sme, dll, lfs_nlte)[source]#
pass departure coefficients to C library; If bmat, linerefs, lineindices are given, use those instead of recalculating them and the code will not check if the line level, energy is matched or not.
- property abund_format#
which abundance format to use for comparison
- Type:
str
- property citation_info#
Bibtex representation of the citation
- Type:
str
- property elements#
elements for which nlte calculations will be performed
- Type:
list
- property flags#
contains a flag for each line, whether it was calculated in NLTE (True) or not (False)
- Type:
array
- property grids#
nlte grid datafiles for each element
- Type:
dict
- property min_energy_diff#
difference between energy levels that are still matched. If None will default to the smallest non zero difference between energy levels in the grid.
- Type:
float
- property selection#
which selection algorithm to use to match linelist and departure coefficients
- Type:
str
- property solar#
defines which default to use as the solar metallicitiies
- Type:
str
- property subgrid_size#
defines size of nlte grid cache.Each entry is for one parameter abund, teff, logg, monh
- Type:
array of shape (4,)
pysme.persistence module#
- pysme.persistence.load(fname, sme)[source]#
Load the SME Structure from disk
- Parameters:
fname (str) – file to load
sme (SME_Structure) – empty sme structure with default values set
- Returns:
sme – loaded sme structure
- Return type:
- pysme.persistence.save(filename, sme, format='flex', _async=False)[source]#
Create a folder structure inside a tarfile See flex-format for details
- Parameters:
filename (str) – Filename of the final file
sme (SME_Structure) – sme structure to save
compressed (bool, optional) – whether to compress the output
- pysme.persistence.save_as_idl(sme, fname)[source]#
Save the SME structure to disk as an idl save file
This writes a IDL script to a temporary file, which is then run with idl as a seperate process. Therefore this reqires a working idl installation.
There are two steps to this. First all the fields from the sme, structure need to be transformed into simple idl readable structures. All large arrays are stored in seperate binary files, for performance. The script then reads those files back into idl.
- pysme.persistence.save_v1(filename, data, folder='', compressed=False)[source]#
Create a folder structure inside a zipfile Add .json and .npy and .npz files with the correct names And subfolders for more complicated objects with the same layout Each class should have a save and a load method which can be used for this purpose
- Parameters:
filename (str) – Filename of the final zipfile
data (SME_struct) – data to save
folder (str, optional) – subfolder to save data to
compressed (bool, optional) – whether to compress the output
pysme.sme module#
- class pysme.sme.CONT_OPTIONS(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
Enum- MASK = 'mask'#
- MATCH = 'match'#
- MATCHLINES = 'matchlines'#
- MATCHLINES_MASK = 'matchlines+mask'#
- MATCH_MASK = 'match+mask'#
- MCMC = 'mcmc'#
- SPLINE = 'spline'#
- SPLINE_MASK = 'spline_mask'#
- class pysme.sme.CONT_SCALE(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
Enum- CUBIC = 'cubic'#
- FIX = 'fix'#
- LINEAR = 'linear'#
- NONE = 'none'#
- QUADRATIC = 'quadratic'#
- class pysme.sme.Fitresults(**kwargs)[source]#
Bases:
Collection- property chisq#
reduced chi-square of the solution
- Type:
float
- property citation_info#
Bibtex representation of the citation
- Type:
str
- property covariance#
covariance matrix
- Type:
array of size (nfree, nfree)
- property derivative#
final Jacobian of each point and each parameter
- Type:
array of size (npoints, nfree)
- property fit_uncertainties#
uncertainties based solely on the least_squares fit
- Type:
array
- property gradient#
final gradients of the free parameters on the cost function
- Type:
array of size (nfree,)
- property iterations#
maximum number of iterations in the solver
- Type:
int
- property parameters#
parameter names
- Type:
list
- property residuals#
final residuals of the fit
- Type:
array of size (npoints,)
- property uncertainties#
uncertainties of the free parameters bases on SME statistics
- Type:
array of size(nfree,)
- property values#
best fit values for the fit parameters
- Type:
array
- class pysme.sme.MASK_VALUES(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
IntFlagMask value specifier used in mob
Values can be combined to mark a point as e.g. line and vrad If cont or vrad are not used it will fallback to the line mask
- BAD = 0#
- CONT = 2#
- LINE = 1#
- VRAD = 4#
- class pysme.sme.Parameters(**kwargs)[source]#
Bases:
Collection- property citation_info#
Bibtex representation of the citation
- Type:
str
- property logg#
surface gravity in log10(cgs)
- Type:
float
- property monh#
metallicity in log scale relative to the base abundances
- Type:
float
- property teff#
effective temperature in Kelvin
- Type:
float
- property vmac#
macro turbulence in km/s
- Type:
float
- property vmic#
micro turbulence in km/s
- Type:
float
- property vsini#
projected rotational velocity in km/s
- Type:
float
- class pysme.sme.ProfileNLTE(**kwargs)[source]#
Bases:
Collection- property citation_info#
Bibtex representation of the citation
- Type:
str
- property element#
Element whose profile-based NLTE provider should be used
- Type:
str or None
- property enabled#
Whether to apply profile-based NLTE corrections during synthesis
- Type:
bool
- property provider#
Explicit profile-NLTE provider name; None uses the default provider for the element
- Type:
str or None
- property summary#
Runtime summary describing which profile-NLTE provider was requested and applied
- Type:
dict
- class pysme.sme.SME_Structure(**kwargs)[source]#
Bases:
Parameters- citation(output='string')[source]#
Create a citation string for use in papers, or other places. The citations are from all components that contribute to the SME structure. SME and PySME, the linelist, the abundance, the atmosphere, and the NLTE grids. The default output is plaintext, but it is also possible to get bibtex format.
- Parameters:
output (str, optional) – the output format, options are: [“string”, “bibtex”, “html”, “markdown”], by default “string”
- Returns:
citation – citation string in the desired output format
- Return type:
str
- import_mask(other, keep_bpm=False)[source]#
Import the mask of another sme structure and apply it to this one Conversion is based on the wavelength
- Parameters:
other (SME_Structure) – the sme structure to import the mask from
- Returns:
self – this sme structure
- Return type:
- static load(filename)[source]#
Load SME data from disk
- Currently supported file formats:
“.npy”: Numpy save file of an SME_Struct
“.sav”, “.inp”, “.out”: IDL save file with an sme structure
“.ech”: Echelle file from (Py)REDUCE
- Parameters:
filename (str, optional) – name of the file to load (default: ‘sme.npy’)
- Returns:
sme – Loaded SME structure
- Return type:
SME_Struct
- Raises:
ValueError – If the file format extension is not recognized
- save(filename, format='flex', _async=False)[source]#
Save the whole SME structure to disk.
The file format is zip file, with one info.json file for simple values, and numpy save files for large arrays. Substructures (linelist, abundance, etc.) have their own folder within the zip file.
- Parameters:
filename (str) – filename to save the structure at
compressed (bool, optional) – whether to compress the output, by default False
- property accft#
- property accgt#
- property accrt#
minimum accuracy for synthethized spectrum at wavelength grid points in sme.wint.
- Type:
float
- property accwi#
minimum accuracy for linear spectrum interpolation vs. wavelength.
- Type:
float
- property accxt#
- property atmo#
model atmosphere data
- Type:
- property atomic#
Atomic linelist data, usually passed to the C library Use sme.linelist instead for other purposes
- Type:
array of size (nlines, 8)
- property cint#
continuum specific intensities from Transf
- Type:
Iliffe_vector of shape (nseg, nmu, …)
- property citation_info#
Bibtex representation of the citation
- Type:
str
- property cont#
continuum intensities
- Type:
Iliffe_vector of shape (nseg, …)
- property cscale#
Continumm polynomial coefficients for each wavelength segment The x coordinates of each polynomial are chosen so that x = 0, at the first wavelength point, i.e. x is shifted by wave[segment][0]
- Type:
array of size (nseg, ndegree)
- property cscale_bounds#
bounds for the continuum parameters
- Type:
array(2, cscale_degree)
- property cscale_degree#
Polynomial degree of the continuum as determined by cscale_flag
- Type:
int
- property cscale_flag#
Flag that describes how to correct for the continuum
- allowed values are:
“none”: No continuum correction
“fix”: Use whatever continuum scale has been set, but don’t change it
“constant”: Zeroth order polynomial, i.e. scale everything by a factor
“linear”: First order polynomial, i.e. approximate continuum by a straight line
“quadratic”: Second order polynomial, i.e. approximate continuum by a quadratic polynomial
- Type:
str
- property cscale_ftol#
tolerance for the continuum least squares fit
- Type:
float
- property cscale_gtol#
tolerance for the continuum least squares fit
- Type:
float
- property cscale_jac#
jacobian approximation used in the continuum fit
- Type:
str
- property cscale_loss#
loss function for the continuum fit
- Type:
str
- property cscale_method#
least squares method used in the continuum fit
- Type:
str
- property cscale_type#
Flag that determines the algorithm to determine the continuum
This is used in combination with cscale_flag, which determines the degree of the fit, if any.
- allowed values are:
“mask”: Fit a polynomial to the pixels marked as continuum in the mask
“match”: Fit a multiplicative correction so the synthetic spectrum matches the observation
“match+mask”: Same as “match”, but only using continuum-mask pixels
“matchlines”: Match mostly on line pixels rather than continuum pixels
“matchlines+mask”: Same as “matchlines”, with continuum-mask restrictions
“spline”: Match using a spline instead of a low-order polynomial
“spline+mask”: Same as “spline”, but only using continuum-mask pixels
“mcmc”: Joint MCMC continuum/radial-velocity fit
- Type:
str
- property cscale_xscale#
array of ‘jac’, Scale of each continuum parameter
- property cscale_xtol#
tolerance for the continuum least squares fit
- Type:
float
- property fitparameters#
Names of the free parameters
- Type:
array of size (nfree)
- property fitresults#
fit results data
- Type:
- property gam6#
van der Waals scaling factor
- Type:
float
- property h2broad#
Whether to use H2 broadening or not
- Type:
bool
- property id#
DateTime when this structure was created
- Type:
str
- property ip_x#
Instrumental broadening table in x direction
- Type:
array
- property ip_y#
Instrumental broadening table in y direction
- Type:
array
- property ipres#
Instrumental resolution for instrumental broadening
- Type:
float, array
- property iptype#
instrumental broadening type
- Type:
str
- property leastsquares_ftol#
minimum accuracy of the best fit cost
- Type:
float
- property leastsquares_gtol#
minimum accuracy of the gradient of the least squares fit
- Type:
float
- property leastsquares_jac#
‘2-point’
- Type:
str
- Type:
leastsquares jacobian calculation, see scipy least_squares for details, default
- property leastsquares_loss#
‘linear’
- Type:
str
- Type:
leastsquares loss to use, see scipy least_squares for details, default
- property leastsquares_method#
‘dogbox’.
- Type:
str
- Type:
leastsquares method to use, see scipy least_squares for details, default
- property leastsquares_xscale#
1
- Type:
str, arraylike
- Type:
leastsquare x-scale to use, see scipy least_squares for details, default
- property leastsquares_xtol#
minimum accuracy of the parameters in the fitting procedure
- Type:
float
- property logg#
surface gravity in log10(cgs)
- Type:
float
- property mask#
mask defining good and bad points for the fit
- Type:
Iliffe_vector of shape (nseg, …)
- property mask_bad#
- property mask_cont#
- property mask_good#
- property mask_line#
- property mask_vrad#
- property meta#
Arbitrary extra information
- Type:
dict
- property mu#
Mu values to calculate radiative transfer at mu values describe the distance from the center of the stellar disk to the edge with mu = cos(theta), where theta is the angle of the observation, i.e. mu = 1 at the center of the disk and 0 at the edge
- Type:
array of size (nmu,)
- property nmu#
- property normalize_by_continuum#
Whether to normalize the synthetic spectrum by the synthetic continuum spectrum or not
- Type:
bool
- property nseg#
Number of wavelength segments
- Type:
int
- property profile_nlte#
profile-based NLTE correction configuration and runtime summary
- Type:
- property sint#
specific intensities from Transf
- Type:
Iliffe_vector of shape (nseg, nmu, …)
- property spec#
observed spectrum
- Type:
Iliffe_vector of shape (nseg, …)
- property species#
Names of the species of each spectral line
- Type:
array of size (nlines,)
- property specific_intensities_only#
Whether to keep the specific intensities or integrate them together
- Type:
bool
- property synth#
synthetic spectrum
- Type:
Iliffe_vector of shape (nseg, …)
- property system_info#
information about the host system running the calculation for debugging
- Type:
- property teff#
effective temperature in Kelvin
- Type:
float
- property telluric#
telluric spectrum that is multiplied with synth during the fit
- Type:
Illife_vector of shape (nseg, …)
- property uncs#
uncertainties of the observed spectrum
- Type:
Iliffe_vector of shape (nseg, …)
- property version#
PySME version used to create this structure
- Type:
str
- property vmac#
macro turbulence in km/s
- Type:
float
- property vmic#
micro turbulence in km/s
- Type:
float
- property vrad#
radial velocity of each segment in km/s
- Type:
array of size (nseg,)
- property vrad_bounds#
radial velocity limits in km/s
- Type:
float
- property vrad_flag#
flag that determines how the radial velocity is determined
- allowed values are:
“none”: No radial velocity correction
“each”: Determine radial velocity for each segment individually
“whole”: Determine one radial velocity for the whole spectrum
- Type:
str
- property vrad_ftol#
tolerance for the radial velocity least squares fit
- Type:
float
- property vrad_gtol#
tolerance for the radial velocity least squares fit
- Type:
float
- property vrad_jac#
jacobian approximation used in the radial velocity fit
- Type:
str
- property vrad_limit#
- property vrad_loss#
loss function for the radial velocity fit
- Type:
str
- property vrad_method#
least squares method used in the radial velocity fit
- Type:
str
- property vrad_xscale#
scale of the vrad parameter
- Type:
array or ‘jac’
- property vrad_xtol#
tolerance for the radial velocity least squares fit
- Type:
float
- property vsini#
projected rotational velocity in km/s
- Type:
float
- property wave#
wavelength
- Type:
Iliffe_vector of shape (nseg, …)
- property wint#
optional wavelength grid passed to SMElib Transf
- Type:
Iliffe_vector of shape (nseg, …)
- property wran#
beginning and end wavelength points of each segment
- Type:
array of size (nseg, 2)
- class pysme.sme.VRAD_OPTIONS(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#
Bases:
Enum- EACH = 'each'#
- FIX = 'fix'#
- NONE = 'none'#
- WHOLE = 'whole'#
- class pysme.sme.Version(**kwargs)[source]#
Bases:
Collection- property arch#
system architecture
- Type:
str
- property build_date#
build date of the Python version used
- Type:
str
- property citation_info#
Bibtex representation of the citation
- Type:
str
- property host#
name of the machine that created the SME Structure
- Type:
str
- property memory_bits#
Platform architecture bit size (usually 32 or 64)
- Type:
int
- property os#
operating system
- Type:
str
- property os_family#
operating system family
- Type:
str
- property os_name#
os name
- Type:
str
- property release#
python version
- Type:
str
pysme.sme_synth module#
Wrapper for SME C library
- class pysme.sme_synth.SME_DLL(libfile=None, datadir=None)[source]#
Bases:
objectObject Oriented interface for the SME C library
- ALMAXRange(accrt=0.0001)[source]#
Compute first-stage ALMAX and line ranges from SMElib preselection logic.
- Parameters:
accrt (float, optional) – Opacity-ratio threshold (same role as accrt in Transf preselection).
- Returns:
almax (array of size (nlines,)) – Line-center opacity-ratio proxy from the first-stage screening.
linerange (array of size (nlines, 2)) – Preselection range for each line.
- CentralDepth(mu, accrt)[source]#
This subroutine explicitly solves the transfer equation for a set of nodes on the star disk in the centers of spectral lines. The results are specific intensities.
- Parameters:
mu (array of size (nmu,)) – mu values along the stellar disk to calculate
accrt (float) – precision of the radiative transfer calculation
- Returns:
table – Centeral depth (i.e. specific intensity) of each line
- Return type:
array of size (nlines,)
- GetContributionfunction(mu, wave, nwmax=400000, long_continuum=True)[source]#
Get the contribution function for a wavelength grid.
- GetDensity()[source]#
Retrieve density in each layer
- Returns:
density – Density of the atmosphere in each layer
- Return type:
array of size (ndepth,)
- GetDepartureCoefficients(line)[source]#
Get the NLTE departure coefficients as stored in the C library
- Parameters:
line (int) – requested line index, i.e. between 0 and number of lines
- Returns:
bmat – departure coefficients for the given line index
- Return type:
array of size (2, nrhox)
- GetFraction(species, mode=0)[source]#
Get species fraction/partition function/number density.
- Parameters:
species (str) – Species name in SPLIST (e.g., ‘Fe’, ‘Fe+’, ‘CO’)
mode (int, optional) – 0: number density (FRACT * PF) 1: partition function other: FRACT
- GetLineOpacity(wave)[source]#
Retrieve line opacity data from the C library
- Parameters:
wave (float) – Wavelength of the line opacity to retrieve
- Returns:
lop (array) – line opacity
cop (array) – continuum opacity including scatter
scr (array) – Scatter
tsf (array) – Total source function
csf (array) – Continuum source function
- GetLineRange()[source]#
Get the effective wavelength range for each line i.e. the wavelengths for which the line has significant impact
- Returns:
linerange – lower and upper wavelength for each spectral line
- Return type:
array of size (nlines, 2)
- GetNLTEflags()[source]#
Get an array that tells us which lines have been used with NLTE correction
- Returns:
nlte_flags – True if line was used with NLTE, False if line is only LTE
- Return type:
array(bool) of size (nlines,)
- GetNelec()[source]#
Get XNE (Electron number density) for each layer in the atmosphere
- Returns:
XNE – XNE in each layer
- Return type:
array of size (ndepth,)
- GetOpacity(switch, species=None, key=None)[source]#
Returns specific cont. opacity, different output depending on the input
- Parameters:
switch (str) – one of [COPSTD, COPRED, COPBLU, AHYD, AH2P, AHMIN, SIGH, AHE1, AHE2, AHEMIN, SIGHE, ACOOL, ALUKE, AHOT, SIGEL, SIGH2]
key (str, optional) – for ACOOL, one of [new, old, fraction]
species (str, optional) – for ACOOL and ALUKE it specifies the element ACOOL: C1, Mg1, Al1, Si1, Fe1, CH, NH, OH ALUKE: N1, O1, Mg2, Si2, Ca2
- InputAbund(abund)[source]#
Pass abundances to radiative transfer code.
Calculate elemental abundances from abundance pattern and metallicity. Metallicity adjustment is not applied to H or He. Renormalize abundances after applying metallicity. Introduced limiter in case the proposed step in abundance is too large.
- Parameters:
abund (Abund) – abundance structure to be passed (see Abund for more details)
- InputDepartureCoefficients(bmat, lineindex)[source]#
Input NLTE departure coefficients
- Parameters:
bmat (array of size (2, ndepth)) – departure coefficient matrix
lineindex (float) – index of the line in the linelist
- InputLineList(linelist)[source]#
Read in line list
- Parameters:
atomic (array of size (nlines, 8)) – atomic linelist data for each line fields are: atom_number, ionization, wlcent, excit, gflog, gamrad, gamqst, gamvw
species (array(string) of size (nlines,)) – names of the elements (with Ionization level)
- InputLinePrecomputedInfo(line_range_s, line_range_e, strong_mask, central_depth=None)[source]#
Input precomputed line ranges and strong mask to SMElib.
- InputModel(teff, grav, vturb, atmo)[source]#
Read in model atmosphere
- Parameters:
teff (float) – effective Temperature in Kelvin
grav (float) – surface gravity in log10(cgs)
vturb (float) – turbulence velocity in km/s
atmo (Atmo) – atmosphere structure (see Atmo for details)
- InputWaveRange(wfirst, wlast)[source]#
Read in Wavelength range
Will raise an exception if wfirst is larger than wlast
- Parameters:
wfirst (float) – first wavelength of the segment
wlast (float) – last wavelength of the segment
- Ionization(ion=0)[source]#
Calculate ionization balance for current atmosphere and abundances. Ionization state is stored in the external library. Ion is a bit flag with values (add them together to use multiple):
- 1:
adopt particle number densities from EOS
- 2:
adopt electron number densities from EOS
- 4:
adopt gas densities (g/cm^3) from EOS
instead of using values from model atmosphere. Different abundance patterns in the model atmosphere (usually scaled solar) and SME (may be non-solar) can affect line shape, e.g. shape of hydrogen lines.
- Parameters:
ion (int) – flag that determines the behaviour of the C function
- OutputLineList()[source]#
Return line list
- Returns:
atomic – relevant data of the linelist wlcent, excit, gflog, gamrad, gamqst, gamvw
- Return type:
array of size (nlines, 6)
- ResetDepartureCoefficients()[source]#
Reset departure coefficients from any previous call, to ensure LTE as default
- SetHlinopWarningMode(mode)[source]#
Set HLINPROF->HLINOP warning mode (0=stderr, 1=record-only, 2=off).
- SetLineInfoMode(mode)[source]#
Set handling mode for precomputed line info (0=internal, 1=use_if_valid, 2=trust).
- SetVWscale(gamma6)[source]#
Set van der Waals scaling factor
- Parameters:
gamma6 (float) – van der Waals scaling factor
- Transf(mu, wave=None, nwmax=400000, accrt=0.001, accwi=0.003, keep_lineop=False, long_continuum=True)[source]#
Radiative Transfer Calculation
Perform the radiative transfer calculation thorugh the atmosphere Requires that all parameters have been set beforehand
- Parameters:
mu (array of shape (nmu,)) – mu angles (1 - cos(phi)) of different limb points along the stellar surface
accrt (float) – accuracy of the radiative transfer integration
accwi (float) – accuracy of the interpolation on the wavelength grid
keep_lineop (bool, optional) – if True do not recompute the line opacities (default: False)
long_continuum (bool, optional) – if True the continuum is calculated at every wavelength (default: True)
nwmax (int, optional) – maximum number of wavelength points if wavelength grid is not set with wave (default: 400000)
wave (array, optional) – wavelength grid to use for the calculation, if not set will use an adaptive wavelength grid with no constant step size (default: None)
- Returns:
nw (int) – number of actual wavelength points, i.e. size of wint_seg
wint_seg (array of shape (nwave,)) – wavelength grid, the number of wavelengthpoints is equal to the number of lines * 2 - 1 One point in the center of each line + plus one between the next line
sint_seg (array of shape (nmu, nwave)) – spectrum for each mu point
cint_seg (array of shape (nmu, nwave)) – continuum for each mu point
- UpdateLineList(atomic, species, index)[source]#
Change line list parameters
- Parameters:
atomic (array of size (nlines, 8)) – atomic linelist data for each line fields are: atom_number, ionization, wlcent, excit, gflog, gamrad, gamqst, gamvw
species (array(string) of size (nlines,)) – names of the elements (with Ionization level)
index (array(int) of size (nlines,)) – indices of the lines to update relative to the overall linelist
- check_data_files_exist()[source]#
Checks if required data files for the SME library exist. If they dont exist, SME will just segfault, without any hint.
- Raises:
FileNotFoundError – If any of the files don’t exist
- property datadir#
Expected directory of the data files
- Type:
str
- property file#
(Expected) Location of the library file
- Type:
str
pysme.solve module#
pysme.uncertainties module#
- pysme.uncertainties.gaussfit(x, y, nterms='none')[source]#
Fit a simple gaussian to data
gauss(x, a, mu, sigma) = a * exp(-z**2/2) with z = (x - mu) / sigma
- Parameters:
x (array(float)) – x values
y (array(float)) – y values
- Returns:
fitted values for x, fit paramters (a, mu, sigma)
- Return type:
gauss(x), parameters
pysme.util module#
Utility functions for SME
safe interpolation
- class pysme.util.Scalar[source]#
Bases:
objectScalar class used to scale data. Can create a scalar, scale input data, save and load previous scalars.
- fit(data)[source]#
Create scalar.
- Parameters:
data (2darray) – Needs to be in the form [num of objects x num of parameters].
- pysme.util.air2vac(wl_air, copy=True)[source]#
Convert wavelengths in air to vacuum wavelength in Angstrom Author: Nikolai Piskunov
- pysme.util.compress_one_grid(line_info, strong_idx, n_lines_total=None, verbose: bool = False)[source]#
对一个格点: - 使用 strong_idx 裁剪 line_info(只保留强线) - 计算 line_width = e - s,并做字典编码: unique_widths + codes - 从 strong_idx 构造完整 bool mask, 再 bit-pack 成 uint8 串
自动根据数据推断 n_lines_total,避免 off-by-one。
- pysme.util.interpolate_3DNLTEH_intensity_continuum_RBF(teff, logg, monh, mu, boundary_vertices)[source]#
Interpolate the 3D NLTE H line intensity and continuum profiles at the given parameters. :param Teff: Effective temperature. :type Teff: float :param logg: Surface gravity. :type logg: float :param FeH: Metallicity. :type FeH: float :param mu: Cosine of the viewing angle. :type mu: float :param Returns:
- pysme.util.interpolate_3DNLTEH_spectrum_RBF(teff, logg, monh, mu, boundary_vertices)[source]#
Interpolate the normalized 3D NLTE H line profile at the given parameters.
- pysme.util.load_bool_sparse(path)[source]#
Load a boolean array previously saved with save_bool_sparse.
This reconstructs the full boolean mask by allocating a flat array of length ‘size’, marking positions in ‘idx’ as True, and reshaping to ‘shape’.
- Parameters:
path (str) – Path to the .npz file produced by save_bool_sparse.
- Returns:
The reconstructed boolean array with the original shape.
- Return type:
numpy.ndarray
- Raises:
KeyError – If the file does not contain the expected keys: ‘idx’, ‘shape’, ‘size’.
Notes
The reconstruction uses C-order (row-major) flattening/reshaping, matching the behavior of np.flatnonzero used during saving.
This function assumes the file structure created by save_bool_sparse (i.e., it is not a general-purpose sparse loader).
Examples
>>> mask_restored = load_bool_sparse('mask_sparse.npz') >>> mask_restored.dtype dtype('bool')
- pysme.util.load_cdr_to_linelist(sme, filepath)[source]#
Load a compressed .npz CDR file and assign its content to sme.linelist._lines.
Parameters: - sme: SME object with .linelist._lines dictionary - filepath: full path to the .npz file with ‘line_info’ inside
- pysme.util.parse_args()[source]#
Parse command line arguments
- Returns:
sme (str) – filename to input sme structure
vald (str) – filename of input linelist or None
fitparameters (list(str)) – names of the parameters to fit, empty list if none are specified
- pysme.util.redirect_output_to_file(output_file)[source]#
Redirect ALL output that would go to the commandline, to a file instead
- Parameters:
output_file (str) – output filename
- pysme.util.safe_interpolation(x_old, y_old, x_new=None, fill_value=0)[source]#
‘Safe’ interpolation method that should avoid the common pitfalls of spline interpolation
masked arrays are compressed, i.e. only non masked entries are used remove NaN input in x_old and y_old only unique x values are used, corresponding y values are ‘random’ if all else fails, revert to linear interpolation
- Parameters:
x_old (array of size (n,)) – x values of the data
y_old (array of size (n,)) – y values of the data
x_new (array of size (m, ) or None, optional) – x values of the interpolated values if None will return the interpolator object (default: None)
- Returns:
y_new – if x_new was given, return the interpolated values otherwise return the interpolator object
- Return type:
array of size (m, ) or interpolator
- pysme.util.save_bool_sparse(path, arr)[source]#
Save a boolean NumPy array in a space-efficient sparse format.
This function stores only the flat indices of True values together with the original array shape and size, then writes them into a compressed .npz file. It is typically more space-efficient than bit-packing when the number of True entries k is much smaller than N/8, where N is the total number of elements in the array.
- Parameters:
path (str) – Output file path (e.g., ‘mask_sparse.npz’).
arr (numpy.ndarray) – Boolean array to save. It will be flattened in C-order to obtain the index list (via np.flatnonzero(arr)).
Notes
The file contains three arrays: ‘idx’ (1D int indices of True entries), ‘shape’ (the original array shape), and ‘size’ (the total number of elements).
The array is reconstructed by creating a flat boolean array of length ‘size’, setting True at positions ‘idx’, and reshaping to ‘shape’.
For dense masks, consider bit-packing or direct compression instead.
Examples
>>> mask = np.array([[True, False], [False, True]], dtype=bool) >>> save_bool_sparse('mask_sparse.npz', mask)
- pysme.util.save_compressed_grid(mask_bits, unique_widths, codes, n_lines_total, out_path)[source]#
把一个格点压缩后的数据保存为 npz: - mask_bits: uint8 bit-packed bool mask - unique_widths: float32 - codes: uint8/uint16/uint32