Exemplo n.º 1
0
    def xray_scattering_lengths(self, condition, energy=8.048):
        vh, vt = self.conditions[condition]
        h_density = calculate_density(self.hf, vh)
        t_density = calculate_density(self.tf, vt)

        h_sld = pt.xray_sld(self.hf, density=h_density, energy=energy)
        t_sld = pt.xray_sld(self.tf, density=t_density, energy=energy)
        h_scatlen = complex(*h_sld[0:2]) * vh / 1e6
        t_scatlen = complex(*t_sld[0:2]) * vt / 1e6
        return h_scatlen, t_scatlen
Exemplo n.º 2
0
    def calculate(self):
        try:
            formula = pt.formula(self.ui.chemical_formula.text(), )

        except (pyparsing.ParseException, TypeError, ValueError):
            return

        density = self.ui.mass_density.value()
        molecular_volume = self.ui.molecular_volume.value()
        neutron_wavelength = self.ui.neutron_wavelength.value()
        xray_energy = self.ui.xray_energy.value()

        if self.ui.use_volume.isChecked():
            density = formula.molecular_mass / formula.volume(
                a=molecular_volume, b=1, c=1)
            self.ui.mass_density.setValue(density)

        elif self.ui.use_density.isChecked():
            volume = formula.mass / density / \
                pt.constants.avogadro_number * 1e24
            self.ui.molecular_volume.setValue(volume)

        real, imag, mu = pt.neutron_sld(formula,
                                        density=density,
                                        wavelength=neutron_wavelength)

        self.ui.neutron_SLD.setText('%.6g' % real + ' + ' + '%.6g' % imag +
                                    'j')

        real, imag = pt.xray_sld(formula, density=density, energy=xray_energy)

        self.ui.xray_SLD.setText('%.6g' % real + ' + ' + '%.6g' % imag + 'j')
Exemplo n.º 3
0
def test():
    from periodictable.constants import avogadro_number
    # Beta casein results checked against Duncan McGillivray's spreadsheet
    # beta casein 23561.9 23880.9 30872.9  1.27 12614 11.55  1.68  2.75
    s = Sequence("beta casein", beta_casein)
    assert abs(s.Dmass-23880.9) < 0.1
    #print "density",s.mass/avogadro_number/s.cell_volume*1e24
    assert abs(s.mass/avogadro_number/s.cell_volume*1e24 - 1.267) < 0.01
    assert abs(s.Dsld-2.75) < 0.01

    # Check that X-ray sld is independent of isotope
    H = isotope_substitution(s.formula, pt.T, pt.H)
    D = isotope_substitution(s.formula, pt.T, pt.D)
    Hsld, Dsld = pt.xray_sld(H, wavelength=1.54), pt.xray_sld(D, wavelength=1.54)
    #print Hsld, Dsld
    assert abs(Hsld[0]-Dsld[0]) < 1e-10
Exemplo n.º 4
0
def test():
    from periodictable.constants import avogadro_number
    # Beta casein results checked against Duncan McGillivray's spreadsheet
    # beta casein 23561.9 23880.9 30872.9  1.27 12614 11.55  1.68  2.75
    s = Sequence("beta casein", beta_casein)
    assert abs(s.D.mass-23880.9) < 0.1
    #print "density",s.mass/avogadro_number/s.cell_volume*1e24
    assert abs(s.natural.mass/avogadro_number/s.cell_volume*1e24 - 1.267) < 0.01
    assert abs(s.D_sld-2.75) < 0.01

    # Check that X-ray sld is independent of isotope
    H = isotope_substitution(s.formula, pt.T, pt.H)
    D = isotope_substitution(s.formula, pt.T, pt.D)
    H_sld, D_sld = pt.xray_sld(H,wavelength=1.54), pt.xray_sld(D,wavelength=1.54)
    #print H_sld, D_sld
    assert abs(H_sld[0] - D_sld[0]) < 1e-10
Exemplo n.º 5
0
def get_iron_oxide(wavelength):
    oxide = pt.formula("Fe2O3")
    dens = 5.24
    rho, mu = pt.xray_sld(oxide,
                          density=dens,
                          wavelength=wavelength / angstrom)
    return ba.MaterialBySLD("Fe203", rho * 1e-6, mu * 1e-6)
