Example #1
0
def exercise_extract_u_cart_plus_u_iso():
    from cctbx import uctbx, sgtbx, xray
    uc = uctbx.unit_cell((1, 1, 1))
    sg = sgtbx.space_group_info("P 1")
    a = flex.xray_scatterer()
    assert a.size() == 0
    s1 = xray.scatterer(label="C", u=0.1)
    s2 = xray.scatterer(label="C", u=0.1)
    s2.flags.set_use_u_iso(False)
    s3 = xray.scatterer(label="C", u=(1, 1, 1, 1, 1, 1))
    s4 = xray.scatterer(label="C", u=(1, 1, 1, 1, 1, 1))
    s4.flags.set_use_u_aniso(False)
    s5 = xray.scatterer(label="C", u=0.1)
    s5.u_star = (1, 1, 1, 1, 1, 1)
    s5.flags.set_use_u_aniso(True)
    s6 = xray.scatterer(label="C", u=0.1)
    s6.u_star = (1, 1, 1, 1, 1, 1)
    s7 = xray.scatterer(label="C", u=(1, 1, 1, 1, 1, 1))
    s7.u_iso = 0.1
    s8 = xray.scatterer(label="C", u=(1, 1, 1, 1, 1, 1))
    s8.u_iso = 0.1
    s8.flags.set_use_u_iso(True)
    s9 = xray.scatterer(label="C")
    s10 = xray.scatterer(label="C")
    s10.flags.set_use_u_iso(False)
    a = flex.xray_scatterer((s1, s2, s3, s4, s5, s6, s7, s8, s9, s10))
    u_cart_total = a.extract_u_cart_plus_u_iso(uc)
    assert approx_equal(u_cart_total, [(0.1, 0.1, 0.1, 0, 0, 0),
                                       (0, 0, 0, 0, 0, 0), (1, 1, 1, 1, 1, 1),
                                       (0, 0, 0, 0, 0, 0),
                                       (1.1, 1.1, 1.1, 1, 1, 1),
                                       (0.1, 0.1, 0.1, 0, 0, 0),
                                       (1, 1, 1, 1, 1, 1),
                                       (1.1, 1.1, 1.1, 1, 1, 1),
                                       (0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0)])
Example #2
0
 def add_new_solvent(self):
     if (self.params.b_iso is None):
         sol_sel = self.model.solvent_selection()
         xrs_mac_h = self.model.get_xray_structure().select(~sol_sel)
         hd_mac = self.model.get_hd_selection().select(~sol_sel)
         xrs_mac = xrs_mac_h.select(~hd_mac)
         b = xrs_mac.extract_u_iso_or_u_equiv() * math.pi**2 * 8
         b_solv = flex.mean_default(b, None)
         if (b_solv is not None and b_solv < self.params.b_iso_min
                 or b_solv > self.params.b_iso_max):
             b_solv = (self.params.b_iso_min + self.params.b_iso_max) / 2.
     else:
         b_solv = self.params.b_iso
     if (self.params.new_solvent == "isotropic"):
         new_scatterers = flex.xray_scatterer(
             self.sites.size(),
             xray.scatterer(occupancy=self.params.occupancy,
                            b=b_solv,
                            scattering_type=self.params.scattering_type))
     elif (self.params.new_solvent == "anisotropic"):
         u_star = adptbx.u_iso_as_u_star(
             self.model.get_xray_structure().unit_cell(),
             adptbx.b_as_u(b_solv))
         new_scatterers = flex.xray_scatterer(
             self.sites.size(),
             xray.scatterer(occupancy=self.params.occupancy,
                            u=u_star,
                            scattering_type=self.params.scattering_type))
     else:
         raise RuntimeError
     new_scatterers.set_sites(self.sites)
     solvent_xray_structure = xray.structure(
         special_position_settings=self.model.get_xray_structure(),
         scatterers=new_scatterers)
     xrs_sol = self.model.get_xray_structure().select(
         self.model.solvent_selection())
     xrs_mac = self.model.get_xray_structure().select(
         ~self.model.solvent_selection())
     xrs_sol = xrs_sol.concatenate(other=solvent_xray_structure)
     sol_sel = flex.bool(xrs_mac.scatterers().size(), False)
     sol_sel.extend(flex.bool(xrs_sol.scatterers().size(), True))
     self.model.add_solvent(
         solvent_xray_structure=solvent_xray_structure,
         residue_name=self.params.output_residue_name,
         atom_name=self.params.output_atom_name,
         chain_id=self.params.output_chain_id,
         refine_occupancies=self.params.refine_occupancies,
         refine_adp=self.params.new_solvent)
     self.fmodel.update_xray_structure(
         xray_structure=self.model.get_xray_structure(), update_f_calc=True)
 def add_new_solvent(self):
   if(self.params.b_iso is None):
     sol_sel = self.model.solvent_selection()
     xrs_mac_h = self.model.xray_structure.select(~sol_sel)
     hd_mac = self.model.xray_structure.hd_selection().select(~sol_sel)
     xrs_mac = xrs_mac_h.select(~hd_mac)
     b = xrs_mac.extract_u_iso_or_u_equiv() * math.pi**2*8
     b_solv = flex.mean_default(b, None)
     if(b_solv is not None and b_solv < self.params.b_iso_min or
        b_solv > self.params.b_iso_max):
       b_solv = (self.params.b_iso_min + self.params.b_iso_max) / 2.
   else:
     b_solv = self.params.b_iso
   if(self.params.new_solvent == "isotropic"):
     new_scatterers = flex.xray_scatterer(
       self.sites.size(),
       xray.scatterer(occupancy       = self.params.occupancy,
                      b               = b_solv,
                      scattering_type = self.params.scattering_type))
   elif(self.params.new_solvent == "anisotropic"):
     u_star = adptbx.u_iso_as_u_star(self.model.xray_structure.unit_cell(),
       adptbx.b_as_u(b_solv))
     new_scatterers = flex.xray_scatterer(
       self.sites.size(),
       xray.scatterer(
         occupancy       = self.params.occupancy,
         u               = u_star,
         scattering_type = self.params.scattering_type))
   else: raise RuntimeError
   new_scatterers.set_sites(self.sites)
   solvent_xray_structure = xray.structure(
     special_position_settings = self.model.xray_structure,
     scatterers                = new_scatterers)
   xrs_sol = self.model.xray_structure.select(self.model.solvent_selection())
   xrs_mac = self.model.xray_structure.select(~self.model.solvent_selection())
   xrs_sol = xrs_sol.concatenate(other = solvent_xray_structure)
   sol_sel = flex.bool(xrs_mac.scatterers().size(), False)
   sol_sel.extend( flex.bool(xrs_sol.scatterers().size(), True) )
   self.model.add_solvent(
     solvent_xray_structure = solvent_xray_structure,
     residue_name           = self.params.output_residue_name,
     atom_name              = self.params.output_atom_name,
     chain_id               = self.params.output_chain_id,
     refine_occupancies     = self.params.refine_occupancies,
     refine_adp             = self.params.new_solvent)
   self.fmodel.update_xray_structure(
     xray_structure = self.model.xray_structure,
     update_f_calc  = True)
Example #4
0
File: gid.py Project: isaxs/pynx
 def __init__(self,unitcell,spacegroup,scatterers):
   self.sg=sgtbx.space_group_info(spacegroup)
   self.uc=uctbx.unit_cell(unitcell)
   self.scatt=scatterers
   self.cctbx_scatterers=flex.xray_scatterer()
   for s in self.scatt:
     self.cctbx_scatterers.append(xray.scatterer(label=s.label,site=s.site,occupancy=s.occupancy,u=s.u_iso))
   try:
     #old cctbx version
     xray.add_scatterers_ext(unit_cell=self.uc,
                           space_group=self.sg.group(),
                           scatterers=self.cctbx_scatterers,
                           site_symmetry_table=sgtbx.site_symmetry_table(),
                           site_symmetry_table_for_new=sgtbx.site_symmetry_table(),
                           min_distance_sym_equiv=0.5,
                           u_star_tolerance=0,
                           assert_min_distance_sym_equiv=True)
   except:
     # cctbx version >= 2011_04_06_0217 
     #print "Whoops, cctbx version 2011"
     xray.add_scatterers_ext(unit_cell=self.uc,
                           space_group=self.sg.group(),
                           scatterers=self.cctbx_scatterers,
                           site_symmetry_table=sgtbx.site_symmetry_table(),
                           site_symmetry_table_for_new=sgtbx.site_symmetry_table(),
                           min_distance_sym_equiv=0.5,
                           u_star_tolerance=0,
                           assert_min_distance_sym_equiv=True,
                           non_unit_occupancy_implies_min_distance_sym_equiv_zero=False)
   cs=crystal.symmetry(self.uc,spacegroup)
   sp=crystal.special_position_settings(cs)
   self.structure=xray.structure(sp,self.cctbx_scatterers)
   self.structure_as_P1=self.structure.expand_to_p1()
Example #5
0
def exercise_intersection():
  sites_frac = flex.vec3_double([
    (0.02,0.10,0.02),
    (0.10,0.02,0.40),
    (0.98,0.10,0.60),
    (0.10,0.98,0.80),
    (0.20,0.50,0.98)])
  from cctbx import xray
  xray_structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(30,30,50,90,90,120),
      space_group_symbol="P1"),
    scatterers=flex.xray_scatterer([
      xray.scatterer(label=str(i), scattering_type="Si", site=site_frac)
        for i,site_frac in enumerate(sites_frac)]))
  d_min = 0.7
  f_calc = xray_structure.structure_factors(d_min=d_min).f_calc()
  fft_map = f_calc.fft_map(resolution_factor=1/6.)
  fft_map.apply_sigma_scaling()
  density_map = fft_map.real_map_unpadded()
  #
  cm1 = xray_structure.center_of_mass()
  cm2 = maptbx.center_of_mass(map_data=density_map, unit_cell=xray_structure.unit_cell(),
    cutoff=20) #large cutoff to make map look like point scattereres
  assert approx_equal(cm1, cm2, 0.1)
def demo():
  """
  Result of ICSD query:
    N * -Cr2O3-[R3-CH] Baster, M.;Bouree, F.;Kowalska, A.;Latacz, Z(2000)
    C 4.961950 4.961950 13.597400 90.000000 90.000000 120.000000
    S GRUP R -3 C
    A Cr1    0.000000 0.000000 0.347570 0.000000
    A O1    0.305830 0.000000 0.250000
  """
  crystal_symmetry = crystal.symmetry(
    unit_cell="4.961950 4.961950 13.597400 90.000000 90.000000 120.000000",
    space_group_symbol="R -3 C")
  scatterers = flex.xray_scatterer()
  scatterers.append(xray.scatterer(
    label="Cr1", site=(0.000000,0.000000,0.347570)))
  scatterers.append(xray.scatterer(
    label="O1", site=(0.305830,0.000000,0.250000)))
  icsd_structure = xray.structure(
    crystal_symmetry=crystal_symmetry,
    scatterers=scatterers)
  icsd_structure.show_summary().show_scatterers()
  print
  icsd_structure.show_distances(distance_cutoff=2.5)
  print
  primitive_structure = icsd_structure.primitive_setting()
  primitive_structure.show_summary().show_scatterers()
  print
  p1_structure = primitive_structure.expand_to_p1()
  p1_structure.show_summary().show_scatterers()
  print
  print "OK"
