Exemplo n.º 1
0
def exercise_trigonometric_ff():
    from math import cos, sin, pi
    sgi = sgtbx.space_group_info("P1")
    cs = sgi.any_compatible_crystal_symmetry(volume=1000)
    miller_set = miller.build_set(cs, anomalous_flag=False, d_min=1)
    miller_set = miller_set.select(flex.random_double(miller_set.size()) < 0.2)
    for i in range(5):
        sites = flex.random_double(9)
        x1, x2, x3 = (matrix.col(sites[:3]), matrix.col(sites[3:6]),
                      matrix.col(sites[6:]))
        xs = xray.structure(crystal.special_position_settings(cs))
        for x in (x1, x2, x3):
            sc = xray.scatterer(site=x, scattering_type="const")
            sc.flags.set_grad_site(True)
            xs.add_scatterer(sc)
        f_sq = structure_factors.f_calc_modulus_squared(xs)
        for h in miller_set.indices():
            h = matrix.col(h)
            phi1, phi2, phi3 = 2 * pi * h.dot(x1), 2 * pi * h.dot(
                x2), 2 * pi * h.dot(x3)
            fc_mod_sq = 3 + 2 * (cos(phi1 - phi2) + cos(phi2 - phi3) +
                                 cos(phi3 - phi1))
            g = []
            g.extend(-2 * (sin(phi1 - phi2) - sin(phi3 - phi1)) * 2 * pi * h)
            g.extend(-2 * (sin(phi2 - phi3) - sin(phi1 - phi2)) * 2 * pi * h)
            g.extend(-2 * (sin(phi3 - phi1) - sin(phi2 - phi3)) * 2 * pi * h)
            grad_fc_mod_sq = g

            f_sq.linearise(h)
            assert approx_equal(f_sq.observable, fc_mod_sq)
            assert approx_equal(f_sq.grad_observable, grad_fc_mod_sq)
Exemplo n.º 2
0
 def peak_search(self, parameters, map, verify_symmetry=True):
   if (parameters is None):
     parameters = peak_search_parameters()
   if (verify_symmetry and libtbx.env.full_testing):
     assert self._tags.verify(map)
   if (map.accessor().is_padded()):
     map = copy(map, flex.grid(map.focus()))
   grid_peaks = peak_list(
     data=map,
     tags=self._tags.tag_array(),
     peak_search_level=parameters.peak_search_level(),
     max_peaks=parameters.max_peaks(),
     peak_cutoff=parameters.peak_cutoff(),
     interpolate=parameters.interpolate())
   if (parameters.min_distance_sym_equiv() is None):
     return grid_peaks
   return peak_cluster_analysis(
     peak_list=grid_peaks,
     special_position_settings=crystal.special_position_settings(
       crystal_symmetry=self.crystal_symmetry(),
       min_distance_sym_equiv=parameters.min_distance_sym_equiv()),
     general_positions_only=parameters.general_positions_only(),
     effective_resolution=parameters.effective_resolution(),
     significant_height_fraction=parameters.significant_height_fraction(),
     cluster_height_fraction=parameters.cluster_height_fraction(),
     min_cross_distance=parameters.min_cross_distance(),
     max_clusters=parameters.max_clusters(),
     min_cubicle_edge=parameters.min_cubicle_edge())
Exemplo n.º 3
0
 def __init__(self, model_id="SBT", n_elements=4):
     if (model_id is None): return
     self.model_id = model_id
     pos = emma.position
     if (type(model_id) == type("")):
         if (model_id == "SBT"):
             emma.model.__init__(
                 self,
                 crystal.special_position_settings(
                     crystal.symmetry((16.8986, 16.8986, 16.8986, 61.1483,
                                       61.1483, 61.1483), "R -3 m :R")),
                 (pos("SI1", (-0.3584, 0.2844, 0.4622)),
                  pos("SI2", (-0.2133, 0.9659, -0.6653)),
                  pos("SI3", (-0.8358, 0.7, 0.3431)),
                  pos("SI4", (0.4799, 1.836, 0.6598))))
         else:
             raise RuntimeError("Unknown model_id: " + model_id)
     else:
         structure = random_structure.xray_structure(model_id,
                                                     elements=["S"] *
                                                     n_elements,
                                                     volume_per_atom=50.,
                                                     min_distance=2.0)
         positions = []
         for scatterer in structure.scatterers():
             positions.append(emma.position(scatterer.label,
                                            scatterer.site))
         emma.model.__init__(self, structure, positions)
Exemplo n.º 4
0
 def get_next(self):
     if (self.coordinate_format == "generic"):
         if (self.i_next_model): return None
         crystal_symmetry = crystal.symmetry(
             unit_cell=self.get_unit_cell(),
             space_group_info=self.get_space_group_info())
         m = emma.model(crystal.special_position_settings(crystal_symmetry),
                        self.positions)
         m.label = "Model 2"
         self.i_next_model += 1
         return m
     if (self.coordinate_format == "pdb"):
         if (self.i_next_model): return None
         self.i_next_model += 1
         return self.pdb_model
     if (self.coordinate_format == "sdb"):
         if (self.i_next_model >= len(self.sdb_files)): return None
         sdb = self.sdb_files[self.i_next_model]
         crystal_symmetry = crystal.symmetry(
             unit_cell=self.get_unit_cell(sdb.unit_cell),
             space_group_info=self.get_space_group_info(
                 sdb.space_group_info))
         if (self.other_symmetry is not None):
             crystal_symmetry = crystal_symmetry.join_symmetry(
                 other_symmetry=self.other_symmetry, force=False)
         m = sdb_file_to_emma_model(crystal_symmetry, sdb)
         self.i_next_model += 1
         return m
     raise RuntimeError("Internal error.")
Exemplo n.º 5
0
def exercise_trigonometric_ff():
    from math import cos, sin, pi

    sgi = sgtbx.space_group_info("P1")
    cs = sgi.any_compatible_crystal_symmetry(volume=1000)
    miller_set = miller.build_set(cs, anomalous_flag=False, d_min=1)
    miller_set = miller_set.select(flex.random_double(miller_set.size()) < 0.2)
    for i in xrange(5):
        sites = flex.random_double(9)
        x1, x2, x3 = (matrix.col(sites[:3]), matrix.col(sites[3:6]), matrix.col(sites[6:]))
        xs = xray.structure(crystal.special_position_settings(cs))
        for x in (x1, x2, x3):
            sc = xray.scatterer(site=x, scattering_type="const")
            sc.flags.set_grad_site(True)
            xs.add_scatterer(sc)
        f_sq = structure_factors.f_calc_modulus_squared(xs)
        for h in miller_set.indices():
            h = matrix.col(h)
            phi1, phi2, phi3 = 2 * pi * h.dot(x1), 2 * pi * h.dot(x2), 2 * pi * h.dot(x3)
            fc_mod_sq = 3 + 2 * (cos(phi1 - phi2) + cos(phi2 - phi3) + cos(phi3 - phi1))
            g = []
            g.extend(-2 * (sin(phi1 - phi2) - sin(phi3 - phi1)) * 2 * pi * h)
            g.extend(-2 * (sin(phi2 - phi3) - sin(phi1 - phi2)) * 2 * pi * h)
            g.extend(-2 * (sin(phi3 - phi1) - sin(phi2 - phi3)) * 2 * pi * h)
            grad_fc_mod_sq = g

            f_sq.linearise(h)
            assert approx_equal(f_sq.observable, fc_mod_sq)
            assert approx_equal(f_sq.grad_observable, grad_fc_mod_sq)
Exemplo n.º 6
0
def run():
    symmetry = crystal.symmetry(unit_cell=(10.67, 10.67, 4.68, 90, 90, 120),
                                space_group_symbol="P 3")

    special_position_settings = crystal.special_position_settings(
        crystal_symmetry=symmetry, min_distance_sym_equiv=0.5)

    site = (0, 0, 0.236)
    u_cif = ((0.17, 0.17, 0.19, 0.09, 0, 0))

    site_symmetry = special_position_settings.site_symmetry(site)

    print "Input Ucif:", u_cif
    u_star = adptbx.u_cif_as_u_star(symmetry.unit_cell(), u_cif)
    if (not site_symmetry.is_compatible_u_star(u_star)):
        print "Warning: ADP tensor is incompatible with site symmetry."
    u_star = site_symmetry.average_u_star(u_star)
    u_cif = adptbx.u_star_as_u_cif(symmetry.unit_cell(), u_star)
    print "Averaged Ucif:", u_cif

    u_cart = adptbx.u_star_as_u_cart(symmetry.unit_cell(), u_star)
    eigenvalues = adptbx.eigenvalues(u_cart)
    if (not adptbx.is_positive_definite(eigenvalues)):
        print "ADP tensor is not positive definite."

    print "Eigenvectors and values:"
    eigensystem = adptbx.eigensystem(u_cart)
    for i in xrange(3):
        print "  v=(%.5f %.5f %.5f) " % eigensystem.vectors(i),
        print "lambda=%.4f" % (eigensystem.values()[i], )
Exemplo n.º 7
0
def special_position_settings_from_inp(inp):
    return crystal.special_position_settings(crystal.symmetry(
        unit_cell=uctbx.unit_cell(inp.ucparams),
        space_group_info=sgtbx.space_group_info(symbol=inp.sgsymbol,
                                                table_id=inp.convention)),
                                             min_distance_sym_equiv=float(
                                                 inp.min_distance_sym_equiv))