Exemplo n.º 6
0
def get_si(wavelength):
    si = pt.formula("Si")
    dens = pt.Si.density
    rho, mu = pt.xray_sld(si,
                          density=pt.Si.density,
                          wavelength=wavelength / angstrom)
    return ba.MaterialBySLD("si", rho * 1e-6, mu * 1e-6)
 def get_iron_oxide(self, wavelength):
     oxide = pt.formula("Fe2O3")
     dens = 5.24
     rho, mu = pt.xray_sld(oxide, density=dens, wavelength=wavelength / angstrom)
     rho *= 1e-6
     mu *= 1e-6
     print("MaterialLibrary > wavelength:{0} formula:{1} density:{2} rho:{3} mu:{4}".format(wavelength, oxide,
                                                                                            dens, rho, mu))
     return ba.MaterialBySLD("Fe203", rho, mu)
 def get_si(self, wavelength):
     si = pt.formula("Si")
     dens = pt.Si.density
     rho, mu = pt.xray_sld(si, density=pt.Si.density, wavelength=wavelength / angstrom)
     rho *= 1e-6
     mu *= 1e-6
     print("MaterialLibrary > wavelength:{0} formula:{1} density:{2} rho:{3} mu:{4}".format(wavelength, si,
                                                                                            dens, rho, mu))
     return ba.MaterialBySLD("si", rho, mu)
Exemplo n.º 9
0
    def calculate(self):
        try:
            formula = pt.formula(self.ui.chemical_formula.text())

        except (pyparsing.ParseException, TypeError, ValueError, KeyError):
            # a problem was experience during parsing of the formula.
            return

        if not len(formula.atoms):
            return

        density = self.ui.mass_density.value()
        molecular_volume = self.ui.molecular_volume.value()
        neutron_wavelength = self.ui.neutron_wavelength.value()
        xray_energy = self.ui.xray_energy.value()

        if self.ui.use_volume.isChecked():
            density = formula.molecular_mass / formula.volume(
                a=molecular_volume, b=1, c=1)
            self.ui.mass_density.setValue(density)

        elif self.ui.use_density.isChecked():
            try:
                volume = (formula.mass / density /
                          pt.constants.avogadro_number * 1e24)
            except ZeroDivisionError:
                volume = np.nan
            self.ui.molecular_volume.setValue(volume)

        try:
            real, imag, mu = pt.neutron_sld(formula,
                                            density=density,
                                            wavelength=neutron_wavelength)

            self.ui.neutron_SLD.setText("%.6g" % real + " + " + "%.6g" % imag +
                                        "j")
        except Exception:
            self.ui.neutron_SLD.setText("NaN")

        try:
            real, imag = pt.xray_sld(formula,
                                     density=density,
                                     energy=xray_energy)

            self.ui.xray_SLD.setText("%.6g" % real + " + " + "%.6g" % imag +
                                     "j")
        except Exception:
            self.ui.xray_SLD.setText("NaN")
Exemplo n.º 10
0
def fasta_table():
    rows = []
    rows += [v for k, v in sorted(AMINO_ACID_CODES.items())]
    rows += [v for k, v in sorted(NUCLEIC_ACID_COMPONENTS.items())]
    rows += [Sequence("beta casein", beta_casein)]

    print("%20s %7s %7s %7s %5s %5s %5s %5s %5s %5s" %
          ("name", "M(H2O)", "M(D2O)", "volume", "den", "#el", "xray", "nH2O",
           "nD2O", "%D2O match"))
    for v in rows:
        protons = sum(num * el.number for el, num in v.formula.atoms.items())
        electrons = protons - v.charge
        Xsld = pt.xray_sld(v.formula, wavelength=pt.Cu.K_alpha)
        print("%20s %7.1f %7.1f %7.1f %5.2f %5d %5.2f %5.2f %5.2f %5.1f" %
              (v.name, v.Hmass, v.Dmass, v.cell_volume, v.formula.density,
               electrons, Xsld[0], v.Hsld, v.Dsld, v.D2Omatch))