Example #7
0
def mg_structure_dict_to_cctbx_crystal_structure(d):
    """ 
    Compatible with pymatgen Structure.to_dict() format
    to a cctbx crystal structure object
    """
    params = " ".join([
        str(o) for o in [
            d['lattice']['a'], d['lattice']['b'], d['lattice']['c'],
            d['lattice']['alpha'], d['lattice']['beta'], d['lattice']['gamma']
        ]
    ])
    unit_cell = uctbx.unit_cell(params)
    symbol = 'P 1'
    crystal_symmetry = crystal.symmetry(unit_cell=unit_cell,
                                        space_group_symbol=symbol)
    """
    site = tuple([0.0, 0.20, 0.3])
    scatterers.append(xray.scatterer(label=lable, site=site, occupancy=occupancy)

    crystal_structure = xray.structure(crystal_symmetry=crystal_symmetry, scatterers=scatterers)
    """
    scatterers = flex.xray_scatterer()
    for site in d['sites']:
        abc = tuple(site['abc'])
        for specie in site['species']:
            label = specie['element'].encode('utf8')
            occupancy = float(specie['occu'])
            scatterers.append(
                xray.scatterer(label=label, site=abc, occupancy=occupancy))
    crystal_structure = xray.structure(crystal_symmetry=crystal_symmetry,
                                       scatterers=scatterers)
    return crystal_structure
Example #8
0
def exercise_is_simple_interaction():
    for space_group_symbol in ["P1", "P41"]:
        for shifts in flex.nested_loop((-2, -2, -2), (2, 2, 2), False):
            shifts = matrix.col(shifts)
            structure = xray.structure(
                crystal_symmetry=crystal.symmetry(
                    unit_cell=(10, 10, 20, 90, 90, 90),
                    space_group_symbol=space_group_symbol),
                scatterers=flex.xray_scatterer([
                    xray.scatterer(label="O",
                                   site=shifts + matrix.col((0, 0, 0))),
                    xray.scatterer(label="N",
                                   site=shifts + matrix.col((0.5, 0.5, 0))),
                    xray.scatterer(label="C",
                                   site=shifts + matrix.col((0.25, 0.25, 0)))
                ]))
            asu_mappings = structure.asu_mappings(buffer_thickness=7)
            pair_generator = crystal.neighbors_simple_pair_generator(
                asu_mappings=asu_mappings, distance_cutoff=7)
            simple_interactions = {}
            for i_pair, pair in enumerate(pair_generator):
                if (asu_mappings.is_simple_interaction(pair)):
                    assert asu_mappings_is_simple_interaction_emulation(
                        asu_mappings, pair)
                    key = (pair.i_seq, pair.j_seq)
                    assert simple_interactions.get(key, None) is None
                    simple_interactions[key] = 1
                else:
                    assert not asu_mappings_is_simple_interaction_emulation(
                        asu_mappings, pair)
            assert len(simple_interactions) == 2
            assert simple_interactions[(0, 2)] == 1
            assert simple_interactions[(1, 2)] == 1
def exercise_symmetry_equivalent():
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(1, 2, 3),
      space_group_symbol='hall: P 2x'),
    scatterers=flex.xray_scatterer((
      xray.scatterer("C", site=(0.1, 0.2, 0.3)),
    )))
  xs.scatterers()[0].flags.set_grad_site(True)
  connectivity_table = smtbx.utils.connectivity_table(xs)
  reparametrisation = constraints.reparametrisation(
    xs, [], connectivity_table)
  site_0 = reparametrisation.add(constraints.independent_site_parameter,
                                 scatterer=xs.scatterers()[0])
  g = sgtbx.rt_mx('x,-y,-z')
  symm_eq = reparametrisation.add(
    constraints.symmetry_equivalent_site_parameter,
    site=site_0, motion=g)
  reparametrisation.finalise()

  assert approx_equal(symm_eq.original.scatterers[0].site, (0.1, 0.2, 0.3),
                      eps=1e-15)
  assert str(symm_eq.motion) == 'x,-y,-z'
  assert symm_eq.is_variable
  reparametrisation.linearise()
  assert approx_equal(symm_eq.value, g*site_0.value, eps=1e-15)

  reparametrisation.store()
  assert approx_equal(symm_eq.value, (0.1, -0.2, -0.3), eps=1e-15)
  assert approx_equal(site_0.value, (0.1, 0.2, 0.3), eps=1e-15)
Example #10
0
def test_addition_scatterers():
  '''
  Test overlaps when adding and moving scatterers
  Test water scatterers with and without labels
  '''
  clashes = get_clashes_result(raw_records=raw_records_3)
  results = clashes.get_results()
  assert(results.n_clashes == 3)
  assert approx_equal(results.clashscore, 1000, eps=0.1)

  # Add water scatterers
  model = clashes.model
  xrs = model.get_xray_structure()
  new_scatterers = flex.xray_scatterer(
    xrs.scatterers().size(),
    xray.scatterer(occupancy = 1, b = 10, scattering_type = "O"))
  new_sites_frac = xrs.unit_cell().fractionalize(xrs.sites_cart()+[0.5,0,0])
  new_scatterers.set_sites(new_sites_frac)
  new_xrs = xray.structure(
    special_position_settings = xrs,
    scatterers                = new_scatterers)
  model.add_solvent(
    solvent_xray_structure = new_xrs,
    refine_occupancies     = False,
    refine_adp             = "isotropic")

  pnps = pnp.manager(model = model)
  clashes = pnps.get_clashes()
  results = clashes.get_results()

  assert(results.n_clashes == 15)
  assert approx_equal(results.clashscore, 2500, eps=5)
 def add_new_solvent(self):
   b_solv = self.params.b_iso
   new_scatterers = flex.xray_scatterer(
             self.sites.size(),
             xray.scatterer(occupancy       = self.params.occupancy,
             b                              = b_solv,
             scattering_type                = self.params.scattering_type,
             label                          = 'HOH'))
   new_scatterers.set_sites(self.sites)
   solvent_xray_structure = xray.structure(
     special_position_settings = self.model.xray_structure,
     scatterers                = new_scatterers)
   xrs_sol = self.model.xray_structure.select(self.model.solvent_selection())
   xrs_mac = self.model.xray_structure.select(~self.model.solvent_selection())
   xrs_sol = xrs_sol.concatenate(other = solvent_xray_structure)
   sol_sel = flex.bool(xrs_mac.scatterers().size(), False)
   sol_sel.extend( flex.bool(xrs_sol.scatterers().size(), True) )
   self.model.add_solvent(
           solvent_xray_structure = solvent_xray_structure,
           residue_name           = self.params.output_residue_name,
           atom_name              = self.params.output_atom_name,
           chain_id               = self.params.output_chain_id,
           refine_occupancies     = self.params.refine_occupancies,
           refine_adp             = self.params.new_solvent)
   self.fmodel.update_xray_structure(
     xray_structure = self.model.xray_structure,
     update_f_calc  = False)
Example #12
0
def test_spacegroup_tidy_pickling():
  quartz_structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
    unit_cell=(5.01,5.01,5.47,90,90,120),
    space_group_symbol="P6222"),
    scatterers=flex.xray_scatterer(
    [
      xray.scatterer(label="Si", site=(1/2.,1/2.,1/3.), u=0.2),
      xray.scatterer(label="O",  site=(0.197,-0.197,0.83333), u=0)
    ])
  )

  asu_mappings = quartz_structure.asu_mappings(buffer_thickness=2)
  pair_asu_table = crystal.pair_asu_table(asu_mappings=asu_mappings)
  pair_asu_table.add_all_pairs(distance_cutoff=1.7)
  pair_sym_table = pair_asu_table.extract_pair_sym_table()
  new_asu_mappings = quartz_structure.asu_mappings(buffer_thickness=5)
  new_pair_asu_table = crystal.pair_asu_table(asu_mappings=new_asu_mappings)
  new_pair_asu_table.add_pair_sym_table(sym_table=pair_sym_table)
  spg = new_pair_asu_table.asu_mappings().space_group()
  pspg = pickle.loads(pickle.dumps(spg))
  mstr = ""
  pmstr = ""
  for rt in spg.all_ops():
    mstr += rt.r().as_xyz() + "\n"
  for rt in pspg.all_ops():
    pmstr += rt.r().as_xyz() + "\n"
  assert mstr == pmstr
 def __init__(self, n_runs, **kwds):
   libtbx.adopt_optional_init_args(self, kwds)
   self.n_runs = n_runs
   self.crystal_symmetry = crystal.symmetry(
     unit_cell=uctbx.unit_cell((5.1534, 5.1534, 8.6522, 90, 90, 120)),
     space_group_symbol='Hall: P 6c')
   self.structure = xray.structure(
     self.crystal_symmetry.special_position_settings(),
     flex.xray_scatterer((
       xray.scatterer('K1',
                       site=(0, 0, -0.00195),
                       u=self.u_cif_as_u_star((0.02427, 0.02427, 0.02379,
                                               0.01214, 0.00000, 0.00000))),
       xray.scatterer('S1',
                      site=(1/3, 2/3, 0.204215),
                      u=self.u_cif_as_u_star((0.01423, 0.01423, 0.01496,
                                              0.00712, 0.00000, 0.00000 ))),
       xray.scatterer('Li1',
                      site=(1/3, 2/3, 0.815681),
                      u=self.u_cif_as_u_star((0.02132, 0.02132, 0.02256,
                                              0.01066, 0.00000, 0.00000 ))),
       xray.scatterer('O1',
                      site=(1/3, 2/3, 0.035931),
                      u=self.u_cif_as_u_star((0.06532, 0.06532, 0.01669,
                                              0.03266, 0.00000, 0.00000 ))),
       xray.scatterer('O2',
                      site=(0.343810, 0.941658, 0.258405),
                      u=self.u_cif_as_u_star((0.02639,  0.02079, 0.05284,
                                              0.01194, -0.00053,-0.01180 )))
     )))
   mi = self.crystal_symmetry.build_miller_set(anomalous_flag=False,
                                               d_min=0.5)
   fo_sq = mi.structure_factors_from_scatterers(
     self.structure, algorithm="direct").f_calc().norm()
   self.fo_sq = fo_sq.customized_copy(sigmas=flex.double(fo_sq.size(), 1))
def exercise_symmetry_equivalent():
    xs = xray.structure(crystal_symmetry=crystal.symmetry(
        unit_cell=(1, 2, 3), space_group_symbol='hall: P 2x'),
                        scatterers=flex.xray_scatterer(
                            (xray.scatterer("C", site=(0.1, 0.2, 0.3)), )))
    xs.scatterers()[0].flags.set_grad_site(True)
    connectivity_table = smtbx.utils.connectivity_table(xs)
    reparametrisation = constraints.reparametrisation(xs, [],
                                                      connectivity_table)
    site_0 = reparametrisation.add(constraints.independent_site_parameter,
                                   scatterer=xs.scatterers()[0])
    g = sgtbx.rt_mx('x,-y,-z')
    symm_eq = reparametrisation.add(
        constraints.symmetry_equivalent_site_parameter, site=site_0, motion=g)
    reparametrisation.finalise()

    assert approx_equal(symm_eq.original.scatterers[0].site, (0.1, 0.2, 0.3),
                        eps=1e-15)
    assert str(symm_eq.motion) == 'x,-y,-z'
    assert symm_eq.is_variable
    reparametrisation.linearise()
    assert approx_equal(symm_eq.value, g * site_0.value, eps=1e-15)

    reparametrisation.store()
    assert approx_equal(symm_eq.value, (0.1, -0.2, -0.3), eps=1e-15)
    assert approx_equal(site_0.value, (0.1, 0.2, 0.3), eps=1e-15)