Exemplo n.º 8
0
 def peak_search(self, parameters, map, verify_symmetry=True):
     if (parameters is None):
         parameters = peak_search_parameters()
     if (verify_symmetry and libtbx.env.full_testing):
         assert self._tags.verify(map)
     if (map.accessor().is_padded()):
         map = copy(map, flex.grid(map.focus()))
     grid_peaks = peak_list(
         data=map,
         tags=self._tags.tag_array(),
         peak_search_level=parameters.peak_search_level(),
         max_peaks=parameters.max_peaks(),
         peak_cutoff=parameters.peak_cutoff(),
         interpolate=parameters.interpolate())
     if (parameters.min_distance_sym_equiv() is None):
         return grid_peaks
     return peak_cluster_analysis(
         peak_list=grid_peaks,
         special_position_settings=crystal.special_position_settings(
             crystal_symmetry=self.crystal_symmetry(),
             min_distance_sym_equiv=parameters.min_distance_sym_equiv()),
         general_positions_only=parameters.general_positions_only(),
         effective_resolution=parameters.effective_resolution(),
         significant_height_fraction=parameters.significant_height_fraction(
         ),
         cluster_height_fraction=parameters.cluster_height_fraction(),
         min_cross_distance=parameters.min_cross_distance(),
         max_clusters=parameters.max_clusters(),
         min_cubicle_edge=parameters.min_cubicle_edge())
Exemplo n.º 9
0
def exercise_tensor_constraints_core(crystal_symmetry):
  from cctbx import crystal
  from cctbx import adptbx
  from scitbx import matrix
  site_symmetry = crystal.special_position_settings(
    crystal_symmetry).site_symmetry(site=(0,0,0))
  unit_cell = crystal_symmetry.unit_cell()
  group = crystal_symmetry.space_group()
  assert site_symmetry.n_matrices() == group.order_p()
  for reciprocal_space in [False, True]:
    c_tensor_constraints = sgtbx.tensor_rank_2_constraints(
      space_group=group,
      reciprocal_space=reciprocal_space).row_echelon_form()
    p_tensor_constraints = python_tensor_constraints(
      self=group, reciprocal_space=reciprocal_space)
    assert c_tensor_constraints.all_eq(p_tensor_constraints)
  adp_constraints = group.adp_constraints()
  u_cart_p1 = adptbx.random_u_cart()
  u_star_p1 = adptbx.u_cart_as_u_star(unit_cell, u_cart_p1)
  u_star = site_symmetry.average_u_star(u_star_p1)
  f = unit_cell.volume()**(2/3.)
  assert approx_equal(
    list(matrix.col(group.average_u_star(u_star=u_star_p1))*f),
    list(matrix.col(u_star)*f))
  independent_params = adp_constraints.independent_params(u_star)
  assert adp_constraints.n_independent_params() == len(independent_params)
  assert adp_constraints.n_independent_params() \
       + adp_constraints.n_dependent_params() == 6
  u_star_vfy = adp_constraints.all_params(independent_params)
  u_cart = adptbx.u_star_as_u_cart(unit_cell, u_star)
  u_cart_vfy = adptbx.u_star_as_u_cart(unit_cell, list(u_star_vfy))
  assert approx_equal(u_cart_vfy, u_cart)
Exemplo n.º 10
0
 def __init__(self, model_id="SBT", n_elements=4):
   if (model_id is None): return
   self.model_id = model_id
   pos = emma.position
   if (type(model_id) == type("")):
     if (model_id == "SBT"):
       emma.model.__init__(self,
         crystal.special_position_settings(crystal.symmetry(
           (16.8986, 16.8986, 16.8986, 61.1483, 61.1483, 61.1483),
           "R -3 m :R")),
         (pos("SI1", (-0.3584, 0.2844, 0.4622)),
          pos("SI2", (-0.2133, 0.9659, -0.6653)),
          pos("SI3", (-0.8358, 0.7, 0.3431)),
          pos("SI4", (0.4799, 1.836, 0.6598))))
     else:
       raise RuntimeError, "Unknown model_id: " + model_id
   else:
     structure = random_structure.xray_structure(
       model_id,
       elements=["S"]*n_elements,
       volume_per_atom=50.,
       min_distance=2.0)
     positions = []
     for scatterer in structure.scatterers():
       positions.append(emma.position(scatterer.label, scatterer.site))
     emma.model.__init__(self, structure, positions)
Exemplo n.º 11
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()
Exemplo n.º 12
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")
Exemplo n.º 13
0
 def _process_occupancies(self):
   def check_if_already_modified():
     if(self.top_selection): return
     if (self._occupancies_modified):
       raise Sorry("Can't modify occupancies (already modified).")
     else:
       self._occupancies_modified = True
   for occ in self.params.occupancies:
     if(occ.atom_selection is None):
       selection = self.top_selection
     else:
       asc = self.pdb_hierarchy.atom_selection_cache(
       special_position_settings=crystal.special_position_settings(
           crystal_symmetry = self.crystal_symmetry))
       sel = asc.selection(occ.atom_selection)
       selection = flex.smart_selection(flags=sel)
     if(occ.randomize):
       self._print_action(
         text = "Randomizing occupancies",
         selection = selection)
       check_if_already_modified()
       self.xray_structure.shake_occupancies(selection=selection.flags)
     if(occ.set is not None):
       self._print_action(
         text = "Setting occupancies to: %8.3f"%occ.set, selection = selection)
       check_if_already_modified()
       self.xray_structure.set_occupancies(
           value = occ.set,
           selection = selection.flags)
Exemplo n.º 14
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")
Exemplo n.º 15
0
def peak_cluster_reduction(crystal_symmetry, peak_list,
                           min_peak_distance, max_reduced_peaks):
  special_position_settings = crystal.special_position_settings(
    crystal_symmetry=crystal_symmetry,
    min_distance_sym_equiv=min_peak_distance)
  peaks = []
  for i,site in enumerate(peak_list.sites()):
    peaks.append(dicts.easy(
      site=special_position_settings.site_symmetry(site).exact_site(),
      height=peak_list.heights()[i]))
  reduced_peaks = []
  for peak in peaks:
    site_symmetry = special_position_settings.site_symmetry(peak.site)
    equiv_sites = sgtbx.sym_equiv_sites(site_symmetry)
    keep = True
    for reduced_peak in reduced_peaks:
      dist = sgtbx.min_sym_equiv_distance_info(
        equiv_sites, reduced_peak.site).dist()
      if (dist < min_peak_distance):
        keep = False
        break
    if (keep == True):
      reduced_peaks.append(peak)
      if (len(reduced_peaks) == max_reduced_peaks): break
  return reduced_peaks
Exemplo n.º 16
0
def exercise_tensor_constraints_core(crystal_symmetry):
    from cctbx import crystal
    from cctbx import adptbx
    from scitbx import matrix
    site_symmetry = crystal.special_position_settings(
        crystal_symmetry).site_symmetry(site=(0, 0, 0))
    unit_cell = crystal_symmetry.unit_cell()
    group = crystal_symmetry.space_group()
    assert site_symmetry.n_matrices() == group.order_p()
    for reciprocal_space in [False, True]:
        c_tensor_constraints = sgtbx.tensor_rank_2_constraints(
            space_group=group,
            reciprocal_space=reciprocal_space).row_echelon_form()
        p_tensor_constraints = python_tensor_constraints(
            self=group, reciprocal_space=reciprocal_space)
        assert c_tensor_constraints.all_eq(p_tensor_constraints)
    adp_constraints = group.adp_constraints()
    u_cart_p1 = adptbx.random_u_cart()
    u_star_p1 = adptbx.u_cart_as_u_star(unit_cell, u_cart_p1)
    u_star = site_symmetry.average_u_star(u_star_p1)
    f = unit_cell.volume()**(2 / 3.)
    assert approx_equal(
        list(matrix.col(group.average_u_star(u_star=u_star_p1)) * f),
        list(matrix.col(u_star) * f))
    independent_params = adp_constraints.independent_params(u_star)
    assert adp_constraints.n_independent_params() == len(independent_params)
    assert adp_constraints.n_independent_params() \
         + adp_constraints.n_dependent_params() == 6
    u_star_vfy = adp_constraints.all_params(independent_params)
    u_cart = adptbx.u_star_as_u_cart(unit_cell, u_star)
    u_cart_vfy = adptbx.u_star_as_u_cart(unit_cell, list(u_star_vfy))
    assert approx_equal(u_cart_vfy, u_cart)
Exemplo n.º 17
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()
Exemplo n.º 18
0
 def get_next(self):
   if (self.coordinate_format == "generic"):
     if (self.i_next_model): return None
     crystal_symmetry = crystal.symmetry(
       unit_cell=self.get_unit_cell(),
       space_group_info=self.get_space_group_info())
     m = emma.model(
       crystal.special_position_settings(crystal_symmetry),
       self.positions)
     m.label = "Model 2"
     self.i_next_model += 1
     return m
   if (self.coordinate_format == "pdb"):
     if (self.i_next_model): return None
     self.i_next_model += 1
     return self.pdb_model
   if (self.coordinate_format == "sdb"):
     if (self.i_next_model >= len(self.sdb_files)): return None
     sdb = self.sdb_files[self.i_next_model]
     crystal_symmetry = crystal.symmetry(
       unit_cell=self.get_unit_cell(sdb.unit_cell),
       space_group_info=self.get_space_group_info(sdb.space_group_info))
     if (self.other_symmetry is not None):
       crystal_symmetry = crystal_symmetry.join_symmetry(
         other_symmetry=self.other_symmetry,
         force=False)
     m = sdb_file_to_emma_model(crystal_symmetry, sdb)
     self.i_next_model += 1
     return m
   raise RuntimeError("Internal error.")
