4. formel

Physical equations and useful formulas as quadrature of vector functions, viscosity, compressibility of water, scatteringLengthDensityCalc or sedimentationProfile. Use scipy.constants for physical constants.

Mass and scattering length of all elements in Elements are taken from :

Units converted to amu for mass and nm for scattering length.

4.1. Functions

loglist([mini, maxi, number]) Log like distribution between mini and maxi with number points.
gauss(x[, mean, sigma]) Normalized Gaussian function.
lorentz(x[, mean, gamma]) Normalized Lorentz function
voigt(x[, center, fwhm, lg, asym, amplitude]) Voigt function for peak analysis (normalized).
lognorm(x[, mean, sigma]) Lognormal distribution function.
box(x[, edges, edgevalue, rtol, atol]) Box function
Ea(z, a[, b]) Mittag-Leffler function for real z and real a,b with 0<a, b<0.
boseDistribution(w, temp) Bose distribution for integer spin particles in non-condensed state (hw>0).

4.2. Quadrature

parQuadratureSimpson(funktion, lowlimit, …) Integrate a function over one of its parameters with weights using the adaptive Simpson rule.
parQuadratureFixedGauss(func, lowlimit, …) Compute a definite integral using fixed-order Gaussian quadrature .
parQuadratureAdaptiveGauss(func, lowlimit, …) Compute a definite integral using fixed-tolerance Gaussian quadrature for vector output.
parDistributedAverage(funktion, sig, parname) Average a function assuming a parameter is distributed with width sig.
sphereAverage(function[, relError]) Spherical average - non-parallel
psphereAverage(funktion[, relError]) Parallel evaluation of spherical average of function.
convolve(A, B[, mode, normA, normB]) Convolve A and B with proper tracking of the output X axis.
smooth(data[, windowlen, window]) Smooth data using a window with requested size and type.

4.3. Centrifugation

sedimentationProfile([t, rm, rb, number, …]) Approximate solution to the Lamm equation of sedimenting particles in centrifuge including bottom equilibrium distribution.
sedimentationProfileFaxen([t, rm, rb, …]) Faxen solution to the Lamm equation of sedimenting particles in centrifuge; no bottom part.

4.4. NMR

DrotfromT12([t12, Drot, F0, Tm, Ts, T1, T2]) Rotational correlation time from T1/T2 or T1 and T2 from NMR proton relaxation measurement.
T1overT2([tr, Drot, F0, T1, T2]) Calculates the T1/T2 from a given rotational correlation time tr or Drot for proton relaxation measurement.

4.5. Material Data

scatteringLengthDensityCalc(composition[, …]) Scattering length density of composites and water with inorganic components for xrays and neutrons.
waterdensity(composition[, T, units, …]) Density of water with inorganic substances (salts).
bufferviscosity(composition[, T, show]) Viscosity of water with inorganic substances as used in biological buffers.
dielectricConstant([material, T, conc, delta]) Dielectric constant of H2O and D2O buffer solutions.
watercompressibility([d2ofract, T, units]) Isothermal compressibility of H2O and D2O mixtures.
cstar(Rg, Mw) Overlap concentration c^* for a polymer.
molarity(objekt, c[, total]) Calculates the molarity.
viscosity([mat, T]) Viscosity of pure solvents.
Dtrans(Rh[, Temp, solvent, visc]) Translational diffusion of a sphere.
Drot(Rh[, Temp, solvent, visc]) Rotational diffusion of a sphere.

4.6. other Stuff

memoize(**memkwargs) A least-recently-used cache decorator to cache expensive function evaluations.
xyz2rphitheta(XYZ[, transpose]) Transformation cartesian coordinates [X,Y,Z] to spherical coordinates [r,phi,theta].
rphitheta2xyz(RPT[, transpose]) Transformation spherical coordinates [r,phi,theta] to cartesian coordinates [x,y,z].
rotationMatrix(vector, angle) Create a rotation matrix corresponding to rotation around vector v by a specified angle.
fibonacciLatticePointsOnSphere(NN[, r]) Fibonacci lattice points on a sphere with radius r (default r=1)
randomPointsOnSphere(NN[, r, skip]) N quasi random points on sphere of radius r based on low-discrepancy sequence.
randomPointsInCube(NN[, skip, dim]) N quasi random points in cube of edge 1 based on low-discrepancy sequence.

4.7. Constants and Tables

felectron Cross section of electron in nm
kB Boltzmann constant in kJ/(mol⋅K)
Elements Elements Dictionary with: { symbol : (electron number; mass; neutron coherent scattering length, neutron incoherent scattering length, name) }; units amu for mass and nm for scattering length

Physical equations and useful formulas as quadrature of vector functions, viscosity, compressibility of water, scatteringLengthDensityCalc or sedimentationProfile. Use scipy.constants for physical constants.

Mass and scattering length of all elements in Elements are taken from :

Units converted to amu for mass and nm for scattering length.

exception jscatter.formel.AccuracyWarning[source]

Bases: exceptions.Warning

jscatter.formel.D0(Rh, Temp=273.15, solvent='h2o', visc=None)

Translational diffusion of a sphere.

Parameters:
Rh : float

Hydrodynamic radius in nm.

Temp : float

Temperature in K.

solvent : float

Solvent type as in viscosity; used if visc==None.

visc : float

Viscosity in Pas => H2O ~ 0.001 Pas =1 cPoise. If visc=None the solvent viscosity is calculated from function viscosity(solvent ,temp) with solvent eg ‘h2o’ (see viscosity).

Returns:
Translational diffusion coefficient : float in nm^2/ns.
jscatter.formel.Drot(Rh, Temp=273.15, solvent='h2o', visc=None)[source]

Rotational diffusion of a sphere.

Parameters:
Rh : float

Hydrodynamic radius in nm.

Temp : float

Temperature in K.

solvent : float

Solvent type as in viscosity; used if visc==None.

visc : float

Viscosity in Pas => H2O ~ 0.001 Pa*s =1 cPoise. If visc=None the solvent viscosity is calculated from function viscosity(solvent ,temp) with solvent eg ‘h2o’.

Returns:
Rotational diffusion coefficient in 1/ns.
jscatter.formel.DrotfromT12(t12=None, Drot=None, F0=20000000.0, Tm=None, Ts=None, T1=None, T2=None)[source]

Rotational correlation time from T1/T2 or T1 and T2 from NMR proton relaxation measurement.

Allows to rescale by temperature and viscosity.

Parameters:
t12 : float

T1/T2 from NMR with unit seconds

Drot : float

!=None means output Drot instead of rotational correlation time.

F0 : float

Resonance frequency of NMR instrument. For Hydrogen F0=20 MHz => w0=F0*2*np.pi

Tm: float

Temperature of measurement in K.

Ts : float

Temperature needed for Drot -> rescaled by visc(T)/T.

T1 : float

NMR T1 result in s

T2 : float

NMR T2 result in s to calc t12 directly remeber if the sequence has a factor of 2

Returns:
Correlation time or Drot : float

Notes

See T1overT2

jscatter.formel.Dtrans(Rh, Temp=273.15, solvent='h2o', visc=None)[source]

Translational diffusion of a sphere.

Parameters:
Rh : float

Hydrodynamic radius in nm.

Temp : float

Temperature in K.

solvent : float

Solvent type as in viscosity; used if visc==None.

visc : float

Viscosity in Pas => H2O ~ 0.001 Pas =1 cPoise. If visc=None the solvent viscosity is calculated from function viscosity(solvent ,temp) with solvent eg ‘h2o’ (see viscosity).

Returns:
Translational diffusion coefficient : float in nm^2/ns.
jscatter.formel.Ea(z, a, b=1)[source]

Mittag-Leffler function for real z and real a,b with 0<a, b<0.

Evaluation of the Mittag-Leffler (ML) function with 1 or 2 parameters by means of the OPC algorithm [1]. The routine evaluates an approximation Et of the ML function E such that |E-Et|/(1+|E|) \approx 10^{-15}

Parameters:
z : real array

Values

a : float, real positive

Parameter alpha

b : float, real positive, default=1

Parameter beta

Returns:
array

Notes

References

[1](1, 2) R. Garrappa, Numerical evaluation of two and three parameter Mittag-Leffler functions, SIAM Journal of Numerical Analysis, 2015, 53(3), 1350-1369

Examples