Exemplo n.º 11
0
def fasta_table():
    rows = []
    rows += [v for k, v in sorted(AMINO_ACID_CODES.items())]
    rows += [v for k, v in sorted(NUCLEIC_ACID_COMPONENTS.items())]
    rows += [Sequence("beta casein", beta_casein)]

    print("%20s %7s %7s %7s %5s %5s %5s %5s %5s %5s"
          % ("name", "M(H2O)", "M(D2O)", "volume",
             "den", "#el", "xray", "nH2O", "nD2O", "%D2O match"))
    for v in rows:
        protons = sum(num*el.number for el, num in v.formula.atoms.items())
        electrons = protons - v.charge
        Xsld = pt.xray_sld(v.formula, wavelength=pt.Cu.K_alpha)
        print("%20s %7.1f %7.1f %7.1f %5.2f %5d %5.2f %5.2f %5.2f %5.1f"%(
            v.name, v.Hmass, v.Dmass, v.cell_volume, v.formula.density,
            electrons, Xsld[0], v.Hsld, v.Dsld, v.D2Omatch))
Exemplo n.º 12
0
    def calculate(self):
        try:
            formula = pt.formula(self.ui.chemical_formula.text(),)

        except (pyparsing.ParseException, TypeError, ValueError):
            return

        density = self.ui.mass_density.value()
        molecular_volume = self.ui.molecular_volume.value()
        neutron_wavelength = self.ui.neutron_wavelength.value()
        xray_energy = self.ui.xray_energy.value()

        if self.ui.use_volume.isChecked():
            density = formula.molecular_mass / formula.volume(
                a=molecular_volume,
                b=1,
                c=1)
            self.ui.mass_density.setValue(density)

        elif self.ui.use_density.isChecked():
            volume = formula.mass / density / \
                pt.constants.avogadro_number * 1e24
            self.ui.molecular_volume.setValue(volume)

        real, imag, mu = pt.neutron_sld(formula,
                                        density=density,
                                        wavelength=neutron_wavelength)

        self.ui.neutron_SLD.setText(
            '%.6g' %
            real +
            ' + ' +
            '%.6g' %
            imag +
            'j')

        real, imag = pt.xray_sld(formula,
                                 density=density,
                                 energy=xray_energy)

        self.ui.xray_SLD.setText('%.6g' % real + ' + ' + '%.6g' % imag + 'j')