Example #15
0
def quartz():
  return xray.structure(
    crystal_symmetry=crystal.symmetry(
      (5.01,5.01,5.47,90,90,120), "P6222"),
    scatterers=flex.xray_scatterer([
      xray.scatterer("Si", (1/2.,1/2.,1/3.)),
      xray.scatterer("O", (0.197,-0.197,0.83333))]))
Example #16
0
 def add_new_solvent(self):
     b_solv = self.params.b_iso
     new_scatterers = flex.xray_scatterer(
         self.sites.size(),
         xray.scatterer(occupancy=self.params.occupancy,
                        b=b_solv,
                        scattering_type=self.params.scattering_type,
                        label='HOH'))
     new_scatterers.set_sites(self.sites)
     solvent_xray_structure = xray.structure(
         special_position_settings=self.model.xray_structure,
         scatterers=new_scatterers)
     xrs_sol = self.model.xray_structure.select(
         self.model.solvent_selection())
     xrs_mac = self.model.xray_structure.select(
         ~self.model.solvent_selection())
     xrs_sol = xrs_sol.concatenate(other=solvent_xray_structure)
     sol_sel = flex.bool(xrs_mac.scatterers().size(), False)
     sol_sel.extend(flex.bool(xrs_sol.scatterers().size(), True))
     self.model.add_solvent(
         solvent_xray_structure=solvent_xray_structure,
         residue_name=self.params.output_residue_name,
         atom_name=self.params.output_atom_name,
         chain_id=self.params.output_chain_id,
         refine_occupancies=self.params.refine_occupancies,
         refine_adp=self.params.new_solvent)
     self.fmodel.update_xray_structure(
         xray_structure=self.model.xray_structure, update_f_calc=False)
Example #17
0
 def _find_peaks(self, min_peak_peak_distance=1.5):
     cg = maptbx.crystal_gridding(
         space_group_info=self.model.crystal_symmetry().space_group_info(),
         symmetry_flags=maptbx.use_space_group_symmetry,
         unit_cell=self.unit_cell,
         pre_determined_n_real=self.map_data.accessor().all())
     cgt = maptbx.crystal_gridding_tags(gridding=cg)
     peak_search_parameters = maptbx.peak_search_parameters(
         peak_search_level=3,
         max_peaks=0,
         peak_cutoff=self.cutoff,
         interpolate=True,
         min_distance_sym_equiv=0,
         general_positions_only=False,  # ???????XXXXXXXXXXXXXX
         min_cross_distance=min_peak_peak_distance,
         min_cubicle_edge=5)
     psr = cgt.peak_search(parameters=peak_search_parameters,
                           map=self.map_data).all(max_clusters=99999999)
     # Convert peaks into water xray.structure
     mean_b = flex.mean(self.model.get_hierarchy().atoms().extract_b())
     sp = crystal.special_position_settings(self.model.crystal_symmetry())
     scatterers = flex.xray_scatterer()
     for site_frac in psr.sites():
         sc = xray.scatterer(label="O",
                             site=site_frac,
                             u=adptbx.b_as_u(mean_b),
                             occupancy=1.0)
         scatterers.append(sc)
     self.xrs_water = xray.structure(sp, scatterers)
     #
     self.ma.add("  total peaks found: %d" %
                 self.xrs_water.scatterers().size())
     self.ma.add("  B factors set to : %8.3f" % mean_b)
     if (self.debug): self._write_pdb_file(file_name_prefix="hoh_all_peaks")
Example #18
0
 def loop(self):
     for i_position in xrange(self.wyckoff_table.size()):
         site_symmetry_i = self.wyckoff_table.random_site_symmetry(
             special_position_settings=self.special_position_settings,
             i_position=i_position)
         equiv_sites_i = sgtbx.sym_equiv_sites(site_symmetry_i)
         for j_position in xrange(self.wyckoff_table.size()):
             for n_trial in xrange(self.max_trials_per_position):
                 site_j = self.wyckoff_table.random_site_symmetry(
                     special_position_settings=self.
                     special_position_settings,
                     i_position=j_position).exact_site()
                 dist_info = sgtbx.min_sym_equiv_distance_info(
                     equiv_sites_i, site_j)
                 if (dist_info.dist() > self.min_cross_distance):
                     structure = xray.structure(
                         special_position_settings=self.
                         special_position_settings,
                         scatterers=flex.xray_scatterer([
                             xray.scatterer(
                                 scattering_type=self.scattering_type,
                                 site=site) for site in
                             [site_symmetry_i.exact_site(), site_j]
                         ]))
                     yield structure, dist_info.dist()
                     break
Example #19
0
 def _append_to_model(self):
     mean_b = flex.mean(self.model.get_hierarchy().atoms().extract_b())
     self.ma.add("  new water B factors will be set to mean B: %8.3f" %
                 mean_b)
     sp = crystal.special_position_settings(self.model.crystal_symmetry())
     scatterers = flex.xray_scatterer()
     for site_frac in self.sites_frac_water:
         sc = xray.scatterer(label="O",
                             site=site_frac,
                             u=adptbx.b_as_u(mean_b),
                             occupancy=1.0)
         scatterers.append(sc)
     xrs_water = xray.structure(sp, scatterers)
     #
     chain_ids_taken = []
     for chain in self.model.get_hierarchy().chains():
         chain_ids_taken.append(chain.id)
     unique_taken = list(set(chain_ids_taken))
     if (len(unique_taken) == 1):
         solvent_chain = unique_taken[0]
     else:
         for solvent_chain in all_chain_ids():
             if (not solvent_chain in chain_ids_taken):
                 break
     self.ma.add("  new water will have chain ID: '%s'" % solvent_chain)
     #
     self.model.add_solvent(solvent_xray_structure=xrs_water,
                            atom_name="O",
                            residue_name="HOH",
                            chain_id=solvent_chain,
                            refine_adp="isotropic")
 def __init__(self, n_runs, **kwds):
   libtbx.adopt_optional_init_args(self, kwds)
   self.n_runs = n_runs
   self.crystal_symmetry = crystal.symmetry(
     unit_cell=uctbx.unit_cell((5.1534, 5.1534, 8.6522, 90, 90, 120)),
     space_group_symbol='Hall: P 6c')
   self.structure = xray.structure(
     self.crystal_symmetry.special_position_settings(),
     flex.xray_scatterer((
       xray.scatterer('K1',
                       site=(0, 0, -0.00195),
                       u=self.u_cif_as_u_star((0.02427, 0.02427, 0.02379,
                                               0.01214, 0.00000, 0.00000))),
       xray.scatterer('S1',
                      site=(1/3, 2/3, 0.204215),
                      u=self.u_cif_as_u_star((0.01423, 0.01423, 0.01496,
                                              0.00712, 0.00000, 0.00000 ))),
       xray.scatterer('Li1',
                      site=(1/3, 2/3, 0.815681),
                      u=self.u_cif_as_u_star((0.02132, 0.02132, 0.02256,
                                              0.01066, 0.00000, 0.00000 ))),
       xray.scatterer('O1',
                      site=(1/3, 2/3, 0.035931),
                      u=self.u_cif_as_u_star((0.06532, 0.06532, 0.01669,
                                              0.03266, 0.00000, 0.00000 ))),
       xray.scatterer('O2',
                      site=(0.343810, 0.941658, 0.258405),
                      u=self.u_cif_as_u_star((0.02639,  0.02079, 0.05284,
                                              0.01194, -0.00053,-0.01180 )))
     )))
   mi = self.crystal_symmetry.build_miller_set(anomalous_flag=False,
                                               d_min=0.5)
   fo_sq = mi.structure_factors_from_scatterers(
     self.structure, algorithm="direct").f_calc().norm()
   self.fo_sq = fo_sq.customized_copy(sigmas=flex.double(fo_sq.size(), 1))
Example #21
0
def compare_with_cctbx_structure_factors(n_scatt, n_refl, output_lines):
    from cctbx import xray
    from cctbx import miller
    from cctbx import crystal
    from cctbx.array_family import flex
    crystal_symmetry = crystal.symmetry(unit_cell=(11, 12, 13, 90, 90, 90),
                                        space_group_symbol="P1")
    scatterers = flex.xray_scatterer()
    miller_indices = flex.miller_index()
    f_calc = flex.complex_double()
    for line in output_lines:
        flds = line.split()
        assert len(flds) in [4, 5]
        if (len(flds) == 4):
            x, y, z, b_iso = [float(s) for s in flds]
            scatterers.append(
                xray.scatterer(site=(x, y, z),
                               b=b_iso,
                               scattering_type="const"))
        else:
            miller_indices.append([int(s) for s in flds[:3]])
            f_calc.append(complex(float(flds[3]), float(flds[4])))
    assert scatterers.size() == n_scatt
    assert miller_indices.size() == n_refl
    xs = xray.structure(crystal_symmetry=crystal_symmetry,
                        scatterers=scatterers)
    fc = miller_array = miller.set(crystal_symmetry=crystal_symmetry,
                                   indices=miller_indices,
                                   anomalous_flag=False).array(data=f_calc)
    fc2 = fc.structure_factors_from_scatterers(xray_structure=xs,
                                               algorithm="direct",
                                               cos_sin_table=False).f_calc()
    for f1, f2 in zip(fc.data(), fc2.data()):
        assert approx_equal(f1, f2, eps=1e-5)
Example #22
0
    def extract_structure(self, phase_nr=1):
        """This method tries to extract the crystal structure from the parsed pcrfile.

    :returns: the extracted structure
    :rtype: cctbx.xray.structure
    """
        from cctbx import xray
        from cctbx import crystal
        from cctbx.array_family import flex
        p = self.cfg['phases'][str(phase_nr)]
        atoms = p['atoms']
        unit_cell = [p['a'], p['b'], p['c'], p['alpha'], p['beta'], p['gamma']]
        special_position_settings = crystal.special_position_settings(
            crystal_symmetry=crystal.symmetry(unit_cell=unit_cell,
                                              space_group_symbol=p['SYMB']))
        scatterers = []
        for k, a in atoms.iteritems():
            scatterers.append(
                xray.scatterer(label=a['LABEL'],
                               scattering_type=a['NTYP'],
                               site=(a['X'], a['Y'], a['Z']),
                               b=a['B']))
        scatterers_flex = flex.xray_scatterer(scatterers)
        structure = xray.structure(
            special_position_settings=special_position_settings,
            scatterers=scatterers_flex)
        return structure.as_py_code()
