예제 #1
0
def exercise():
    from cctbx import factor_kev_angstrom
    w = wavelengths.characteristic("CU")
    assert w.label() == "Cu"
    assert approx_equal(w.as_angstrom(), 1.5418)
    assert approx_equal(w.as_kev(), factor_kev_angstrom / 1.5418)
    assert approx_equal(w.as_ev() / 1000, factor_kev_angstrom / 1.5418)
    n = 0
    for w in wavelengths.characteristic_iterator():
        n += 1
        uu = wavelengths.characteristic(w.label())
        assert uu.label() == w.label()
        assert uu.as_ev() == w.as_ev()
    assert n == 15
예제 #2
0
def exercise():
  from cctbx import factor_kev_angstrom
  w = wavelengths.characteristic("CU")
  assert w.label() == "Cu"
  assert approx_equal(w.as_angstrom(), 1.5418)
  assert approx_equal(w.as_kev(), factor_kev_angstrom / 1.5418)
  assert approx_equal(w.as_ev() / 1000, factor_kev_angstrom / 1.5418)
  n = 0
  for w in wavelengths.characteristic_iterator():
    n += 1
    uu = wavelengths.characteristic(w.label())
    assert uu.label() == w.label()
    assert uu.as_ev() == w.as_ev()
  assert n == 15
예제 #3
0
def run (args) :
  if (len(args) == 0) or ("--help" in args) :
    raise Usage("""
eltbx.show_fp_fdp.py --elements=S,CL --wavelength=1.54
eltbx.show_fp_fdp.py --elements=S,CL --source=CuA1""")
  parser = option_parser()
  parser.add_option('--elements')
  parser.add_option('--xray_source')
  parser.add_option('--wavelength')
  options, args = parser.parse_args(args)

  if (options.xray_source is not None) :
    print "Source: %s" % options.xray_source
  elif (options.wavelength is not None) :
    print "Wavelength: %g Angstrom" % float(options.wavelength)
  print
  for element in options.elements.split(','):
    print "Element: %s" % element
    fdp = []
    for table_name, table in (('Henke et al.', henke.table),
                              ('Sasaki et al.', sasaki.table)):
      inelastic_scattering = table(element)
      if (options.xray_source) :
        fp_fdp = inelastic_scattering.at_angstrom(
          wavelengths.characteristic(options.xray_source).as_angstrom())
      elif (options.wavelength) :
        fp_fdp = inelastic_scattering.at_angstrom(float(options.wavelength))
      else :
        raise Sorry("Either --xray_source=... or --wavelength=... required")
      print "  %-14s: f'=%-9.6g, f''=%-9.6f" % (
        table_name, fp_fdp.fp(), fp_fdp.fdp())
      fdp.append(fp_fdp.fdp())
    print "  diff f''=%.2f %%" % ((fdp[1] - fdp[0])/(fdp[1] + fdp[0]) * 100)
예제 #4
0
def to_diffraction_pattern(crystal_structure, wavelength='Cu'):
    """
    Args:
        wavelength = (Cr, Fe, Cu, Mo, Ag)

    Return structure:
        {'wavelength':wavelength, 'meta':['d_spacing', 'two_theta', 'amplitude', 'hkl'], 'data':[]}

    Wavelengths from cctbx/eltbx/wavelengths.cpp
    // BEGIN_COMPILED_IN_REFERENCE_DATA
          {"CrA1", 2.28970}, {"CrA2", 2.29361}, {"Cr", 2.2909},
          {"FeA1", 1.93604}, {"FeA2", 1.93998}, {"Fe", 1.9373},
          {"CuA1", 1.54056}, {"CuA2", 1.54439}, {"Cu", 1.5418},
          {"MoA1", 0.70930}, {"MoA2", 0.71359}, {"Mo", 0.7107},
          {"AgA1", 0.55941}, {"AgA2", 0.56380}, {"Ag", 0.5608},
          {"", 0}
    // END_COMPILED_IN_REFERENCE_DATA
    """

    #d_min = 3
    # f_calc is the intensity?
    # Need to sanatize the Site labels !!

    miller_indices = crystal_structure.build_miller_set(anomalous_flag=False,
                                                        d_min=1,
                                                        d_max=20)
    wavelength_in_ang = wavelengths.characteristic(wavelength).as_angstrom()
    unit_cell = crystal_structure.unit_cell()
    pattern = []
    f_calc = crystal_structure.structure_factors(d_min=1,
                                                 algorithm="direct").f_calc()
    for hkl, j in zip(f_calc.indices(), f_calc.data()):
        two_theta = unit_cell.two_theta(hkl, wavelength_in_ang, deg=True)
        d = unit_cell.d(hkl)
        #print hkl, d, abs(j), two_theta
        #xrds.append({"hkl":list(hkl), "amplitude":abs(j), "d-spacing":d, "two_theta":two_theta})
        pattern.append([abs(j), list(hkl), two_theta, d])

    #return xrds
    '''
    f_calc = crystal_structure.structure_factors(d_min=d_min).f_calc()
    millers = crystal_structure.structure_factors(d_min=d_min).miller_set()
    miller_indices =  millers.indices()
    wavelength = wavelengths.characteristic('CU').as_angstrom()
    two_thetas = crystal_structure.unit_cell().two_theta(millers.indices(), wavelength, deg=True)
    d_spacings = f_calc.d_spacings()
    unit_cell = c.crystal_structure.unit_cell()
    '''
    d = {
        'wavelength': {
            'element': wavelength,
            'in_angstroms': wavelength_in_ang
        },
        'meta': ['amplitude', 'hkl', 'two_theta', 'd_spacing'],
        'pattern': pattern
    }
    return d