Exemplo n.º 19
0
 def _renumber_residues(self):
   if((self.params.increment_resseq) or
      (self.params.renumber_residues)):
     print("Re-numbering residues", file=self.log)
     renumber_from  = self.params.increment_resseq
     atom_selection = self.params.selection
     pdb_hierarchy  = self.pdb_hierarchy
     selected_i_seqs = None
     if (atom_selection is not None):
       sel_cache = pdb_hierarchy.atom_selection_cache(
       special_position_settings=crystal.special_position_settings(
           crystal_symmetry = self.crystal_symmetry))
       selected_i_seqs = sel_cache.selection(atom_selection).iselection()
     for model in pdb_hierarchy.models():
       for chain in model.chains():
         if (selected_i_seqs is not None):
           chain_i_seqs = chain.atoms().extract_i_seq()
           intersection = selected_i_seqs.intersection(chain_i_seqs)
           if (len(intersection) == 0):
             continue
           elif (len(intersection) != len(chain_i_seqs)):
             print("Warning: chain '%s' is only partially selected (%d out of %d) - will not renumber." % (chain.id, len(intersection), len(chain_i_seqs)), file=self.log)
             continue
         if (renumber_from is None):
           counter = 1
           for rg in chain.residue_groups():
             rg.resseq=counter
             counter += 1
         else :
           for rg in chain.residue_groups():
             resseq = rg.resseq_as_int()
             resseq += renumber_from
             rg.resseq = "%4d" % resseq
Exemplo n.º 20
0
Arquivo: gid.py Projeto: 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()
Exemplo n.º 21
0
def run():
  symmetry = crystal.symmetry(
    unit_cell=(10.67, 10.67, 4.68, 90, 90, 120),
    space_group_symbol="P 3")

  special_position_settings = crystal.special_position_settings(
    crystal_symmetry=symmetry,
    min_distance_sym_equiv=0.5)

  site = (0, 0, 0.236)
  u_cif = ((0.17, 0.17, 0.19, 0.09, 0, 0))

  site_symmetry = special_position_settings.site_symmetry(site)

  print "Input Ucif:", u_cif
  u_star = adptbx.u_cif_as_u_star(symmetry.unit_cell(), u_cif)
  if (not site_symmetry.is_compatible_u_star(u_star)):
    print "Warning: ADP tensor is incompatible with site symmetry."
  u_star = site_symmetry.average_u_star(u_star)
  u_cif = adptbx.u_star_as_u_cif(symmetry.unit_cell(), u_star)
  print "Averaged Ucif:", u_cif

  u_cart = adptbx.u_star_as_u_cart(symmetry.unit_cell(), u_star)
  eigenvalues = adptbx.eigenvalues(u_cart)
  if (not adptbx.is_positive_definite(eigenvalues)):
    print "ADP tensor is not positive definite."

  print "Eigenvectors and values:"
  eigensystem = adptbx.eigensystem(u_cart)
  for i in xrange(3):
    print "  v=(%.5f %.5f %.5f) " % eigensystem.vectors(i),
    print "lambda=%.4f" % (eigensystem.values()[i],)
Exemplo n.º 22
0
def run(server_info, inp, status):
    print "<pre>"
    # check input to prevent XSS
    try:
        unit_cell = uctbx.unit_cell(inp.ucparams)
        space_group_info = sgtbx.space_group_info(symbol=inp.sgsymbol,
                                                  table_id=inp.convention)
    except Exception:
        print "Please check your inputs."
        print "</pre>"
        return
    io_utils.show_input_symbol(inp.sgsymbol, inp.convention)
    special_position_settings = crystal.special_position_settings(
        crystal.symmetry(unit_cell=uctbx.unit_cell(inp.ucparams),
                         space_group_info=sgtbx.space_group_info(
                             symbol=inp.sgsymbol, table_id=inp.convention)),
        min_distance_sym_equiv=float(inp.min_distance_sym_equiv))
    special_position_settings.show_summary()
    print "Minimum distance between symmetrically equivalent sites:",
    print special_position_settings.min_distance_sym_equiv()
    print

    skip_columns = io_utils.interpret_skip_columns(inp.skip_columns)

    wyckoff_table = special_position_settings.space_group_info().wyckoff_table(
    )
    unit_cell = special_position_settings.unit_cell()
    print "</pre><table border=2 cellpadding=2>"
    status.in_table = True
    print "<tr>"
    if (skip_columns): print "<th>"
    print "<th colspan=3>" + inp.coor_type + " coordinates"
    print "<th>Multiplicity"
    print "<th>Wyckoff letter"
    print "<th>Site symmetry<br>point group type"
    print "<th>Special position operator"
    print "</tr>"
    for line in inp.coordinates:
        skipped, coordinates = io_utils.interpret_coordinate_line(
            line, skip_columns)
        if (inp.coor_type != "Fractional"):
            coordinates = unit_cell.fractionalize(coordinates)
        site_symmetry = special_position_settings.site_symmetry(coordinates)
        exact_site = site_symmetry.exact_site()
        if (inp.coor_type != "Fractional"):
            exact_site = unit_cell.orthogonalize(exact_site)
        wyckoff_mapping = wyckoff_table.mapping(site_symmetry)
        print "<tr>"
        if (skip_columns): print "<td>", skipped
        for x in exact_site:
            print "<td><tt>%.6g</tt>" % (x, )
        print "<td align=center>", wyckoff_mapping.position().multiplicity()
        print "<td align=center>", wyckoff_mapping.position().letter()
        print "<td align=center>", site_symmetry.point_group_type()
        print "<td><tt>" + str(site_symmetry.special_op_simplified()) + "</tt>"
        print "</tr>"
    print "</table><pre>"
    status.in_table = False

    print "</pre>"
Exemplo n.º 23
0
def special_position_settings_from_inp(inp):
    return crystal.special_position_settings(
        crystal.symmetry(
            unit_cell=uctbx.unit_cell(inp.ucparams),
            space_group_info=sgtbx.space_group_info(symbol=inp.sgsymbol, table_id=inp.convention),
        ),
        min_distance_sym_equiv=float(inp.min_distance_sym_equiv),
    )
Exemplo n.º 24
0
 def as_xray_structure(self, min_distance_sym_equiv=0.5):
   result = xray.structure(
     special_position_settings=crystal.special_position_settings(
       crystal_symmetry=self.crystal_symmetry(),
       min_distance_sym_equiv=min_distance_sym_equiv))
   for atm in self.atoms:
     result.add_scatterer(atm.as_xray_scatterer())
   return result
Exemplo n.º 25
0
 def as_xray_structure(self, min_distance_sym_equiv=0.5):
     result = xray.structure(
         special_position_settings=crystal.special_position_settings(
             crystal_symmetry=self.crystal_symmetry(),
             min_distance_sym_equiv=min_distance_sym_equiv))
     for atm in self.atoms:
         result.add_scatterer(atm.as_xray_scatterer())
     return result
Exemplo n.º 26
0
 def __init__(
         self,
         pdb_hierarchy,
         crystal_symmetry,
         rotamer_manager,
         sin_cos_table,
         mon_lib_srv,
         map_data_scale=2.5,
         diff_map_data_threshold=-2.5,
         rotatable_hd=None,
         bselection=None,
         map_data=None,
         vdw_radii=None,
         backbone_sample=False,  # XXX
         diff_map_data=None,
         log=None):
     adopt_init_args(self, locals())
     self.processed = 0
     self.total_time_residue_loop = 0
     t0 = time.time()
     self.atoms = self.pdb_hierarchy.atoms()
     self.cmv = None
     if (self.map_data is not None):
         self.cmv = mmtbx.refinement.real_space.common_map_values(
             pdb_hierarchy=self.pdb_hierarchy,
             unit_cell=self.crystal_symmetry.unit_cell(),
             map_data=self.map_data)
     self.mes = []
     if (self.bselection is None):
         o = mmtbx.refinement.real_space.side_chain_fit_evaluator(
             pdb_hierarchy=self.pdb_hierarchy,
             crystal_symmetry=self.crystal_symmetry,
             rotamer_evaluator=self.rotamer_manager.rotamer_evaluator,
             map_data=self.map_data,
             diff_map_data=self.diff_map_data,
             map_data_scale=self.map_data_scale,
             diff_map_data_threshold=self.diff_map_data_threshold)
         self.mes.extend(o.mes)
         self.bselection = o.sel_all()  # or all_possible() ?
     if (self.log is None): self.log = sys.stdout
     self.special_position_settings = crystal.special_position_settings(
         crystal_symmetry=self.crystal_symmetry)
     # Even better would be to pass it here. Ideally just use model
     asc = self.pdb_hierarchy.atom_selection_cache()
     self.selection_water_as_set = \
       set(asc.selection(string = "water").iselection())
     self.target_map = map_data
     self.mes.append("outliers start: %d" % self.count_outliers())
     #
     self.loop(function=self.one_residue_iteration)
     #
     self.mes.append("outliers final: %d" % self.count_outliers())
     #
     self.mes.append("residues processed: %d" % self.processed)
     if (self.processed > 0):
         self.mes.append("average time/residue: %6.4f" %
                         (self.total_time_residue_loop / self.processed))
     self.mes.append("time to fit residues: %6.4f" % (time.time() - t0))