Example #23
0
  def extract_structure(self, phase_nr=1):
    """This method tries to extract the crystal structure from the parsed pcrfile.

    :returns: the extracted structure
    :rtype: cctbx.xray.structure
    """
    from cctbx import xray
    from cctbx import crystal
    from cctbx.array_family import flex
    p = self.cfg['phases'][str(phase_nr)]
    atoms = p['atoms']
    unit_cell = [ p['a'], p['b'], p['c'], p['alpha'], p['beta'], p['gamma'] ]
    special_position_settings=crystal.special_position_settings(
              crystal_symmetry=crystal.symmetry(
                    unit_cell=unit_cell,
                    space_group_symbol=p['SYMB']))
    scatterers = []
    for k, a in atoms.iteritems():
      scatterers.append(xray.scatterer(label=a['LABEL'],
                                       scattering_type=a['NTYP'],
                                       site=(a['X'], a['Y'], a['Z']),
                                       b=a['B']))
    scatterers_flex=flex.xray_scatterer(scatterers)
    structure = xray.structure(special_position_settings=special_position_settings,
                               scatterers=scatterers_flex)
    return structure.as_py_code()
def exercise_is_simple_interaction():
  for space_group_symbol in ["P1", "P41"]:
    for shifts in flex.nested_loop((-2,-2,-2),(2,2,2),False):
      shifts = matrix.col(shifts)
      structure = xray.structure(
        crystal_symmetry=crystal.symmetry(
          unit_cell=(10,10,20,90,90,90),
          space_group_symbol=space_group_symbol),
        scatterers=flex.xray_scatterer([
          xray.scatterer(label="O", site=shifts+matrix.col((0,0,0))),
          xray.scatterer(label="N", site=shifts+matrix.col((0.5,0.5,0))),
          xray.scatterer(label="C", site=shifts+matrix.col((0.25,0.25,0)))]))
      asu_mappings = structure.asu_mappings(buffer_thickness=7)
      pair_generator = crystal.neighbors_simple_pair_generator(
        asu_mappings=asu_mappings,
        distance_cutoff=7)
      simple_interactions = {}
      for i_pair,pair in enumerate(pair_generator):
        if (asu_mappings.is_simple_interaction(pair)):
          assert asu_mappings_is_simple_interaction_emulation(
            asu_mappings, pair)
          key = (pair.i_seq,pair.j_seq)
          assert simple_interactions.get(key, None) is None
          simple_interactions[key] = 1
        else:
          assert not asu_mappings_is_simple_interaction_emulation(
            asu_mappings, pair)
      assert len(simple_interactions) == 2
      assert simple_interactions[(0,2)] == 1
      assert simple_interactions[(1,2)] == 1
Example #25
0
def exercise_rigid_pivoted_rotatable():
  uc = uctbx.unit_cell((1, 1, 1))
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=uc,
      space_group_symbol='hall: P 2x 2y'),
    scatterers=flex.xray_scatterer(( #triangle
      xray.scatterer('C0', site=(0,0,0)),
      xray.scatterer('C1', site=(0,2,0)),
      xray.scatterer('C2', site=(1,1,0)),
      )))
  r = constraints.ext.reparametrisation(xs.unit_cell())
  sc = xs.scatterers()
  pivot = r.add(constraints.independent_site_parameter, sc[0])
  pivot_neighbour = r.add(constraints.independent_site_parameter, sc[1])
  azimuth = r.add(constraints.independent_scalar_parameter,
                  value=pi/2, variable=True)
  size = r.add(constraints.independent_scalar_parameter,
                  value=1, variable=False)
  rg = r.add(constraints.rigid_pivoted_rotatable_group,
                pivot=pivot,
                pivot_neighbour=pivot_neighbour,
                azimuth=azimuth,
                size=size,
                scatterers=(sc[1], sc[2]))
  site_proxy = r.add(constraints.rigid_site_proxy, rg, 1)
  r.finalise()
  r.linearise()
  r.store()
  #check that proxy and the final results are the same...
  assert approx_equal(
    uc.distance(col(site_proxy.value), col(sc[2].site)), 0, eps=1e-15)
  #rotation happens around the center of gravity
  assert approx_equal(
    uc.distance(col((0,1,1)), col(sc[2].site)), 0, eps=1e-15)
Example #26
0
    def __init__(self,
                 space_group=SpaceGroup('P 1'),
                 lattice=Lattice(1.0, 1.0, 1.0, 90.0, 90.0, 90.0),
                 sites=[]):
        """
        Crystal object.
        Functions as a wrapper to a cctbx xray.structure object,
        but adds additional variables and functionality.
        Core object of this package.
        
        Input:
            SpaceGroup  space_group                            space group for the current crystal
            List of Site objects  sites                        List of Site objects.
        
        Warning:
            'crystal_structure' must be given,
            or 'space_group', 'lattice', and 'sites' must be given,
            or creation of the crystal will fail.
        """

        try:
            crystal_symmetry = crystal.symmetry(
                unit_cell=str(lattice),
                space_group_symbol=space_group.cctbx_name)
        except Exception as e:
            raise SymmetryError(
                "SpaceGroup {s} is incompatible with Lattice -> {l} cctbx error {e}"
                .format(l=str(lattice), s=SpaceGroup.cctbx_name, e=e))

        scatterers = flex.xray_scatterer()
        for i, site in enumerate(sites):
            # the element name can be pulled from scatterer via the s.element_symbol() method (if it's an element!!!)
            # example: 'atom-b-12',or 'vacancy-c-3'
            # we need to set the scattering_type so we can freely use the label to store metadata

            #scattering_type = something
            #scatterers.append(xray.scatterer(label=atom.name, site=tuple(atom.abc), occupancy=atom.occupancy), scattering_type=atom.name)

            #Method #2
            # explicitly add metadata to _meta
            st_temp, dash, num = site.label.partition("-")
            if dash == "-":
                k = site.label
            else:
                k = "-".join([site.label, str(i)])

            # problems here not sure what's up
            k = str(k)
            # print "label = ", k, ' type of label = ', type(k)
            # print "site = ", tuple(site.abc)
            # print "occupancy = ", site.occupancy
            scatterers.append(
                xray.scatterer(label=k,
                               site=tuple(site.abc),
                               occupancy=site.occupancy))

        # Test for coherency of Lattice and SpaceGroup
        self.crystal_structure = xray.structure(
            crystal_symmetry=crystal_symmetry, scatterers=scatterers)
Example #27
0
 def merge(Cls, *others):
     """Returns new instance of the Fragment. The scatterers in the new
     fragment are obtained by merging two frag"""
     scatterers = flex.xray_scatterer()
     for other in others:
         for scatterer in other.scatterers:
             scatterers.append(scatterer)
     return Cls(scatterers)
def get_xrs():
  crystal_symmetry = crystal.symmetry(
    unit_cell=(10,10,10,90,90,90),
    space_group_symbol="P 1")
  return xray.structure(
    crystal_symmetry=crystal_symmetry,
    scatterers=flex.xray_scatterer([
      xray.scatterer(label="C", site=(0,0,0))]))
Example #29
0
def exercise_real_space_refinement(verbose):
    if (verbose):
        out = sys.stdout
    else:
        out = StringIO()
    out_of_bounds_clamp = maptbx.out_of_bounds_clamp(0)
    out_of_bounds_raise = maptbx.out_of_bounds_raise()
    crystal_symmetry = crystal.symmetry(unit_cell=(10, 10, 10, 90, 90, 90),
                                        space_group_symbol="P 1")
    xray_structure = xray.structure(crystal_symmetry=crystal_symmetry,
                                    scatterers=flex.xray_scatterer([
                                        xray.scatterer(label="C",
                                                       site=(0, 0, 0))
                                    ]))
    miller_set = miller.build_set(crystal_symmetry=crystal_symmetry,
                                  anomalous_flag=False,
                                  d_min=1)
    f_calc = miller_set.structure_factors_from_scatterers(
        xray_structure=xray_structure).f_calc()
    fft_map = f_calc.fft_map()
    fft_map.apply_sigma_scaling()
    real_map = fft_map.real_map_unpadded()
    #### unit_cell test
    delta_h = .005
    basic_map = maptbx.basic_map(
        maptbx.basic_map_unit_cell_flag(), real_map, real_map.focus(),
        crystal_symmetry.unit_cell().orthogonalization_matrix(),
        out_of_bounds_clamp.as_handle(), crystal_symmetry.unit_cell())
    testing_function_for_rsfit(basic_map, delta_h, xray_structure, out)
    ### non_symmetric test
    #
    minfrac = crystal_symmetry.unit_cell().fractionalize((-5, -5, -5))
    maxfrac = crystal_symmetry.unit_cell().fractionalize((5, 5, 5))
    gridding_first = [ifloor(n * b) for n, b in zip(fft_map.n_real(), minfrac)]
    gridding_last = [iceil(n * b) for n, b in zip(fft_map.n_real(), maxfrac)]
    data = maptbx.copy(real_map, gridding_first, gridding_last)
    #
    basic_map = maptbx.basic_map(
        maptbx.basic_map_non_symmetric_flag(), data, fft_map.n_real(),
        crystal_symmetry.unit_cell().orthogonalization_matrix(),
        out_of_bounds_clamp.as_handle(), crystal_symmetry.unit_cell())
    testing_function_for_rsfit(basic_map, delta_h, xray_structure, out)
    ### asu test
    #
    minfrac = crystal_symmetry.unit_cell().fractionalize((0, 0, 0))
    maxfrac = crystal_symmetry.unit_cell().fractionalize((10, 10, 10))
    gridding_first = [ifloor(n * b) for n, b in zip(fft_map.n_real(), minfrac)]
    gridding_last = [iceil(n * b) for n, b in zip(fft_map.n_real(), maxfrac)]
    data = maptbx.copy(real_map, gridding_first, gridding_last)
    #
    basic_map = maptbx.basic_map(
        maptbx.basic_map_asu_flag(), data, crystal_symmetry.space_group(),
        crystal_symmetry.direct_space_asu().as_float_asu(), real_map.focus(),
        crystal_symmetry.unit_cell().orthogonalization_matrix(),
        out_of_bounds_clamp.as_handle(), crystal_symmetry.unit_cell(), 0.5,
        True)
    testing_function_for_rsfit(basic_map, delta_h, xray_structure, out)