예제 #5
0
def run(args):
    two_thetas_obs = flex.double()
    miller_indices = flex.miller_index()
    for line in two_theta_and_index_list:
        fields = line.split()
        assert len(fields) == 4
        two_thetas_obs.append(float(fields[0]))
        miller_indices.append([int(s) for s in fields[1:]])

    wavelength = wavelengths.characteristic("CU").as_angstrom()
    unit_cell_start = uctbx.unit_cell((10, 10, 10, 80, 100, 80))
    show_fit(two_thetas_obs, miller_indices, wavelength, unit_cell_start)

    refined_accu = []
    assert len(args) in [0, 1]
    if (len(args) != 0):
        arg = args[0]
        if (arg.find(",") > 0):
            modes = eval("[" + arg + "]")
        elif (arg.find(":") > 0):
            modes = eval("range(" + arg.replace(":", ",") + "+1)")
        else:
            modes = [eval(arg)]
    else:
        modes = range(8)
    print "modes:", modes
    print
    for mode in modes:
        refined = refinery(two_thetas_obs,
                           miller_indices,
                           wavelength,
                           unit_cell_start,
                           mode=mode)
        refined_accu.append(refined)
        print

    p = open("tmp.xy", "w")
    print >> p, "@with g0"
    print >> p, '@ title "%s"' % "\\n".join(
        [platform.platform(), platform.node()])
    for i, r in enumerate(refined_accu):
        print >> p, '@ s%d legend "%s"' % (i, r.plot_legend)
        print >> p, '@ s%d symbol 1' % i
    for refined in refined_accu:
        for x, y in enumerate(refined.functionals):
            if (x > 15): break
            print >> p, x, y
        print >> p, "&"
    del p

    if (0):
        show_fit(two_thetas_obs, miller_indices, wavelength,
                 refined.unit_cell())

    print refined.unit_cell()
    print
    print libtbx.utils.format_cpu_times()
예제 #6
0
def rietveld_refine_structure(
        crystalstructure,
        wavelength=wavelengths.characteristic("CU").as_angstrom(),
        I_obs=None,
        Profile=None,
        ProfileFile=None):
    """This function tries to rietveld refine a structure using FullProf.

  If I_obs is given neither a Profile or a ProfileFile may be specified.
  'Profile' and 'ProfileFile' are also exclusive.

  :param crystalstructure: the starting model for the refinement
  :type crystalstructure: cctbx.xray.structure
  :param wavelength: the x-ray wavelength for the given intensity data
  :type wavelength: float
  :param I_obs: observed Intensities
  :type I_obs: cctbx.miller
  :param Profile: a XRD profile given as a list/tuple of (2-theta, intensity)-tuples
  :type Profile: list/tuple(tuple(2theta,I))
  :param ProfileFile: path to a XRD profile as FullProf .prf file
  :type ProfileFile: string
  """
    # Check preconditions
    if [I_obs, Profile, ProfileFile].count(None) != 2:
        raise ValueError(
            "You may only pass one of I_obs, Profile and ProfileFile")
    # start work
    from iotbx.write_pcr import write_pcr
    import tempfile
    import shutil
    import os
    # write pcr file and execute FullProf
    try:
        f = tempfile.NamedTemporaryFile(suffix=".pcr", delete=False)
    except IOError:
        raise
    pcrfile = f.name
    basepath = os.path.splitext(pcrfile)[0]
    write_pcr(f,
              crystalstructure,
              jobtype=0,
              wavelength=wavelength,
              I_obs=I_obs)
    f.close()
    try:
        if ProfileFile is not None:
            shutil.copyfile(ProfileFile, basepath + ".dat")
        elif Profile is not None:
            # write out profile file for FullProf
            # XXX: todo implement
            pass
    except IOError:
        raise
    run_fullprof(pcrfile, verbose=0)
    # XXX Todo: extract refined structure from resulting .pcr/.new
    # XXX Todo: extract Rwp of refined structure from resulting .pcr/.new
    return None, None
def run(args):
  two_thetas_obs = flex.double()
  miller_indices = flex.miller_index()
  for line in two_theta_and_index_list:
    fields = line.split()
    assert len(fields) == 4
    two_thetas_obs.append(float(fields[0]))
    miller_indices.append([int(s) for s in fields[1:]])

  wavelength = wavelengths.characteristic("CU").as_angstrom()
  unit_cell_start = uctbx.unit_cell((10,10,10,80,100,80))
  show_fit(
    two_thetas_obs, miller_indices, wavelength, unit_cell_start)

  refined_accu = []
  assert len(args) in [0,1]
  if (len(args) != 0):
    arg = args[0]
    if (arg.find(",") > 0):
      modes = eval("["+arg+"]")
    elif (arg.find(":") > 0):
      modes = eval("range("+arg.replace(":",",")+"+1)")
    else:
      modes = [eval(arg)]
  else:
    modes = range(8)
  print "modes:", modes
  print
  for mode in modes:
    refined = refinery(
      two_thetas_obs, miller_indices, wavelength, unit_cell_start, mode=mode)
    refined_accu.append(refined)
    print

  p = open("tmp.xy", "w")
  print >> p, "@with g0"
  print >> p, '@ title "%s"' % "\\n".join([
    platform.platform(),
    platform.node()])
  for i,r in enumerate(refined_accu):
    print >> p, '@ s%d legend "%s"' % (i, r.plot_legend)
    print >> p, '@ s%d symbol 1' % i
  for refined in refined_accu:
    for x,y in enumerate(refined.functionals):
      if (x > 15): break
      print >> p, x,y
    print >> p, "&"
  del p

  if (0):
    show_fit(
      two_thetas_obs, miller_indices, wavelength, refined.unit_cell())

  print refined.unit_cell()
  print
  print libtbx.utils.format_cpu_times()