import numpy as np
import jscatter as js
from scipy import special
x=np.r_[-10:10:0.1]
# tests
np.all(js.formel.Ea(x,1,1)-np.exp(x)<1e-10)
z = np.linspace(0., 2., 50)
np.allclose(js.formel.Ea(np.sqrt(z), 0.5), np.exp(z)*special.erfc(-np.sqrt(z)))
z = np.linspace(-2., 2., 50)
np.allclose(js.formel.Ea(z**2, 2.), np.cosh(z))
jscatter.formel.Elements = {u'ac': (89, 227.0, 0, 0, u'Actinium'), u'ag': (47, 107.8682, 5.921999999999999e-06, 2.1483699284957805e-06, u'Silver'), u'al': (13, 26.9815386, 3.4489999999999995e-06, 2.5544769849751453e-07, u'Aluminium'), u'am': (95, 243.0, 8.3e-06, 1.5450968080927583e-06, u'Americium'), u'ar': (18, 39.948, 1.909e-06, 1.3380930871145783e-06, u'Argon'), u'as': (33, 74.9216, 6.58e-06, 6.9098829894267095e-07, u'Arsenic'), u'at': (85, 210.0, 0, 0, u'Astatine'), u'au': (79, 196.966569, 7.63e-06, 1.8498192550829797e-06, u'Gold'), u'b': (5, 10.81, (5.299999999999999e-06-2.13e-07j), 3.6780660900548136e-06, u'Boron'), u'ba': (56, 137.327, 5.07e-06, 1.092548430592079e-06, u'Barium'), u'be': (4, 9.012182, 7.79e-06, 1.1968268412042979e-07, u'Beryllium'), u'bi': (83, 208.9804, 8.531999999999999e-06, 2.5854414729132051e-07, u'Bismuth'), u'br': (35, 79.904, 6.794999999999999e-06, 8.9206205807638555e-07, u'Bromine'), u'c': (6, 12.011, 6.6459999999999996e-06, 8.9206205807638557e-08, u'Carbon'), u'ca': (20, 40.078, 4.7e-06, 6.3078313050503997e-07, u'Calcium'), u'cd': (48, 112.411, (4.87e-06-7e-07j), 5.2472664459600194e-06, u'Cadmium'), u'ce': (58, 140.116, 4.839999999999999e-06, 8.9206205807638557e-08, u'Cerium'), u'cl': (17, 35.45, 9.577e-06, 6.4943098108538266e-06, u'Chlorine'), u'cm': (96, 247.0, 0, 0, u'Curium'), u'co': (27, 58.933195, 2.4900000000000003e-06, 6.180387232371033e-06, u'Cobalt'), u'cr': (24, 51.9961, 3.6349999999999995e-06, 3.8161076102369575e-06, u'Chromium'), u'cs': (55, 132.9054519, 5.42e-06, 1.2927207364566026e-06, u'Caesium'), u'cu': (29, 63.546, 7.718e-06, 2.0920709679710014e-06, u'Copper'), u'd': (1, 2.01410178, 6.671e-06, 4.0389827515005893e-06, u'Deuterium'), u'dy': (66, 162.5, (1.6899999999999997e-05-2.7600000000000004e-07j), 2.0806283791440397e-05, u'Dysprosium'), u'er': (68, 167.259, 7.79e-06, 2.9586351363515986e-06, u'Erbium'), u'eu': (63, 151.964, (7.2199999999999995e-06-1.26e-06j), 4.4603102903819282e-06, u'Europium'), u'f': (9, 18.9984032, 5.6539999999999996e-06, 7.9788456080286533e-08, u'Fluorine'), u'fe': (26, 55.845, 9.45e-06, 1.7841241161527711e-06, u'Iron'), u'fr': (87, 223.0, 0, 0, u'Francium'), u'ga': (31, 69.723, 7.2879999999999995e-06, 1.1283791670955127e-06, u'Gallium'), u'gd': (64, 157.25, (6.5e-06-1.382e-05j), 3.4664388359580353e-05, u'Gadolinium'), u'ge': (32, 72.63, 8.185e-06, 1.196826841204298e-06, u'Germanium'), u'h': (1, 1.008, -3.7406e-06, 2.5273867216936192e-05, u'Hydrogen'), u'he': (2, 4.002602, 3.2599999999999997e-06, 0.0, u'Helium'), u'hf': (72, 178.49, 7.699999999999999e-06, 4.5486418414672306e-06, u'Hafnium'), u'hg': (80, 200.592, 1.2692e-05, 7.2471464191311507e-06, u'Mercury'), u'ho': (67, 164.93032, 8.01e-06, 1.6925687506432688e-06, u'Holmium'), u'i': (53, 126.90447, 5.28e-06, 1.5706373285785543e-06, u'Iodine'), u'in': (49, 114.818, (4.065e-06-5.39e-08j), 2.0729648968280128e-06, u'Indium'), u'ir': (77, 192.217, 1.0599999999999998e-05, 0.0, u'Iridium'), u'k': (19, 39.0983, 3.6699999999999996e-06, 1.4658075357087598e-06, u'Potassium'), u'kr': (36, 83.798, 7.81e-06, 2.8209479177387817e-07, u'Krypton'), u'la': (57, 138.90547, 8.239999999999999e-06, 2.9987087695693435e-06, u'Lanthanum'), u'li': (3, 6.94, -1.8999999999999998e-06, 2.7057581899030051e-06, u'Lithium'), u'lu': (71, 174.9668, 7.21e-06, 2.3601743597065738e-06, u'Lutetium'), u'mg': (12, 24.305, 5.374999999999999e-06, 7.9788456080286539e-07, u'Magnesium'), u'mn': (25, 54.938045, -3.73e-06, 1.7841241161527711e-06, u'Manganese'), u'mo': (42, 95.96, 6.714999999999999e-06, 5.6418958354775635e-07, u'Molybdenum'), u'n': (7, 14.007, 9.359999999999998e-06, 1.9947114020071636e-06, u'Nitrogen'), u'na': (11, 22.98976928, 3.6299999999999995e-06, 3.5904805236128943e-06, u'Sodium'), u'nb': (41, 92.90638, 7.054e-06, 1.3819765978853419e-07, u'Niobium'), u'nd': (60, 144.242, 7.69e-06, 8.5563586777479037e-06, u'Neodymium'), u'ne': (10, 20.1797, 4.566e-06, 2.5231325220201604e-07, u'Neon'), u'ni': (28, 58.6934, 1.03e-05, 6.4327509825806867e-06, u'Nickel'), u'np': (93, 237.0, 1.055e-05, 1.9947114020071636e-06, u'Neptunium'), u'o': (8, 15.999, 5.802999999999999e-06, 7.9788456080286533e-08, u'Oxygen'), u'os': (76, 190.23, 1.07e-05, 1.5450968080927583e-06, u'Osmium'), u'p': (15, 30.973762, 5.13e-06, 1.9947114020071635e-07, u'Phosphorus'), u'pa': (91, 231.03588, 0, 0, u'Protactinium'), u'pb': (82, 207.2, 9.404999999999999e-06, 1.5450968080927585e-07, u'Lead'), u'pd': (46, 106.42, 5.91e-06, 8.6027349452212777e-07, u'Palladium'), u'pm': (61, 145.0, 1.26e-05, 3.2163754912903434e-06, u'Promethium'), u'po': (84, 209.0, 0, 0, u'Polonium'), u'pr': (59, 140.90765, 4.58e-06, 3.4549414947133547e-07, u'Praseodymium'), u'pt': (78, 195.084, 9.6e-06, 1.0171072362820549e-06, u'Platinum'), u'pu': (94, 244.0, 0, 0, u'Plutonium'), u'ra': (88, 226.0, 0, 0, u'Radium'), u'rb': (37, 85.4678, 7.09e-06, 1.9947114020071636e-06, u'Rubidium'), u're': (75, 186.207, 9.199999999999998e-06, 2.6761861742291566e-06, u'Rhenium'), u'rh': (45, 102.9055, 5.88e-06, 1.5450968080927583e-06, u'Rhodium'), u'rn': (86, 222.0, 0, 0, u'Radon'), u'ru': (44, 101.07, 7.03e-06, 1.7841241161527711e-06, u'Ruthenium'), u's': (16, 32.06, 2.847e-06, 2.3601743597065741e-07, u'Sulfur'), u'sb': (51, 121.76, 5.57e-06, 2.3601743597065741e-07, u'Antimony'), u'sc': (21, 44.955912, 1.229e-05, 5.9841342060214899e-06, u'Scandium'), u'se': (34, 78.96, 7.97e-06, 1.5957691216057308e-06, u'Selenium'), u'si': (14, 28.085, 4.1491e-06, 1.7841241161527711e-07, u'Silicon'), u'sm': (62, 150.36, (8e-07-1.6499999999999999e-06j), 1.7616814099864821e-05, u'Samarium'), u'sn': (50, 118.71, 6.225e-06, 4.1841419359420025e-07, u'Tin'), u'sr': (38, 87.62, 7.019999999999999e-06, 6.9098829894267095e-07, u'Strontium'), u'ta': (73, 180.94788, 6.91e-06, 2.8209479177387817e-07, u'Tantalum'), u'tb': (65, 158.92535, 7.38e-06, 1.7841241161527711e-07, u'Terbium'), u'tc': (43, 97.0, 6.799999999999999e-06, 1.9947114020071636e-06, u'Technetium'), u'te': (52, 127.6, 5.7999999999999995e-06, 8.4628437532163442e-07, u'Tellurium'), u'th': (90, 232.03806, 1.031e-05, 0.0, u'Thorium'), u'ti': (22, 47.867, -3.438e-06, 4.7789888400881402e-06, u'Titanium'), u'tl': (81, 204.38, 8.775999999999999e-06, 1.2927207364566026e-06, u'Thallium'), u'tm': (69, 168.93421, 7.07e-06, 8.9206205807638555e-07, u'Thulium'), u'u': (92, 238.02891, 8.417e-06, 1.9947114020071635e-07, u'Uranium'), u'v': (23, 50.9415, -3.824e-07, 6.3580937037245231e-06, u'Vanadium'), u'w': (74, 183.84, 4.86e-06, 3.6015452047682909e-06, u'Tungsten'), u'xe': (54, 131.293, 4.9199999999999995e-06, 0.0, u'Xenon'), u'y': (39, 88.90585, 7.75e-06, 1.092548430592079e-06, u'Yttrium'), u'yb': (70, 173.054, 1.243e-05, 5.6418958354775635e-06, u'Ytterbium'), u'zn': (30, 65.38, 5.68e-06, 7.8278127909640072e-07, u'Zinc'), u'zr': (40, 91.224, 7.16e-06, 3.9894228040143269e-07, u'Zirconium')}

Elements Dictionary with: { symbol : (electron number; mass; neutron coherent scattering length, neutron incoherent scattering length, name) }; units amu for mass and nm for scattering length

jscatter.formel.Nscatlength = {u'ac': [0, 0], u'ag': [5.921999999999999e-06, 2.1483699284957805e-06], u'al': [3.4489999999999995e-06, 2.5544769849751453e-07], u'am': [8.3e-06, 1.5450968080927583e-06], u'ar': [1.909e-06, 1.3380930871145783e-06], u'as': [6.58e-06, 6.9098829894267095e-07], u'at': [0, 0], u'au': [7.63e-06, 1.8498192550829797e-06], u'b': [(5.299999999999999e-06-2.13e-07j), 3.6780660900548136e-06], u'ba': [5.07e-06, 1.092548430592079e-06], u'be': [7.79e-06, 1.1968268412042979e-07], u'bi': [8.531999999999999e-06, 2.5854414729132051e-07], u'br': [6.794999999999999e-06, 8.9206205807638555e-07], u'c': [6.6459999999999996e-06, 8.9206205807638557e-08], u'ca': [4.7e-06, 6.3078313050503997e-07], u'cd': [(4.87e-06-7e-07j), 5.2472664459600194e-06], u'ce': [4.839999999999999e-06, 8.9206205807638557e-08], u'cl': [9.577e-06, 6.4943098108538266e-06], u'cm': [0, 0], u'co': [2.4900000000000003e-06, 6.180387232371033e-06], u'cr': [3.6349999999999995e-06, 3.8161076102369575e-06], u'cs': [5.42e-06, 1.2927207364566026e-06], u'cu': [7.718e-06, 2.0920709679710014e-06], 'd': [6.671e-06, 4.0389827515005893e-06], u'dy': [(1.6899999999999997e-05-2.7600000000000004e-07j), 2.0806283791440397e-05], u'er': [7.79e-06, 2.9586351363515986e-06], u'eu': [(7.2199999999999995e-06-1.26e-06j), 4.4603102903819282e-06], u'f': [5.6539999999999996e-06, 7.9788456080286533e-08], u'fe': [9.45e-06, 1.7841241161527711e-06], u'fr': [0, 0], u'ga': [7.2879999999999995e-06, 1.1283791670955127e-06], u'gd': [(6.5e-06-1.382e-05j), 3.4664388359580353e-05], u'ge': [8.185e-06, 1.196826841204298e-06], u'h': [-3.7406e-06, 2.5273867216936192e-05], u'he': [3.2599999999999997e-06, 0.0], u'hf': [7.699999999999999e-06, 4.5486418414672306e-06], u'hg': [1.2692e-05, 7.2471464191311507e-06], u'ho': [8.01e-06, 1.6925687506432688e-06], u'i': [5.28e-06, 1.5706373285785543e-06], u'in': [(4.065e-06-5.39e-08j), 2.0729648968280128e-06], u'ir': [1.0599999999999998e-05, 0.0], u'k': [3.6699999999999996e-06, 1.4658075357087598e-06], u'kr': [7.81e-06, 2.8209479177387817e-07], u'la': [8.239999999999999e-06, 2.9987087695693435e-06], u'li': [-1.8999999999999998e-06, 2.7057581899030051e-06], u'lu': [7.21e-06, 2.3601743597065738e-06], u'mg': [5.374999999999999e-06, 7.9788456080286539e-07], u'mn': [-3.73e-06, 1.7841241161527711e-06], u'mo': [6.714999999999999e-06, 5.6418958354775635e-07], u'n': [9.359999999999998e-06, 1.9947114020071636e-06], u'na': [3.6299999999999995e-06, 3.5904805236128943e-06], u'nb': [7.054e-06, 1.3819765978853419e-07], u'nd': [7.69e-06, 8.5563586777479037e-06], u'ne': [4.566e-06, 2.5231325220201604e-07], u'ni': [1.03e-05, 6.4327509825806867e-06], u'np': [1.055e-05, 1.9947114020071636e-06], u'o': [5.802999999999999e-06, 7.9788456080286533e-08], u'os': [1.07e-05, 1.5450968080927583e-06], u'p': [5.13e-06, 1.9947114020071635e-07], u'pa': [0, 0], u'pb': [9.404999999999999e-06, 1.5450968080927585e-07], u'pd': [5.91e-06, 8.6027349452212777e-07], u'pm': [1.26e-05, 3.2163754912903434e-06], u'po': [0, 0], u'pr': [4.58e-06, 3.4549414947133547e-07], u'pt': [9.6e-06, 1.0171072362820549e-06], u'pu': [0, 0], u'ra': [0, 0], u'rb': [7.09e-06, 1.9947114020071636e-06], u're': [9.199999999999998e-06, 2.6761861742291566e-06], u'rh': [5.88e-06, 1.5450968080927583e-06], u'rn': [0, 0], u'ru': [7.03e-06, 1.7841241161527711e-06], u's': [2.847e-06, 2.3601743597065741e-07], u'sb': [5.57e-06, 2.3601743597065741e-07], u'sc': [1.229e-05, 5.9841342060214899e-06], u'se': [7.97e-06, 1.5957691216057308e-06], u'si': [4.1491e-06, 1.7841241161527711e-07], u'sm': [(8e-07-1.6499999999999999e-06j), 1.7616814099864821e-05], u'sn': [6.225e-06, 4.1841419359420025e-07], u'sr': [7.019999999999999e-06, 6.9098829894267095e-07], 't': [4.791999999999999e-06, 1.0555020614111882e-06], u'ta': [6.91e-06, 2.8209479177387817e-07], u'tb': [7.38e-06, 1.7841241161527711e-07], u'tc': [6.799999999999999e-06, 1.9947114020071636e-06], u'te': [5.7999999999999995e-06, 8.4628437532163442e-07], u'th': [1.031e-05, 0.0], u'ti': [-3.438e-06, 4.7789888400881402e-06], u'tl': [8.775999999999999e-06, 1.2927207364566026e-06], u'tm': [7.07e-06, 8.9206205807638555e-07], u'u': [8.417e-06, 1.9947114020071635e-07], u'v': [-3.824e-07, 6.3580937037245231e-06], u'w': [4.86e-06, 3.6015452047682909e-06], u'xe': [4.9199999999999995e-06, 0.0], u'y': [7.75e-06, 1.092548430592079e-06], u'yb': [1.243e-05, 5.6418958354775635e-06], u'zn': [5.68e-06, 7.8278127909640072e-07], u'zr': [7.16e-06, 3.9894228040143269e-07]}