Example #30
0
 def __init__(self,
              xray_structure,
              solvent_radius,
              shrink_truncation_radius,
              ignore_hydrogen_atoms=False,
              crystal_gridding=None,
              grid_step=None,
              d_min=None,
              resolution_factor=1 / 4,
              atom_radii_table=None,
              use_space_group_symmetry=False):
     self.xray_structure = xray_structure
     if crystal_gridding is None:
         self.crystal_gridding = maptbx.crystal_gridding(
             unit_cell=xray_structure.unit_cell(),
             space_group_info=xray_structure.space_group_info(),
             step=grid_step,
             d_min=d_min,
             resolution_factor=resolution_factor,
             symmetry_flags=sgtbx.search_symmetry_flags(
                 use_space_group_symmetry=use_space_group_symmetry))
     else:
         self.crystal_gridding = crystal_gridding
     if use_space_group_symmetry:
         atom_radii = cctbx.masks.vdw_radii(
             xray_structure, table=atom_radii_table).atom_radii
         asu_mappings = xray_structure.asu_mappings(
             buffer_thickness=flex.max(atom_radii) + solvent_radius)
         scatterers_asu_plus_buffer = flex.xray_scatterer()
         frac = xray_structure.unit_cell().fractionalize
         for sc, mappings in zip(xray_structure.scatterers(),
                                 asu_mappings.mappings()):
             for mapping in mappings:
                 scatterers_asu_plus_buffer.append(
                     sc.customized_copy(site=frac(mapping.mapped_site())))
         xs = xray.structure(crystal_symmetry=xray_structure,
                             scatterers=scatterers_asu_plus_buffer)
     else:
         xs = xray_structure.expand_to_p1()
     self.vdw_radii = cctbx.masks.vdw_radii(xs, table=atom_radii_table)
     self.mask = cctbx.masks.around_atoms(
         unit_cell=xs.unit_cell(),
         space_group_order_z=xs.space_group().order_z(),
         sites_frac=xs.sites_frac(),
         atom_radii=self.vdw_radii.atom_radii,
         gridding_n_real=self.crystal_gridding.n_real(),
         solvent_radius=solvent_radius,
         shrink_truncation_radius=shrink_truncation_radius)
     if use_space_group_symmetry:
         tags = self.crystal_gridding.tags()
         tags.tags().apply_symmetry_to_mask(self.mask.data)
     self.flood_fill = cctbx.masks.flood_fill(self.mask.data,
                                              xray_structure.unit_cell())
     self.exclude_void_flags = [False] * self.flood_fill.n_voids()
     self.solvent_accessible_volume = self.n_solvent_grid_points() \
         / self.mask.data.size() * xray_structure.unit_cell().volume()
def exercise_unmerged () :
  quartz_structure = xray.structure(
    special_position_settings=crystal.special_position_settings(
      crystal_symmetry=crystal.symmetry(
        unit_cell=(5.01,5.01,5.47,90,90,120),
        space_group_symbol="P6222")),
    scatterers=flex.xray_scatterer([
      xray.scatterer(
        label="Si",
        site=(1/2.,1/2.,1/3.),
        u=0.2),
      xray.scatterer(
        label="O",
        site=(0.197,-0.197,0.83333),
        u=0.1)]))
  quartz_structure.set_inelastic_form_factors(
    photon=1.54,
    table="sasaki")
  fc = abs(quartz_structure.structure_factors(d_min=1.0).f_calc())
  symm = fc.crystal_symmetry()
  icalc = fc.expand_to_p1().f_as_f_sq().set_observation_type_xray_intensity()
  # generate 'unmerged' data
  i_obs = icalc.customized_copy(crystal_symmetry=symm)
  # now make up sigmas and some (hopefully realistic) error
  flex.set_random_seed(12345)
  n_refl = i_obs.size()
  sigmas = flex.random_double(n_refl) * flex.mean(fc.data())
  sigmas = icalc.customized_copy(data=sigmas).apply_debye_waller_factors(
    u_iso=0.15)
  err = (flex.double(n_refl, 0.5) - flex.random_double(n_refl)) * 2
  i_obs = i_obs.customized_copy(
    sigmas=sigmas.data(),
    data=i_obs.data() + err)
  # check for unmerged acentrics
  assert i_obs.is_unmerged_intensity_array()
  i_obs_centric = i_obs.select(i_obs.centric_flags().data())
  i_obs_acentric = i_obs.select(~(i_obs.centric_flags().data()))
  i_mrg_acentric = i_obs_acentric.merge_equivalents().array()
  i_mixed = i_mrg_acentric.concatenate(i_obs_centric)
  assert not i_mixed.is_unmerged_intensity_array()
  # XXX These results of these functions are heavily dependent on the
  # behavior of the random number generator, which is not consistent across
  # platforms - therefore we can only check for very approximate values.
  # Exact numerical results are tested with real data (stored elsewhere).
  # CC1/2, etc.
  assert approx_equal(i_obs.cc_one_half(), 0.9998, eps=0.001)
  assert i_obs.resolution_filter(d_max=1.2).cc_one_half() > 0
  assert i_obs.cc_anom() > 0.1
  r_ano = i_obs.r_anom()
  assert approx_equal(r_ano, 0.080756, eps=0.0001)
  # merging stats
  i_mrg = i_obs.merge_equivalents()
  assert i_mrg.r_merge() < 0.1
  assert i_mrg.r_meas() < 0.1
  assert i_mrg.r_pim() < 0.05
Example #32
0
def exercise_lbfgs(test_case, use_geo, out, d_min=2):
    sites_cart, geo_manager = cctbx.geometry_restraints.manager.\
      construct_non_crystallographic_conserving_bonds_and_angles(
        sites_cart=flex.vec3_double(test_case.sites),
        edge_list_bonds=test_case.bonds,
        edge_list_angles=test_case.angles())
    scatterers = flex.xray_scatterer(sites_cart.size(),
                                     xray.scatterer(scattering_type="C", b=20))
    for sc, lbl in zip(scatterers, test_case.labels):
        sc.label = lbl
    structure = xray.structure(crystal_symmetry=geo_manager.crystal_symmetry,
                               scatterers=scatterers)
    structure.set_sites_cart(sites_cart=sites_cart)
    f_calc = structure.structure_factors(d_min=d_min,
                                         anomalous_flag=False).f_calc()
    fft_map = f_calc.fft_map()
    fft_map.apply_sigma_scaling()
    if (use_geo):
        axis = matrix.col(flex.random_double_point_on_sphere())
        rot = scitbx.math.r3_rotation_axis_and_angle_as_matrix(axis=axis,
                                                               angle=25,
                                                               deg=True)
        trans = matrix.col(flex.random_double_point_on_sphere()) * 1.0
        structure.apply_rigid_body_shift(rot=rot, trans=trans)
        geo_manager.energies_sites(sites_cart=structure.sites_cart()).show(
            f=out)
        minimized = real_space_refinement_simple.lbfgs(
            sites_cart=structure.sites_cart(),
            density_map=fft_map.real_map(),
            geometry_restraints_manager=geo_manager,
            gradients_method="fd",
            real_space_target_weight=1,
            real_space_gradients_delta=d_min / 3)
        geo_manager.energies_sites(sites_cart=minimized.sites_cart).show(f=out)
    else:
        minimized = real_space_refinement_simple.lbfgs(
            sites_cart=structure.sites_cart(),
            density_map=fft_map.real_map(),
            unit_cell=structure.unit_cell(),
            gradients_method="fd",
            real_space_gradients_delta=d_min / 3)
    rmsd_start = sites_cart.rms_difference(structure.sites_cart())
    rmsd_final = sites_cart.rms_difference(minimized.sites_cart)
    print("RMSD start, final:", rmsd_start, rmsd_final, file=out)
    if (use_geo):
        assert rmsd_start >= 1 - 1e-6
        assert rmsd_final < 0.2

    def show_f_g(label, f, g):
        print(label, "f, |g|:", f, flex.mean_sq(g)**0.5, file=out)

    show_f_g(label="start", f=minimized.f_start, g=minimized.g_start)
    show_f_g(label="final", f=minimized.f_final, g=minimized.g_final)
    assert minimized.f_final <= minimized.f_start
    return minimized
def exercise_u_iso_proportional_to_pivot_u_iso():
  # Test working constraint
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(),
      space_group_symbol='hall: P 2x 2y'),
    scatterers=flex.xray_scatterer((
      xray.scatterer('C0', u=0.12),
      xray.scatterer('C1'),
      )))
  r = constraints.ext.reparametrisation(xs.unit_cell())
  sc = xs.scatterers()

  u_iso = r.add(constraints.independent_u_iso_parameter, sc[0])
  u_iso_1 = r.add(constraints.u_iso_proportional_to_pivot_u_iso,
                pivot_u_iso=u_iso,
                multiplier=2,
                scatterer=sc[1])
  r.finalise()
  r.linearise()
  assert approx_equal(u_iso_1.value, 0.24, eps=1e-15)

  # Test conflicting constraints
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(),
      space_group_symbol='hall: P 2x 2y'),
    scatterers=flex.xray_scatterer((
      xray.scatterer('C0', u=0.12),
      xray.scatterer('C1', u=0.21),
      xray.scatterer('C2')
    )))
  with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    r = constraints.reparametrisation(
      structure=xs,
      constraints=[constraints.adp.shared_u((0, 2)),
                   constraints.adp.shared_u((1, 2))],
      connectivity_table=smtbx.utils.connectivity_table(xs))
    assert len(w) == 1
    assert w[-1].category == constraints.ConflictingConstraintWarning
    assert w[-1].message.conflicts == set(((2, 'U'),))
def demo():
  """
  Result of ICSD query:
    N * -Cr2O3-[R3-CH] Baster, M.;Bouree, F.;Kowalska, A.;Latacz, Z(2000)
    C 4.961950 4.961950 13.597400 90.000000 90.000000 120.000000
    S GRUP R -3 C
    A Cr1    0.000000 0.000000 0.347570 0.000000
    A O1    0.305830 0.000000 0.250000
  """
  crystal_symmetry = crystal.symmetry(
    unit_cell="4.961950 4.961950 13.597400 90.000000 90.000000 120.000000",
    space_group_symbol="R -3 C")
  scatterers = flex.xray_scatterer()
  scatterers.append(xray.scatterer(
    label="Cr1", site=(0.000000,0.000000,0.347570)))
  scatterers.append(xray.scatterer(
    label="O1", site=(0.305830,0.000000,0.250000)))
  icsd_structure = xray.structure(
    crystal_symmetry=crystal_symmetry,
    scatterers=scatterers)
  icsd_structure.show_summary().show_scatterers()
  print
  icsd_pairs = icsd_structure.show_distances(
    distance_cutoff=2.5, keep_pair_asu_table=True)
  print
  primitive_structure = icsd_structure.primitive_setting()
  primitive_structure.show_summary().show_scatterers()
  print
  p1_structure = primitive_structure.expand_to_p1()
  p1_structure.show_summary().show_scatterers()
  print
  p1_pairs = p1_structure.show_distances(
    distance_cutoff=2.5, keep_pair_asu_table=True)
  print
  for label,structure,pairs in [("ICSD", icsd_structure,icsd_pairs),
                                ("P1", p1_structure,p1_pairs)]:
    print "Coordination sequences for", label, "structure"
    term_table = crystal.coordination_sequences.simple(
      pair_asu_table=pairs.pair_asu_table,
      max_shell=10)
    crystal.coordination_sequences.show_terms(
      structure=structure,
      term_table=term_table)
    print
  icsd_f_calc = icsd_structure.structure_factors(
    d_min=1, algorithm="direct").f_calc()
  icsd_f_calc_in_p1 = icsd_f_calc.primitive_setting().expand_to_p1()
  p1_f_calc = icsd_f_calc_in_p1.structure_factors_from_scatterers(
    xray_structure=p1_structure, algorithm="direct").f_calc()
  for h,i,p in zip(icsd_f_calc_in_p1.indices(),
                   icsd_f_calc_in_p1.data(),
                   p1_f_calc.data()):
    print h, abs(i), abs(p)*3
  print "OK"