예제 #8
0
def rietveld_refine_structure(crystalstructure,
                      wavelength=wavelengths.characteristic("CU").as_angstrom(),
                      I_obs=None, Profile=None, ProfileFile=None):
  """This function tries to rietveld refine a structure using FullProf.

  If I_obs is given neither a Profile or a ProfileFile may be specified.
  'Profile' and 'ProfileFile' are also exclusive.

  :param crystalstructure: the starting model for the refinement
  :type crystalstructure: cctbx.xray.structure
  :param wavelength: the x-ray wavelength for the given intensity data
  :type wavelength: float
  :param I_obs: observed Intensities
  :type I_obs: cctbx.miller
  :param Profile: a XRD profile given as a list/tuple of (2-theta, intensity)-tuples
  :type Profile: list/tuple(tuple(2theta,I))
  :param ProfileFile: path to a XRD profile as FullProf .prf file
  :type ProfileFile: string
  """
  # Check preconditions
  if [I_obs, Profile, ProfileFile].count(None) != 2:
    raise(ValueError("You may only pass one of I_obs, Profile and ProfileFile"))
  # start work
  from write_pcr import write_pcr
  import tempfile
  import shutil
  import os
  # write pcr file and execute FullProf
  try:
    f = tempfile.NamedTemporaryFile(suffix=".pcr", delete=False)
  except IOError: raise
  pcrfile = f.name
  basepath = os.path.splitext(pcrfile)[0]
  write_pcr(f, crystalstructure, jobtype=0,
            wavelength=wavelength, I_obs=I_obs)
  f.close()
  try:
    if ProfileFile is not None:
      shutil.copyfile(ProfileFile, basepath+".dat")
    elif Profile is not None:
      # write out profile file for FullProf
      # XXX: todo implement
      pass
  except IOError: raise
  run_fullprof(pcrfile, verbose=0)
  # XXX Todo: extract refined structure from resulting .pcr/.new
  # XXX Todo: extract Rwp of refined structure from resulting .pcr/.new
  return None, None
예제 #9
0
파일: utils.py 프로젝트: mpkocher/abitbx
def to_diffraction_pattern(crystal_structure, wavelength='Cu'):
    """
    Args:
        wavelength = (Cr, Fe, Cu, Mo, Ag)

    Return structure:
        {'wavelength':wavelength, 'meta':['d_spacing', 'two_theta', 'amplitude', 'hkl'], 'data':[]}

    Wavelengths from cctbx/eltbx/wavelengths.cpp
    // BEGIN_COMPILED_IN_REFERENCE_DATA
          {"CrA1", 2.28970}, {"CrA2", 2.29361}, {"Cr", 2.2909},
          {"FeA1", 1.93604}, {"FeA2", 1.93998}, {"Fe", 1.9373},
          {"CuA1", 1.54056}, {"CuA2", 1.54439}, {"Cu", 1.5418},
          {"MoA1", 0.70930}, {"MoA2", 0.71359}, {"Mo", 0.7107},
          {"AgA1", 0.55941}, {"AgA2", 0.56380}, {"Ag", 0.5608},
          {"", 0}
    // END_COMPILED_IN_REFERENCE_DATA
    """

    #d_min = 3
    # f_calc is the intensity?
    # Need to sanatize the Site labels !!

    miller_indices = crystal_structure.build_miller_set(anomalous_flag=False, d_min=1, d_max=20)
    wavelength_in_ang = wavelengths.characteristic(wavelength).as_angstrom()
    unit_cell = crystal_structure.unit_cell()
    pattern = []
    f_calc = crystal_structure.structure_factors(d_min=1, algorithm="direct").f_calc()
    for hkl, j in zip(f_calc.indices(), f_calc.data()):
        two_theta = unit_cell.two_theta(hkl, wavelength_in_ang, deg=True)
        d = unit_cell.d(hkl)
        #print hkl, d, abs(j), two_theta
        #xrds.append({"hkl":list(hkl), "amplitude":abs(j), "d-spacing":d, "two_theta":two_theta})
        pattern.append([abs(j), list(hkl), two_theta, d])

    #return xrds

    '''
    f_calc = crystal_structure.structure_factors(d_min=d_min).f_calc()
    millers = crystal_structure.structure_factors(d_min=d_min).miller_set()
    miller_indices =  millers.indices()
    wavelength = wavelengths.characteristic('CU').as_angstrom()
    two_thetas = crystal_structure.unit_cell().two_theta(millers.indices(), wavelength, deg=True)
    d_spacings = f_calc.d_spacings()
    unit_cell = c.crystal_structure.unit_cell()
    '''
    d = {'wavelength':{'element':wavelength, 'in_angstroms': wavelength_in_ang}, 'meta':['amplitude', 'hkl', 'two_theta', 'd_spacing'], 'pattern':pattern}
    return d
