Skip to content

Commit

Permalink
more cleanups and linting
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Jan 4, 2025
1 parent dff32b8 commit 30386ec
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 32 deletions.
34 changes: 17 additions & 17 deletions python/xraydb/xray.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import sys
"""
calculations using XrayDB
"""
from collections import namedtuple
import numpy as np

from .utils import (R_ELECTRON_CM, AVOGADRO, PLANCK_HC, E_MASS,
from .utils import (R_ELECTRON_CM, AVOGADRO, PLANCK_HC,
QCHARGE, SI_PREFIXES, index_nearest)

R0 = 1.e8 * R_ELECTRON_CM

from .xraydb import XrayDB, XrayLine
from .chemparser import chemparse

R0 = 1.e8 * R_ELECTRON_CM

fluxes = namedtuple('IonChamberFluxes', ('incident', 'transmitted',
'photo', 'incoherent', 'coherent'))

Expand Down Expand Up @@ -532,8 +534,8 @@ def xray_line(element, line):
if lfinal is None:
lfinal = val[3][0]
return XrayLine(value/scale, scale, linit, lfinal)
else:
return lines.get(line.title(), None)

return lines.get(line.title(), None)


def fluor_yield(element, edge, line, energy):
Expand Down Expand Up @@ -564,7 +566,7 @@ def fluor_yield(element, edge, line, energy):
etc) and probabilities for each of these.
"""
e0, fyield, jump = xray_edge(element, edge)
e0, fyield, _ = xray_edge(element, edge)
trans = xray_lines(element, initial_level=edge)

lines = []
Expand Down Expand Up @@ -665,7 +667,7 @@ def ionization_potential(gas):
return 32.0


def guess_edge(energy, edges=['K', 'L3', 'L2', 'L1', 'M5']):
def guess_edge(energy, edges=('K', 'L3', 'L2', 'L1', 'M5')):
"""guess an element and edge based on energy (in eV)
Args:
Expand All @@ -676,7 +678,7 @@ def guess_edge(energy, edges=['K', 'L3', 'L2', 'L1', 'M5']):
a tuple of (atomic symbol, edge) for best guess
Notes:
by default, the list of edges is ['K', 'L3', 'L2', 'L1', 'M5']
by default, the list of edges is ('K', 'L3', 'L2', 'L1', 'M5')
"""
xdb = get_xraydb()
Expand All @@ -692,7 +694,7 @@ def guess_edge(energy, edges=['K', 'L3', 'L2', 'L1', 'M5']):
maxz = 0
xquery = xdb.tables['xray_levels'].select()
for row in xdb.session.execute(xquery).fetchall():
ir, elem, edgename, en, eyield, xjump = row
ir, elem, edgename, en, eyield, _ = row
iz = xdb.atomic_number(elem)
maxz = max(iz, maxz)
if ename == edgename.lower():
Expand All @@ -710,8 +712,7 @@ def guess_edge(energy, edges=['K', 'L3', 'L2', 'L1', 'M5']):
diff = 0.25*diff
elif edge in ('L1', 'M5'): # penalize L1 and M5 edges
diff = 2.0*diff
if diff < min_diff:
min_diff = diff
min_diff = min(diff, min_diff)
ret.append((edge, iz, diff))

for edge, iz, diff in ret:
Expand Down Expand Up @@ -917,7 +918,6 @@ def ionchamber_fluxes(gas='nitrogen', volts=1.0, length=100.0, energy=10000.0,
from .materials import material_mu

xdb = get_xraydb()
fin = fout = fphoto = 0.0

units = sensitivity_units.replace('Volts', 'V').replace('Volt', 'V')
units = units.replace('Amperes', 'A').replace('Ampere', 'A')
Expand Down Expand Up @@ -1009,11 +1009,11 @@ def dynamical_theta_offset(energy, crystal='Si', hkl=(1, 1, 1), a=None,
"""
lattice_constants = {'Si': 5.4309, 'Ge': 5.6578, 'C': 3.567}
h_, k_, l_ = hkl
hklsum = (h_ + k_ + l_)
hklsum = h_ + k_ + l_
if hklsum % 4 == 0 and (h_ % 2 == 0 and k_ % 2 == 0 and l_ % 2 == 0):
eqr = 8
pass
elif (h_ % 2 == 1 and k_ % 2 == 1 and l_ % 2 == 1): # all odd
eqr =4*np.sqrt(2)
pass
else:
raise ValueError("hkl must sum to 4 or be all odd")