Exemplo n.º 13
0
def cgi_call():
    form = cgi.FieldStorage()
    #print >>sys.stderr, form
    #print >>sys.stderr, "sample",form.getfirst('sample')
    #print >>sys.stderr, "mass",form.getfirst('mass')
    
    # Parse inputs
    errors = {};
    calculate = form.getfirst('calculate','all')
    if calculate not in ('scattering','activation','all'):
        errors['calculate'] = "calculate should be one of 'scattering', 'activation' or 'all'"
    try: chem = formula(form.getfirst('sample'))
    except: errors['sample'] = error()
    try: fluence = float(form.getfirst('flux',100000))
    except: errors['flux'] = error()
    try: fast_ratio = float(form.getfirst('fast','0'))
    except: errors['fast'] = error()
    try: Cd_ratio = float(form.getfirst('Cd','0'))
    except: errors['Cd'] = error()
    try: exposure = parse_hours(form.getfirst('exposure','1'))
    except: errors['exposure'] = error()
    try: 
        mass_str = form.getfirst('mass','1')
        if mass_str.endswith('kg'):
           mass = 1000*float(mass_str[:-2])
        elif mass_str.endswith('mg'):
           mass = 0.001*float(mass_str[:-2])
        elif mass_str.endswith('ug'):
           mass = 1e-6*float(mass_str[:-2])
        elif mass_str.endswith('g'):
           mass = float(mass_str[:-1])
        else:
           mass = float(mass_str)
    except: errors['mass'] = error()
    try: density_type,density_value = parse_density(form.getfirst('density','0'))
    except: errors['density'] = error()
    try: 
        #print >>sys.stderr,form.getlist('rest[]')
        rest_times = [parse_rest(v) for v in form.getlist('rest[]')]
        if not rest_times: rest_times = [0,1,24,360]
    except: errors['rest'] = error()
    try: decay_level = float(form.getfirst('decay','0.001'))
    except: errors['decay'] = error()
    try: thickness = float(form.getfirst('thickness', '1'))
    except: errors['thickness'] = error()
    try:
        wavelength_str = form.getfirst('wavelength','1').strip()
        if wavelength_str.endswith('meV'):
             wavelength = nsf.neutron_wavelength(float(wavelength_str[:-3]))
        elif wavelength_str.endswith('m/s'):
             wavelength = nsf.neutron_wavelength_from_velocity(float(wavelength_str[:-3]))
        elif wavelength_str.endswith('Ang'):
             wavelength = float(wavelength_str[:-3])
        else:
             wavelength = float(wavelength_str)
        #print >>sys.stderr,wavelength_str
    except: errors['wavelength'] = error()
    try:
        xray_source = form.getfirst('xray','Cu Ka').strip()
        if xray_source.endswith('Ka'):
            xray_wavelength = elements.symbol(xray_source[:-2].strip()).K_alpha
        elif xray_source.endswith('keV'):
            xray_wavelength = xsf.xray_wavelength(float(xray_source[:-3]))
        elif xray_source.endswith('Ang'):
            xray_wavelength = float(xray_source[:-3])
        elif xray_source[0].isalpha():
            xray_wavelength = elements.symbol(xray_source).K_alpha
        else:
            xray_wavelength = float(xray_source)
        #print >>sys.stderr,"xray",xray_source,xray_wavelength
    except: errors['xray'] = error()
    try:
        abundance_source = form.getfirst('abundance','IAEA')
        if abundance_source == "NIST":
            abundance = activation.NIST2001_isotopic_abundance
        elif abundance_source == "IAEA":
            abundance = activation.IAEA1987_isotopic_abundance
        else:
            raise ValueError("abundance should be NIST or IAEA")
    except: errors['abundance'] = error()
        

    if errors: return {'success':False, 'error':'invalid request', 'detail':errors}

    # Fill in defaults
    #print >>sys.stderr,density_type,density_value,chem.density
    if density_type == 'default' or density_value == 0:
        # default to a density of 1
        if chem.density is None: chem.density = 1
    elif density_type == 'volume':
        chem.density = chem.molecular_mass/density_value
    elif density_type == 'natural':
        # if density is given, assume it is for natural abundance
        chem.natural_density = density_value
    elif density_type == 'isotope':
        chem.density = density_value
    else:
        raise ValueError("unknown density type %r"%density_type)

    result = {'success': True}
    result['sample'] = {
            'formula': str(chem),
            'mass': mass,
            'density': chem.density,
            'thickness': thickness,
            'natural_density': chem.natural_density,
        }
        
    # Run calculations
    if calculate in ('activation', 'all'):
      try:
        env = activation.ActivationEnvironment(fluence=fluence,fast_ratio=fast_ratio, Cd_ratio=Cd_ratio)
        sample = activation.Sample(chem, mass=mass)
        sample.calculate_activation(env,exposure=exposure,rest_times=rest_times,abundance=abundance)
        decay_time = sample.decay_time(decay_level)
        total = [0]*len(sample.rest_times)
        rows = []
        for el,activity_el in activation.sorted_activity(sample.activity.items()):
            total = [t+a for t,a in zip(total,activity_el)]
            rows.append({'isotope':el.isotope,'reaction':el.reaction,'product':el.daughter,
                         'halflife':el.Thalf_str,'comments':el.comments,'levels':activity_el})
        result['activation'] = {
            'flux': fluence,
            'fast': fast_ratio,
            'Cd': Cd_ratio,
            'exposure': exposure,
            'rest': rest_times,
            'activity': rows, 
            'total': total,
            'decay_level': decay_level,
            'decay_time': decay_time,
        }
        #print >>sys.stderr,result
      except:
        result['activation'] = {"error": error()}
        
    #nsf_sears.replace_neutron_data()
    if calculate in ('scattering', 'all'):
      try: 
        sld,xs,penetration = neutron_scattering(chem, wavelength=wavelength)
        result['scattering'] = {
            'neutron': {
                'wavelength': wavelength,
                'energy': nsf.neutron_energy(wavelength),
                'velocity': nsf.VELOCITY_FACTOR/wavelength,
            },
            'xs': {'coh': xs[0], 'abs': xs[1], 'incoh': xs[2]},
            'sld': {'real': sld[0], 'imag': sld[1], 'incoh': sld[2]},
            'penetration': penetration,
            'transmission': 100*exp(-thickness/penetration),
        }
        
      except:
        missing = [str(el) for el in chem.atoms if not el.neutron.has_sld()]
        if any(missing):
            msg = "missing neutron cross sections for "+", ".join(missing)
        else:
            msg = error()
        result['scattering'] = {'error': msg }


      try: 
        xsld = xray_sld(chem, wavelength=xray_wavelength) 
        result['xray_scattering'] = {
            'xray': {
                'wavelength': xray_wavelength,
                'energy': xsf.xray_energy(xray_wavelength),
            },
            'sld': {'real': xsld[0], 'imag': xsld[1]},
        }
      except: 
        result['xray_scattering'] = {'error': error()}

    return result