Dictionary with coherent and incoherent neutron scattering length. units nm

jscatter.formel.T1overT2(tr=None, Drot=None, F0=20000000.0, T1=None, T2=None)[source]

Calculates the T1/T2 from a given rotational correlation time tr or Drot for proton relaxation measurement.

tr=1/(6*D_rot) with rotational diffusion D_rot and correlation time tr.

Parameters:
tr : float

Rotational correlation time.

Drot : float

If given tr is calculated from Drot.

F0 : float

NMR frequency e.g. F0=20e6 Hz=> w0=F0*2*np.pi is for Bruker Minispec with B0=0.47 Tesla

T1 : float

NMR T1 result in s

T2 : float

NMR T2 resilt in s to calc t12 directly

Returns:
T1/T2 : float

Notes

J(\omega)=\tau/(1+\omega^2\tau^2)

T1^{-1}=\frac{\sigma}{3} (2J(\omega_0)+8J(2\omega_0))

T2^{-1}=\frac{\sigma}{3} (3J(0)+ 5J(\omega_0)+2J(2\omega_0))

tr=T1/T2

References

[1]Intermolecular electrostatic interactions and Brownian tumbling in protein solutions. Krushelnitsky A Physical chemistry chemical physics 8, 2117-28 (2006)
[2]The principle of nuclear magnetism A. Abragam Claredon Press, Oxford,1961
jscatter.formel.boseDistribution(w, temp)[source]

Bose distribution for integer spin particles in non-condensed state (hw>0).

n(w) &= \frac{1}{e^{hw/kT}-1} &\ hw>0 &= 0 &\: hw=0 \: This is not real just for convenience!

Parameters:
w : array

Frequencies in units 1/ns

temp : float

Temperature in K

Returns:
dataArray
jscatter.formel.box(x, edges=None, edgevalue=0, rtol=1e-05, atol=1e-08)[source]

Box function

For equal edges and edge value> 0 the delta function is given.

Parameters:
x : array
edges : list of float, float, default=[0]

Edges of the box. If only one number is given the box goes from [-edge:edge]

edgevalue : float, default=0

Value to use if x==edge for both edges.

rtol,atol : float

The relative/absolute tolerance parameter for the edge detection. See numpy.isclose.

Returns:
dataArray

Notes

Edges may be smoothed by convolution with a Gaussian.:

edge=2
x=np.r_[-4*edge:4*edge:200j]
f=js.formel.box(x,edges=edge)
res=js.formel.convolve(f,js.formel.gauss(x,0,0.2))
jscatter.formel.bufferviscosity(composition, T=293.15, show=False)[source]

Viscosity of water with inorganic substances as used in biological buffers.

Solvent with composition of H2O and D2O and additional components at temperature T. Ternary solutions allowed. Units are mol; 1l h2o = 55.50843 mol Based on data from ULTRASCAN3 [1] supplemented by the viscosity of H2O/D2O mixturees for conc=0.

Parameters:
composition : list of compositional strings

Compositional strings of chemical name as ‘float’+’name’ First float is content in Mol followed by component name as ‘h2o’ or ‘d2o’ light and heavy water were mixed with prepended fractions.

[‘1.5urea’,‘0.1sodiumchloride’,‘2h2o’,‘1d2o’] for 1.5 M urea + 100 mM NaCl in a 2:1 mixture of h2o/d2o. By default ‘1h2o’ is assumed.

T : float, default 293.15

Temperature in K

show : bool, default False

Show composition and validity range of components and result in mPas.

Returns:
float viscosity in Pa*s

Notes

  • Viscosities of H2O/D2O mixtures mix by linear interpolation between concentrations (accuracy 0.2%) [2].
  • The change in viscosity due to components is added based on data from Ultrascan3 [1].
  • Multicomponent mixtures are composed of binary mixtures.
  • Glycerol%” is in unit “%weight/weight” for range=”0-32%, here the unit is changed to weight% insthead of M.
  • Propanol1, Propanol2 are 1-Propanol, 2-Propanol

References

[1](1, 2, 3) http://www.ultrascan3.uthscsa.edu/
[2](1, 2) Viscosity of light and heavy water and their mixtures Kestin Imaishi Nott Nieuwoudt Sengers, Physica A: Statistical Mechanics and its Applications 134(1):38-58
[3]Thermal Offset Viscosities of Liquid H2O, D2O, and T2O C. H. Cho, J. Urquidi, S. Singh, and G. Wilse Robinson J. Phys. Chem. B 1999, 103, 1991-1994

availible components:

h2o1 d2o1
     aceticacid                acetone                   ammoniumacetate          
 ammoniumchloride          ammoniumhydroxide         ammoniumsulfate          
 bariumchloride            cadmiumchloride           cadmiumsulfate           
 calciumchloride           cesiumchloride            citricacid               
 cobaltouschloride         creatinine                cupricsulfate            
 edtadisodium              ethanol                   ethyleneglycol           
 ferricchloride            formicacid                fructose                 
 glucose                   glycerol                  glycerol%                
 guanidinehydrochloride    hydrochloricacid          inulin                   
 lacticacid                lactose                   lanthanumnitrate         
 leadnitrate               lithiumchloride           magnesiumchloride        
 magnesiumsulfate          maltose                   manganoussulfate         
 mannitol                  methanol                  nickelsulfate            
 nitricacid                oxalicacid                phosphoricacid           
 potassiumbicarbonate      potassiumbiphthalate      potassiumbromide         
 potassiumcarbonate        potassiumchloride         potassiumchromate        
 potassiumdichromate       potassiumferricyanide     potassiumferrocyanide    
 potassiumhydroxide        potassiumiodide           potassiumnitrate         
 potassiumoxalate          potassiumpermanganate     potassiumphosphate,dibasic
 potassiumphosphate,monobasic potassiumsulfate          potassiumthiocyanate     
 procainehydrochloride     propanol1                 propanol2                
 propyleneglycol           silvernitrate             sodiumacetate            
 sodiumbicarbonate         sodiumbromide             sodiumcarbonate          
 sodiumchloride            sodiumcitrate             sodiumdiatrizoate        
 sodiumdichromate          sodiumferrocyanide        sodiumhydroxide          
 sodiummolybdate           sodiumphosphate,dibasic   sodiumphosphate,monobasic
 sodiumphosphate,tribasic  sodiumsulfate             sodiumtartrate           
 sodiumthiocyanate         sodiumthiosulfate         sodiumtungstate          
 strontiumchloride         sucrose                   sulfuricacid             
 tartaricacid              tetracainehydrochloride   trichloroaceticacid      
 trifluoroethanol          tris(hydroxymethyl)aminomethane urea                     
 zincsulfate              
jscatter.formel.convolve(A, B, mode='same', normA=False, normB=False)[source]

Convolve A and B with proper tracking of the output X axis.

Approximate the convolution integral as the discrete, linear convolution of two one-dimensional sequences. Missing values are linear interpolated to have matching steps. Values outside of X ranges are set to zero.

Parameters:
A,B : dataArray, ndarray
To be convolved arrays (length N and M).
  • dataArray convolves Y with Y values
  • ndarray A[0,:] is X and A[1,:] is Y
normA,normB : bool, default False

Determines if A or B should be normalised that \int_{x_{min}}^{x_{max}} A(x) dx = 1.

mode : ‘full’,’same’,’valid’, default ‘same’
See example for the difference in range.
  • ‘full’ Returns the convolution at each point of overlap,
    with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.
  • ‘same’ Returns output of length max(M, N).
    Boundary effects are still visible.
  • ‘valid’ Returns output of length M-N+1.
Returns:
dataArray (with attributes from A)

Notes

  • A\circledast B (t)= \int_{-\infty}^{\infty} A(x) B(t-x) dx = \int_{x_{min}}^{x_{max}} A(x) B(t-x) dx
  • If A,B are only 1d array use np.convolve.
  • If attributes of B are needed later use .setattr(B,’B-‘) to prepend ‘B-‘ for B attributes.

References

[1]Wikipedia, “Convolution”, http://en.wikipedia.org/wiki/Convolution.

Examples

Demonstrate the difference between modes