Expand Down Expand Up @@ -1117,7 +1117,7 @@ def darwin_width(energy, crystal='Si', hkl=(1, 1, 1), a=None,

lattice_constants = {'Si': 5.4309, 'Ge': 5.6578, 'C': 3.567}
h_, k_, l_ = hkl
hklsum = (h_ + k_ + l_)
hklsum = h_ + k_ + l_
if hklsum % 4 == 0 and (h_ % 2 == 0 and k_ % 2 == 0 and l_ % 2 == 0):
eqr = 8
elif (h_ % 2 == 1 and k_ % 2 == 1 and l_ % 2 == 1): # all odd
Expand Down
29 changes: 14 additions & 15 deletions python/xraydb/xraydb.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
XrayEdge = namedtuple('XrayEdge', ('energy', 'fyield', 'jump_ratio'))
XrayLine = namedtuple('XrayLine', ('energy', 'intensity', 'initial_level',
'final_level'))
ElementData = namedtuple('ElementData', ('Z', 'symbol', 'name', 'mass', 'density'))
ComptonEnergies = namedtuple('ComptonEnergies', ('incident', 'xray_90deg', 'xray_mean', 'electron_mean'))

ElementData = namedtuple('ElementData',
('Z', 'symbol', 'name', 'mass', 'density'))

ComptonEnergies = namedtuple('ComptonEnergies',
('incident', 'xray_90deg', 'xray_mean', 'electron_mean'))

def make_engine(dbname):
"create engine for sqlite connection, perhaps trying a few sqlachemy variants"
Expand Down Expand Up @@ -78,10 +79,10 @@ def __init__(self, dbname='xraydb.sqlite', read_only=True):
parent, _ = os.path.split(__file__)
dbname = os.path.join(parent, dbname)
if not os.path.exists(dbname):
raise IOError("Database '%s' not found!" % dbname)
raise IOError(f"Database '{dbname}' not found!")

if not isxrayDB(dbname):
raise ValueError("'%s' is not a valid X-ray Database file!" % dbname)
raise ValueError(f"'{dbname}' is not a valid X-ray Database file!")
self._cache = {}
self.dbname = os.path.abspath(dbname)
self.engine = make_engine(dbname)
Expand Down Expand Up @@ -161,14 +162,12 @@ def get_version(self, long=False, with_history=False):
rows = rows[-1:]
if long or with_history:
for row in rows:
out.append("XrayDB Version: %s [%s] '%s'" % (row.tag,
row.date,
row.notes))
out.append("Python Version: %s" % __version__)
out.append(f"XrayDB Version: {row.tag} [row.date] '{row.notes}'")
out.append(f"Python Version: {__version__}")
out = "\n".join(out)
else:
out = "XrayDB Version: %s, Python Version: %s" % (rows[0].tag,
__version__)
out = f"XrayDB Version: {rows[0].tag}, Python Version: {__version__}"

return out

def f0_ions(self, element=None):
Expand Down Expand Up @@ -409,7 +408,7 @@ def _elem_data(self, element):
elif element.lower() in self.__atomic_names:
row = [r for r in rows if r.name == element.lower()][0]
else:
raise ValueError("unknown element '%s'" % repr(element))
raise ValueError(f"unknown element '{repr(element)}'")
return ElementData(int(row.atomic_number),
row.element.title(), row.name,
row.molar_mass, row.density)
Expand Down Expand Up @@ -699,7 +698,7 @@ def cross_section_elam(self, element, energies, kind='photo'):
elem = self.symbol(element)
kind = kind.lower()
if kind not in ('coh', 'incoh', 'photo'):
raise ValueError('unknown cross section kind=%s' % kind)
raise ValueError(f'unknown cross section kind={kind}')

tablename = 'photoabsorption' if kind == 'photo' else 'scattering'

Expand Down Expand Up @@ -757,7 +756,7 @@ def mu_elam(self, element, energies, kind='total'):
elif kind.lower().startswith('incoh'):
xsec = calc(element, energies, kind='incoh')
else:
raise ValueError('unknown cross section kind=%s' % kind)
raise ValueError(f'unknown cross section kind={kind}')
return xsec

def coherent_cross_section_elam(self, element, energies):
Expand Down Expand Up @@ -808,5 +807,5 @@ def ionization_potential(self, gas):
itab = self.tables['ionization_potentials']
out = self.query(itab).filter(itab.c.gas == gas).all()
if len(out) != 1:
raise ValueError('unknown gas for ionization potential: %s' % gas)
raise ValueError(f'unknown gas for ionization potential: {gas}')
return float(out[0].potential)

0 comments on commit 30386ec

Please sign in to comment.