Example #35
0
 def __init__(
     self,
     xray_structure,
     solvent_radius,
     shrink_truncation_radius,
     ignore_hydrogen_atoms=False,
     crystal_gridding=None,
     grid_step=None,
     d_min=None,
     resolution_factor=1 / 4,
     atom_radii_table=None,
     use_space_group_symmetry=False,
 ):
     self.xray_structure = xray_structure
     if crystal_gridding is None:
         self.crystal_gridding = maptbx.crystal_gridding(
             unit_cell=xray_structure.unit_cell(),
             space_group_info=xray_structure.space_group_info(),
             step=grid_step,
             d_min=d_min,
             resolution_factor=resolution_factor,
             symmetry_flags=sgtbx.search_symmetry_flags(use_space_group_symmetry=use_space_group_symmetry),
         )
     else:
         self.crystal_gridding = crystal_gridding
     if use_space_group_symmetry:
         atom_radii = cctbx.masks.vdw_radii(xray_structure, table=atom_radii_table).atom_radii
         asu_mappings = xray_structure.asu_mappings(buffer_thickness=flex.max(atom_radii) + solvent_radius)
         scatterers_asu_plus_buffer = flex.xray_scatterer()
         frac = xray_structure.unit_cell().fractionalize
         for sc, mappings in zip(xray_structure.scatterers(), asu_mappings.mappings()):
             for mapping in mappings:
                 scatterers_asu_plus_buffer.append(sc.customized_copy(site=frac(mapping.mapped_site())))
         xs = xray.structure(crystal_symmetry=xray_structure, scatterers=scatterers_asu_plus_buffer)
     else:
         xs = xray_structure.expand_to_p1()
     self.vdw_radii = cctbx.masks.vdw_radii(xs, table=atom_radii_table)
     self.mask = cctbx.masks.around_atoms(
         unit_cell=xs.unit_cell(),
         space_group_order_z=xs.space_group().order_z(),
         sites_frac=xs.sites_frac(),
         atom_radii=self.vdw_radii.atom_radii,
         gridding_n_real=self.crystal_gridding.n_real(),
         solvent_radius=solvent_radius,
         shrink_truncation_radius=shrink_truncation_radius,
     )
     if use_space_group_symmetry:
         tags = self.crystal_gridding.tags()
         tags.tags().apply_symmetry_to_mask(self.mask.data)
     self.flood_fill = cctbx.masks.flood_fill(self.mask.data, xray_structure.unit_cell())
     self.exclude_void_flags = [False] * self.flood_fill.n_voids()
     self.solvent_accessible_volume = (
         self.n_solvent_grid_points() / self.mask.data.size() * xray_structure.unit_cell().volume()
     )
Example #36
0
def exercise_covariance():
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      (5.01,5.01,5.47,90,90,120), "P6222"),
    scatterers=flex.xray_scatterer([
      xray.scatterer("Si", (1/2.,1/2.,1/3.)),
      xray.scatterer("O", (0.197,-0.197,0.83333))]))
  uc = xs.unit_cell()
  flags = xs.scatterer_flags()
  for f in flags:
    f.set_grad_site(True)
  xs.set_scatterer_flags(flags)
  cov = flex.double((1e-8,1e-9,2e-9,3e-9,4e-9,5e-9,
                          2e-8,1e-9,2e-9,3e-9,4e-9,
                               3e-8,1e-9,2e-9,3e-9,
                                    2e-8,1e-9,2e-9,
                                         3e-8,1e-9,
                                              4e-8))
  param_map = xs.parameter_map()
  assert approx_equal(cov,
    covariance.extract_covariance_matrix_for_sites(flex.size_t([0,1]), cov, param_map))
  cov_cart = covariance.orthogonalize_covariance_matrix(cov, uc, param_map)
  O = matrix.sqr(uc.orthogonalization_matrix())
  for i in range(param_map.n_scatterers):
    cov_i = covariance.extract_covariance_matrix_for_sites(flex.size_t([i]), cov, param_map)
    cov_i_cart = covariance.extract_covariance_matrix_for_sites(flex.size_t([i]), cov_cart, param_map)
    assert approx_equal(
      O * matrix.sym(sym_mat3=cov_i) * O.transpose(),
      matrix.sym(sym_mat3=cov_i_cart).as_mat3())
  for f in flags: f.set_grads(False)
  flags[0].set_grad_u_aniso(True)
  flags[0].set_use_u_aniso(True)
  flags[1].set_grad_u_iso(True)
  flags[1].set_use_u_iso(True)
  xs.set_scatterer_flags(flags)
  param_map = xs.parameter_map()
  cov = flex.double(7*7, 0)
  cov.reshape(flex.grid(7,7))
  cov.matrix_diagonal_set_in_place(flex.double([i for i in range(7)]))
  cov = cov.matrix_symmetric_as_packed_u()
  assert approx_equal([i for i in range(6)],
                      covariance.extract_covariance_matrix_for_u_aniso(
                        0, cov, param_map).matrix_packed_u_diagonal())
  assert covariance.variance_for_u_iso(1, cov, param_map) == 6
  try: covariance.variance_for_u_iso(0, cov, param_map)
  except RuntimeError: pass
  else: raise Exception_expected
  try: covariance.extract_covariance_matrix_for_u_aniso(1, cov, param_map)
  except RuntimeError: pass
  else: raise Exception_expected
  approx_equal(covariance.extract_covariance_matrix_for_sites(
    flex.size_t([1]), cov, param_map), (0,0,0,0,0,0))
def exercise_u_iso_proportional_to_pivot_u_iso():
    # Test working constraint
    xs = xray.structure(crystal_symmetry=crystal.symmetry(
        unit_cell=(), space_group_symbol='hall: P 2x 2y'),
                        scatterers=flex.xray_scatterer((
                            xray.scatterer('C0', u=0.12),
                            xray.scatterer('C1'),
                        )))
    r = constraints.ext.reparametrisation(xs.unit_cell())
    sc = xs.scatterers()

    u_iso = r.add(constraints.independent_u_iso_parameter, sc[0])
    u_iso_1 = r.add(constraints.u_iso_proportional_to_pivot_u_iso,
                    pivot_u_iso=u_iso,
                    multiplier=2,
                    scatterer=sc[1])
    r.finalise()
    r.linearise()
    assert approx_equal(u_iso_1.value, 0.24, eps=1e-15)

    # Test conflicting constraints
    xs = xray.structure(
        crystal_symmetry=crystal.symmetry(unit_cell=(),
                                          space_group_symbol='hall: P 2x 2y'),
        scatterers=flex.xray_scatterer(
            (xray.scatterer('C0', u=0.12), xray.scatterer('C1', u=0.21),
             xray.scatterer('C2'))))
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        r = constraints.reparametrisation(
            structure=xs,
            constraints=[
                constraints.adp.shared_u((0, 2)),
                constraints.adp.shared_u((1, 2))
            ],
            connectivity_table=smtbx.utils.connectivity_table(xs))
        assert len(w) == 1
        assert w[-1].category == constraints.ConflictingConstraintWarning
        assert w[-1].message.conflicts == set(((2, 'U'), ))
Example #38
0
def exercise_extract_u_cart_plus_u_iso():
  from cctbx import uctbx, sgtbx, xray
  uc = uctbx.unit_cell((1,1,1))
  sg = sgtbx.space_group_info("P 1")
  a = flex.xray_scatterer()
  assert a.size() == 0
  s1 = xray.scatterer(label = "C", u = 0.1)
  s2 = xray.scatterer(label = "C", u = 0.1)
  s2.flags.set_use_u_iso(False)
  s3 = xray.scatterer(label = "C", u = (1,1,1,1,1,1))
  s4 = xray.scatterer(label = "C", u = (1,1,1,1,1,1))
  s4.flags.set_use_u_aniso(False)
  s5 = xray.scatterer(label = "C", u = 0.1)
  s5.u_star=(1,1,1,1,1,1)
  s5.flags.set_use_u_aniso(True)
  s6 = xray.scatterer(label = "C", u = 0.1)
  s6.u_star=(1,1,1,1,1,1)
  s7 = xray.scatterer(label = "C", u = (1,1,1,1,1,1))
  s7.u_iso=0.1
  s8 = xray.scatterer(label = "C", u = (1,1,1,1,1,1))
  s8.u_iso=0.1
  s8.flags.set_use_u_iso(True)
  s9 = xray.scatterer(label = "C")
  s10 = xray.scatterer(label = "C")
  s10.flags.set_use_u_iso(False)
  a = flex.xray_scatterer((s1,s2,s3,s4,s5,s6,s7,s8,s9,s10))
  u_cart_total = a.extract_u_cart_plus_u_iso(uc)
  assert approx_equal(u_cart_total,
    [(0.1,0.1,0.1,0,0,0),
    (0,0,0,0,0,0),
    (1,1,1,1,1,1),
    (0,0,0,0,0,0),
    (1.1,1.1,1.1,1,1,1),
    (0.1,0.1,0.1,0,0,0),
    (1,1,1,1,1,1),
    (1.1,1.1,1.1,1,1,1),
    (0,0,0,0,0,0),
    (0,0,0,0,0,0)])
def exercise_lbfgs(test_case, use_geo, out, d_min=2):
  sites_cart, geo_manager = cctbx.geometry_restraints.manager.construct_non_crystallographic_conserving_bonds_and_angles(
    sites_cart=flex.vec3_double(test_case.sites),
    edge_list_bonds=test_case.bonds,
    edge_list_angles=test_case.angles())
  scatterers = flex.xray_scatterer(
    sites_cart.size(), xray.scatterer(scattering_type="C", b=20))
  for sc,lbl in zip(scatterers, test_case.labels):
    sc.label = lbl
  structure = xray.structure(
    crystal_symmetry=geo_manager.crystal_symmetry,
    scatterers=scatterers)
  structure.set_sites_cart(sites_cart=sites_cart)
  f_calc = structure.structure_factors(
    d_min=d_min, anomalous_flag=False).f_calc()
  fft_map = f_calc.fft_map()
  fft_map.apply_sigma_scaling()
  if (use_geo):
    axis = matrix.col(flex.random_double_point_on_sphere())
    rot = scitbx.math.r3_rotation_axis_and_angle_as_matrix(
      axis=axis, angle=25, deg=True)
    trans = matrix.col(flex.random_double_point_on_sphere()) * 1.0
    structure.apply_rigid_body_shift(rot=rot, trans=trans)
    geo_manager.energies_sites(sites_cart=structure.sites_cart()).show(f=out)
    minimized = real_space_refinement_simple.lbfgs(
      sites_cart=structure.sites_cart(),
      density_map=fft_map.real_map(),
      geometry_restraints_manager=geo_manager,
      real_space_target_weight=1,
      real_space_gradients_delta=d_min/3)
    geo_manager.energies_sites(sites_cart=minimized.sites_cart).show(f=out)
  else:
    minimized = real_space_refinement_simple.lbfgs(
      sites_cart=structure.sites_cart(),
      density_map=fft_map.real_map(),
      unit_cell=structure.unit_cell(),
      real_space_gradients_delta=d_min/3)
  rmsd_start = sites_cart.rms_difference(structure.sites_cart())
  rmsd_final = sites_cart.rms_difference(minimized.sites_cart)
  print >> out, "RMSD start, final:", rmsd_start, rmsd_final
  if (use_geo):
    assert rmsd_start >= 1-1e-6
    assert rmsd_final < 0.2
  def show_f_g(label, f, g):
    print >> out, label, "f, |g|:", f, flex.mean_sq(g)**0.5
  show_f_g(label="start", f=minimized.f_start, g=minimized.g_start)
  show_f_g(label="final", f=minimized.f_final, g=minimized.g_final)
  assert minimized.f_final <= minimized.f_start
  return minimized