import jscatter as js;import numpy as np
s1=3;s2=4;m1=50;m2=10
G1=js.formel.gauss(np.r_[0:100.1:0.1],mean=m1,sigma=s1)
G2=js.formel.gauss(np.r_[-30:30.1:0.2],mean=m2,sigma=s2)
p=js.grace()
p.title('Convolution of Gaussians (width s mean m)')
p.subtitle(r's1\S2\N+s2\S2\N=s_conv\S2\N ;  m1+m2=mean_conv')
p.plot(G1,le='mean 50 sigma 3')
p.plot(G2,le='mean 10 sigma 4')
ggf=js.formel.convolve(G1,G2,'full')
p.plot(ggf,le='full')
gg=js.formel.convolve(G1,G2,'same')
p.plot(gg,le='same')
gg=js.formel.convolve(G1,G2,'valid')
p.plot(gg,le='valid')
gg.fit(js.formel.gauss,{'mean':40,'sigma':1},{},{'x':'X'})
p.plot(gg.modelValues(),li=1,sy=0,le='fit m=$mean s=$sigma')
p.legend(x=100,y=0.1)
p.xaxis(max=150,label='x axis')
p.yaxis(min=0,max=0.15,label='y axis')
jscatter.formel.cstar(Rg, Mw)[source]

Overlap concentration c^* for a polymer.

c^* = \frac{ 3M_w }{ 4N_A \pi R_g^3 }

Parameters:
Rg : float in nm

radius of gyration

Mw : float

molecular weight

Returns:
Concentration % w/vol

References

[1]Overlap concentration of macromolecules in solution Ying, Q. & Chu, B. Macromolecules 20, 362–366 (1987)
jscatter.formel.debug = False

Variable to allow printout for debugging as if debug:print(‘message’)

jscatter.formel.dielectricConstant(material='d2o', T=293.15, conc=0, delta=5.5)[source]

Dielectric constant of H2O and D2O buffer solutions.

Dielectric constant \epsilon of H2O and D2O (error +- 0.02) with added buffer salts.

\epsilon (c)=\epsilon (c=0)+2c\: delta\; for\; c<2M

Parameters:
material : string ‘d2o’ (default) or ‘h2o’

Material ‘d2o’ (default) or ‘h2o’

T : float

Temperature in °C

conc : float

Salt concentration in mol/l.

delta : float

Total excess polarisation dependent on the salt and presumably on the temperature!

Returns:
dielectric constant : float

Notes

Salt delta(+-1) deltalambda (not used here)
HCl -10 0
LiCI 7 -3.5
NaCI 5.5
-4 default
KCl 5 -4
RbCl 5 -4.5
NaF 6 -4
KF 6.5 -3.5
NaI -7.5 -9.5
KI -8 -9.5
MgCI, -15 -6
BaCl2 -14 -8.5
LaCI. -22 -13.5
NaOH -10.5 -3
Na2SO. -11 -9.5

References

[1]The dielectric constant of water and heavy water between 0 and 40.degree. J. Phys. Chem., 1967, 71 (3), pp 656–662 http://dx.doi.org/10.1021/j100862a028
[2]Dielectric Constant of Deuterium Oxide C.G Malmberg, Journal of Research of National Bureau of Standards, Vol 60 No 6, (1958) 2874 http://nvlpubs.nist.gov/nistpubs/jres/60/jresv60n6p609_A1b.pdf
[3]Dielectric Properties of Aqueous Ionic Solutions. Parts I and II Hasted et al. J Chem Phys 16 (1948) 1 http://link.aip.org/link/doi/10.1063/1.1746645
jscatter.formel.felectron = 2.8179403267e-06

Cross section of electron in nm

jscatter.formel.fibonacciLatticePointsOnSphere(NN, r=1)[source]

FibonacciLatticePointsOnSphere; see fibonacciLatticePointsOnSphere()

jscatter.formel.gauss(x, mean=1, sigma=1)[source]

Normalized Gaussian function.

g(x)= \frac{1}{sigma\sqrt{2\pi}} e^{-0.5(\frac{x-mean}{sigma})^2}

Parameters:
x : float

Values

mean : float

Mean value

sigma : float

1/e width

Returns:
Gaussian : dataArray
jscatter.formel.kB = 0.00831447086363271

Boltzmann constant in kJ/(mol⋅K)

jscatter.formel.loglist(mini=0.1, maxi=5, number=100)[source]

Log like distribution between mini and maxi with number points.

Parameters:
mini,maxi : float, default 0.1, 5

Start and endpoint.

number : int, default 100

Number of points

Returns:
ndarray
jscatter.formel.lognorm(x, mean=1, sigma=1)[source]

Lognormal distribution function.

f(x>0)= \frac{1}{\sqrt{2\pi}\sigma x }\,e^{ -\frac{(\ln(x)-\mu)^2}{2\sigma^2}}

Parameters:
x : array

x values

mean : float

mean

sigma : float

sigma

Returns:
lognorm distribution : dataArray
jscatter.formel.lorentz(x, mean=1, gamma=1)[source]

Normalized Lorentz function

f(x) = \frac{gamma}{\pi((x-mean)^2+gamma^2)}

Parameters:
x : array

X values

gamma : float

Half width half maximum

mean : float

Mean value

Returns:
Lorentz function : dataArray
jscatter.formel.memoize(**memkwargs)[source]

A least-recently-used cache decorator to cache expensive function evaluations.

Memoize caches results and retrieves from cache if same parameters are used again. This can speedup computation in a model if a part is computed with same parameters several times. During fits it may be faster to calc result for a list of and take from cache.

Parameters:
function : function

Function to evaluate as e.g. f(Q,a,b,c,d)

memkwargs : dict

Keyword args with substitute values to cache for later interpolation. Empty for normal caching of a function. E.g. memkwargs={‘Q’:np.r_[0:10:0.1],’t’:np.r_[0:100:5]} caches with these values. The needed values can be interpolated from the returned result. See example below.

maxsize : int, default 128

maximum size of the cache. Last is dropped.

Returns:
cached function with new methods
  • last(i) to retrieve the ith evaluation result in cache (last is i=-1).
  • clear() to clear the cached results.
  • hitsmisses counts hits and misses.

Notes

Only keyword arguments for the memoized function are supported!!!! Only one attribute and X are supported for fitting as .interpolate works only for two cached attributes.

Examples

The example uses a model that computes like I(q,n,..)=F(q)*B(t,n,..). F(q) is cheap to calculate B(t,n,..) not. In the following its better to calc the function for a list of q , put it to cache and take in the fit from there. B is only calculated once.

Use it like this:

import jscatter as js
import numpy as np

# define some data
TT=js.loglist(0.01,80,30)
QQ=np.r_[0.1:1.5:0.15]
# in the data we have 'q' and 'X'
data=js.dynamic.finiteZimm(t=TT,q=QQ,NN=124,pmax=100,tintern=10,ll=0.38,Dcm=0.01,mu=0.5,viscosity=1.001,Temp=300)

# a short definition for the same as below
# makes a unique list of all X values    -> interpolation is exact for X
tt=list(set(data.X.flatten));tt.sort()
# use correct values from data for q     -> interpolation is exact for q
fZ=js.formel.memoize(q=data.q,t=tt)(js.dynamic.finiteZimm)
def fitfunc(Q,Ti,NN,tint,ll,D,mu,viscosity,Temp):
   res= fZ(t=Ti,q=Q,NN=NN,tintern=tint,ll=ll,Dcm=D,pmax=40,mu=mu,viscosity=viscosity,Temp=Temp)
   return res.interpolate(q=Q,X=Ti,deg=2)[0]

# do the fit
data.setlimit(tint=[0.5,40],D=[0,1])
data.makeErrPlot(yscale='l')
NN=20
data.fit(model=fitfunc,
         freepar={'tint':10,'D':0.1,},
         fixpar={'NN':20,'ll':0.38/(NN/124.)**0.5,'mu':0.5,'viscosity':0.001,'Temp':300},
         mapNames={'Ti':'X','Q':'q'},)

# define the function to memoize, first the long usual way as decorator
@js.formel.memoize(Q=np.r_[0:3:0.2],Time=np.r_[0:50:0.5,50:100:5])
def fZ(Q,Time,NN,tintern,ll,Dcm,mu,viscosity,Temp):
    # finiteZimm accepts t and q as array and returns a dataList with different Q and same X=t
    res=js.dynamic.finiteZimm(t=Time,q=Q,NN=NN,pmax=20,tintern=tintern,
                          ll=ll,Dcm=Dcm,mu=mu,viscosity=viscosity,Temp=Temp)
    return res
# define the fitfunc
def fitfunc(Q,Ti,NN,tint,ll,D,mu,viscosity,Temp):
   #this is the cached result for the list of Q
   res= fZ(Time=Ti,Q=Q,NN=NN,tintern=tint,ll=ll,Dcm=D,mu=mu,viscosity=viscosity,Temp=Temp)
   # interpolate for the single Q value the cached result has again 'q'
   return res.interpolate(q=Q,X=Ti,deg=2)[0]
# do the fit
data.setlimit(tint=[0.5,40],D=[0,1])
data.makeErrPlot(yscale='l')
data.fit(model=fitfunc,
         freepar={'tint':6,'D':0.1,},
         fixpar={'NN':20,'ll':0.38/(20/124.)**0.5,'mu':0.5,'viscosity':0.001,'Temp':300},
         mapNames={'Ti':'X','Q':'q'})
# the result depends on the interpolation;
jscatter.formel.molarity(objekt, c, total=None)[source]

Calculates the molarity.

Parameters:
objekt : object,float

Objekt with method .mass() or molecular weight in Da.

c : float

Concentration in g/ml -> mass/Volume

total : float, default None

Total volume in milliliter [ml] Concentration is calculated by c[g]/total[ml] if given.

Returns:
molarity : float in mol/liter (= mol/1000cm^3)
jscatter.formel.pDA(funktion, sig, parname, type='normal', nGauss=30, **kwargs)

Average a function assuming a parameter is distributed with width sig.

Function average over a parameter with weights determined from probability distribution. Adaptive integration over given distribution or summation with weights is used.

Parameters:
funktion : function

Function to integrate with distribution weight. Function needs to return dataArray.

sig : float

width parameter of the distribution, see Notes

parname : string

Name of the parameter of funktion which shows a distribution

type : ‘normal’,’lognorm’,’gamma’,’lorentz’,’uniform’,’poisson’,’duniform’, default ‘normal’

Type of the distribution

kwargs : parameters

Any additonal kword parameter to pass to function. The value of parname will be the mean value of the distribution.

nGauss : float , default=30

Order of quadrature integration as number of intervals in Gauss–Legendre quadrature over distribution. Distribution is integrated in probability interval [0.001..0.999].

ncpu : int, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • not given or 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
dataArray as returned from function with
  • .parname_mean = mean of parname
  • .parname_std = standard deviation of parname

Notes

The used distributions are from scipy.stats. Choose the distribution according to the problem.

mean is the value in kwargs[parname]. mean and sig are used as:

  • norm :
    mean , std
    stats.norm(loc=mean,scale=sig)
  • lognorm :
    mean and sig evaluate to mean and std
    mu=math.log(mean**2/(sig+mean**2)**0.5)
    nu=(math.log(sig/mean**2+1))**0.5
    stats.lognorm(s=nu,scale=math.exp(mu))
  • gamma :
    mean and sig evaluate to mean and std
    stats.gamma(a=mean**2/sig**2,scale=sig**2/mean)
  • lorentz = cauchy:
    mean and std are not defined. Use FWHM instead to describe width.
    sig=FWHM
    stats.cauchy(loc=mean,scale=sig))
  • uniform :
    sig is width
    stats.uniform(loc=mean-sig/2.,scale=sig))
  • poisson:

    stats.poisson(mu=mean,loc=sig)

  • duniform:
    sig>1
    stats.randint(low=mean-sig, high=mean+sig)