예제 #10
0
def write_pcr(s,
              phases,
              title="unnamed",
              jobtype=0,
              nprof=0,
              nbckgd=0,
              wavelength=wavelengths.characteristic("CU").as_angstrom(),
              I_obs=None,
              scale_down=1.0):
    """Write a pcr file to a file or IO buffer.

  :param s: a buffer/file to write to
  :type s: StringIO or filestream
  :param phases: a list/tuple/set of structures or a single crystal structucture
  :type phases: list(cctbx.xray_structure) or cctbx.xray_structure
  :param title: a title to be used in the pcr file
  :type title: string
  :param jobtype: the jobtype to be used (0=xray refine, 2=xray powdersim)
  :type jobtype: integer
  :param nprof: the default peak profile to be used
  :type nprof: integer
  :param nbckgd: the type of background to be used
  :type nbckgd: integer
  :param wavelength: the wavelength to be used in Angstroms
  :type wavelength: float
  :param I_obs: observed intensities
  :type I_obs: cctbx.miller
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float
  """
    # handle case of being called with only one phase
    if not isinstance(phases, (tuple, list, set)):
        phases = (phases, )

    # XXX Todo: handle case of given I_obs (= refine without a full profile)
    pcrfile = _pcr_skelleton(phases=phases,
                             title=title,
                             jobtype=jobtype,
                             nprof=nprof,
                             nbckgd=nbckgd,
                             scale_down=scale_down)
    if jobtype == 2:
        pcrfile = _set_ref_flags(pcrfile)
    else:
        pcrfile = _set_ref_flags(pcrfile,
                                 freeparams=["scale", "lattice", "profile"])
    print(pcrfile, file=s)
예제 #11
0
def write_pcr(s,
              phases,
              title="unnamed",
              jobtype=0,
              nprof=0,
              nbckgd=0,
              wavelength=wavelengths.characteristic("CU").as_angstrom(),
              I_obs=None,
              scale_down=1.0):
  """Write a pcr file to a file or IO buffer.

  :param s: a buffer/file to write to
  :type s: StringIO or filestream
  :param phases: a list/tuple/set of structures or a single crystal structucture
  :type phases: list(cctbx.xray_structure) or cctbx.xray_structure
  :param title: a title to be used in the pcr file
  :type title: string
  :param jobtype: the jobtype to be used (0=xray refine, 2=xray powdersim)
  :type jobtype: integer
  :param nprof: the default peak profile to be used
  :type nprof: integer
  :param nbckgd: the type of background to be used
  :type nbckgd: integer
  :param wavelength: the wavelength to be used in Angstroms
  :type wavelength: float
  :param I_obs: observed intensities
  :type I_obs: cctbx.miller
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float
  """
  # handle case of being called with only one phase
  if not isinstance(phases, (tuple, list, set)):
    phases = (phases, )

  # XXX Todo: handle case of given I_obs (= refine without a full profile)
  pcrfile = _pcr_skelleton(phases=phases,
                  title=title,
                  jobtype=jobtype,
                  nprof=nprof,
                  nbckgd=nbckgd,
                  scale_down=scale_down)
  if jobtype == 2:
    pcrfile = _set_ref_flags(pcrfile)
  else:
    pcrfile = _set_ref_flags(pcrfile, freeparams=["scale","lattice","profile"])
  print(pcrfile, file=s)
예제 #12
0
def run():
    two_thetas_obs = flex.double()
    miller_indices = flex.miller_index()
    for line in two_theta_and_index_list:
        fields = line.split()
        assert len(fields) == 4
        two_thetas_obs.append(float(fields[0]))
        miller_indices.append([int(s) for s in fields[1:]])

    wavelength = wavelengths.characteristic("CU").as_angstrom()
    unit_cell_start = uctbx.unit_cell((10, 10, 10, 90, 90, 90))
    show_fit(two_thetas_obs, miller_indices, wavelength, unit_cell_start)

    refined = refinery(two_thetas_obs, miller_indices, wavelength,
                       unit_cell_start)
    print()

    show_fit(two_thetas_obs, miller_indices, wavelength, refined.unit_cell())

    print(refined.unit_cell())
    print()
    print(libtbx.utils.format_cpu_times())
예제 #13
0
def run(args):
    if (len(args) == 0) or ("--help" in args):
        raise Usage("""
eltbx.show_fp_fdp.py --elements=S,CL --wavelength=1.54
eltbx.show_fp_fdp.py --elements=S,CL --source=CuA1""")
    parser = option_parser()
    parser.add_option('--elements')
    parser.add_option('--xray_source')
    parser.add_option('--wavelength')
    options, args = parser.parse_args(args)

    if (options.xray_source is not None):
        print("Source: %s" % options.xray_source)
    elif (options.wavelength is not None):
        print("Wavelength: %g Angstrom" % float(options.wavelength))
    print()
    for element in options.elements.split(','):
        print("Element: %s" % element)
        fdp = []
        for table_name, table in (('Henke et al.', henke.table),
                                  ('Sasaki et al.', sasaki.table)):
            inelastic_scattering = table(element)
            if (options.xray_source):
                fp_fdp = inelastic_scattering.at_angstrom(
                    wavelengths.characteristic(
                        options.xray_source).as_angstrom())
            elif (options.wavelength):
                fp_fdp = inelastic_scattering.at_angstrom(
                    float(options.wavelength))
            else:
                raise Sorry(
                    "Either --xray_source=... or --wavelength=... required")
            print("  %-14s: f'=%-9.6g, f''=%-9.6f" %
                  (table_name, fp_fdp.fp(), fp_fdp.fdp()))
            fdp.append(fp_fdp.fdp())
        print("  diff f''=%.2f %%" % ((fdp[1] - fdp[0]) /
                                      (fdp[1] + fdp[0]) * 100))
예제 #14
0
def run():
  two_thetas_obs = flex.double()
  miller_indices = flex.miller_index()
  for line in two_theta_and_index_list:
    fields = line.split()
    assert len(fields) == 4
    two_thetas_obs.append(float(fields[0]))
    miller_indices.append([int(s) for s in fields[1:]])

  wavelength = wavelengths.characteristic("CU").as_angstrom()
  unit_cell_start = uctbx.unit_cell((10,10,10,90,90,90))
  show_fit(
    two_thetas_obs, miller_indices, wavelength, unit_cell_start)

  refined = refinery(
    two_thetas_obs, miller_indices, wavelength, unit_cell_start)
  print

  show_fit(
    two_thetas_obs, miller_indices, wavelength, refined.unit_cell())

  print refined.unit_cell()
  print
  print libtbx.utils.format_cpu_times()