Exemplo n.º 14
0
    fPt = formula("Pt")
    fNiFe = formula("Ni80Fe20",density=0.8*Ni.density+0.2*Fe.density)
    fFePt = formula("Fe55Pt45",density=0.55*Fe.density+0.45*Pt.density)
    # Note: we have been given the Cu K-alpha SLD of the glass substrate
    # but the formula itself was not provided.  The common glass
    # preparations below do not come close to matching the given SLD
    # unless density is lowered to about 1.85.  Since most glass has
    # a density in [2.2, 2.5], none of these formulas can be used, and we
    # will restrict ourselves to an approximate SLD provided by the grower.
    #fglass = formula("SiO2",density=2.2)
    #fglass = mix_by_weight('SiO2',75,'Na2O',15,'CaO',10,density=2.52)
    #fglass = mix_by_weight('SiO2',73,'B2O3',10,'Na2O',8,'K2O',8,'CaO',1,density=2.2)
    glass_sld = 15,0.5

    # Bulk SLD
    cap.rho.value, cap.irho.value = xray_sld(fPt, wavelength=Cu.K_alpha)
    NiFe.rho.value, NiFe.irho.value = xray_sld(fNiFe, wavelength=Cu.K_alpha)
    FePt.rho.value, FePt.irho.value = xray_sld(fFePt, wavelength=Cu.K_alpha)
    seed.rho.value, seed.irho.value = xray_sld(fFePt, wavelength=Cu.K_alpha)
    glass.rho.value,glass.irho_value = glass_sld

    # Expected thickness/interface
    Lseed.thickness.value =  15
    LFePt.thickness.value = 200
    LNiFe.thickness.value = 500
    Lcap.thickness.value =   25
    for i,L in enumerate(sample[1:-2]):
        L.interface.value = 10

# Fit parameters
#probe.theta_offset.dev(0.01)  # accurate to 0.01 degrees
Exemplo n.º 15
0
    fPt = formula("Pt")
    fNiFe = formula("Ni80Fe20", density=0.8 * Ni.density + 0.2 * Fe.density)
    fFePt = formula("Fe55Pt45", density=0.55 * Fe.density + 0.45 * Pt.density)
    # Note: we have been given the Cu K-alpha SLD of the glass substrate
    # but the formula itself was not provided.  The common glass
    # preparations below do not come close to matching the given SLD
    # unless density is lowered to about 1.85.  Since most glass has
    # a density in [2.2, 2.5], none of these formulas can be used, and we
    # will restrict ourselves to an approximate SLD provided by the grower.
    #fglass = formula("SiO2",density=2.2)
    #fglass = mix_by_weight('SiO2',75,'Na2O',15,'CaO',10,density=2.52)
    #fglass = mix_by_weight('SiO2',73,'B2O3',10,'Na2O',8,'K2O',8,'CaO',1,density=2.2)
    glass_sld = 15, 0.5

    # Bulk SLD
    cap.rho.value, cap.irho.value = xray_sld(fPt, wavelength=Cu.K_alpha)
    NiFe.rho.value, NiFe.irho.value = xray_sld(fNiFe, wavelength=Cu.K_alpha)
    FePt.rho.value, FePt.irho.value = xray_sld(fFePt, wavelength=Cu.K_alpha)
    seed.rho.value, seed.irho.value = xray_sld(fFePt, wavelength=Cu.K_alpha)
    glass.rho.value, glass.irho_value = glass_sld

    # Expected thickness/interface
    Lseed.thickness.value = 15
    LFePt.thickness.value = 200
    LNiFe.thickness.value = 500
    Lcap.thickness.value = 25
    for i, L in enumerate(sample[1:-2]):
        L.interface.value = 10

# Fit parameters
#probe.theta_offset.dev(0.01)  # accurate to 0.01 degrees