For more distribution look into this source code and use it appropriate with scipy.stats.

Examples

import jscatter as js
p=js.grace()
q=js.loglist(0.1,5,500)
sp=js.ff.sphere(q=q,radius=5)
p.plot(sp,sy=[1,0.2],legend='single radius')
p.yaxis(scale='l',label='I(Q)')
p.xaxis(scale='n',label='Q / nm')
sig=0.2
p.title('radius distribution with width %.g' %(sig))
sp2=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=100)
p.plot(sp2,li=[1,2,2],sy=0,legend='normal 100 points Gauss ')
sp4=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=30)
p.plot(sp4,li=[1,2,3],sy=0,legend='normal 30 points Gauss  ')
sp5=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=5)
p.plot(sp5,li=[1,2,5],sy=0,legend='normal 5 points Gauss  ')
sp3=js.formel.pDA(js.ff.sphere,sig,'radius',type='lognormal',q=q,radius=5)
p.plot(sp3,li=[3,2,4],sy=0,legend='lognormal')
sp6=js.formel.pDA(js.ff.sphere,sig,'radius',type='gamma',q=q,radius=5)
p.plot(sp6,li=[2,2,6],sy=0,legend='gamma ')
# an unrealistic example
sp7=js.formel.pDA(js.ff.sphere,1,'radius',type='poisson',q=q,radius=5)
p.plot(sp7,li=[1,2,6],sy=0,legend='poisson ')
sp8=js.formel.pDA(js.ff.sphere,1,'radius',type='duniform',q=q,radius=5)
p.plot(sp8,li=[1,2,6],sy=0,legend='duniform ')
p.legend()
jscatter.formel.pQAG(func, lowlimit, uplimit, parname, weights=None, tol=1e-08, rtol=1e-08, maxiter=50, miniter=8, **kwargs)

Compute a definite integral using fixed-tolerance Gaussian quadrature for vector output.

Adaptive integration of func from a to b using Gaussian quadrature adaptivly increasing number of points by 8. If function returns ndarray each element is integrated and returned as ndarray of same dimension. If function returns dataArray, only the .Y values is integrated and returned as dataArray.

Parameters:
func : function

A Python function or method to integrate.

lowlimit : float

Lower limit of integration.

uplimit : float

Upper limit of integration.

parname : string

name of the integration variable which should be a scalar.

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
kwargs : dict, optional

Extra keyword arguments to pass to function, if any.

tol, rtol : float, optional

Iteration stops when error between last two iterates is less than tol OR the relative change is less than rtol.

maxiter : int, default 50, optional

Maximum order of Gaussian quadrature.

miniter : int, default 8, optional

Minimum order of Gaussian quadrature.

ncpu : int, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • not given or 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
val : float

Gaussian quadrature approximation (within tolerance) to integral for all vector elements.

err : float

Difference between last two estimates of the integral.

Notes

Reimplementation of scipy.integrate.quadrature.quadrature to work with vector output of the integrand function.

References

[1]https://en.wikipedia.org/wiki/Gaussian_quadrature

Examples

t=np.r_[1:100]
gg=js.formel.gauss(t,50,10)
js.formel.parQuadratureAdaptiveGauss(js.formel.gauss,0,100,'x',mean=50,sigma=10)
jscatter.formel.pQFG(func, lowlimit, uplimit, parname, n=5, weights=None, **kwargs)

Compute a definite integral using fixed-order Gaussian quadrature .

Integrate func over parname from a to b using Gauss-Legendre quadrature [1] of order n for all .X. If function returns ndarray all is integrated and returned as ndarray. If function returns dataArray, only the .Y values is integrated and returned as dataArray.

Parameters:
func : callable

A Python function or method returning a vector array of dimension 1. If func returns dataArray .Y is integrated.

lowlimit : float

Lower limit of integration.

uplimit : float

Upper limit of integration.

parname : string

Name of the integration variable which should be a scalar. after evaluation the correspinding attribute has the mean value with weights.

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
kwargs : dict, optional

Extra keyword arguments to pass to function, if any.

n : int, optional

Order of quadrature integration. Default is 5.

ncpu : int,default=1, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
array or dataArray

Notes

Reimplementation of scipy.integrate.quadrature.fixed_quad to work with vector output of the integrand function and weights.

References

[1](1, 2) https://en.wikipedia.org/wiki/Gaussian_quadrature

Examples

t=np.r_[1:100]
gg=js.formel.gauss(t,50,10)
js.formel.parQuadratureFixedGauss(js.formel.gauss,0,100,'x',mean=50,sigma=10,n=50)
jscatter.formel.pQS(funktion, lowlimit, uplimit, parname, weights=None, tol=1e-06, rtol=1e-06, dX=None, **kwargs)

Integrate a function over one of its parameters with weights using the adaptive Simpson rule.

Integrate by adaptive Simpson integration for all .X values at once. Only .Y values are integrated and checked for tol criterion. Attributes and non .Y columns correspond to the weighted mean of parname.

Parameters:
funktion : function

Function returning dataArray or array

lowlimit,uplimit : float

Interval borders to integrate

parname : string

Parname to integrate

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
tol,rtol : float, default=1e-6
Relative error or absolute error to stop integration. Stop if one is full filled.
Tol is divided for each new interval that the sum of tol is kept.
.IntegralErr_funktEvaluations in dataArray contains error and number of points in interval.
dX : float, default=None

Minimal distance between integration points to determine a minimal step for integration variable.

kwargs :

Additional parameters to pass to funktion. If parname is in kwargs it is overwritten.

Returns:
dataArray or array

dataArrays have additional parameters as error and weights.

Notes

What is the meaning of tol in simpson method? If the error in an interval exceeds tol, the algorithm subdivides the interval in two equal parts with each tol/2 and applies the method to each subinterval in a recursive manner. The condition in interval i is error=|f(ai,mi)+f(mi,bi)-f(ai,bi)|/15 < tol. The recursion stops in an interval if the improvement is smaller than tol. Thus tol is the upper estimate for the total error.

Here we use a absolute (tol) and relative (rtol) criterion: |f(ai,mi)+f(mi,bi)-f(ai,bi)|/15 < rtol*fnew with fnew= ( f(ai,mi)+f(mi,bi) + [f(ai,mi)+f(mi,bi)-f(ai,bi)]/15 ) as the next improved value As this is tested for all .X the worst case is better than tol, rtol.

The algorithm is efficient as it memoizes function evaluation at each interval border and reuses the result. This reduces computing time by about a factor 3-4.

Different distribution can be found in scipy.stats. But any distribution given explicitly can be used. E.g. triangular np.c_[[-1,0,1],[0,1,0]].T

References

[1]https://en.wikipedia.org/wiki/Adaptive_Simpson’s_method

Examples

import jscatter as js
import numpy as np
import scipy
# testcase: integrate over x of a function
# area under normalized gaussian is 1
js.formel.parQuadratureSimpson(js.formel.gauss,-10,10,'x',mean=0,sigma=1)
#
# normal distribtion of parameter D with width ds
t=np.r_[0:150:0.5]
D=0.3
ds=0.1
diff=js.dynamic.simpleDiffusion(t=t,q=0.5,D=D)
distrib =scipy.stats.norm(loc=D,scale=ds)
x=np.r_[D-5*ds:D+5*ds:30j]
pdf=np.c_[x,distrib.pdf(x)].T
diff_g=js.formel.parQuadratureSimpson(js.dynamic.simpleDiffusion,-3*ds+D,3*ds+D,parname='D',
                                         weights=pdf,tol=0.01,q=0.5,t=t)
# compare it
p=js.grace()
p.plot(diff,le='monodisperse')
p.plot(diff_g,le='polydisperse')
p.xaxis(scale='l')
p.legend()
jscatter.formel.parDistributedAverage(funktion, sig, parname, type='normal', nGauss=30, **kwargs)[source]

Average a function assuming a parameter is distributed with width sig.

Function average over a parameter with weights determined from probability distribution. Adaptive integration over given distribution or summation with weights is used.

Parameters:
funktion : function

Function to integrate with distribution weight. Function needs to return dataArray.

sig : float

width parameter of the distribution, see Notes

parname : string

Name of the parameter of funktion which shows a distribution

type : ‘normal’,’lognorm’,’gamma’,’lorentz’,’uniform’,’poisson’,’duniform’, default ‘normal’

Type of the distribution

kwargs : parameters

Any additonal kword parameter to pass to function. The value of parname will be the mean value of the distribution.

nGauss : float , default=30

Order of quadrature integration as number of intervals in Gauss–Legendre quadrature over distribution. Distribution is integrated in probability interval [0.001..0.999].

ncpu : int, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • not given or 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
dataArray as returned from function with
  • .parname_mean = mean of parname
  • .parname_std = standard deviation of parname

Notes

The used distributions are from scipy.stats. Choose the distribution according to the problem.

mean is the value in kwargs[parname]. mean and sig are used as:

  • norm :
    mean , std
    stats.norm(loc=mean,scale=sig)
  • lognorm :
    mean and sig evaluate to mean and std
    mu=math.log(mean**2/(sig+mean**2)**0.5)
    nu=(math.log(sig/mean**2+1))**0.5
    stats.lognorm(s=nu,scale=math.exp(mu))
  • gamma :
    mean and sig evaluate to mean and std
    stats.gamma(a=mean**2/sig**2,scale=sig**2/mean)
  • lorentz = cauchy:
    mean and std are not defined. Use FWHM instead to describe width.
    sig=FWHM
    stats.cauchy(loc=mean,scale=sig))
  • uniform :
    sig is width
    stats.uniform(loc=mean-sig/2.,scale=sig))
  • poisson:

    stats.poisson(mu=mean,loc=sig)

  • duniform:
    sig>1
    stats.randint(low=mean-sig, high=mean+sig)

For more distribution look into this source code and use it appropriate with scipy.stats.

Examples

import jscatter as js
p=js.grace()
q=js.loglist(0.1,5,500)
sp=js.ff.sphere(q=q,radius=5)
p.plot(sp,sy=[1,0.2],legend='single radius')
p.yaxis(scale='l',label='I(Q)')
p.xaxis(scale='n',label='Q / nm')
sig=0.2
p.title('radius distribution with width %.g' %(sig))
sp2=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=100)
p.plot(sp2,li=[1,2,2],sy=0,legend='normal 100 points Gauss ')
sp4=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=30)
p.plot(sp4,li=[1,2,3],sy=0,legend='normal 30 points Gauss  ')
sp5=js.formel.pDA(js.ff.sphere,sig,'radius',type='normal',q=q,radius=5,nGauss=5)
p.plot(sp5,li=[1,2,5],sy=0,legend='normal 5 points Gauss  ')
sp3=js.formel.pDA(js.ff.sphere,sig,'radius',type='lognormal',q=q,radius=5)
p.plot(sp3,li=[3,2,4],sy=0,legend='lognormal')
sp6=js.formel.pDA(js.ff.sphere,sig,'radius',type='gamma',q=q,radius=5)
p.plot(sp6,li=[2,2,6],sy=0,legend='gamma ')
# an unrealistic example
sp7=js.formel.pDA(js.ff.sphere,1,'radius',type='poisson',q=q,radius=5)
p.plot(sp7,li=[1,2,6],sy=0,legend='poisson ')
sp8=js.formel.pDA(js.ff.sphere,1,'radius',type='duniform',q=q,radius=5)
p.plot(sp8,li=[1,2,6],sy=0,legend='duniform ')
p.legend()
jscatter.formel.parQuadratureAdaptiveGauss(func, lowlimit, uplimit, parname, weights=None, tol=1e-08, rtol=1e-08, maxiter=50, miniter=8, **kwargs)[source]