예제 #15
0
def generator(xray_structure,
              data_are_intensities=True,
              title=None,
              wavelength=None,
              temperature=None,
              full_matrix_least_squares_cycles=None,
              conjugate_gradient_least_squares_cycles=None,
              overall_scale_factor=None,
              weighting_scheme_params=None,
              sort_scatterers=True,
              unit_cell_dims=None,
              unit_cell_esds=None):
    space_group = xray_structure.space_group()
    assert not space_group.is_centric() or space_group.is_origin_centric(),\
           centric_implies_centrosymmetric_error_msg
    assert [
        full_matrix_least_squares_cycles,
        conjugate_gradient_least_squares_cycles
    ].count(None) in (0, 1)
    if title is None:
        title = '????'
    if wavelength is None:
        wavelength = wavelengths.characteristic('Mo').as_angstrom()
    sgi = xray_structure.space_group_info()
    uc = xray_structure.unit_cell()

    yield 'TITL %s in %s\n' % (title, sgi.type().lookup_symbol())
    if unit_cell_dims is None:
        unit_cell_dims = uc.parameters()
    yield 'CELL %.5f %s\n' % (wavelength,
                              ' '.join(('%.4f ', ) * 3 +
                                       ('%.3f', ) * 3) % unit_cell_dims)
    if unit_cell_esds:
        yield 'ZERR %i %f %f %f %f %f %f\n' % (
            (sgi.group().order_z(), ) + unit_cell_esds)
    else:
        yield 'ZERR %i 0. 0. 0. 0. 0. 0.\n' % sgi.group().order_z()

    latt = 1 + 'PIRFABC'.find(sgi.group().conventional_centring_type_symbol())
    if not space_group.is_origin_centric(): latt = -latt
    yield 'LATT %i\n' % latt
    for i in xrange(space_group.n_smx()):
        rt_mx = space_group(0, 0, i)
        if rt_mx.is_unit_mx(): continue
        yield 'SYMM %s\n' % rt_mx
    yield '\n'

    uc_content = xray_structure.unit_cell_content()
    for e in uc_content:
        uc_content[e] = "%.1f" % uc_content[e]
    sfac = []
    unit = []
    prior = ('C', 'H')
    for e in prior:
        if e in uc_content:
            sfac.append(e)
            unit.append(uc_content[e])
    dsu = [(tiny_pse.table(e).atomic_number(), e) for e in uc_content]
    dsu.sort()
    sorted = [item[-1] for item in dsu]
    for e in sorted:
        if (e not in prior):
            sfac.append(e)
            unit.append(uc_content[e])
    yield 'SFAC %s\n' % ' '.join(sfac)
    for e in sfac:
        yield 'DISP %s 0 0 0\n' % e
    yield 'UNIT %s\n' % ' '.join(unit)
    sf_idx = dict([(e, i + 1) for i, e in enumerate(sfac)])
    yield '\n'

    if temperature:
        yield 'TEMP %.0f\n' % temperature

    if full_matrix_least_squares_cycles:
        yield 'L.S. %i\n' % full_matrix_least_squares_cycles

    if conjugate_gradient_least_squares_cycles:
        yield 'CGLS %i\n' % conjugate_gradient_least_squares_cycles

    yield '\n'

    if weighting_scheme_params is not None:
        if (isinstance(weighting_scheme_params, str)):
            yield 'WGHT %s\n' % weighting_scheme_params
        else:
            a, b = weighting_scheme_params
            if b is None:
                yield 'WGHT %.6f\n' % a
            else:
                yield 'WGHT %.6f %.6f\n' % (a, b)

    if overall_scale_factor is not None:
        yield 'FVAR %.8f\n' % overall_scale_factor

    fmt_tmpl = ('%-4s', '%2i') + ('%11.6f', ) * 3 + ('%11.5f', )
    fmt_iso = ' '.join(fmt_tmpl + ('%10.5f', ))
    fmt_aniso = ' '.join(fmt_tmpl + ('%.5f', ) * 2 + ('=\n ', ) +
                         ('%.5f', ) * 4)
    if sort_scatterers:
        dsu = [(tiny_pse.table(sc.scattering_type).atomic_number(), sc)
               for sc in xray_structure.scatterers()]
        dsu.sort(reverse=True)
        scatterers = flex.xray_scatterer([item[-1] for item in dsu])
    else:
        scatterers = xray_structure.scatterers()
    atomname_set = set()
    for sc in scatterers:
        assert sc.fp == 0  # not implemented
        assert sc.fdp == 0  # not implemented
        assert sc.flags.use_u_iso() ^ sc.flags.use_u_aniso(),\
               both_iso_and_aniso_in_use_error_msg
        atomname = sc.label.strip()
        assert len(atomname) != 0
        assert len(atomname) <= 4
        if (atomname in atomname_set):
            raise RuntimeError('Duplicate atom name: "%s"' % atomname)
        atomname_set.add(atomname)
        params = (atomname, sf_idx[sc.scattering_type]) + sc.site
        occ = sc.weight()
        if not sc.flags.grad_occupancy(): occ += 10
        params += (occ, )
        if sc.flags.use_u_iso():
            yield fmt_iso % (params + (sc.u_iso, )) + "\n"
        else:
            u11, u22, u33, u12, u13, u23 = adptbx.u_star_as_u_cif(
                uc, sc.u_star)
            yield fmt_aniso % (params + (u11, u22, u33, u23, u13, u12)) + "\n"

    if data_are_intensities: hklf = 4
    else: hklf = 3
    yield 'HKLF %i\n' % hklf