Exemplo n.º 27
0
 def _get_special_position_indices(self):
   special_position_settings = crystal.special_position_settings(
     crystal_symmetry = self.crystal_symmetry)
   site_symmetry_table = \
     special_position_settings.site_symmetry_table(
       sites_cart = self.pdb_hierarchy.atoms().extract_xyz(),
       unconditional_general_position_flags=(
         self.pdb_hierarchy.atoms().extract_occ() != 1))
   return site_symmetry_table.special_position_indices()
Exemplo n.º 28
0
    def run(self):
        # I'm guessing self.data_manager, self.params and self.logger
        # are already defined here...

        # this must be mmtbx.model.manager?
        model = self.data_manager.get_model()
        atoms = model.get_atoms()
        all_bsel = flex.bool(atoms.size(), False)
        for selection_string in self.params.atom_selection_program.inselection:
            print("Selecting '%s'" % selection_string, file=self.logger)
            isel = model.iselection(string=selection_string)
            all_bsel.set_selected(isel, True)
            if self.params.atom_selection_program.write_pdb_file is None:
                print("  %d atom%s selected" % plural_s(isel.size()),
                      file=self.logger)
                for atom in atoms.select(isel):
                    print("    %s" % atom.format_atom_record(),
                          file=self.logger)
        print("", file=self.logger)
        if self.params.atom_selection_program.write_pdb_file is not None:
            print("Writing file:",
                  show_string(
                      self.params.atom_selection_program.write_pdb_file),
                  file=self.logger)
            ss_ann = model.get_ss_annotation()
            if not model.crystal_symmetry() or \
              (not model.crystal_symmetry().unit_cell()):
                model = shift_and_box_model(model, shift_model=False)
            selected_model = model.select(all_bsel)
            if (ss_ann is not None):
                selected_model.set_ss_annotation(ss_ann.\
                    filter_annotation(
                        hierarchy=selected_model.get_hierarchy(),
                        asc=selected_model.get_atom_selection_cache(),
                        remove_short_annotations=False,
                        remove_3_10_helices=False,
                        remove_empty_annotations=True,
                        concatenate_consecutive_helices=False,
                        split_helices_with_prolines=False,
                        filter_sheets_with_long_hbonds=False))
            if self.params.atom_selection_program.cryst1_replacement_buffer_layer is not None:
                box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center(
                    sites_cart=selected_model.get_atoms().extract_xyz(),
                    buffer_layer=self.params.atom_selection_program.
                    cryst1_replacement_buffer_layer)
                sp = crystal.special_position_settings(box.crystal_symmetry())
                sites_frac = box.sites_frac()
                xrs_box = selected_model.get_xray_structure(
                ).replace_sites_frac(box.sites_frac())
                xray_structure_box = xray.structure(sp, xrs_box.scatterers())
                selected_model.set_xray_structure(xray_structure_box)
            pdb_str = selected_model.model_as_pdb()
            f = open(self.params.atom_selection_program.write_pdb_file, 'w')
            f.write(pdb_str)
            f.close()
            print("", file=self.logger)
Exemplo n.º 29
0
    def __init__(
            self,
            model,  # changed in place
            params=None,
            log=null_out(),
            reference_map=None):
        """
    Substitute secondary structure elements in real_h hierarchy with ideal
    ones _in_place_.
    Returns reference torsion proxies - the only thing that cannot be restored
    with little effort outside the procedure.
    """

        self.model = model
        self.params = params

        self.ss_annotation = self.model.get_ss_annotation()
        self.log = log
        self.reference_map = reference_map

        self.idealized_counts = None

        t0 = time()
        if self.model.get_hierarchy().models_size() > 1:
            raise Sorry("Multi model files are not supported")
        for m in self.model.get_hierarchy().models():
            for chain in m.chains():
                if len(chain.conformers()) > 1:
                    raise Sorry("Alternative conformations are not supported.")

        self.processed_params = self._process_params(params)
        if not self.processed_params.enabled:
            return None
        if self.ss_annotation is None:
            return None

        # ann = ss_annotation
        if self.model.ncs_constraints_present():
            print("Using master NCS to reduce amount of work", file=self.log)

        expected_n_hbonds = 0
        for h in self.ss_annotation.helices:
            expected_n_hbonds += h.get_n_maximum_hbonds()
        self.edited_h = self.model.get_hierarchy().deep_copy()

        # gathering initial special position atoms
        special_position_settings = crystal.special_position_settings(
            crystal_symmetry=self.model.crystal_symmetry())
        site_symmetry_table = \
            special_position_settings.site_symmetry_table(
              sites_cart = self.model.get_sites_cart(),
              unconditional_general_position_flags=(
                self.model.get_atoms().extract_occ() != 1))
        self.original_spi = site_symmetry_table.special_position_indices()

        t1 = time()
Exemplo n.º 30
0
 def _set_atomic_charge(self):
   if(self.params.set_charge.charge_selection is not None):
     print("Setting atomic charge", file=self.log)
     selection = self.params.set_charge.charge_selection
     charge    = self.params.set_charge.charge
     sel_cache = self.pdb_hierarchy.atom_selection_cache(
       special_position_settings=crystal.special_position_settings(
           crystal_symmetry = self.crystal_symmetry))
     isel = sel_cache.selection(selection).iselection()
     self.pdb_hierarchy.set_atomic_charge(iselection=isel, charge=charge)
Exemplo n.º 31
0
def run(args, command_name=libtbx.env.dispatcher_name):
    parser = argparse.ArgumentParser(
        prog=command_name,
        usage='%s pdb_file "atom_selection" [...]' % command_name)
    parser.add_argument("file_name",
                        nargs=1,
                        help="File name of the model file")
    parser.add_argument(
        "inselections",
        help="Atom selection strings",
        nargs='+',
    )
    parser.add_argument("--write-pdb-file",
                        action="store",
                        help="write selected atoms to new PDB file",
                        default=None)
    parser.add_argument(
        "--cryst1-replacement-buffer-layer",
        action="store",
        type=float,
        help="replace CRYST1 with pseudo unit cell covering the selected"
        " atoms plus a surrounding buffer layer",
        default=None)
    co = parser.parse_args(args)
    pdb_inp = iotbx.pdb.input(file_name=co.file_name[0])
    model = mmtbx.model.manager(model_input=pdb_inp, process_input=True)
    atoms = model.get_atoms()
    all_bsel = flex.bool(atoms.size(), False)
    for selection_string in co.inselections:
        print selection_string
        isel = model.iselection(selstr=selection_string)
        all_bsel.set_selected(isel, True)
        if (not co.write_pdb_file):
            print "  %d atom%s selected" % plural_s(isel.size())
            for atom in atoms.select(isel):
                print "    %s" % atom.format_atom_record()
    print
    if (co.write_pdb_file):
        print "Writing file:", show_string(co.write_pdb_file)
        selected_model = model.select(all_bsel)
        if (co.cryst1_replacement_buffer_layer is not None):
            box = uctbx.non_crystallographic_unit_cell_with_the_sites_in_its_center(
                sites_cart=selected_model.get_atoms().extract_xyz(),
                buffer_layer=co.cryst1_replacement_buffer_layer)
            sp = crystal.special_position_settings(box.crystal_symmetry())
            sites_frac = box.sites_frac()
            xrs_box = selected_model.get_xray_structure().replace_sites_frac(
                box.sites_frac())
            xray_structure_box = xray.structure(sp, xrs_box.scatterers())
            selected_model.set_xray_structure(xray_structure_box)
        pdb_str = selected_model.model_as_pdb()
        f = open(co.write_pdb_file, 'w')
        f.write(pdb_str)
        f.close()
        print