Compute a definite integral using fixed-tolerance Gaussian quadrature for vector output.

Adaptive integration of func from a to b using Gaussian quadrature adaptivly increasing number of points by 8. If function returns ndarray each element is integrated and returned as ndarray of same dimension. If function returns dataArray, only the .Y values is integrated and returned as dataArray.

Parameters:
func : function

A Python function or method to integrate.

lowlimit : float

Lower limit of integration.

uplimit : float

Upper limit of integration.

parname : string

name of the integration variable which should be a scalar.

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
kwargs : dict, optional

Extra keyword arguments to pass to function, if any.

tol, rtol : float, optional

Iteration stops when error between last two iterates is less than tol OR the relative change is less than rtol.

maxiter : int, default 50, optional

Maximum order of Gaussian quadrature.

miniter : int, default 8, optional

Minimum order of Gaussian quadrature.

ncpu : int, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • not given or 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
val : float

Gaussian quadrature approximation (within tolerance) to integral for all vector elements.

err : float

Difference between last two estimates of the integral.

Notes

Reimplementation of scipy.integrate.quadrature.quadrature to work with vector output of the integrand function.

References

[1]https://en.wikipedia.org/wiki/Gaussian_quadrature

Examples

t=np.r_[1:100]
gg=js.formel.gauss(t,50,10)
js.formel.parQuadratureAdaptiveGauss(js.formel.gauss,0,100,'x',mean=50,sigma=10)
jscatter.formel.parQuadratureFixedGauss(func, lowlimit, uplimit, parname, n=5, weights=None, **kwargs)[source]

Compute a definite integral using fixed-order Gaussian quadrature .

Integrate func over parname from a to b using Gauss-Legendre quadrature [1] of order n for all .X. If function returns ndarray all is integrated and returned as ndarray. If function returns dataArray, only the .Y values is integrated and returned as dataArray.

Parameters:
func : callable

A Python function or method returning a vector array of dimension 1. If func returns dataArray .Y is integrated.

lowlimit : float

Lower limit of integration.

uplimit : float

Upper limit of integration.

parname : string

Name of the integration variable which should be a scalar. after evaluation the correspinding attribute has the mean value with weights.

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
kwargs : dict, optional

Extra keyword arguments to pass to function, if any.

n : int, optional

Order of quadrature integration. Default is 5.

ncpu : int,default=1, optional

Number of cpus in the pool. Set this to zero if the integrated function uses multiprocessing to avoid errors.

  • 0 -> all cpus are used
  • int>0 min (ncpu, mp.cpu_count)
  • int<0 ncpu not to use
Returns:
array or dataArray

Notes

Reimplementation of scipy.integrate.quadrature.fixed_quad to work with vector output of the integrand function and weights.

References

[1](1, 2) https://en.wikipedia.org/wiki/Gaussian_quadrature

Examples

t=np.r_[1:100]
gg=js.formel.gauss(t,50,10)
js.formel.parQuadratureFixedGauss(js.formel.gauss,0,100,'x',mean=50,sigma=10,n=50)
jscatter.formel.parQuadratureSimpson(funktion, lowlimit, uplimit, parname, weights=None, tol=1e-06, rtol=1e-06, dX=None, **kwargs)[source]

Integrate a function over one of its parameters with weights using the adaptive Simpson rule.

Integrate by adaptive Simpson integration for all .X values at once. Only .Y values are integrated and checked for tol criterion. Attributes and non .Y columns correspond to the weighted mean of parname.

Parameters:
funktion : function

Function returning dataArray or array

lowlimit,uplimit : float

Interval borders to integrate

parname : string

Parname to integrate

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
tol,rtol : float, default=1e-6
Relative error or absolute error to stop integration. Stop if one is full filled.
Tol is divided for each new interval that the sum of tol is kept.
.IntegralErr_funktEvaluations in dataArray contains error and number of points in interval.
dX : float, default=None

Minimal distance between integration points to determine a minimal step for integration variable.

kwargs :

Additional parameters to pass to funktion. If parname is in kwargs it is overwritten.

Returns:
dataArray or array

dataArrays have additional parameters as error and weights.

Notes

What is the meaning of tol in simpson method? If the error in an interval exceeds tol, the algorithm subdivides the interval in two equal parts with each tol/2 and applies the method to each subinterval in a recursive manner. The condition in interval i is error=|f(ai,mi)+f(mi,bi)-f(ai,bi)|/15 < tol. The recursion stops in an interval if the improvement is smaller than tol. Thus tol is the upper estimate for the total error.

Here we use a absolute (tol) and relative (rtol) criterion: |f(ai,mi)+f(mi,bi)-f(ai,bi)|/15 < rtol*fnew with fnew= ( f(ai,mi)+f(mi,bi) + [f(ai,mi)+f(mi,bi)-f(ai,bi)]/15 ) as the next improved value As this is tested for all .X the worst case is better than tol, rtol.

The algorithm is efficient as it memoizes function evaluation at each interval border and reuses the result. This reduces computing time by about a factor 3-4.

Different distribution can be found in scipy.stats. But any distribution given explicitly can be used. E.g. triangular np.c_[[-1,0,1],[0,1,0]].T

References

[1]https://en.wikipedia.org/wiki/Adaptive_Simpson’s_method

Examples

import jscatter as js
import numpy as np
import scipy
# testcase: integrate over x of a function
# area under normalized gaussian is 1
js.formel.parQuadratureSimpson(js.formel.gauss,-10,10,'x',mean=0,sigma=1)
#
# normal distribtion of parameter D with width ds
t=np.r_[0:150:0.5]
D=0.3
ds=0.1
diff=js.dynamic.simpleDiffusion(t=t,q=0.5,D=D)
distrib =scipy.stats.norm(loc=D,scale=ds)
x=np.r_[D-5*ds:D+5*ds:30j]
pdf=np.c_[x,distrib.pdf(x)].T
diff_g=js.formel.parQuadratureSimpson(js.dynamic.simpleDiffusion,-3*ds+D,3*ds+D,parname='D',
                                         weights=pdf,tol=0.01,q=0.5,t=t)
# compare it
p=js.grace()
p.plot(diff,le='monodisperse')
p.plot(diff_g,le='polydisperse')
p.xaxis(scale='l')
p.legend()
jscatter.formel.psphereAverage(funktion, relError=300, *args, **kwargs)[source]

parallel sphereAverage; see psphereAverage()

jscatter.formel.randomPointsInCube(NN, skip=0, dim=3)[source]

Random points in cube; see randomPointsInCube()

jscatter.formel.randomPointsOnSphere(NN, r=1, skip=0)[source]

Random points on sphere; see randomPointsOnSphere()

jscatter.formel.rotationMatrix(vector, angle)[source]

Create a rotation matrix corresponding to rotation around vector v by a specified angle.

R = vv^T + cos(a) (I - vv^T) + sin(a) skew(v)

Parameters:
vector : array

Rotation around a general vector

angle : float

Angle in rad

Returns:
Rotation matrix

Examples

R=js.formel.rotationMatrix([0,0,1],np.deg2rad(-90))
v=[1,0,0]
rv=np.dot(R,v)
#
# rotate fibonacci Grid
qfib=js.formel.fibonacciLatticePointsOnSphere(300,1)
qfib=qfib[qfib[:,2]<np.pi/2,:]           # select half sphere
qfib[:,2]*=(30/90.)                      # shrink to cone of 30°
qfx=js.formel.rphitheta2xyz(qfib)        # transform to cartesian
R=js.formel.rotationMatrix([0,1,0],np.deg2rad(-90)) # rotation around y axis
Rfx=np.einsum('ij,jk->ki',R,qfx.T)                  # do rotation
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
sc=ax.scatter(qfx[:,0], qfx[:,1], qfx[:,2], s=2, color='r')
sc=ax.scatter(Rfx[:,0], Rfx[:,1], Rfx[:,2], s=2, color='b')
ax.scatter(0,0,0, s=55, color='g',alpha=0.5)
pyplot.show(block=False)
jscatter.formel.rphitheta2xyz(RPT, transpose=False)[source]

Transformation spherical coordinates [r,phi,theta] to cartesian coordinates [x,y,z].

Parameters:
RPT : array Nx3
Coordinates with [r,phi,theta]
  • r : float length
  • phi : float azimuth -pi < phi < pi
  • theta : float polar angle 0 < theta < pi
transpose : bool

Transpose RPT before transformation.

Returns:
xyz : array Nx3 with [x,y,z] coordinates
jscatter.formel.sQS(funktion, lowlimit, uplimit, parname, weights=None, tol=1e-06, rtol=1e-06, **kwargs)

Integrate a scalar function over one of its parameters with weights using the adaptive Simpson rule.

Integrate by adaptive Simpson integration for scalar function.

Parameters:
funktion : function

function to integrate

lowlimit,uplimit : float

interval to integrate

parname : string

parname to integrate

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
tol,rtol : float, default=1e-6
Relative error for intervals or absolute integral error to stop integration.
kwargs :

additional parameters to pass to funktion if parname is in kwargs it is overwritten

Returns:
float

Notes

What is the meaning of tol in simpson method? See parQuadratureSimpson.

References

[1]https://en.wikipedia.org/wiki/Adaptive_Simpson’s_method

Examples

distrib =scipy.stats.norm(loc=1,scale=0.2)
x=np.linspace(0,1,1000)
pdf=np.c_[x,distrib.pdf(x)].T
# define function
f1=lambda x,p1,p2,p3:js.dA(np.c_[x,x*p1+x*x*p2+p3].T)
# calc the weighted integral
result=js.formel.parQuadratureSimpson(f1,0,1,parname='p2',weights=pdf,tol=0.01,p1=1,p3=1e-2,x=x)
# something simple should be 1
js.formel.simpleQuadratureSimpson(js.formel.gauss,-10,10,'x',mean=0,sigma=1)
jscatter.formel.scatteringLengthDensityCalc(composition, density=None, T=293, units='mol', mode='all')[source]

Scattering length density of composites and water with inorganic components for xrays and neutrons.

Parameters:
composition : list of concentration + chemical formula

A string with chemical formula as letter + number and prepended concentration in mol or mmol. E.g. ‘0.1C3H8O3’ or ‘0.1C3H1D7O3’ for glycerol and deuterated glycerol (‘D’ for deuterium).

  • For single atoms append 1 to avoid confusion. Fractional numbers allowed, but think of meaning (Isotope mass fraction??)
  • For compositions use a list of strings preceded by mass fraction or concentration in mol of component. This will be normalized to total amount
Examples:
  • [‘4.5H2O1’,‘0.5D2O1’] mixture of 10% heavy and 90% light water.
  • [‘1.0h2o’,‘0.1c3h8o3’] for 10% mass glycerol added to 100% h2o with units=’mass’
  • [‘55000H2O1’,‘50Na3P1O4’,‘137Na1Cl1’] for a 137mMol NaCl +50mMol phophate H2O buffer (1l is 55000 mM H2O)
  • [‘1Au1’] gold with density 19.302 g/ml