Example #40
0
    def limit_to_range(self, **kwargs):
        """Returns a copy of object with its scatterers falling into coordina
        te ranges specified by **kwargs. For example kwargs could be:
            x = (0,0.5), z = (0, 0.8)"""
        map_kwargs = {'x':0, 'y':1, 'z':2}
        init_scatterers = flex.xray_scatterer()
        for scatterer in self._scatterers:

            check_list =[[scatterer.site[map_kwargs[key]], kwargs[key]]  
                    for key in kwargs]
            cond = all([ all([item[0] >= item[1][0], item[0] <= item[1][1]]) 
                            for item in check_list]) 
            if cond:
                init_scatterers.append(scatterer)
        return Fragment(init_scatterers)
Example #41
0
 def scatterers(O, u_iso=0):
   assert O.types is not None
   from cctbx import xray
   from cctbx.array_family import flex
   result = flex.xray_scatterer()
   sites = iter(O.sites)
   for type,count in zip(O.types, O.type_counts):
     for _ in range(count):
       result.append(xray.scatterer(
         label="%s%d"%(type, len(result)+1),
         scattering_type=type,
         site=next(sites),
         u=u_iso))
   assert len(result) == len(O.sites)
   return result
Example #42
0
 def scatterers(O, u_iso=0):
   assert O.types is not None
   from cctbx import xray
   from cctbx.array_family import flex
   result = flex.xray_scatterer()
   sites = iter(O.sites)
   for type,count in zip(O.types, O.type_counts):
     for _ in xrange(count):
       result.append(xray.scatterer(
         label="%s%d"%(type, len(result)+1),
         scattering_type=type,
         site=sites.next(),
         u=u_iso))
   assert len(result) == len(O.sites)
   return result
def exercise_unmerged():
    quartz_structure = xray.structure(
        special_position_settings=crystal.special_position_settings(
            crystal_symmetry=crystal.symmetry(unit_cell=(5.01, 5.01, 5.47, 90,
                                                         90, 120),
                                              space_group_symbol="P6222")),
        scatterers=flex.xray_scatterer([
            xray.scatterer(label="Si", site=(1 / 2., 1 / 2., 1 / 3.), u=0.2),
            xray.scatterer(label="O", site=(0.197, -0.197, 0.83333), u=0.1)
        ]))
    quartz_structure.set_inelastic_form_factors(photon=1.54, table="sasaki")
    fc = abs(quartz_structure.structure_factors(d_min=1.0).f_calc())
    symm = fc.crystal_symmetry()
    icalc = fc.expand_to_p1().f_as_f_sq().set_observation_type_xray_intensity()
    # generate 'unmerged' data
    i_obs = icalc.customized_copy(crystal_symmetry=symm)
    # now make up sigmas and some (hopefully realistic) error
    flex.set_random_seed(12345)
    n_refl = i_obs.size()
    sigmas = flex.random_double(n_refl) * flex.mean(fc.data())
    sigmas = icalc.customized_copy(data=sigmas).apply_debye_waller_factors(
        u_iso=0.15)
    err = (flex.double(n_refl, 0.5) - flex.random_double(n_refl)) * 2
    i_obs = i_obs.customized_copy(sigmas=sigmas.data(),
                                  data=i_obs.data() + err)
    # check for unmerged acentrics
    assert i_obs.is_unmerged_intensity_array()
    i_obs_centric = i_obs.select(i_obs.centric_flags().data())
    i_obs_acentric = i_obs.select(~(i_obs.centric_flags().data()))
    i_mrg_acentric = i_obs_acentric.merge_equivalents().array()
    i_mixed = i_mrg_acentric.concatenate(i_obs_centric)
    assert not i_mixed.is_unmerged_intensity_array()
    # XXX These results of these functions are heavily dependent on the
    # behavior of the random number generator, which is not consistent across
    # platforms - therefore we can only check for very approximate values.
    # Exact numerical results are tested with real data (stored elsewhere).
    # CC1/2, etc.
    assert approx_equal(i_obs.cc_one_half(), 0.9999, eps=0.001)
    assert approx_equal(i_obs.cc_one_half_sigma_tau(), 0.9999, eps=0.001)
    assert i_obs.resolution_filter(d_max=1.2).cc_one_half() > 0
    assert i_obs.cc_anom() > 0.1
    r_ano = i_obs.r_anom()
    assert approx_equal(r_ano, 0.080756, eps=0.0001)
    # merging stats
    i_mrg = i_obs.merge_equivalents()
    assert i_mrg.r_merge() < 0.1
    assert i_mrg.r_meas() < 0.1
    assert i_mrg.r_pim() < 0.05
Example #44
0
    def __init__(self, space_group = SpaceGroup('P 1'), lattice = Lattice(1.0, 1.0, 1.0, 90.0, 90.0, 90.0), sites=[]):
        """
        Crystal object.
        Functions as a wrapper to a cctbx xray.structure object,
        but adds additional variables and functionality.
        Core object of this package.
        
        Input:
            SpaceGroup  space_group                            space group for the current crystal
            List of Site objects  sites                        List of Site objects.
        
        Warning:
            'crystal_structure' must be given,
            or 'space_group', 'lattice', and 'sites' must be given,
            or creation of the crystal will fail.
        """
        
        try:
            crystal_symmetry = crystal.symmetry(unit_cell=str(lattice), space_group_symbol=space_group.cctbx_name)
        except Exception as e:
            raise SymmetryError("SpaceGroup {s} is incompatible with Lattice -> {l} cctbx error {e}".format(l=str(lattice), s=SpaceGroup.cctbx_name, e=e))

        scatterers = flex.xray_scatterer()
        for i, site in enumerate(sites):
            # the element name can be pulled from scatterer via the s.element_symbol() method (if it's an element!!!)
            # example: 'atom-b-12',or 'vacancy-c-3'
            # we need to set the scattering_type so we can freely use the label to store metadata
            
            #scattering_type = something
            #scatterers.append(xray.scatterer(label=atom.name, site=tuple(atom.abc), occupancy=atom.occupancy), scattering_type=atom.name)
            
            #Method #2
            # explicitly add metadata to _meta
            st_temp, dash, num = site.label.partition("-")
            if dash == "-":
                k = site.label
            else:
                k = "-".join([site.label, str(i)])
            
            # problems here not sure what's up
            k = str(k)
            # print "label = ", k, ' type of label = ', type(k)
            # print "site = ", tuple(site.abc)
            # print "occupancy = ", site.occupancy
            scatterers.append(xray.scatterer(label=k, site=tuple(site.abc), occupancy=site.occupancy))
        
        # Test for coherency of Lattice and SpaceGroup
        self.crystal_structure = xray.structure(crystal_symmetry=crystal_symmetry, scatterers=scatterers)
Example #45
0
File: clash.py Project: dials/cctbx
def to_xray_structure(atoms, symmetry):
    """
  A utility function to convert atoms into cctbx.xray.structure
  """

    from cctbx import xray
    from cctbx.array_family import flex
    cell = symmetry.unit_cell()

    return xray.structure(crystal_symmetry=symmetry,
                          scatterers=flex.xray_scatterer([
                              xray.scatterer(
                                  label=a.pdb_label_columns(),
                                  site=cell.fractionalize(a.xyz),
                              ) for a in atoms
                          ]))
Example #46
0
 def _initialize_from_XYZ(self, **kwargs):
     coordinates_list = read_XYZ(self.fname, **kwargs)
     self.scatterers = flex.xray_scatterer()
     for line in coordinates_list:
         line_list = line.strip().split()
         self.scatterers.append(
             xray.scatterer(
                 label = line_list[1],
                 scattering_type = line_list[0],
                 site = (
                 float(line_list[2]),
                 float(line_list[3]),
                 float(line_list[4]),
                 ),
                 **kwargs
                 ))
Example #47
0
 def get_cctbx_structure(self,cctbx_atoms=None,cctbx_symm=None):
     if cctbx_atoms is None:
         cctbx_atoms = []
         for site_label in self.structure.site().keys():
             cctbx_atoms.append(cctbx.xray.scatterer(label=str(site_label),
                                                     site=(self.structure.site()[site_label]['coordinates']),
                                                     u=self.structure.site()[site_label]['u_isotropic'],
                                                     occupancy=self.structure.site()[site_label]['occupancy'],
                                                     scattering_type=str(self.structure.site()[site_label]['atom_type'])))
     if cctbx_symm is None:
         cctbx_symm = cctbx.crystal.symmetry(unit_cell=self.lattice.parameters(),
                                             space_group_symbol=self.structure.space_group())
     settings = cctbx.crystal.special_position_settings(crystal_symmetry=cctbx_symm)
     cctbx_struct = cctbx.xray.structure(special_position_settings=settings,
                                         scatterers = flex.xray_scatterer(cctbx_atoms))
     return cctbx_struct
Example #48
0
def exercise_cc_peak():
  def get_map():
    av = [random.random() for i in xrange(10*20*30)]
    m = flex.double(av)
    m = m-flex.min(m)
    m = m/flex.max(m)
    m.resize(flex.grid((10,20,30)))
    return m
  m1 = get_map()
  m2 = get_map()
  for t in range(0,11):
    t=t/10.
    ccp=maptbx.cc_peak(map_1=m1, map_2=m2, cutoff=t)
  #
  sites_frac = flex.vec3_double([
    (0.50,0.50,0.50)])
  from cctbx import xray
  xray_structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(5,5,5,90,90,90),
      space_group_symbol="P1"),
    scatterers=flex.xray_scatterer([
      xray.scatterer(label=str(i), scattering_type="C", site=site_frac)
        for i,site_frac in enumerate(sites_frac)]))
  fc1 = xray_structure.structure_factors(d_min=1.6).f_calc()
  fc2 = xray_structure.structure_factors(d_min=1.7).f_calc()
  for t in range(0,11):
    t=t/10.
    ccp=maptbx.cc_peak(map_coeffs_1=fc1, map_coeffs_2=fc2, cutoff=t)
  #
  m1_he = maptbx.volume_scale(map = m1,  n_bins = 10000).map_data()
  m2_he = maptbx.volume_scale(map = m2,  n_bins = 10000).map_data()
  cutoffs = flex.double([i/20. for i in range(1,20)])
  df = maptbx.discrepancy_function(map_1=m1_he, map_2=m2_he, cutoffs=cutoffs)
  #
  fc1 = xray_structure.structure_factors(d_min=2.2).f_calc()
  fc2 = xray_structure.structure_factors(d_min=2.2).f_calc()
  for t in range(0,10):
    t=t/10.
    ccp=maptbx.cc_peak(map_coeffs_1=fc1, map_coeffs_2=fc2, cutoff=t)
    assert approx_equal(ccp, 1)
  # 1D case
  m1_he_1d = maptbx.volume_scale_1d(map = m1.as_1d(),  n_bins = 10000).map_data()
  m2_he_1d = maptbx.volume_scale_1d(map = m2.as_1d(),  n_bins = 10000).map_data()
  df_1d = maptbx.discrepancy_function(
    map_1=m1_he_1d, map_2=m2_he_1d, cutoffs=cutoffs)
  assert approx_equal(df, df_1d)