Exemplo n.º 32
0
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
Exemplo n.º 33
0
def exercise_special_position_settings():
    xs = crystal.symmetry((3, 4, 5), "P 2 2 2")
    sp = crystal.special_position_settings(xs, 1, 2, False)
    assert sp.min_distance_sym_equiv() == 1
    assert sp.u_star_tolerance() == 2
    assert sp.assert_min_distance_sym_equiv() == False
    assert sp.site_symmetry((0, 0, 0)).multiplicity() == 1
    assert sp.site_symmetry(site=(0, 0, 0)).multiplicity() == 1
    assert sp.site_symmetry(site_cart=(0, 0, 0)).multiplicity() == 1
    assert str(sp.sym_equiv_sites((0, 0, 0)).special_op()) == "0,0,0"
    sites_cart = flex.vec3_double([(2, 1, 3), (0, 0, 0)])
    t = sp.site_symmetry_table(sites_cart=sites_cart)
    assert list(t.special_position_indices()) == [1]
    assert approx_equal(
        t.apply_symmetry_sites(unit_cell=xs.unit_cell(),
                               sites_cart=sites_cart), sites_cart)
    #
    for min_distance_sym_equiv, special_op in [(1e-6, "0,0,0"), (0, "x,y,z")]:
        sp = crystal.special_position_settings(
            crystal_symmetry=xs, min_distance_sym_equiv=min_distance_sym_equiv)
        assert str(sp.sym_equiv_sites((0, 0, 0)).special_op()) == special_op
    #
    sites_cart = flex.vec3_double([(0, 0, 0)])
    sp = xs.special_position_settings()
    asu_mappings = sp.asu_mappings(buffer_thickness=3, sites_cart=sites_cart)
    assert list(asu_mappings.site_symmetry_table().special_position_indices()) \
        == [0]
    #
    pair_generator = sp.pair_generator(distance_cutoff=1,
                                       sites_cart=sites_cart)
    assert pair_generator.count_pairs() == 0
    sp0 = xs.special_position_settings(min_distance_sym_equiv=0)
    pair_generator = sp0.pair_generator(distance_cutoff=1,
                                        sites_cart=sites_cart)
    assert pair_generator.count_pairs() == 3
    #
    pair_asu_table = sp.pair_asu_table(distance_cutoff=1,
                                       sites_cart=sites_cart)
    assert pair_asu_table.table()[0].size() == 0
    pair_asu_table = sp0.pair_asu_table(distance_cutoff=1,
                                        sites_cart=sites_cart)
    assert pair_asu_table.table()[0][0].size() == 3
Exemplo n.º 34
0
 def _apply_keep_remove(self):
   cn = [self.params.remove, self.params.keep].count(None)
   if(not cn in [1,2]):
     raise Sorry("'keep' and 'remove' keywords cannot be used simultaneously.")
   s1 = self.pdb_hierarchy.atoms_size()
   if(self.params.remove is not None):
     asc = self.pdb_hierarchy.atom_selection_cache(
       special_position_settings=crystal.special_position_settings(
           crystal_symmetry = self.crystal_symmetry))
     sel = ~asc.selection(self.params.remove)
     self.pdb_hierarchy = self.pdb_hierarchy.select(sel)
     s2 = self.pdb_hierarchy.atoms_size()
     print("Size before:", s1, "size after:", s2, file=self.log)
   if(self.params.keep is not None):
     asc = self.pdb_hierarchy.atom_selection_cache(
       special_position_settings=crystal.special_position_settings(
           crystal_symmetry = self.crystal_symmetry))
     sel = asc.selection(self.params.keep)
     self.pdb_hierarchy = self.pdb_hierarchy.select(sel)
     s2 = self.pdb_hierarchy.atoms_size()
     print("Size before:", s1, "size after:", s2, file=self.log)
Exemplo n.º 35
0
 def __init__(self, xray_structure, params, pdb_hierarchy, log=None):
     self.log = log
     self.pdb_hierarchy = pdb_hierarchy
     self.crystal_symmetry = xray_structure.crystal_symmetry()
     if (self.log is None): self.log = sys.stdout
     self.xray_structure = xray_structure
     self.params = params
     asc = self.pdb_hierarchy.atom_selection_cache(
         special_position_settings=crystal.special_position_settings(
             crystal_symmetry=self.crystal_symmetry))
     if (self.params.random_seed is not None):
         random.seed(self.params.random_seed)
         flex.set_random_seed(self.params.random_seed)
     self.top_selection = flex.smart_selection(
         flags=flex.bool(xray_structure.scatterers().size(), True))
     if (self.params.selection is not None):
         self.top_selection = flex.smart_selection(
             flags=asc.selection(self.params.selection))
     self._rotate_about_axis()
     self._process_adp()
     self._process_sites()
     self._process_occupancies()
     self._put_in_box()
     self._change_of_basis()
     # Up to this point we are done with self.xray_structure
     self.pdb_hierarchy.adopt_xray_structure(self.xray_structure)
     # Now only manipulations that use self.pdb_hierarchy are done
     if (self.params.set_chemical_element_simple_if_necessary
             or self.params.rename_chain_id.old_id
             or self.params.renumber_residues
             or self.params.increment_resseq
             or self.params.convert_semet_to_met
             or self.params.convert_met_to_semet
             or self.params.set_charge.charge
             or self.params.truncate_to_polyala
             or self.params.truncate_to_polygly
             or self.params.remove_alt_confs or self.params.move_waters_last
             or self.params.remove_fraction or self.params.keep
             or self.params.remove):
         del self.xray_structure  # it is invalide below this point
         self._set_chemical_element_simple_if_necessary()
         self._rename_chain_id()
         self._renumber_residues()
         self._convert_semet_to_met()
         self._convert_met_to_semet()
         self._set_atomic_charge()
         self._truncate_to_poly_ala()
         self._truncate_to_poly_gly()
         self._remove_alt_confs()
         self._move_waters()
         self._remove_atoms()
         self._apply_keep_remove()
Exemplo n.º 36
0
 def __init__(self,
              pdb_hierarchy,
              crystal_symmetry,
              rotamer_manager,
              sin_cos_table,
              mon_lib_srv,
              bselection=None,
              map_data=None,
              vdw_radii=None,
              do_all=False,
              backbone_sample=True,
              diff_map_data=None,
              massage_map=True,
              tune_up_only=False,
              log=None):
     adopt_init_args(self, locals())
     self.number_of_outliers = None
     if (self.log is None): self.log = sys.stdout
     self.sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
     self.atom_names = flex.std_string(
         [i.strip() for i in self.pdb_hierarchy.atoms().extract_name()])
     self.special_position_settings = None
     self.special_position_indices = None
     if (self.crystal_symmetry is not None):
         self.special_position_settings = crystal.special_position_settings(
             crystal_symmetry=self.crystal_symmetry)
         self.special_position_indices = self.get_special_position_indices()
     # Even better would be to pass it here. Ideally just use model
     self.atom_selection_cache = self.pdb_hierarchy.atom_selection_cache()
     self.selection_water_as_set = set(self.atom_selection_cache.\
         selection(string = "water").iselection())
     if (self.massage_map and self.map_data is not None):
         self.target_map = self.prepare_target_map()
     else:
         self.target_map = map_data
     print >> self.log, \
       "outliers start: %d"%self.count_outliers()
     #
     if (not self.tune_up_only):
         self.loop(function=self.one_residue_iteration)
         assert approx_equal(self.sites_cart,
                             self.pdb_hierarchy.atoms().extract_xyz())
         print >> self.log, \
           "outliers after map fit: %d"%self.count_outliers()
     print >> self.log, "tune up"
     assert approx_equal(self.sites_cart,
                         self.pdb_hierarchy.atoms().extract_xyz())
     self.loop(function=self.one_residue_tune_up)
     print >> self.log, \
       "outliers final: %d"%self.count_outliers()
     assert approx_equal(self.sites_cart,
                         self.pdb_hierarchy.atoms().extract_xyz())
Exemplo n.º 37
0
 def assign_wyckoff(self, abc, tol=0.1):
     #FIXME This needs improvement and to be tested
     cctbx_name = self.space_group.cctbx_name
     sg_symbol = sgtbx.space_group_symbols(cctbx_name)
     sg = sgtbx.space_group(sg_symbol)
     unit_cell = uctbx.unit_cell(str(self.get_lattice()))
     symmetry = crystal.symmetry(unit_cell=unit_cell, space_group=sg)
     special_position_settings = crystal.special_position_settings(symmetry,min_distance_sym_equiv=0.5)
     site_symmetry = special_position_settings.site_symmetry(abc)
     wyckoff_table = special_position_settings.space_group_info().wyckoff_table()
     wyckoff_mapping = wyckoff_table.mapping(site_symmetry)
     letter = wyckoff_mapping.position().letter()
     return letter
 def expand_to_p1(self):
     new_model = model(
         crystal.special_position_settings(
             crystal.symmetry.cell_equivalent_p1(self)))
     for pos in self._positions:
         site_symmetry = self.site_symmetry(pos.site)
         equiv_sites = sgtbx.sym_equiv_sites(site_symmetry)
         i = 0
         for site in equiv_sites.coordinates():
             i += 1
             new_model.add_position(
                 position(label=pos.label + "_%03d" % i, site=site))
     return new_model