Remember to adjust density.

density : float, default=None

Density in g/cm**3 = g/ml. If not given function waterdensity is tried to calculate the solution density with inorganic components. In this case ‘h2o1’ and/or ‘d2o1’ need to be in composition. Otherwise measure by weighting a volume from pipette (lower accuracy) or densiometry (higher accuracy).

units : ‘mol’

Anything except ‘mol’ prepended unit is mass fraction (default). ‘mol’ prepended units is mol and mass fraction is calculated as mass=[mol]*mass_of_molecule e.g. 1l Water with 123mmol NaCl [‘55.5H2O1’,‘0.123Na1Cl1’]

mode :
  • ‘xsld’ xray scattering length density in nm**-2
  • ‘edensity’ electron density in e/nm**3
  • ‘ncohsld’ coherent scattering length density in nm**-2
  • ‘incsld’ incoherent scattering length density in nm**-2
  • ‘all’ [xsld, edensity, ncohsld, incsld,
    masses, masses full protonated, masses full deuterated, d2o/h2o fraction in composition]
T : float, default=293

Temperature in °K

Returns:
sld : float or list of float corresponding to mode

Notes

  • edensity=be*massdensity/weightpermol*sum_atoms(numberofatomi*chargeofatomi)
  • be = scattering length electron =µ0*e**2/4/pi/m=2.8179403267e-6 nm
  • masses, masses full protonated, masses full deuterated for each chemical in composition.
  • In mode ‘all’ the masses can be used to calc the deuterated density if same volume is assumed. e.g. fulldeuterated_density=protonated_density/massfullprotonated*massfulldeuterated

For density reference of H2O/D2O see waterdensity.

Examples

# 5% D2O in H2O with 10% mass NaCl
js.formel.scatteringLengthDensityCalc(['9.5H2O1','0.5D2O1','1Na1Cl1'],units='mass')
# protein NaPi buffer in D2O prevalue in mmol; 55000 mmol H2O is 1 liter.
js.formel.scatteringLengthDensityCalc(['55000D2O1','50Na3P1O4','137Na1Cl1'])
# silica
js.formel.scatteringLengthDensityCalc('1Si1O2',density=2.65)
# gold
js.formel.scatteringLengthDensityCalc(['1Au1'],density=19.32)
# PEG1000
js.formel.scatteringLengthDensityCalc(['1C44H88O23'],density=1.21)
jscatter.formel.sedimentationProfile(t=1000.0, rm=48, rb=85, number=100, rlist=None, c0=0.01, S=None, Dt=None, omega=246, Rh=10, temp=293, densitydif=0.41, visc='h2o')[source]

Approximate solution to the Lamm equation of sedimenting particles in centrifuge including bottom equilibrium distribution.

Bottom equilibrium distribution is not in faxen solution. Results in particle concentration profile between rm and rb for time t

Parameters:
t : float or list

Time after start in seconds. If list, results at these times is given as dataList.

rm : float

Axial position of meniscus in mm.

rb : float

Axial position of bottom in mm.

number : int

Number of points between rm and rb to calculate.

rlist : list of float

Explicit list of positions where to calculate eg to zoom bottom.

c0 : float

Initial concentration in cell; just a scaling factor.

S : float

Sedimentation coefficient in Svedberg; 77 S is r=10 nm particle in H2O.

Dt : float

Translational diffusion coefficient in m**2/s; 1.99e-11 is r=10 nm particle.

omega : float

Radial velocity rounds per second; 246 rps=2545 rad/s is 20800g in centrifuge fresco 21.

Rh : float

Hydrodynamic radius in nm ; if given the Dt and s are calculated from this.

densitydif : float

Density difference between solvent and particle in g/ml; Protein in ‘h2o’=> is used =>1.41-1.= 0.41 g/cm**3.

visc : float, ‘h2o’, ‘d2o’

Viscosity of the solvent in Pas. (H2O ~ 0.001 Pa*s =1 cPoise) If ‘h2o’ or ‘d2o’ the corresponding viscosity at given temperature is used.

temp : float

temperature in K.

Returns:
concentration profile : dataArray, dataList

Columns [position in [mm]; ; conc_meniscus_part; conc_bottom_part]

Notes

From [1]:”The deviations from the expected results are smaller than 1% for simulated curves and are valid for a great range of molecular masses from 0.4 to at least 7000 kDa. The presented approximate solution, an essential part of LAMM allows the estimation of s and D with an accuracy comparable to that achieved using numerical solutions, e.g the program SEDFIT of Schuck et al.”

Default values are for Heraeus Fresco 21 at 21000g.

References

[1](1, 2) A new approximate whole boundary solution of the Lamm equation for the analysis of sedimentation velocity experiments J. Behlke, O. Ristau Biophysical Chemistry 95 (2002) 59–68

Examples

Sedimentation (up concentration) of unilamellar liposomes of DOPC. The density of DOPC is about 1.01 g/ccm in water with 1 g/ccm. Lipid volume fraction is 33% for 50nm radius (10% for 200 nm) for a bilayer thickness of 6.5 nm.

import numpy as np
import jscatter as js

t1=np.r_[100:6e3:11j]  # time in seconds

# open plot()
p=js.grace(1.5,1.5)
p.multi(2,1)

# calculate sedimentation profile for two different particles
# data correspond to Fresco 21 with dual rotor
# default is solvent='h2o',temp=293
Rh2=150       # nm
g=21000. # g # RZB number
omega=g*246/21000
D100nm=js.formel.sedimentationProfile(t=t1,Rh=50,c0=0.05,omega=omega,rm=58,rb=85,densitydif=0.0033)
D400nm=js.formel.sedimentationProfile(t=t1,Rh=200,c0=0.05,omega=omega,rm=58,rb=85,densitydif=0.001)
# plot it
p[0].plot(D100nm,li=[1,2,-1],sy=0,legend='%s nm-> t=$time s' )
p[1].plot(D400nm,li=[1,2,-1],sy=0,legend='%s nm-> t=$time s' )
# pretty up
p[0].yaxis(min=0,max=0.2,label='concentration')
p[1].yaxis(min=0,max=0.2,label='concentration')
p[1].xaxis(label='position mm')
p[0].xaxis(label='')
p[0].text(x=70,y=0.15,string='D=100 nm')
p[1].text(x=70,y=0.15,string='D=400 nm')
p[0].legend(x=50,y=0.2,charsize=0.5)
p[1].legend(x=50,y=0.2,charsize=0.5)
p[0].title('Concentration profile in first 6000s')
p[0].subtitle('at 21000g ')
jscatter.formel.sedimentationProfileFaxen(t=1000.0, rm=48, rb=85, number=100, rlist=None, c0=0.01, s=77, Dt=1.99e-11, w=246, Rh=None, visc='h2o', temp=293, densitydif=None)[source]

Faxen solution to the Lamm equation of sedimenting particles in centrifuge; no bottom part.

Bottom equillibrium distribution is not in Faxen solution included. Results in particle distribution along axis for time t.

Parameters:
t : float

Time after start in seconds. If list, results at these times is given as dataList.

rm : float

Axial position of meniscus in mm.

rb : float

Axial position of bottom in mm.

rlist : array, optional

Explicit list of radial values to use between rm=max(rlist) and rb=min(rlist)

number : integer

Number of points between rm and rb to calculate.

c0 : float

Initial concentration in cell; just a scaling factor.

s : float

Sedimentation coefficient in Svedberg; 77 S is r=10 nm particle in H2O.

Dt : float

Translational diffusion coefficient in m**2/s; 1.99e-11 is r=10 nm particle.

w : float

Radial velocity rounds per second; 246 rps=2545 rad/s is 20800g in centrifuge fresco 21.

Rh : float

Hydrodynamic radius in nm ; if given Dt and s are calculated from Rh.

visc : float, ‘h2o’,’d2o’

Viscosity in units Pas. If ‘h2o’ or ‘d2o’ the corresponding viscosity at given temperature is used.

densitydif : float

Density difference between solvent and particle in g/ml; protein in ‘h2o’=> is used =>1.35-1.= 0.35 g/cm**3

temp : float

temperature in K.

Returns:
Concentration distribution : dataArray, dataList

.pelletfraction is the content in pellet as fraction already diffused out .rmeniscus

Notes

Default values are for Heraeus Fresco 21 at 21000g.

References

[1]Über eine Differentialgleichung aus der physikalischen Chemie. Faxén, H. Ark. Mat. Astr. Fys. 21B:1-6 (1929)
jscatter.formel.simpleQuadratureSimpson(funktion, lowlimit, uplimit, parname, weights=None, tol=1e-06, rtol=1e-06, **kwargs)[source]

Integrate a scalar function over one of its parameters with weights using the adaptive Simpson rule.

Integrate by adaptive Simpson integration for scalar function.

Parameters:
funktion : function

function to integrate

lowlimit,uplimit : float

interval to integrate

parname : string

parname to integrate

weights : ndarray shape(2,N),default=None
  • Weights for integration along parname as a Gaussian with a<weights[0]<b and weights[1] contains weight values.
  • Missing values are linear interpolated (faster). If None equal weights are used.
tol,rtol : float, default=1e-6
Relative error for intervals or absolute integral error to stop integration.
kwargs :

additional parameters to pass to funktion if parname is in kwargs it is overwritten

Returns:
float

Notes

What is the meaning of tol in simpson method? See parQuadratureSimpson.

References

[1]https://en.wikipedia.org/wiki/Adaptive_Simpson’s_method

Examples

distrib =scipy.stats.norm(loc=1,scale=0.2)
x=np.linspace(0,1,1000)
pdf=np.c_[x,distrib.pdf(x)].T
# define function
f1=lambda x,p1,p2,p3:js.dA(np.c_[x,x*p1+x*x*p2+p3].T)
# calc the weighted integral
result=js.formel.parQuadratureSimpson(f1,0,1,parname='p2',weights=pdf,tol=0.01,p1=1,p3=1e-2,x=x)
# something simple should be 1
js.formel.simpleQuadratureSimpson(js.formel.gauss,-10,10,'x',mean=0,sigma=1)
jscatter.formel.smooth(data, windowlen=7, window='flat')[source]

Smooth data using a window with requested size and type.

This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the beginning and end part of the output signal. Adapted from SciPy/Cookbook.

Parameters:
data : array, dataArray

Data to smooth. If is dataArray the .Y is smoothed and returned.

windowlen : int, default = 7

The length of the smoothing window; should be an odd integer. Smaller 3 returns unchanged data.

window : ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’,’gaussian’, default =’flat’
Type of window.
  • ‘flat’ will produce a moving average smoothing.
  • ‘gaussian’ normalized Gaussian window with sigma=windowlen/7.
Returns:
array (only the smoothed array)

Notes

See numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.gaussian

Examples

import jscatter as js
import numpy as np
t=np.r_[-5:5:0.01]
data=np.sin(t)+np.random.randn(len(t))*0.1
y=js.formel.smooth(data)
#
# smooth dataArray and replace .Y values.
data2=js.dA(np.vstack([t,data]))
data2.Y=js.formel.smooth(data2, windowlen=40, window='gaussian')
p=js.grace()
p.plot(t,data)
p.plot(t,y)
p.plot(data2)
p.plot(data2.prune(number=200)) # reduces number of points by real averaging.
jscatter.formel.sphereAverage(function, relError=300, *args, **kwargs)[source]