Example #49
0
def quartz_p1(metrical_matrix=None):
  if metrical_matrix is not None:
    unit_cell = uctbx.unit_cell(metrical_matrix=metrical_matrix)
  else:
    unit_cell = uctbx.unit_cell(parameters=(5.01,5.01,5.47,90,90,120))
  return xray.structure(
    crystal_symmetry=crystal.symmetry(
    unit_cell=unit_cell,
    space_group_symbol='hall:  P 1'),
    scatterers=flex.xray_scatterer((
      xray.scatterer( #0
        label='Si',
        site=(0.500000, 0.500000, 0.333333),
        u=0.000000),
      xray.scatterer( #1
        label='Si',
        site=(0.000000, 0.500000, 0.666667),
        u=0.000000),
      xray.scatterer( #2
        label='Si',
        site=(0.500000, 0.000000, 0.000000),
        u=0.000000),
      xray.scatterer( #3
        label='O',
        site=(0.197000, 0.803000, 0.833333),
        u=0.000000),
      xray.scatterer( #4
        label='O',
        site=(0.394000, 0.197000, 0.166667),
        u=0.000000),
      xray.scatterer( #5
        label='O',
        site=(0.803000, 0.606000, 0.500000),
        u=0.000000),
      xray.scatterer( #6
        label='O',
        site=(0.197000, 0.394000, 0.500000),
        u=0.000000),
      xray.scatterer( #7
        label='O',
        site=(0.606000, 0.803000, 0.166667),
        u=0.000000),
      xray.scatterer( #8
        label='O',
        site=(0.803000, 0.197000, 0.833333),
        u=0.000000)
        )))
def exercise(args):
  verbose =  "--verbose" in args
  if (not verbose):
    out = StringIO()
  else:
    out = sys.stdout
  crystal_symmetry = crystal.symmetry(
    unit_cell=(8,9,10,83,97,113),
    space_group_symbol="P1")
  miller_set = miller.set(
    crystal_symmetry=crystal_symmetry,
    indices=flex.miller_index([(1,2,3), (2,3,4), (-1,3,-2)]),
    anomalous_flag=False)
  for n_scatterers in xrange(2,2+5):
    for i_trial in xrange(5):
      scatterers = flex.xray_scatterer()
      for i in xrange(n_scatterers):
        scatterers.append(xray.scatterer(
          site=[random.random() for i in xrange(3)],
          u=random.random()*0.1,
          occupancy=random.random(),
          scattering_type="const",
          fp=(random.random()-0.5)*2,
          fdp=(random.random()-0.5)*2))
      xray_structure = xray.structure(
        crystal_symmetry=crystal_symmetry,
        scatterers=scatterers)
      sf = structure_factors(
        xray_structure=xray_structure,
        miller_set=miller_set)
      f_calc = miller_set.structure_factors_from_scatterers(
        xray_structure=xray_structure,
        algorithm="direct",
        cos_sin_table=False).f_calc()
      assert approx_equal(sf.fs(), f_calc.data())
      f_obs = miller_set.array(data=flex.abs(sf.fs()))
      compare_analytical_and_finite(
        f_obs=f_obs,
        xray_structure=xray_structure,
        out=out)
      compare_analytical_and_finite(
        f_obs=f_obs.customized_copy(
          data=f_obs.data()*(flex.random_double(size=f_obs.size())+0.5)),
        xray_structure=xray_structure,
        out=out)
  print "OK"
def run():
  quartz_structure = xray.structure(
    special_position_settings=crystal.special_position_settings(
      crystal_symmetry=crystal.symmetry(
        unit_cell=(5.01,5.01,5.47,90,90,120),
        space_group_symbol="P6222")),
    scatterers=flex.xray_scatterer([
      xray.scatterer(
        label="Si",
        site=(1/2.,1/2.,1/3.),
        u=0.2),
      xray.scatterer(
        label="O",
        site=(0.197,-0.197,0.83333),
        u=0)]))

  quartz_structure.show_summary().show_scatterers()

  from libtbx import easy_pickle
  easy_pickle.dump("beach", quartz_structure)

  from libtbx import easy_pickle
  quartz_structure = easy_pickle.load("beach")

  for scatterer in quartz_structure.scatterers():
    print "%s:" % scatterer.label, "%8.4f %8.4f %8.4f" % scatterer.site
    site_symmetry = quartz_structure.site_symmetry(scatterer.site)
    print "  point group type:", site_symmetry.point_group_type()
    print "  special position operator:", site_symmetry.special_op_simplified()

  for table in ["xray", "electron"]:
    print "Scattering type table:", table

    reg = quartz_structure.scattering_type_registry(table=table)
    reg.show_summary()

    f_calc = quartz_structure.structure_factors(d_min=2).f_calc()
    f_calc.show_summary().show_array()

    f_calc.d_spacings().show_array()

    low_resolution_only = f_calc.select(f_calc.d_spacings().data() > 2.5)
    low_resolution_only.show_array()

    print
Example #52
0
def exercise_with_fixed_structure():
  structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(46.7058, 46.7058, 79.3998, 90, 90, 120),
      space_group_symbol="P 31"),
    scatterers=flex.xray_scatterer(
      [xray.scatterer(scattering_type="const", site=site) for site in [
        (0.0169, 0.8953, 0.1115),
        (0.9395, 0.1282, 0.1780),
        (0.2998, 0.3497, 0.0593),
        (0.8220, 0.8814, 0.1601),
        (0.6478, 0.4879, 0.3141)]]))
  sfweight = exercise_SFweight_spline_core(
    structure=structure, d_min=5, verbose="--Verbose" in sys.argv[1:])
  assert approx_equal(flex.mean(flex.abs(sfweight.fb())), 1.7545459)
  assert approx_equal(flex.mean(flex.abs(sfweight.fd())), 1.8437204)
  assert approx_equal(flex.mean(sfweight.centroid_phases()), -0.033979132)
  assert approx_equal(flex.mean(sfweight.figures_of_merit()), 0.018943642)
def exercise_u_iso_proportional_to_pivot_u_eq():
  xs = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=(),
      space_group_symbol='hall: P 2x 2y'),
    scatterers=flex.xray_scatterer((
      xray.scatterer('C0', u=(1, 1, 1, 0, 0, 0)),
      xray.scatterer('C1'),
      xray.scatterer('C2', site=(0.1, 0.2, 0.3), u=(1, 2, 3, 0, 0, 0)),
      xray.scatterer('C3'),
      )))
  r = constraints.ext.reparametrisation(xs.unit_cell())
  sc = xs.scatterers()
  sc[0].flags.set_grad_u_aniso(True)
  sc[2].flags.set_grad_u_aniso(True)

  u_0 = r.add(constraints.special_position_u_star_parameter,
              site_symmetry=xs.site_symmetry_table().get(0),
              scatterer=sc[0])
  u_iso_1 = r.add(constraints.u_iso_proportional_to_pivot_u_eq,
                pivot_u=u_0,
                multiplier=3,
                scatterer=sc[1])
  u_2 = r.add(constraints.independent_u_star_parameter, sc[2])
  u_iso_3 = r.add(constraints.u_iso_proportional_to_pivot_u_eq,
                pivot_u=u_2,
                multiplier=2,
                scatterer=sc[3])
  r.finalise()
  m = 3 + 6
  n = m + 6 + 1 + 1
  r.linearise()
  assert approx_equal(u_iso_1.value, 3, eps=1e-15)
  assert approx_equal(u_iso_3.value, 4, eps=1e-15)
  jt0 = sparse.matrix(m, n)
  for i in xrange(m): jt0[i, i] = 1
  p, q = u_0.argument(0).index, u_0.index
  jt0[p, q] = jt0[p+1, q+1] = jt0[p+2, q+2] = 1
  q = u_iso_1.index
  jt0[p, q] = jt0[p+1, q] = jt0[p+2, q] = 1
  p, q = u_2.index, u_iso_3.index
  jt0[p, q] = jt0[p+1, q] = jt0[p+2, q] = 2/3
  assert sparse.approx_equal(tolerance=1e-15)(r.jacobian_transpose, jt0)
 def loop(self):
   for i_position in xrange(self.wyckoff_table.size()):
     site_symmetry_i = self.wyckoff_table.random_site_symmetry(
       special_position_settings=self.special_position_settings,
       i_position=i_position)
     equiv_sites_i = sgtbx.sym_equiv_sites(site_symmetry_i)
     for j_position in xrange(self.wyckoff_table.size()):
       for n_trial in xrange(self.max_trials_per_position):
         site_j = self.wyckoff_table.random_site_symmetry(
           special_position_settings=self.special_position_settings,
           i_position=j_position).exact_site()
         dist_info = sgtbx.min_sym_equiv_distance_info(equiv_sites_i, site_j)
         if (dist_info.dist() > self.min_cross_distance):
           structure = xray.structure(
             special_position_settings=self.special_position_settings,
             scatterers=flex.xray_scatterer(
              [xray.scatterer(scattering_type=self.scattering_type, site=site)
               for site in [site_symmetry_i.exact_site(), site_j]]))
           yield structure, dist_info.dist()
           break
Example #55
0
def run():
  print __doc__
  crystal_symmetry = crystal.symmetry(
    unit_cell=(5, 5, 6, 90, 90, 120),
    space_group_symbol="P 31")
  distance_cutoff = 2.5
  scatterers = flex.xray_scatterer()
  for i,site in enumerate([(0.7624, 0.5887, 0.3937),
                           (0.2813, 0.9896, 0.9449),
                           (0.4853, 0.8980, 0.4707)]):
    scatterers.append(xray.scatterer(
      label="Se%d"%(i+1), site=site))
  given_structure = xray.structure(
    crystal_symmetry=crystal_symmetry,
    scatterers=scatterers)
  print "=================="
  print "Original structure"
  print "=================="
  given_structure.show_summary().show_scatterers()
  print "Interatomic distances:"
  given_structure.show_distances(distance_cutoff=distance_cutoff)
  print
  print
  print "====================================================="
  print "Other hand with sites flipped and space group changed"
  print "====================================================="
  other_hand = given_structure.change_hand()
  other_hand.show_summary().show_scatterers()
  print "Interatomic distances:"
  other_hand.show_distances(distance_cutoff=distance_cutoff)
  print
  print "=================================="
  print "Other hand with sites flipped only"
  print "=================================="
  other_sites_orig_symmetry = xray.structure(
    crystal_symmetry=crystal_symmetry,
    scatterers=other_hand.scatterers())
  other_sites_orig_symmetry.show_summary().show_scatterers()
  print "Interatomic distances:"
  other_sites_orig_symmetry.show_distances(distance_cutoff=distance_cutoff)
  print