Exemplo n.º 39
0
def exercise_special_position_settings():
  xs = crystal.symmetry((3,4,5), "P 2 2 2")
  sp = crystal.special_position_settings(xs, 1, 2, False)
  assert sp.min_distance_sym_equiv() == 1
  assert sp.u_star_tolerance() == 2
  assert sp.assert_min_distance_sym_equiv() == False
  assert sp.site_symmetry((0,0,0)).multiplicity() == 1
  assert sp.site_symmetry(site=(0,0,0)).multiplicity() == 1
  assert sp.site_symmetry(site_cart=(0,0,0)).multiplicity() == 1
  assert str(sp.sym_equiv_sites((0,0,0)).special_op()) == "0,0,0"
  sites_cart = flex.vec3_double([(2,1,3), (0,0,0)])
  t = sp.site_symmetry_table(sites_cart=sites_cart)
  assert list(t.special_position_indices()) == [1]
  assert approx_equal(
    t.apply_symmetry_sites(unit_cell=xs.unit_cell(), sites_cart=sites_cart),
    sites_cart)
  #
  for min_distance_sym_equiv,special_op in [(1e-6, "0,0,0"), (0, "x,y,z")]:
    sp = crystal.special_position_settings(
      crystal_symmetry=xs,
      min_distance_sym_equiv=min_distance_sym_equiv)
    assert str(sp.sym_equiv_sites((0,0,0)).special_op()) == special_op
  #
  sites_cart = flex.vec3_double([(0,0,0)])
  sp = xs.special_position_settings()
  asu_mappings = sp.asu_mappings(buffer_thickness=3, sites_cart=sites_cart)
  assert list(asu_mappings.site_symmetry_table().special_position_indices()) \
      == [0]
  #
  pair_generator = sp.pair_generator(distance_cutoff=1, sites_cart=sites_cart)
  assert pair_generator.count_pairs() == 0
  sp0 = xs.special_position_settings(min_distance_sym_equiv=0)
  pair_generator = sp0.pair_generator(distance_cutoff=1, sites_cart=sites_cart)
  assert pair_generator.count_pairs() == 3
  #
  pair_asu_table = sp.pair_asu_table(distance_cutoff=1, sites_cart=sites_cart)
  assert pair_asu_table.table()[0].size() == 0
  pair_asu_table = sp0.pair_asu_table(distance_cutoff=1, sites_cart=sites_cart)
  assert pair_asu_table.table()[0][0].size() == 3
Exemplo n.º 40
0
def dummy_structure(space_group_info, volume, n_scatterers):
  structure = xray.structure(
    special_position_settings=crystal.special_position_settings(
      crystal_symmetry=crystal.symmetry(
        unit_cell=space_group_info.any_compatible_unit_cell(volume=volume),
        space_group_info=space_group_info)))
  b_iso = 20
  u_iso = adptbx.b_as_u(b_iso)
  u_star = adptbx.u_iso_as_u_star(structure.unit_cell(), u_iso)
  scatterer = xray.scatterer(label="C", site=(0.123,0.234,0.345), u=u_star)
  for i in xrange(n_scatterers):
    structure.add_scatterer(scatterer)
  return structure
Exemplo n.º 41
0
 def as_xray_structure(self, crystal_symmetry=None, force_symmetry=False,
                             min_distance_sym_equiv=0.5):
   crystal_symmetry = self.crystal_symmetry().join_symmetry(
     other_symmetry=crystal_symmetry,
     force=force_symmetry)
   assert crystal_symmetry.unit_cell() is not None
   assert crystal_symmetry.space_group_info() is not None
   structure = xray.structure(crystal.special_position_settings(
     crystal_symmetry=crystal_symmetry,
     min_distance_sym_equiv=min_distance_sym_equiv))
   for site in self.sites:
     structure.add_scatterer(site.as_xray_scatterer(structure.unit_cell()))
   return structure
Exemplo n.º 42
0
def run(server_info, inp, status):
  print "<pre>"
  io_utils.show_input_symbol(inp.sgsymbol, inp.convention)
  special_position_settings = crystal.special_position_settings(
    crystal.symmetry(
      unit_cell=uctbx.unit_cell(inp.ucparams),
      space_group_info=sgtbx.space_group_info(
        symbol=inp.sgsymbol,
        table_id=inp.convention)),
    min_distance_sym_equiv=float(inp.min_distance_sym_equiv))
  special_position_settings.show_summary()
  print "Minimum distance between symmetrically equivalent sites:",
  print special_position_settings.min_distance_sym_equiv()
  print

  skip_columns = io_utils.interpret_skip_columns(inp.skip_columns)

  wyckoff_table=special_position_settings.space_group_info().wyckoff_table()
  unit_cell = special_position_settings.unit_cell()
  print "</pre><table border=2 cellpadding=2>"
  status.in_table = True
  print "<tr>"
  if (skip_columns): print "<th>"
  print "<th colspan=3>" + inp.coor_type + " coordinates"
  print "<th>Multiplicity"
  print "<th>Wyckoff letter"
  print "<th>Site symmetry<br>point group type"
  print "<th>Special position operator"
  print "</tr>"
  for line in inp.coordinates:
    skipped, coordinates = io_utils.interpret_coordinate_line(line,skip_columns)
    if (inp.coor_type != "Fractional"):
      coordinates = unit_cell.fractionalize(coordinates)
    site_symmetry = special_position_settings.site_symmetry(coordinates)
    exact_site = site_symmetry.exact_site()
    if (inp.coor_type != "Fractional"):
      exact_site = unit_cell.orthogonalize(exact_site)
    wyckoff_mapping = wyckoff_table.mapping(site_symmetry)
    print "<tr>"
    if (skip_columns): print "<td>", skipped
    for x in exact_site: print "<td><tt>%.6g</tt>" % (x,)
    print "<td align=center>", wyckoff_mapping.position().multiplicity()
    print "<td align=center>", wyckoff_mapping.position().letter()
    print "<td align=center>", site_symmetry.point_group_type()
    print "<td><tt>" + str(site_symmetry.special_op_simplified()) + "</tt>"
    print "</tr>"
  print "</table><pre>"
  status.in_table = False

  print "</pre>"
Exemplo n.º 43
0
Arquivo: adp.py Projeto: dials/cctbx
def get_plain_pair_sym_table(crystal_symmetry, sites_frac, plain_pairs_radius=5):
  asu_mappings = crystal.symmetry.asu_mappings(crystal_symmetry,
    buffer_thickness = plain_pairs_radius)
  special_position_settings = crystal.special_position_settings(
    crystal_symmetry = crystal_symmetry)
  sites_cart = crystal_symmetry.unit_cell().orthogonalize(sites_frac)
  site_symmetry_table = special_position_settings.site_symmetry_table(
    sites_cart = sites_cart)
  asu_mappings.process_sites_frac(
    original_sites      = sites_frac,
    site_symmetry_table = site_symmetry_table)
  pair_asu_table = crystal.pair_asu_table(asu_mappings=asu_mappings)
  pair_asu_table.add_all_pairs(distance_cutoff = plain_pairs_radius)
  return pair_asu_table.extract_pair_sym_table()
 def expand_to_p1(self):
   new_model = model(
     crystal.special_position_settings(
       crystal.symmetry.cell_equivalent_p1(self)))
   for pos in self._positions:
     site_symmetry = self.site_symmetry(pos.site)
     equiv_sites = sgtbx.sym_equiv_sites(site_symmetry)
     i = 0
     for site in equiv_sites.coordinates():
       i += 1
       new_model.add_position(position(
         label=pos.label+"_%03d"%i,
         site=site))
   return new_model
Exemplo n.º 45
0
 def assign_wyckoff(self, abc, tol=0.1):
     #FIXME This needs improvement and to be tested
     cctbx_name = self.space_group.cctbx_name
     sg_symbol = sgtbx.space_group_symbols(cctbx_name)
     sg = sgtbx.space_group(sg_symbol)
     unit_cell = uctbx.unit_cell(str(self.get_lattice()))
     symmetry = crystal.symmetry(unit_cell=unit_cell, space_group=sg)
     special_position_settings = crystal.special_position_settings(
         symmetry, min_distance_sym_equiv=0.5)
     site_symmetry = special_position_settings.site_symmetry(abc)
     wyckoff_table = special_position_settings.space_group_info(
     ).wyckoff_table()
     wyckoff_mapping = wyckoff_table.mapping(site_symmetry)
     letter = wyckoff_mapping.position().letter()
     return letter
Exemplo n.º 46
0
def exercise_site_symmetry(space_group_info):
  special_position_settings = crystal.special_position_settings(
    crystal_symmetry=space_group_info.any_compatible_crystal_symmetry(
      volume=1000))
  z2p_op = space_group_info.group().z2p_op()
  special_position_settings_p = crystal.special_position_settings(
    crystal_symmetry=special_position_settings.change_basis(z2p_op),
    min_distance_sym_equiv
      =special_position_settings.min_distance_sym_equiv()*0.99)
  wyckoff_table = space_group_info.wyckoff_table()
  for i_position in xrange(wyckoff_table.size()):
    site_symmetry = wyckoff_table.random_site_symmetry(
      special_position_settings=special_position_settings,
      i_position=i_position)
    s = site_symmetry.special_op()
    assert s.multiply(s) == s
    for m in site_symmetry.matrices():
      assert m.multiply(s) == s
    tab = sgtbx.site_symmetry_table()
    tab.process(site_symmetry)
    ss_ops = tab.get(0)
    assert ss_ops.multiplicity() == site_symmetry.multiplicity()
    assert ss_ops.multiplicity() * ss_ops.n_matrices() \
        == site_symmetry.space_group().order_z()
    site_p = z2p_op.c() * site_symmetry.exact_site()
    site_symmetry_p = special_position_settings_p.site_symmetry(site_p)
    ss_ops_p = ss_ops.change_basis(z2p_op)
    assert ss_ops_p.multiplicity() == site_symmetry_p.multiplicity()
    assert ss_ops_p.special_op() == site_symmetry_p.special_op()
    assert ss_ops_p.multiplicity() * ss_ops_p.n_matrices() \
        == site_symmetry_p.space_group().order_z()
    references = [str(m) for m in site_symmetry_p.matrices()]
    testees = [str(m) for m in ss_ops_p.matrices()]
    references.sort()
    testees.sort()
    assert " ".join(testees) == " ".join(references)