Spherical average - non-parallel

A Fibonacci lattice or Monte Carlo integration with pseudo random grid is used.

Parameters:
function : function

Function to evaluate returning a list of return values (all are integrated) function gets cartesian coordinate of point on unit sphere as first argument

relError : float, default 300
Determines how points on sphere are selected for integration
  • >=1 Fibonacci Lattice with relError*2+1 points (min 15 points)
  • 0<1 Pseudo random points on sphere (see randomPointsOnSphere).
    Stops if relative improvement in mean is less than relError (uses steps of 20*ncpu new points). Final error is (stddev of N points) /sqrt(N) as for Monte Carlo methods. even if it is not a correct 1-sigma error in this case.
args,kwargs :

Forwarded to function

Returns:
array like :

Values from function and appended Monte Carlo error estimates.

Examples

def f(x,r):
   return [js.formel.xyz2rphitheta(x)[1:].sum()*r]
js.formel.sphereAverage(f,relError=500,r=1)
js.formel.sphereAverage(f,relError=0.01,r=1)
jscatter.formel.viscosity(mat='h2o', T=293.15)[source]

Viscosity of pure solvents. For buffer solvents use bufferviscosity.

Parameters:
mat : string ‘h2o’,’d2o’,’toluol’,’methylcyclohexan’, default h2o

Solvent

T : float

Temperature T in Kelvin default 293K

Returns:
float : viscosity in Pa*s

water H2O ~ 0.001 Pa*s =1 cPoise # Poise=0.1 Pa*s

References

[1]The Viscosity of Toluene in the Temperature Range 210 to 370 K M. J. Assael, N.K. Dalaouti, J.H., Dymond International Journal of Thermophysics, Vol. 21,291 No. 2, 2000 # accuracy +- 0.4 % laut paper Max error von Experiment data
[2]Thermal Offset Viscosities of Liquid H2O, D2O, and T2O C. H. Cho, J. Urquidi, S. Singh, and G. Wilse Robinson J. Phys. Chem. B 1999, 103, 1991-1994
jscatter.formel.voigt(x, center=0, fwhm=1, lg=1, asym=0, amplitude=1)[source]

Voigt function for peak analysis (normalized).

The Voigt function is a convolution of gaussian and lorenzian shape peaks for peak analysis. The Lorenzian shows a stronger contribution outside FWHM with a sharper peak. Asymmetry of the shape can be added by a sigmoidal change of the FWHM [2].

Parameters:
x : array

Axis values.

center : float

Center of the distribution.

fwhm : float

Full width half maximum of the Voigt function.

lg : float, default = 1
Lorenzian/gaussian fraction of both FWHM, describes the contributions of gaussian and lorenzian shape.
  • lorenzian/gaussian >> 1 lorenzian,
  • lorenzian/gaussian ~ 1 central part gaussian, outside lorenzian wings
  • lorenzian/gaussian << 1. gaussian
asym : float, default=0

asymmetry factor in sigmoidal as 2*fwhm/(1+np.exp(asym*(x-center))) For a=0 the Voigt is symmetric with fwhm.

amplitude : float, default = 1

amplitude

Returns:
Voigt function : dataArray

.center .sigma .gamma .fwhm .asymmetry .lorenzianOverGaussian

References

[1]https://en.wikipedia.org/wiki/Voigt_profile
[2](1, 2) Aaron L. Stancik, Eric B. Brauns A simple asymmetric lineshape for fitting infrared absorption spectra Vibrational Spectroscopy 47 (2008) 66–69
jscatter.formel.watercompressibility(d2ofract=1, T=278, units='psnmg')[source]

Isothermal compressibility of H2O and D2O mixtures.

Compressibility in units ps^2*nm/(g/mol) or in 1/bar. Linear mixture according to d2ofract.

Parameters:
d2ofract : float, default 1

Fraction D2O

T : float, default 278K

Temperature in K

units : string ‘psnmg’

ps^2*nm/(g/mol) or 1/bar

Returns:
float

Notes

To get kT*compressibility =compr*k_B/Nav*300/cm**3 in hwater 1.91e-24 cm**3 at 20°C

References

[1]Isothermal compressibility of Deuterium Oxide at various Temperatures Millero FJ and Lepple FK Journal of chemical physics 54,946-949 (1971) http://dx.doi.org/10.1063/1.1675024
[2]Precise representation of volume properties of water at one atmosphere G. S. Kell J. Chem. Eng. Data, 1967, 12 (1), pp 66–69 http://dx.doi.org/10.1021/je60032a018
jscatter.formel.waterdensity(composition, T=293.15, units='mol', showvalidity=False)[source]

Density of water with inorganic substances (salts).

Solvent with composition of H2O and D2O and additional inorganic components at temperature T. Ternary solutions allowed. Units are mol; 1l h2o = 55.50843 mol

Parameters:
composition : list of compositional strings
Compositional string of chemical formula as ‘float’+’chemical char’ + integer
First float is content in mol (is later normalised to sum of contents)
chemical letter + number of atoms in formula (single atoms append 1 ,fractional numbers allowed)
e.g.
‘h2o1’ or ‘d2o1’ light and heavy water with ‘d1’ for deuterium
‘c3h8o3’ or ‘c3h1d7o3’ partial deuterated glycerol
[‘55.55h2o1’,‘2.5Na1Cl1’] for 2.5 mol NaCl added to 1l h2o (55.55 mol)
[‘20H2O1’,‘35.55D2O1’,‘0.1Na1Cl1’] h2o/d2o mixture with 100mMol NaCl
units : default=’mol’

Anything except ‘mol’ unit is mass fraction ‘mol’ units is mol and mass fraction is calculated as mass=[mol]*mass_of_molecule e.g. 1l Water with 123mM NaCl [‘55.5H2O1’,‘0.123Na1Cl1’]

T : float, default=293.15

temperature in K

showvalidity : bool, default False

Show additionally validity range for temperature and concentration according to [4]. - Temperature range in °C - concentration in wt % or up to a saturated solution (satd) - error in 1/100 % see [4].

Returns:
float in g/ml

Notes

  • D2O maximum density 1.10596 at T=273.15+11.23 K [1] .
  • For mixtures of H2O/D2O molar volumes add with an accuracy of about 2e-4 cm**3/mol compared to 18 cm**3/mol molar volume [3].
  • Additional densities of binary aqueous solutions [4].

References

[1](1, 2) The dilatation of heavy water K. Stokland, E. Ronaess and L. Tronstad Trans. Faraday Soc., 1939,35, 312-318 DOI: 10.1039/TF9393500312
[2]Effects of Isotopic Composition, Temperature, Pressure, and Dissolved Gases on the Density of Liquid Water George S. Kell JPCRD 6(4) pp. 1109-1131 (1977)
[3](1, 2) Excess volumes for H2O + D2O liquid mixtures Bottomley G Scott R Australian Journal of Chemistry 1976 vol: 29 (2) pp: 427
[4](1, 2, 3, 4) Densities of binary aqueous solutions of 306 inorganic substances P. Novotny, O. Sohnel J. Chem. Eng. Data, 1988, 33 (1), pp 49–55 DOI: 10.1021/je00051a018

availible components:

h2o1 d2o1
TRIS c4h11n1o3
TABS c8h19n1o6s1

     ag1cl104     ag1n1o3      al1cl3012    al1n3o9      al2s3o12     ba1br2      
 ba1cl2       ba1cl2o6     ba1i2        ba1n2o6      c4h11n1o3    c8h19n1o6s1 
 ca1br2       ca1cl2       ca1i2        ca1n2o6      cd1br2       cd1c12      
 cd1i2        cd1n2o6      cd1so4       co1n2o6      co1s1o4      cs1br1      
 cs1cl1       cs1f1        cs1i1        cs1n1o3      cs2s1o4      cu1cl2      
 cu1n2o6      cu1s1o4      dy1cl3       er1cl3       fe1cl3       fe1s1o4     
 gd1cl3       h1br1        h1cl1        h1cl104      h1i1         h1n1o3      
 h2s1o4       h3b103       h3p1o4       hg1c2n2      hg1cl2       k1ag1c2n2   
 k1al1s2o8    k1br1        k1br1o3      k1cl1        k1cl103      k1cl104     
 k1f1         k1h1c1o3     k1h1s1o4     k1h2p1o4     k1i1         k1i103      
 k1mn1o4      k1n1o2       k1n1o3       k1n3         k1o1h1       k1s1c1n1    
 k1tart1      k2c1o3       k2cr104      k2cr207      k2s1o4       k3co1c6n6   
 k3fe1c6n6    k4fe1c6n6    k4mo1c8n8    la1cl3       li1br1       li1cl1      
 li1cl104     li1i1        li1n1o3      li1o1h1      li2s1o4      mg1br2      
 mg1br206     mg1cl2       mg1cl2o8     mg1i2        mg1n2o6      mg1s1o4     
 mn1cl1       mn1s1o4      n1h3         n1h40x1      n1h4ac1      n1h4al1s2o8 
 n1h4cl1      n1h4cl104    n1h4fe1s2o8  n1h4h1s1o4   n1h4h2p1o4   n1h4i1      
 n1h4n1o3     n2h8ni1s2o8  n2h8s1o4     n2s203       na1ac1       na1br1      
 na1br1o3     na1cl1       na1cl103     na1cl104     na1f1        na1form1    
 na1h1s1o4    na1h2p1o4    na1i1        na1i103      na1k1tart1   na1mn104    
 na1n1o2      na1n1o3      na1n3        na1o1h1      na1ox1       na1s1c1n1   
 na1tart1     na2b407      na2c1o3      na2cr1o4     na2cr207     na2h1p1o4   
 na2mo104     na2s1        na2s103      na2s1o4      na2w104      na3p1o4     
 na4p207      na5p307      nd1cl3       ni1cl2       ni1n2o6      ni1s1o4     
 pb1n2o6      pr1cl3       rb1br1       rb1cl1       rb1f1        rb1i1       
 rb1n1o3      rb2so4       sm1cl3       sr1ac2       sr1br2       sr1br206    
 sr1cl2       sr1i2        sr1n2o6      ti1n1o3      ti2s1o4      u1o2n2o6    
 u1o2s104     yb1cl3       zn1br2       zn1cl2       zn1i2        zn1n2o6     
 zn1s1o1     
jscatter.formel.xyz2rphitheta(XYZ, transpose=False)[source]

Transformation cartesian coordinates [X,Y,Z] to spherical coordinates [r,phi,theta].

Parameters:
XYZ : array Nx3

Coordinates with [x,y,z] ( XYZ.shape[1]==3).

transpose : bool

Transpose XYZ before transformation.

Returns:
rphitheta : array Nx3
Coordinates with [r,phi,theta]
  • phi : float azimuth -pi < phi < pi
  • theta : float polar angle 0 < theta < pi
  • r : float length

Examples

Single coordinates

js.formel.xyz2rphitheta([1,0,0])

Transform Fibonacci lattice on sphere to xyz coordinates

fib=js.formel.fibonacciLatticePointsOnSphere(10,1)
js.formel.xyz2rphitheta(fib)

Tranformation 2D X,Z coordinates in plane to r,phi coordinates (Z=0)

rp=js.formel.xyz2rphitheta([data.X,data.Z,abs(data.X*0)],transpose=True) )[:,:2]