예제 #16
0
def _pcr_skelleton(phases,
                  title="unnamed",
                  jobtype=0,
                  nprof=0,
                  nbckgd=0,
                  wavelength=wavelengths.characteristic("CU").as_angstrom(),
                  scale_down=1.0):
  """Create a pcr skelleton with placeholder strings for different refinement
  options.

  (for internal use)

  :param phases: a list/tuple/set of structures
  :type phases: list(cctbx.xray_structure)
  :param title: a title to be used in the pcr file
  :type title: string
  :param jobtype: the jobtype to be used
  :type jobtype: integer
  :param nprof: the default peak profile to be used
  :type nprof: integer
  :param nbckgd: the type of background to be used
  :type nbckgd: integer
  :param wavelength: the wavelength to be used in Angstroms
  :type wavelength: float
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float

  :returns: the pcr skelleton as a string
  :rtype: string
  """
  nphase = len(phases)

  ret = "COMM " + title + "\n"
  ret += """\
!Job Npr Nph Nba Nex Nsc Nor Dum Iwg Ilo Ias Res Ste Nre Cry Uni Cor Opt Aut
  {0}   {1}   {2}   {3}   0   0   0   {dum}   0   0   0   0   0   0   0   0   0   0   1
""".format(jobtype,nprof,nphase,nbckgd,dum=1 if jobtype == 2 else 0)
  ret += """\
!
!Ipr Ppl Ioc Mat Pcr Ls1 Ls2 Ls3 Syo Prf Ins Rpa Sym Hkl Fou Sho Ana
  2   0   1   1   1   0   0   0   1   1  {filetype}   0   1   4   2   0   0
!
! lambda1 Lambda2    Ratio    Bkpos    Wdt    Cthm     muR   AsyLim   Rpolarz ->Patt# 1
 {xlambda} {xlambda}  1.0000   60.000  5.0000  0.0000  0.0000   50.00    0.0000
!
!NCY  Eps  R_at  R_an  R_pr  R_gl     Thmin       Step       Thmax    PSD    Sent0
 20  0.01  1.00  1.00  1.00  1.00     10.0000   0.100000   100.0000   0.000   0.000
!
!
  #__npar__#    !Number of refined parameters
""".format(filetype="0", xlambda=wavelength)
  ret += """\
!
!  Zero    Code    SyCos    Code   SySin    Code  Lambda     Code MORE ->Patt# 1
  0.00000    0.0  0.00000    0.0  0.00000    0.0 0.000000    0.00   0
!   Background coefficients/codes  for Pattern#  1  (Polynomial of 6th degree)
       0.000       0.000       0.000       0.000       0.000       0.000
        0.00        0.00        0.00        0.00        0.00        0.00
"""
  for i in range(nphase):
    ret += _make_phase_block(phases[i], number=i+1, name="", scale_down=scale_down)
  return ret
예제 #17
0
def simulate_powder_pattern(crystalstructure,
                     wavelength=wavelengths.characteristic("CU").as_angstrom(),
                     filename="",
                     keep_results=False,
                     scale_down=1.0):
  """
  Get integrated intensities and a a simulated XRD profile calculated with
  FullProf (has to be installed and callable via "fp2k").

  :param crystalstructure: a crystal structure to calculate the intensities for
  :type crystalstructure: cctbx.xray.structure
  :param wavelength: x-ray wavelength in angstroms
  :type wavelength: float
  :param filename: a filepath to save the in- and output of FullProf to
  :type filename: string
  :param keep_results: keep the (temporary) files from FullProf for a later \
  manual inspection
  :type keep_results: boolean
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float

  :returns: calculated integral intensities, calculated profile
  :rtype: cctbx.miller, list(tuple(float,int))

  XXX Todo: implement extraction of calculated profile
  """
  from write_pcr import write_pcr
  from iotbx.reflection_file_reader import any_reflection_file
  import tempfile
  import os
  # write pcr file and execute FullProf
  try:
    if filename == "":
      f = tempfile.NamedTemporaryFile(suffix=".pcr", delete=False)
    else:
      f = open(filename, "w")
  except IOError: raise
  pcrfile = f.name
  basepath = os.path.splitext(pcrfile)[0]
  write_pcr(f, crystalstructure, jobtype=2,
            wavelength=wavelength, scale_down=scale_down)
  f.close()
  if scale_down > 10000: raise
  run_fullprof(pcrfile, verbose=0)

  # fix hkl file for hkl reader
  hklfile = basepath + ".fou"
  f = open(hklfile, "r")
  lines = f.readlines()[1:]
  f.close()
  hklfile = basepath + ".hkl"
  if keep_results == True:
    os.rename(hklfile, basepath + ".hkldata")   # backup old hkl file
  f = open(hklfile, "w")
  f.writelines(lines)
  f.close()

  # extract intensities
  f_calc = None
  try:
    rf = any_reflection_file(file_name=hklfile)
    f_calc = rf.as_miller_arrays(
                          crystal_symmetry=crystalstructure.crystal_symmetry(),
                          assume_shelx_observation_type_is="intensities")[0]
  except KeyboardInterrupt: raise
  except Exception:
    # an overflow occured
    return simulate_powder_pattern(crystalstructure, wavelength=wavelength,
                                   filename=filename, keep_results=keep_results,
                                   scale_down=scale_down*10.0)
  profile = None

  # clean up
  if keep_results == False:
    for ext in [".pcr", ".sym", ".fou", ".ins", ".prf", ".sim", ".sum", ".out",
                ".hkl", ".hkldata", "1.fst", "1.sub"]:
      try:
        os.unlink(basepath + ext)
      except KeyboardInterrupt: raise
      except Exception: pass

  return f_calc, profile