Exemplo n.º 47
0
 def __init__(self,
       space_group_info,
       unit_cell_volume=1000,
       min_distance_sym_equiv=1,
       min_cross_distance=1,
       scattering_type="const",
       max_trials_per_position=10):
   adopt_init_args(self, locals())
   self.special_position_settings = crystal.special_position_settings(
     crystal_symmetry=crystal.symmetry(
       unit_cell=space_group_info.any_compatible_unit_cell(
         volume=unit_cell_volume),
       space_group_info=space_group_info),
     min_distance_sym_equiv=min_distance_sym_equiv)
   self.wyckoff_table = space_group_info.wyckoff_table()
Exemplo n.º 48
0
  def __init__(self):
    sgi = sgtbx.space_group_info("Hall: %s" % self.hall)
    cs = sgi.any_compatible_crystal_symmetry(volume=1000)
    xs = xray.structure(crystal.special_position_settings(cs))
    for sc in self.scatterers():
      sc.flags.set_use_u_iso(False).set_use_u_aniso(False)\
              .set_grad_site(True)
      xs.add_scatterer(sc)
    self.reference_xs = xs.as_emma_model()
    self.xray_structure = xs

    mi = cs.build_miller_set(d_min=0.5, anomalous_flag=False)
    ma = mi.structure_factors_from_scatterers(xs, algorithm="direct").f_calc()
    self.fo_sq = ma.norm().customized_copy(
      sigmas=flex.double(ma.size(), 1.))
Exemplo n.º 49
0
def run():
  uc = (10,12,14,90,90,90)
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 1")
  assert harker.planes_cartesian(cs).count() == 0
  assert harker.planes_cartesian(cs).min_distance((0,0,0)) is None
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 2 2 2")
  assert harker.planes_cartesian(cs).count() == 3
  assert ae(harker.planes_cartesian(cs).min_distance((0.123,0.234,0)), 0)
  assert ae(harker.planes_cartesian(cs).min_distance((0.123,0,0.234)), 0)
  assert ae(harker.planes_cartesian(cs).min_distance((0,0.123,0.234)), 0)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.234,0.345)), 1)
  assert ae(harker.planes_cartesian(cs).min_distance((0.234,0.1,0.345)), 1.2)
  assert ae(harker.planes_cartesian(cs).min_distance((0.234,0.345,0.1)), 1.4)
  assert ae(harker.planes_cartesian(cs).min_distance((0.2,0.2,0.1)), 1.4)
  assert ae(harker.planes_cartesian(cs).min_distance((0.2,0.1,0.1)), 1.2)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.2,0.2)), 1)
  assert ae(harker.planes_cartesian(cs).min_distance((-0.2,0.1,0.1)), 1.2)
  assert ae(harker.planes_cartesian(cs).min_distance((0.2,-0.1,0.1)), 1.2)
  assert ae(harker.planes_cartesian(cs).min_distance((0.2,0.1,-0.1)), 1.2)
  assert ae(harker.planes_cartesian(cs).min_distance((-0.2,-0.1,-0.1)), 1.2)
  uc = (10,10,12,90,90,120)
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 3")
  assert harker.planes_cartesian(cs).count() == 1
  assert ae(harker.planes_cartesian(cs).min_distance((0,0,0)), 0)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.2,1/3.)), 4)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.2,1/2.)), 6)
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 31")
  assert harker.planes_cartesian(cs).count() == 1
  assert ae(harker.planes_cartesian(cs).min_distance((0,0,0)), 4)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.2,1/3.)), 0)
  assert ae(harker.planes_cartesian(cs).min_distance((0.1,0.2,1/2.)), 2)
  uc = (10,10,12,90,90,90)
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 4 2 2")
  assert harker.planes_cartesian(cs).count() == 5
  cs = crystal.symmetry(unit_cell=uc, space_group_symbol="P 41 2 2")
  assert harker.planes_cartesian(cs).count() == 6
  ps = crystal.symmetry(unit_cell=uc, space_group_symbol="P 4/m m m")
  for x,d,t in (((0.1,0.2,0.3),0.6,"1"),
                ((0.1,0.2,0.75),0,"1"),
                ((0.1,0.0,0.3),0,"m")):
    ss = crystal.special_position_settings(ps).site_symmetry(x)
    assert ss.point_group_type() == t
    eq = sgtbx.sym_equiv_sites(ss)
    for x in eq.coordinates():
      assert ae(harker.planes_cartesian(cs).min_distance(x), d)
  print "OK"
Exemplo n.º 50
0
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
Exemplo n.º 51
0
def make_special_position_settings(cell, space_group, min_dist_sym_equiv=0.000001):
    """Takes cell and space group, returns cctbx structure
    input:  cell: (a b c alpha beta gamma) as a tuple
            space_group: 'space_group' like a string
            min_dist_sym_equiv: float
    output: <cctbx.crystal.special_position_settings object>
                contains cell, space group and special positions
    """

    assert type(cell) == tuple, 'cell must be supplied as a tuple'
    assert len(cell) == 6, 'expected 6 cell parameters'

    special_position_settings = crystal.special_position_settings(
        crystal_symmetry=crystal.symmetry(
            unit_cell=cell,
            space_group_symbol=space_group),
        min_distance_sym_equiv=min_dist_sym_equiv)
    return special_position_settings
Exemplo n.º 52
0
  def __init__(self):
    sgi = sgtbx.space_group_info("Hall: %s" % self.hall)
    cs = sgi.any_compatible_crystal_symmetry(volume=1000)
    xs = xray.structure(crystal.special_position_settings(cs))
    for i, sc in enumerate(self.scatterers()):
      sc.flags.set_use_u_iso(False).set_use_u_aniso(True)\
              .set_grad_u_aniso(True)
      xs.add_scatterer(sc)
      site_symm = xs.site_symmetry_table().get(i)
      u_cart = adptbx.random_u_cart(u_scale=self.random_u_cart_scale)
      u_star = adptbx.u_cart_as_u_star(cs.unit_cell(), u_cart)
      xs.scatterers()[-1].u_star = site_symm.average_u_star(u_star)
    self.xray_structure = xs

    mi = cs.build_miller_set(d_min=0.5, anomalous_flag=False)
    ma = mi.structure_factors_from_scatterers(xs, algorithm="direct").f_calc()
    self.fo_sq = ma.norm().customized_copy(
      sigmas=flex.double(ma.size(), 1.))
Exemplo n.º 53
0
 def __init__(self,
              pdb_hierarchy,
              map_data,
              crystal_symmetry,
              rotamer_manager,
              sin_cos_table,
              mon_lib_srv,
              do_all=False,
              backbone_sample=True,
              diff_map_data=None,
              massage_map=True,
              tune_up_only=False,
              log = None):
   adopt_init_args(self, locals())
   self.number_of_outliers = None
   if(self.log is None): self.log = sys.stdout
   self.sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
   self.special_position_settings = crystal.special_position_settings(
     crystal_symmetry = self.crystal_symmetry)
   self.special_position_indices = self.get_special_position_indices()
   self.selection_water_as_set = set(self.pdb_hierarchy.\
     atom_selection_cache().selection(string = "water").iselection())
   if(self.massage_map):
     self.target_map = self.prepare_target_map()
   else:
     self.target_map = map_data
   print >> self.log, \
     "outliers start: %d (percent: %6.2f)"%self.count_outliers()
   #
   if(not self.tune_up_only):
     self.loop(function = self.one_residue_iteration)
     self.pdb_hierarchy.atoms().set_xyz(self.sites_cart)
     print >> self.log, \
       "outliers after map fit: %d (percent: %6.2f)"%self.count_outliers()
   print >> self.log, "tune up"
   self.loop(function = self.one_residue_tune_up)
   print >> self.log, \
     "outliers final: %d (percent: %6.2f)"%self.count_outliers()
Exemplo n.º 54
0
    def __init__(self, symmetry = None, fragments = None, 
                    gen_unique_labels = False,
                    min_distance_sym_equiv = 0.0001):
        """Initialization of the Model's instance with symmetry (should be an
        istance of cctbx.crystal.symmetry) and list of fragments. Each fragment
        should be an istance of Fragment. min_distance_sym_equiv - if atoms are
        located close to the special position(within the given value) some of
        their coordinates will be rounded. Give this parameter some small value
        if you want to avoid this."""
        self._fragments = fragments
        self._symmetry = symmetry
        self._scatterers = flex.xray_scatterer()
        self._special_position_settings = crystal.special_position_settings(
                self._symmetry, min_distance_sym_equiv)
        if fragments:
            for fragment in fragments:
                for scatterer in fragment._scatterers:
                    self._scatterers.append(scatterer)

            if gen_unique_labels == True:
                self.gen_unique_labels()

        self._iucr_structure = None
def exercise():
    from iotbx import file_reader
    from cctbx.array_family import flex
    from cctbx import crystal
    from cctbx import xray
    from libtbx import easy_run

    file_base = "tmp_iotbx_simple_map_coefficients"
    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.0, 1 / 2.0, 1 / 3.0),
                    u=0.2,
                    fp=0.255,  # from Sasaki table @ 1.54 Angstrom
                    fdp=0.325,
                ),
                xray.scatterer(label="O", site=(0.197, -0.197, 0.83333), u=0),
            ]
        ),
    )
    fc = quartz_structure.structure_factors(d_min=1.0).f_calc()
    I = fc.amplitudes().f_as_f_sq()
    PHI = fc.average_bijvoet_mates().phases(deg=True).set_observation_type(None)
    FOM = PHI.customized_copy(data=flex.double(PHI.data().size(), 1.0)).set_observation_type(None)
    mtz = I.as_mtz_dataset(column_root_label="I")
    mtz.add_miller_array(PHI, column_root_label="PHI", column_types="P")
    mtz.add_miller_array(FOM, column_root_label="FOM", column_types="W")
    mtz_file = file_base + ".mtz"
    mtz.mtz_object().write(mtz_file)
    map_file = "%s_map.mtz" % file_base
    # Fo map
    args = [mtz_file, "output_file=%s" % map_file]
    cmd = "iotbx.simple_map_coefficients"
    result = easy_run.fully_buffered("%s %s" % (cmd, " ".join(args))).raise_if_errors()
    assert "Applying weights in FOM" in result.stdout_lines
    map_in = file_reader.any_file(map_file).assert_file_type("hkl")
    map_coeffs = map_in.file_server.miller_arrays[0]
    real_map = map_coeffs.fft_map().apply_sigma_scaling().real_map_unpadded()
    site = quartz_structure.sites_frac()[0]
    assert real_map.eight_point_interpolation(site) > 3
    # anomalous map
    args.append("map_type=anom")
    result = easy_run.fully_buffered("%s %s" % (cmd, " ".join(args))).raise_if_errors()
    assert not "Applying weights in FOM" in result.stdout_lines
    map_in = file_reader.any_file(map_file).assert_file_type("hkl")
    map_coeffs = map_in.file_server.miller_arrays[0]
    real_map = map_coeffs.fft_map().apply_sigma_scaling().real_map_unpadded()
    assert real_map.eight_point_interpolation(site) > 3
    # no FOM
    mtz = I.as_mtz_dataset(column_root_label="I")
    mtz.add_miller_array(PHI, column_root_label="PHI", column_types="P")
    mtz.mtz_object().write(mtz_file)
    args = [mtz_file, "output_file=%s" % map_file]
    result = easy_run.fully_buffered("%s %s" % (cmd, " ".join(args))).raise_if_errors()
    assert not "Applying weights in FOM" in result.stdout_lines
    map_in = file_reader.any_file(map_file).assert_file_type("hkl")
    map_coeffs = map_in.file_server.miller_arrays[0]
    real_map = map_coeffs.fft_map().apply_sigma_scaling().real_map_unpadded()
    site = quartz_structure.sites_frac()[0]
    assert real_map.eight_point_interpolation(site) > 3
    # now check for error when use_weights=True
    args.append("use_weights=True")
    result = easy_run.fully_buffered("%s %s" % (cmd, " ".join(args)))
    assert result.return_code == 1
    print "OK"
Exemplo n.º 56
0
def test_molecule(space_group_info, use_primitive_setting, flag_f_part,
                  d_min=3., grid_resolution_factor=0.48, max_prime=5,
                  verbose=0):
  if (use_primitive_setting):
    space_group_info = space_group_info.primitive_setting()
  elements = ("N", "C", "C", "O", "N", "C", "C", "O")
  structure = random_structure.xray_structure(
    space_group_info,
    elements=elements,
    volume_per_atom=50,
    min_distance=1.,
    general_positions_only=True,
    random_u_iso=True,
    random_occupancy=True)
  if (0 or verbose):
    structure.show_summary().show_scatterers()
  miller_set_f_obs = miller.build_set(
    crystal_symmetry=structure,
    anomalous_flag=(random.random() < 0.5),
    d_min=d_min)
  f_obs = abs(miller_set_f_obs.structure_factors_from_scatterers(
    xray_structure=structure,
    algorithm="direct").f_calc())
  if (0 or verbose):
    f_obs.show_summary()
  if (0 or verbose):
    f_obs.show_array()
  miller_set_p1 = miller.set.expand_to_p1(f_obs)
  special_position_settings_p1 = crystal.special_position_settings(
    crystal_symmetry=miller_set_p1)
  structure_p1 = xray.structure(
    special_position_settings=special_position_settings_p1)
  structure_fixed = xray.structure(special_position_settings=structure)
  for scatterer in structure.scatterers():
    if (flag_f_part and   structure_fixed.scatterers().size()
                        < structure.scatterers().size()//2):
      structure_fixed.add_scatterer(scatterer)
    else:
      structure_p1.add_scatterer(scatterer)
  if (0 or verbose):
    if (flag_f_part):
      structure_fixed.show_summary().show_scatterers()
    structure_p1.show_summary().show_scatterers()
  f_calc_fixed = None
  if (flag_f_part):
    f_calc_fixed = f_obs.structure_factors_from_scatterers(
      xray_structure=structure_fixed,
      algorithm="direct").f_calc()
  f_calc_p1 = miller_set_p1.structure_factors_from_scatterers(
    xray_structure=structure_p1,
    algorithm="direct").f_calc()
  symmetry_flags = translation_search.symmetry_flags(
    is_isotropic_search_model=False,
    have_f_part=flag_f_part)
  gridding = miller_set_f_obs.crystal_gridding(
    symmetry_flags=symmetry_flags,
    resolution_factor=grid_resolution_factor,
    max_prime=max_prime).n_real()
  grid_tags = maptbx.grid_tags(gridding)
  run_fast_terms(
    structure_fixed, structure_p1,
    f_obs, f_calc_fixed, f_calc_p1,
    symmetry_flags, gridding, grid_tags,
    test_origin=True,
    verbose=verbose)
  peak_list = run_fast_nv1995(
    f_obs, f_calc_fixed, f_calc_p1,
    symmetry_flags, gridding, grid_tags, verbose)
  assert peak_list.heights()[0] > 0.99
Exemplo n.º 57
0
def test_atom(space_group_info, use_primitive_setting,
              n_elements=3, d_min=3.,
              grid_resolution_factor=0.48, max_prime=5, verbose=0):
  if (use_primitive_setting):
    space_group_info = space_group_info.primitive_setting()
  structure = random_structure.xray_structure(
    space_group_info,
    n_scatterers=n_elements,
    volume_per_atom=150,
    min_distance=1.,
    general_positions_only=True)
  miller_set_f_obs = miller.build_set(
    crystal_symmetry=structure,
    anomalous_flag=(random.random() < 0.5),
    d_min=d_min)
  symmetry_flags = translation_search.symmetry_flags(
    is_isotropic_search_model=True,
    have_f_part=(n_elements>=2))
  gridding = miller_set_f_obs.crystal_gridding(
    symmetry_flags=symmetry_flags,
    resolution_factor=grid_resolution_factor,
    max_prime=max_prime).n_real()
  structure.build_scatterers(
    elements=["Se"]*n_elements,
    grid=gridding)
  if (0 or verbose):
    structure.show_summary().show_scatterers()
  f_obs = abs(miller_set_f_obs.structure_factors_from_scatterers(
    xray_structure=structure,
    algorithm="direct").f_calc())
  if (0 or verbose):
    f_obs.show_summary()
  if (0 or verbose):
    f_obs.show_array()
  miller_set_p1 = miller.set.expand_to_p1(f_obs)
  special_position_settings_p1 = crystal.special_position_settings(
    crystal_symmetry=miller_set_p1)
  structure_fixed = xray.structure(special_position_settings=structure)
  for scatterer in structure.scatterers():
    structure_p1 = xray.structure(
      special_position_settings=special_position_settings_p1)
    scatterer_at_origin = scatterer.customized_copy(site=(0,0,0))
    structure_p1.add_scatterer(scatterer_at_origin)
    if (0 or verbose):
      structure_p1.show_summary().show_scatterers()
    f_calc_p1 = miller_set_p1.structure_factors_from_scatterers(
      xray_structure=structure_p1,
      algorithm="direct").f_calc()
    if (0 or verbose):
      f_calc_p1.show_array()
    f_calc_fixed = None
    if (structure_fixed.scatterers().size() > 0):
      f_calc_fixed = f_obs.structure_factors_from_scatterers(
        xray_structure=structure_fixed,
        algorithm="direct").f_calc()
    symmetry_flags = translation_search.symmetry_flags(
      is_isotropic_search_model=True,
      have_f_part=(f_calc_fixed is not None))
    if (structure_fixed.scatterers().size() <= 1):
      gridding = miller_set_f_obs.crystal_gridding(
        symmetry_flags=symmetry_flags,
        resolution_factor=grid_resolution_factor,
        max_prime=max_prime).n_real()
      grid_tags = maptbx.grid_tags(gridding)
    run_fast_terms(
      structure_fixed, structure_p1,
      f_obs, f_calc_fixed, f_calc_p1,
      symmetry_flags, gridding, grid_tags,
      verbose=verbose)
    peak_list = run_fast_nv1995(
      f_obs, f_calc_fixed, f_calc_p1,
      symmetry_flags, gridding, grid_tags, verbose)
    structure_fixed.add_scatterer(scatterer)
    if (0 or verbose):
      structure_fixed.show_summary().show_scatterers()
    if (structure_fixed.scatterers().size() < n_elements):
      assert peak_list.heights()[0] < 1
    else:
      assert peak_list.heights()[0] > 0.99
  assert peak_list.heights()[0] > 0.99