예제 #18
0
def simulate_powder_pattern(
        crystalstructure,
        wavelength=wavelengths.characteristic("CU").as_angstrom(),
        filename="",
        keep_results=False,
        scale_down=1.0):
    """
  Get integrated intensities and a a simulated XRD profile calculated with
  FullProf (has to be installed and callable via "fp2k").

  :param crystalstructure: a crystal structure to calculate the intensities for
  :type crystalstructure: cctbx.xray.structure
  :param wavelength: x-ray wavelength in angstroms
  :type wavelength: float
  :param filename: a filepath to save the in- and output of FullProf to
  :type filename: string
  :param keep_results: keep the (temporary) files from FullProf for a later \
  manual inspection
  :type keep_results: boolean
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float

  :returns: calculated integral intensities, calculated profile
  :rtype: cctbx.miller, list(tuple(float,int))

  XXX Todo: implement extraction of calculated profile
  """
    from iotbx.write_pcr import write_pcr
    from iotbx.reflection_file_reader import any_reflection_file
    import tempfile
    import os
    # write pcr file and execute FullProf
    try:
        if filename == "":
            f = tempfile.NamedTemporaryFile(suffix=".pcr", delete=False)
        else:
            f = open(filename, "w")
    except IOError:
        raise
    pcrfile = f.name
    basepath = os.path.splitext(pcrfile)[0]
    write_pcr(f,
              crystalstructure,
              jobtype=2,
              wavelength=wavelength,
              scale_down=scale_down)
    f.close()
    if scale_down > 10000: raise
    run_fullprof(pcrfile, verbose=0)

    # fix hkl file for hkl reader
    hklfile = basepath + ".fou"
    f = open(hklfile, "r")
    lines = f.readlines()[1:]
    f.close()
    hklfile = basepath + ".hkl"
    if keep_results == True:
        os.rename(hklfile, basepath + ".hkldata")  # backup old hkl file
    f = open(hklfile, "w")
    f.writelines(lines)
    f.close()

    # extract intensities
    f_calc = None
    try:
        rf = any_reflection_file(file_name=hklfile)
        f_calc = rf.as_miller_arrays(
            crystal_symmetry=crystalstructure.crystal_symmetry(),
            assume_shelx_observation_type_is="intensities")[0]
    except KeyboardInterrupt:
        raise
    except Exception:
        # an overflow occured
        return simulate_powder_pattern(crystalstructure,
                                       wavelength=wavelength,
                                       filename=filename,
                                       keep_results=keep_results,
                                       scale_down=scale_down * 10.0)
    profile = None

    # clean up
    if keep_results == False:
        for ext in [
                ".pcr", ".sym", ".fou", ".ins", ".prf", ".sim", ".sum", ".out",
                ".hkl", ".hkldata", "1.fst", "1.sub"
        ]:
            try:
                os.unlink(basepath + ext)
            except KeyboardInterrupt:
                raise
            except Exception:
                pass

    return f_calc, profile
예제 #19
0
def _pcr_skelleton(phases,
                  title="unnamed",
                  jobtype=0,
                  nprof=0,
                  nbckgd=0,
                  wavelength=wavelengths.characteristic("CU").as_angstrom(),
                  scale_down=1.0):
  """Create a pcr skelleton with placeholder strings for different refinement
  options.

  (for internal use)

  :param phases: a list/tuple/set of structures
  :type phases: list(cctbx.xray_structure)
  :param title: a title to be used in the pcr file
  :type title: string
  :param jobtype: the jobtype to be used
  :type jobtype: integer
  :param nprof: the default peak profile to be used
  :type nprof: integer
  :param nbckgd: the type of background to be used
  :type nbckgd: integer
  :param wavelength: the wavelength to be used in Angstroms
  :type wavelength: float
  :param scale_down: factor to divide intensities by (to avoid overflows)
  :type scale_down: float

  :returns: the pcr skelleton as a string
  :rtype: string
  """
  nphase = len(phases)

  ret = "COMM " + title + "\n"
  ret += """\
!Job Npr Nph Nba Nex Nsc Nor Dum Iwg Ilo Ias Res Ste Nre Cry Uni Cor Opt Aut
  {0}   {1}   {2}   {3}   0   0   0   {dum}   0   0   0   0   0   0   0   0   0   0   1
""".format(jobtype,nprof,nphase,nbckgd,dum=1 if jobtype == 2 else 0)
  ret += """\
!
!Ipr Ppl Ioc Mat Pcr Ls1 Ls2 Ls3 Syo Prf Ins Rpa Sym Hkl Fou Sho Ana
  2   0   1   1   1   0   0   0   1   1  {filetype}   0   1   4   2   0   0
!
! lambda1 Lambda2    Ratio    Bkpos    Wdt    Cthm     muR   AsyLim   Rpolarz ->Patt# 1
 {xlambda} {xlambda}  1.0000   60.000  5.0000  0.0000  0.0000   50.00    0.0000
!
!NCY  Eps  R_at  R_an  R_pr  R_gl     Thmin       Step       Thmax    PSD    Sent0
 20  0.01  1.00  1.00  1.00  1.00     10.0000   0.100000   100.0000   0.000   0.000
!
!
  #__npar__#    !Number of refined parameters
""".format(filetype="0", xlambda=wavelength)
  ret += """\
!
!  Zero    Code    SyCos    Code   SySin    Code  Lambda     Code MORE ->Patt# 1
  0.00000    0.0  0.00000    0.0  0.00000    0.0 0.000000    0.00   0
!   Background coefficients/codes  for Pattern#  1  (Polynomial of 6th degree)
       0.000       0.000       0.000       0.000       0.000       0.000
        0.00        0.00        0.00        0.00        0.00        0.00
"""
  for i in range(nphase):
    ret += _make_phase_block(phases[i], number=i+1, name="", scale_down=scale_down)
  return ret
예제 #20
0
def generator(xray_structure,
              data_are_intensities=True,
              title=None,
              wavelength=None,
              temperature=None,
              full_matrix_least_squares_cycles=None,
              conjugate_gradient_least_squares_cycles=None,
              overall_scale_factor=None,
              weighting_scheme_params=None,
              sort_scatterers=True,
              unit_cell_dims=None,
              unit_cell_esds=None
              ):
  space_group = xray_structure.space_group()
  assert not space_group.is_centric() or space_group.is_origin_centric(),\
         centric_implies_centrosymmetric_error_msg
  assert [full_matrix_least_squares_cycles,
          conjugate_gradient_least_squares_cycles].count(None) in (0, 1)
  if title is None:
    title = '????'
  if wavelength is None:
    wavelength = wavelengths.characteristic('Mo').as_angstrom()
  sgi = xray_structure.space_group_info()
  uc = xray_structure.unit_cell()

  yield 'TITL %s in %s\n' % (title, sgi.type().lookup_symbol())
  if unit_cell_dims is None:
    unit_cell_dims = uc.parameters()
  yield 'CELL %.5f %s\n' % (
    wavelength,
    ' '.join(('%.4f ',)*3 + ('%.3f',)*3) % unit_cell_dims)
  if unit_cell_esds:
    yield 'ZERR %i %f %f %f %f %f %f\n' % ((sgi.group().order_z(),) + unit_cell_esds)
  else:
    yield 'ZERR %i 0. 0. 0. 0. 0. 0.\n' % sgi.group().order_z()

  latt = 1 + 'PIRFABC'.find(sgi.group().conventional_centring_type_symbol())
  if not space_group.is_origin_centric(): latt = -latt
  yield 'LATT %i\n' % latt
  for i in xrange(space_group.n_smx()):
    rt_mx = space_group(0, 0, i)
    if rt_mx.is_unit_mx(): continue
    yield 'SYMM %s\n' % rt_mx
  yield '\n'

  uc_content = xray_structure.unit_cell_content()
  for e in uc_content:
    uc_content[e] = "%.1f" % uc_content[e]
  sfac = []
  unit = []
  prior = ('C', 'H')
  for e in prior:
    if e in uc_content:
      sfac.append(e)
      unit.append(uc_content[e])
  dsu = [ (tiny_pse.table(e).atomic_number(), e) for e in uc_content ]
  dsu.sort()
  sorted = [ item[-1] for item in dsu ]
  for e in sorted:
    if (e not in prior):
      sfac.append(e)
      unit.append(uc_content[e])
  yield 'SFAC %s\n' % ' '.join(sfac)
  for e in sfac:
    yield 'DISP %s 0 0 0\n' % e
  yield 'UNIT %s\n' % ' '.join(unit)
  sf_idx = dict([ (e, i + 1) for i, e in enumerate(sfac) ])
  yield '\n'

  if temperature:
    yield 'TEMP %.0f\n' % temperature

  if full_matrix_least_squares_cycles:
    yield 'L.S. %i\n' % full_matrix_least_squares_cycles

  if conjugate_gradient_least_squares_cycles:
    yield 'CGLS %i\n' % conjugate_gradient_least_squares_cycles

  yield '\n'

  if weighting_scheme_params is not None:
    if (isinstance(weighting_scheme_params, str)):
      yield 'WGHT %s\n' % weighting_scheme_params
    else:
      a, b = weighting_scheme_params
      if b is None:
        yield 'WGHT %.6f\n' % a
      else:
        yield 'WGHT %.6f %.6f\n' % (a, b)

  if overall_scale_factor is not None:
    yield 'FVAR %.8f\n' % overall_scale_factor

  fmt_tmpl = ('%-4s', '%2i') + ('%11.6f',)*3 + ('%11.5f',)
  fmt_iso = ' '.join(fmt_tmpl + ('%10.5f',))
  fmt_aniso = ' '.join(fmt_tmpl + ('%.5f',)*2 + ('=\n ',) + ('%.5f',)*4)
  if sort_scatterers:
    dsu = [ (tiny_pse.table(sc.scattering_type).atomic_number(), sc)
            for sc in xray_structure.scatterers() ]
    dsu.sort(reverse=True)
    scatterers = flex.xray_scatterer([ item[-1] for item in dsu ])
  else:
    scatterers = xray_structure.scatterers()
  atomname_set = set()
  for sc in scatterers:
    assert sc.fp == 0 # not implemented
    assert sc.fdp == 0 # not implemented
    assert sc.flags.use_u_iso() ^ sc.flags.use_u_aniso(),\
           both_iso_and_aniso_in_use_error_msg
    atomname = sc.label.strip()
    assert len(atomname) != 0
    assert len(atomname) <= 4
    if (atomname in atomname_set):
      raise RuntimeError('Duplicate atom name: "%s"' % atomname)
    atomname_set.add(atomname)
    params = (atomname, sf_idx[sc.scattering_type]) + sc.site
    occ = sc.weight()
    if not sc.flags.grad_occupancy(): occ += 10
    params += (occ, )
    if sc.flags.use_u_iso():
      yield fmt_iso % (params + (sc.u_iso,)) + "\n"
    else:
      u11, u22, u33, u12, u13, u23 = adptbx.u_star_as_u_cif(uc, sc.u_star)
      yield fmt_aniso % (params + (u11, u22, u33, u23, u13, u12)) + "\n"

  if data_are_intensities: hklf = 4
  else: hklf = 3
  yield 'HKLF %i\n' % hklf