def exercise_multiple_atoms(mon_lib_srv, ener_lib):
  geometry, xrs = make_initial_grm(mon_lib_srv, ener_lib, raw_records1)

  # output for debugging!!!
  # show_sorted_geometry(geometry, xrs, 'before_exersice_multiple_atoms.geo')

  xrs_add = iotbx.pdb.input(source_info=None, lines=raw_records3) \
      .xray_structure_simple()
  proxy1 = geometry_restraints.bond_simple_proxy(
      i_seqs=(3,9),
      distance_ideal=2.0,
      weight=3000)
  proxy2 = geometry_restraints.bond_simple_proxy(
      i_seqs=(4,10),
      distance_ideal=2.0,
      weight=3000)

  new_xrs = xrs.concatenate(xrs_add)
  all_sites_cart = new_xrs.sites_cart()
  number_of_new_atoms = len(xrs_add.sites_cart())
  new_geometry = geometry.new_included_bonded_atoms(
      proxies=[proxy1, proxy2],
      sites_cart=all_sites_cart,
      site_symmetry_table=xrs_add.site_symmetry_table(),
      nonbonded_types=flex.std_string(["OH2"]*number_of_new_atoms),
      nonbonded_charges=flex.int(number_of_new_atoms, 0),
      skip_max_proxy_distance_calculation=True)
  # output for debugging!!!
  # show_sorted_geometry(new_geometry, new_xrs,
  #     'after_exersice_multiple_atoms.geo')

  assert new_geometry.pair_proxies().bond_proxies.simple.size() == 8
  assert new_geometry.pair_proxies().bond_proxies.asu.size() == 2
  assert new_geometry.pair_proxies().nonbonded_proxies.simple.size() == 11
  assert new_geometry.pair_proxies().nonbonded_proxies.asu.size() == 4
 def __init__(O,
       sites_cart,
       geometry_restraints_manager,
       geometry_restraints_flags,
       lbfgs_termination_params,
       lbfgs_exception_handling_params):
   O.grm = geometry_restraints_manager
   cs = O.grm.crystal_symmetry
   sst = O.grm.site_symmetry_table
   sites_frac = cs.unit_cell().fractionalize(sites_cart)
   O.x = sst.pack_coordinates(sites_frac=sites_frac)
   O.proxies = geometry_restraints.shared_bond_simple_proxy()
   for i_seq,pair_sym_dict in enumerate(O.grm.shell_sym_tables[0]):
     for j_seq,sym_ops in pair_sym_dict.items():
       assert i_seq <= j_seq
       bond_params = O.grm.bond_params_table[i_seq][j_seq]
       for rt_mx_ji in sym_ops:
         O.proxies.append(geometry_restraints.bond_simple_proxy(
           i_seqs=[i_seq, j_seq],
           rt_mx_ji=rt_mx_ji,
           params=bond_params))
   def get_target_result():
     f, _ = O.compute_functional_and_gradients()
     return dev_target_result(
       target=f,
       n_bond_proxies=O.proxies.size(),
       bond_residual_sum=f)
   O.first_target_result = get_target_result()
   import scitbx.lbfgs
   O.minimizer = scitbx.lbfgs.run(
     target_evaluator=O,
     termination_params=lbfgs_termination_params,
     exception_handling_params=lbfgs_exception_handling_params)
   f, _ = O.compute_functional_and_gradients()
   O.final_target_result = get_target_result()
Example #3
0
def get_basepair_hbond_proxies(
    pdb_hierarchy,
    bp_phil_params,
    hbond_distance_cutoff=3.4):
  assert pdb_hierarchy is not None
  bond_proxies_result = []
  angle_proxies_result = []
  if len(bp_phil_params) > 0:
    # return bond_proxies_result, angle_proxies_result
    selection_cache = pdb_hierarchy.atom_selection_cache()
    pdb_atoms = pdb_hierarchy.atoms()
    # dashes = open('dashes.pml', 'w')
    pdb_atoms = pdb_hierarchy.atoms()
    for base_pair in bp_phil_params:
      if (base_pair.base1 is not None and base_pair.base2 is not None
          and base_pair.enabled):
        selected_atoms_1 = selection_cache.iselection(base_pair.base1)
        selected_atoms_2 = selection_cache.iselection(base_pair.base2)
        if len(selected_atoms_1) == 0:
          raise Sorry("Selection %s in base_pair retusulted in 0 atoms." % (
              base_pair.base1))
        if len(selected_atoms_2) == 0:
          raise Sorry("Selection %s in base_pair retusulted in 0 atoms." % (
              base_pair.base2))
        a1 = pdb_atoms[selected_atoms_1[0]]
        a2 = pdb_atoms[selected_atoms_2[0]]
        if base_pair.saenger_class == 0:
          hbonds, saenger_class = get_h_bonds_for_basepair(
            a1, a2, distance_cutoff=hbond_distance_cutoff,
            log=sys.stdout, verbose=-1)
          base_pair.saenger_class = saenger_class
        hbonds = get_h_bonds_for_particular_basepair((a1, a2), base_pair.saenger_class)
        for hb in hbonds:
          dist = hb[0].distance(hb[1])
          if dist < hbond_distance_cutoff:
            if base_pair.restrain_hbonds:
              hb_target, hb_sigma = get_hb_lenght_targets(hb)
              p = geometry_restraints.bond_simple_proxy(
                i_seqs=[hb[0].i_seq, hb[1].i_seq],
                distance_ideal=hb_target,
                weight=1.0/hb_sigma**2,
                slack=0,
                top_out=False,
                limit=1,
                origin_id=1)
              bond_proxies_result.append(p)
              # print "bond:", hb[0].id_str(), hb[1].id_str(), "(%4.2f, %4.2f)" % (hb_target, hb_sigma)
              # s1 = pdb_atoms[hb[0].i_seq].id_str()
              # s2 = pdb_atoms[hb[1].i_seq].id_str()
              # ps = "dist chain \"%s\" and resi %s and name %s, chain \"%s\" and resi %s and name %s\n" % (
              #   s1[14:15], s1[15:19], s1[5:8], s2[14:15], s2[15:19], s2[5:8])
              # dashes.write(ps)
            if base_pair.restrain_hb_angles:
              angle_proxies_result += get_angle_proxies_for_bond(hb)
          else:
            print "NA hbond rejected:",hb[0].id_str(), hb[1].id_str(), "distance=%.2f" % dist
  # dashes.close()
  return geometry_restraints.shared_bond_simple_proxy(bond_proxies_result), \
      angle_proxies_result
def exercise_add_new_bond_restraint_in_place(mon_lib_srv, ener_lib):
  geometry, xrs = make_initial_grm(mon_lib_srv, ener_lib, raw_records4)

  proxy = geometry_restraints.bond_simple_proxy(
    i_seqs=(0,3),
    distance_ideal=2.0,
    weight=3000)
  assert not geometry.is_bonded_atoms(0,3)
  assert not geometry.is_bonded_atoms(3,0)
  geometry.add_new_bond_restraints_in_place([proxy], xrs.sites_cart())
  assert geometry.is_bonded_atoms(0,3)
  assert geometry.is_bonded_atoms(3,0)
  assert geometry.pair_proxies().bond_proxies.simple.size() == 8
  assert geometry.pair_proxies().bond_proxies.asu.size() == 0
  assert geometry.pair_proxies().nonbonded_proxies.simple.size() == 8
  assert geometry.pair_proxies().nonbonded_proxies.asu.size() == 0
 def _add_bond(i_seqs,
               bond_params_table,
               bond_asu_table,
               value,
               esd,
               rt_mx_ji,
               ):
   proxy = geometry_restraints.bond_simple_proxy(
     i_seqs=i_seqs,
     distance_ideal=value,
     weight=1/esd**2)
   bond_params_table.update(i_seq=i_seqs[0],
                            j_seq=i_seqs[1],
                            params=proxy)
   bond_asu_table.add_pair(
     i_seq=i_seqs[0],
     j_seq=i_seqs[1],
     rt_mx_ji=rt_mx_ji,
     )
def exercise_single_atom(mon_lib_srv, ener_lib):
  geometry, xrs = make_initial_grm(mon_lib_srv, ener_lib, raw_records1)

  # output for debugging!!!
  # show_sorted_geometry(geometry, xrs, 'before_exersice_single_atoms.geo')

  xrs_add = iotbx.pdb.input(source_info=None, lines=raw_records2) \
      .xray_structure_simple()
  proxy1 = geometry_restraints.bond_simple_proxy(
      i_seqs=(3,9),
      distance_ideal=2.0,
      weight=3000,
      origin_id=1)

  new_xrs = xrs.concatenate(xrs_add)
  all_sites_cart = new_xrs.sites_cart()
  number_of_new_atoms = len(xrs_add.sites_cart())
  new_geometry = geometry.new_included_bonded_atoms(
      proxies=[proxy1],
      sites_cart=all_sites_cart,
      site_symmetry_table=xrs_add.site_symmetry_table(),
      nonbonded_types=flex.std_string(["OH2"]*number_of_new_atoms),
      nonbonded_charges=flex.int(number_of_new_atoms, 0),
      skip_max_proxy_distance_calculation=True)
  # output for debugging!!!
  # show_sorted_geometry(new_geometry, new_xrs,
  #     'after_exersice_single_atoms.geo')
  assert new_geometry.is_bonded_atoms(3,9)

  assert new_geometry.pair_proxies().bond_proxies.simple.size() == 8
  assert new_geometry.pair_proxies().bond_proxies.asu.size() == 1
  # That's the way to get them:
  simple, asu = new_geometry.get_covalent_bond_proxies()
  assert simple.size() + asu.size() == 8
  simple, asu = new_geometry.get_all_bond_proxies()
  assert simple.size() + asu.size() == 9, "%d, %d" % (simple.size(), asu.size())
  assert new_geometry.pair_proxies().nonbonded_proxies.simple.size() == 10
  assert new_geometry.pair_proxies().nonbonded_proxies.asu.size() ==2
  assert new_geometry.get_hbond_proxies_iseqs() == [(3, 9)]
  simple, asu = new_geometry.get_covalent_bond_proxies()
  assert simple.size() + asu.size() == 8, "%d" % (simple.size() + asu.size())
Example #7
0
def _apply_link_using_proxies(link,
                              atom_group1,
                              atom_group2,
                              bond_params_table,
                              bond_asu_table,
                              geometry_proxy_registries,
                        #      distance,
                              rt_mx_ji,
                              ):
  ######################################
  def _get_restraint_i_seqs(atom_group1,
                            atom_group2,
                            restraint,
                            ):
    i_seqs = []
    keys = restraint.cif_keywords()
    if "value_dist" in keys:
      attrs = [
        "atom_1_comp_id",
        "atom_id_1",
        "atom_2_comp_id",
        "atom_id_2",
        ]
    elif "period" in keys:
      attrs = [
        "atom_1_comp_id",
        "atom_id_1",
        "atom_2_comp_id",
        "atom_id_2",
        "atom_3_comp_id",
        "atom_id_3",
        "atom_4_comp_id",
        "atom_id_4",
        ]
    elif "value_angle" in keys:
      attrs = [
        "atom_1_comp_id",
        "atom_id_1",
        "atom_2_comp_id",
        "atom_id_2",
        "atom_3_comp_id",
        "atom_id_3",
        ]
    elif "volume_sign" in keys:
      attrs = [
        "atom_centre_comp_id",
        "atom_id_centre",
        "atom_1_comp_id",
        "atom_id_1",
        "atom_2_comp_id",
        "atom_id_2",
        "atom_3_comp_id",
        "atom_id_3",
        ]
    elif "plane_id" in keys:
      attrs = [
        "atom_comp_id",
        "atom_id",
        ]
    else:
      assert 0
    for i, attr in enumerate(attrs):
      if i%2:
        # name
        name = getattr(restraint, attr)
        for atom in atoms:
          # uses names to confirm link
          if atom.name.strip()==name.strip():
            i_seqs.append(atom.i_seq)
            break
        else:
          # name not found, could be hydrogen or ...
          return None
      else:
        # atoms
        if getattr(restraint, attr)==1:
          atoms = atom_group1.atoms()
        else:
          atoms = atom_group2.atoms()
    return i_seqs
  ###############
  def _check_i_seqs(atom_group1, atom_group2, i_seqs):
    atoms = []
    for i_seq in i_seqs:
      for atom in list(atom_group1.atoms())+list(atom_group2.atoms()):
        if atom.i_seq==i_seq:
          atoms.append(atom)
          break
    d2 = linking_utils.get_distance2(*atoms) # XXXX needs to be sym aware
    if d2>9: return False
    return True
  #############
  assert link
  count = 0
  #
  bond_i_seqs = []
  for bond in link.bond_list:
    i_seqs = _get_restraint_i_seqs(atom_group1,
                                   atom_group2,
                                   bond,
      )
    if i_seqs is None: continue
    if not _check_i_seqs(atom_group1, atom_group2, i_seqs): # check distances
      tmp = atom_group2
      atom_group2 = atom_group1
      atom_group1 = tmp
      i_seqs = _get_restraint_i_seqs(atom_group1,
                                     atom_group2,
                                     bond,
        )
      if i_seqs is None: continue
    value = "value_dist"
    proxy = geometry_restraints.bond_simple_proxy(
      i_seqs=i_seqs,
      distance_ideal=getattr(bond, value),
      weight=1/bond.value_dist_esd**2)
    bond_params_table.update(i_seq=i_seqs[0],
                             j_seq=i_seqs[1],
                             params=proxy)
    #if rt_mx_ji is None: continue
    bond_asu_table.add_pair(
      i_seq=i_seqs[0],
      j_seq=i_seqs[1],
      rt_mx_ji=rt_mx_ji,
      )
    count+=1
    bond_i_seqs.append(i_seqs)
  #
  for angle in link.angle_list:
    i_seqs = _get_restraint_i_seqs(atom_group1,
                                   atom_group2,
                                   angle,
        )
    if i_seqs is None: continue
    proxy = geometry_restraints.angle_proxy(
      i_seqs=i_seqs,
      angle_ideal=angle.value_angle,
      weight=1/angle.value_angle_esd**2)
    geometry_proxy_registries.angle.add_if_not_duplicated(proxy=proxy)
  #
  for tor in link.tor_list:
    i_seqs = _get_restraint_i_seqs(atom_group1,
                                   atom_group2,
                                   tor,
        )
    if i_seqs is None: continue
    proxy = geometry_restraints.dihedral_proxy(
      i_seqs=i_seqs,
      angle_ideal=tor.value_angle,
      weight=1/tor.value_angle_esd**2,
      periodicity=tor.period,
      )
    geometry_proxy_registries.dihedral.add_if_not_duplicated(proxy=proxy)
  #
  for chir in link.chir_list:
    i_seqs = _get_restraint_i_seqs(atom_group1,
                                   atom_group2,
                                   chir,
        )
    if i_seqs is None: continue
    volume_ideal = 2.4
    if chir.volume_sign[:4].lower()=="nega":
      volume_ideal = -2.4
    elif chir.volume_sign[:4].lower()=="zero":
      volume_ideal = 0.
    proxy = geometry_restraints.chirality_proxy(
      i_seqs=i_seqs,
      volume_ideal=volume_ideal,
      both_signs=False,
      weight=25.,
      )
    geometry_proxy_registries.chirality.add_if_not_duplicated(proxy=proxy)
  #
  planes = {}
  weights = {}
  for plane in link.plane_list:
    i_seqs = _get_restraint_i_seqs(atom_group1,
                                   atom_group2,
                                   plane,
        )
    if i_seqs is None: continue
    planes.setdefault(plane.plane_id, [])
    planes[plane.plane_id]+=i_seqs
    weights.setdefault(plane.plane_id, [])
    weights[plane.plane_id].append(1/plane.dist_esd**2)
  if planes:
    for plane_id in planes:
      if len(planes[plane_id])<4: continue
      proxy = geometry_restraints.planarity_proxy(
        i_seqs=planes[plane_id],
        weights=weights[plane_id],
        )
      geometry_proxy_registries.planarity.add_if_not_duplicated(proxy=proxy)
  return count, bond_i_seqs
def adjust_geometry_restraints_manager(hierarchy,
                                       grm,
                                       error_i_seqs,
                                       log=None,
                                       ):
  # obsolete
  t0=time.time()
  mon_lib_srv = server.server()
  pdb_atoms = hierarchy.atoms()
  sites_cart = pdb_atoms.extract_xyz()
  resnames=[]
  bond_counters = [0,0]
  angle_counters = [0,0]
  checked=[]
  for i_seq in error_i_seqs:
    atom = pdb_atoms[i_seq]
    ag = atom.parent()
    if ag.resname in checked: continue
    rg = ag.parent()
    # need to be able to check in user defined location
    monomer_restraints = mon_lib_srv.get_comp_comp_id_direct(
      ag.resname,
      pH_range="low",
      )
    checked.append(ag.resname)
    if monomer_restraints is None: continue
    resnames.append('"%s%s %s%5s"' % (' ',
                                      ag.resname,
                                      rg.parent().id,
                                      rg.resseq,
                                      ))
    for bond in monomer_restraints.bond_list:
      bond.show()
      atom1 = ag.get_atom(bond.atom_id_1)
      atom2 = ag.get_atom(bond.atom_id_2)
      i_seqs = (atom1.i_seq, atom2.i_seq)
      bond_param = grm.bond_params_table.lookup(*list(i_seqs))
      if bond_param:
        bond_param.distance_ideal = bond.value_dist
        bond_counters[0]+=1
      else:
        proxy = geometry_restraints.bond_simple_proxy(
          i_seqs=i_seqs,
          distance_ideal=bond.value_dist,
          weight=1/(bond.value_dist_esd**2),
          )
        grm.add_new_bond_restraints_in_place([proxy], sites_cart)
        bond_counters[1]+=1
    lookup={}
    for angle in monomer_restraints.angle_list:
      atom1 = ag.get_atom(angle.atom_id_1)
      atom2 = ag.get_atom(angle.atom_id_2)
      atom3 = ag.get_atom(angle.atom_id_3)
      i_seqs = (atom1.i_seq, atom2.i_seq, atom3.i_seq)
      lookup[i_seqs]=angle
      i_seqs = (atom3.i_seq, atom2.i_seq, atom1.i_seq)
      lookup[i_seqs]=angle
    for angle_proxy in grm.angle_proxies:
      if angle_proxy.i_seqs in lookup:
        i_seqs = angle_proxy.i_seqs
        angle = lookup[i_seqs]
        angle_proxy.angle_ideal = angle.value_angle
        angle_proxy.weight = 1/angle.value_angle_esd**2
        angle_counters[0]+=1
        del lookup[i_seqs]
        i_seqs = list(i_seqs)
        i_seqs.reverse()
        del lookup[tuple(i_seqs)]
    if lookup:
      done = []
      for i_seqs in lookup:
        if i_seqs in done: continue
        proxy =  geometry_restraints.angle_proxy(
          i_seqs=i_seqs,
          angle_ideal=angle.value_angle,
          weight=1/angle.value_angle_esd**2,
          )
        grm.add_angles_in_place([proxy])
        angle_counters[1]+=1
        i_seqs=list(i_seqs)
        i_seqs.reverse()
        done.append(tuple(i_seqs))
def adjust_geometry_proxies_registeries(hierarchy,
                                        #bond_params_table,
                                        #bond_asu_table,
                                        gpr,
                                        error_i_seqs,
                                        log=None,
                                        ):
  t0=time.time()
  mon_lib_srv = server.server()
  pdb_atoms = hierarchy.atoms()
  sites_cart = pdb_atoms.extract_xyz()
  resnames=[]
  bond_counters = [0,0]
  angle_counters = [0,0]
  checked=[]
  atoms_added={}
  for i_seq in error_i_seqs:
    atom = pdb_atoms[i_seq]
    ag = atom.parent()
    if ag.resname in checked: continue
    rg = ag.parent()
    # need to be able to check in user defined location
    monomer_restraints = mon_lib_srv.get_comp_comp_id_direct(
      ag.resname,
      pH_range="low",
      )
    checked.append(ag.resname)
    if monomer_restraints is None: continue
    atom_dict = monomer_restraints.atom_dict()
    resnames.append('"%s%s %s%5s"' % (' ',
                                      ag.resname,
                                      rg.parent().id,
                                      rg.resseq,
                                      ))
    for bond in monomer_restraints.bond_list:
      atom1 = ag.get_atom(bond.atom_id_1)
      if atom1 is None: continue
      atom2 = ag.get_atom(bond.atom_id_2)
      if atom2 is None: continue
      i_seqs = [atom1.i_seq, atom2.i_seq]
      i_seqs.sort()
      bond_table_entry = gpr.bond_simple.table[i_seqs[0]]
      if i_seqs[1] in bond_table_entry:
        bond_simple = gpr.bond_simple.proxies[i_seqs[0]]
        bond_simple.distance_ideal = bond.value_dist
        bond_simple.weight=1/bond.value_dist_esd**2
        bond_counters[0]+=1
      else:
        proxy = geometry_restraints.bond_simple_proxy(
          i_seqs=i_seqs,
          distance_ideal=bond.value_dist,
          weight=1/(bond.value_dist_esd**2),
          )
        gpr.bond_simple.proxies.append(proxy)
        atoms_added[atom1.i_seq] = atom_dict.get(atom1.name.strip(), None)
        atoms_added[atom2.i_seq] = atom_dict.get(atom2.name.strip(), None)
        bond_counters[1]+=1
    lookup={}
    for angle in monomer_restraints.angle_list:
      atom1 = ag.get_atom(angle.atom_id_1)
      if atom1 is None: continue
      atom2 = ag.get_atom(angle.atom_id_2)
      if atom2 is None: continue
      atom3 = ag.get_atom(angle.atom_id_3)
      if atom3 is None: continue
      i_seqs = (atom1.i_seq, atom2.i_seq, atom3.i_seq)
      lookup[i_seqs]=angle
      i_seqs = (atom3.i_seq, atom2.i_seq, atom1.i_seq)
      lookup[i_seqs]=angle
    for angle_proxy in gpr.angle.proxies:
      if angle_proxy.i_seqs in lookup:
        i_seqs = angle_proxy.i_seqs
        angle = lookup[i_seqs]
        angle_proxy.angle_ideal = angle.value_angle
        angle_proxy.weight = 1/angle.value_angle_esd**2
        angle_counters[0]+=1
        del lookup[i_seqs]
        i_seqs = list(i_seqs)
        i_seqs.reverse()
        del lookup[tuple(i_seqs)]
    if lookup:
      done = []
      for i_seqs in lookup:
        if i_seqs in done: continue
        proxy =  geometry_restraints.angle_proxy(
          i_seqs=i_seqs,
          angle_ideal=angle.value_angle,
          weight=1/angle.value_angle_esd**2,
          )
        gpr.angle.add_if_not_duplicated(proxy)
        angle_counters[1]+=1
        i_seqs=list(i_seqs)
        i_seqs.reverse()
        done.append(tuple(i_seqs))
  if resnames:
    print >> log, "\n  Adjusted restraints in %d residue(s) for low pH in %0.1fs" % (
      len(resnames),
      time.time()-t0,
      )
    print >> log, "    Residues changed"
    for resname in resnames:
      print >> log, "      %s" % resname
    print >> log, "    Changed %d bond restraint(s),  added %d bond restraint(s)" % (
      bond_counters[0],
      bond_counters[1],
      )
    print >> log, "    Changed %d angle restraint(s), added %d angle restraint(s)\n" % (
      angle_counters[0],
      angle_counters[1],
      )
  #else:
  #  print >> log, "  Time to perform restraint checks: %0.1f" % (time.time()-t0)
  return atoms_added
Example #10
0
def exercise_geometry_restraints_as_cif():
  quartz = 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))]))
  bond_proxies = geometry_restraints.shared_bond_simple_proxy((
    geometry_restraints.bond_simple_proxy(
      i_seqs=[0,1],
      rt_mx_ji=sgtbx.rt_mx("x-y,x,z-2/3"),
      distance_ideal=1.6,
      weight=3.2),
    geometry_restraints.bond_simple_proxy(
      i_seqs=[0,1],
      distance_ideal=1.7,
      weight=1.8),
  ))
  dihedral_proxies = geometry_restraints.shared_dihedral_proxy((
    geometry_restraints.dihedral_proxy(
      i_seqs = [1,0,1,0],
      sym_ops = (sgtbx.rt_mx("1+y,1-x+y, z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("x-y,x,z-2/3"),
                 sgtbx.rt_mx("1-x,y-x,1/3-z")),
      angle_ideal=-30,
      weight=2),
    geometry_restraints.dihedral_proxy(
      i_seqs = [1,0,1,0],
      sym_ops = (sgtbx.rt_mx("1+y,1-x+y, z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3"),
                 sgtbx.rt_mx("x-y,x,1/3+z")),
      angle_ideal=90,
      weight=3),
  ))
  angle_proxies = geometry_restraints.shared_angle_proxy((
    geometry_restraints.angle_proxy(
      i_seqs = [1,0,1],
      sym_ops = (sgtbx.rt_mx("x-y,x,z-2/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3")),
      angle_ideal=103,
      weight=2),
    geometry_restraints.angle_proxy(
      i_seqs = [1,0,1],
      sym_ops = (sgtbx.rt_mx("y+1,-x+y+1,z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3")),
      angle_ideal=110,
      weight=5),
    geometry_restraints.angle_proxy(
      i_seqs = [0,1,0],
      sym_ops = (sgtbx.rt_mx("y,-x+y,z+2/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-x+y,-x,z+1/3")),
      angle_ideal=150,
      weight=5),
  ))
  bond_similarity_proxies = geometry_restraints.shared_bond_similarity_proxy((
    geometry_restraints.bond_similarity_proxy(
      i_seqs=[(0,1),(0,1),(0,1)],
      sym_ops=(sgtbx.rt_mx("x-y,x,z-2/3"),
               sgtbx.rt_mx("-y,x-y,z-1/3"),
               sgtbx.rt_mx("y+1,-x+y+1,z-1/3")),
      weights=(1,1,1)),
  ))
  cif_block = iotbx.cif.model.block()
  iotbx.cif.restraints.add_to_cif_block(
    cif_block, quartz,
    bond_proxies=bond_proxies,
    angle_proxies=angle_proxies,
    dihedral_proxies=dihedral_proxies,
    bond_similarity_proxies=bond_similarity_proxies)
  s = StringIO()
  cif_block.show(out=s)
  assert not show_diff(s.getvalue(), """\
loop_
  _restr_distance_atom_site_label_1
  _restr_distance_atom_site_label_2
  _restr_distance_site_symmetry_2
  _restr_distance_target
  _restr_distance_target_weight_param
  _restr_distance_diff
  Si  O  2_554  1.6000  0.5590  -0.0160
  Si  O  1      1.7000  0.7454  -2.3838

loop_
  _restr_angle_atom_site_label_1
  _restr_angle_atom_site_label_2
  _restr_angle_atom_site_label_3
  _restr_angle_site_symmetry_1
  _restr_angle_site_symmetry_2
  _restr_angle_site_symmetry_3
  _restr_angle_target
  _restr_angle_target_weight_param
  _restr_angle_diff
  O   Si  O   2_554  1  4_554  103.0000  0.7071   1.6926
  O   Si  O   3_664  1  4_554  110.0000  0.4472  -1.3127
  Si  O   Si  3      1  5      150.0000  0.4472   3.0700

loop_
  _restr_torsion_atom_site_label_1
  _restr_torsion_atom_site_label_2
  _restr_torsion_atom_site_label_3
  _restr_torsion_atom_site_label_4
  _restr_torsion_site_symmetry_1
  _restr_torsion_site_symmetry_2
  _restr_torsion_site_symmetry_3
  _restr_torsion_site_symmetry_4
  _restr_torsion_angle_target
  _restr_torsion_weight_param
  _restr_torsion_diff
  O  Si  O  Si  3_664  1  2_554  7_655  -30.0000  0.7071   6.9078
  O  Si  O  Si  3_664  1  4_554  2       90.0000  0.5774  11.7036

loop_
  _restr_equal_distance_class_class_id
  _restr_equal_distance_class_target_weight_param
  _restr_equal_distance_class_average
  _restr_equal_distance_class_esd
  _restr_equal_distance_class_diff_max
  1  1.0000  1.6160  0.0000  0.0000

loop_
  _restr_equal_distance_atom_site_label_1
  _restr_equal_distance_atom_site_label_2
  _restr_equal_distance_site_symmetry_2
  _restr_equal_distance_class_id
  Si  O  2_554  1
  Si  O  4_554  1
  Si  O  3_664  1

""")
def exercise(verbose=0):
  distance_ideal = 1.8
  default_vdw_distance = 3.6
  vdw_1_4_factor = 3.5/3.6
  sites_cart_manual = flex.vec3_double([
    (1,3,0), (2,3,0), (3,2,0), (3,1,0), (4,1,0), (3,4,0), (4,3,0), (5,3,0),
    (6,2,0), (7,2,0), (8,3,0), (7,4,0), (6,4,0), (7,5,0), (6,6,0), (8,6,0)])
  bond_proxies = geometry_restraints.bond_sorted_asu_proxies(asu_mappings=None)
  for i_seqs in [(0,1),(1,2),(2,3),(3,4),(1,5),(2,6),(5,6),
                 (6,7),(7,8),(8,9),(9,10),(10,11),(11,12),
                 (12,7),(11,13),(13,14),(14,15),(15,13)]:
    bond_proxies.process(geometry_restraints.bond_simple_proxy(
      i_seqs=i_seqs, distance_ideal=distance_ideal, weight=100))
  angle_proxies = geometry_restraints.shared_angle_proxy()
  for i_seqs,angle_ideal in [[(0,1,2),135],
                             [(0,1,5),135],
                             [(1,2,3),135],
                             [(3,2,6),135],
                             [(2,3,4),120],
                             [(1,2,6),90],
                             [(2,6,5),90],
                             [(6,5,1),90],
                             [(5,1,2),90],
                             [(2,6,7),135],
                             [(5,6,7),135],
                             [(6,7,8),120],
                             [(6,7,12),120],
                             [(7,8,9),120],
                             [(8,9,10),120],
                             [(9,10,11),120],
                             [(10,11,12),120],
                             [(11,12,7),120],
                             [(12,7,8),120],
                             [(10,11,13),120],
                             [(12,11,13),120],
                             [(11,13,15),150],
                             [(11,13,14),150],
                             [(13,15,14),60],
                             [(15,14,13),60],
                             [(14,13,15),60]]:
    angle_proxies.append(geometry_restraints.angle_proxy(
      i_seqs=i_seqs, angle_ideal=angle_ideal, weight=1))
  if (0 or verbose):
    dump_pdb(file_name="manual.pdb", sites_cart=sites_cart_manual)
  for traditional_convergence_test in [True,False]:
    for sites_cart_selection in [True, False]:
      sites_cart = sites_cart_manual.deep_copy()
      if sites_cart_selection:
        sites_cart_selection = flex.bool(sites_cart.size(), True)
        sites_cart_selection[1] = False
      assert bond_proxies.asu.size() == 0
      bond_params_table = geometry_restraints.extract_bond_params(
        n_seq=sites_cart.size(),
        bond_simple_proxies=bond_proxies.simple)
      manager = geometry_restraints.manager.manager(
        bond_params_table=bond_params_table,
        angle_proxies=angle_proxies)
      minimized = geometry_restraints.lbfgs.lbfgs(
        sites_cart=sites_cart,
        geometry_restraints_manager=manager,
        lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
          traditional_convergence_test=traditional_convergence_test,
          drop_convergence_test_max_drop_eps=1.e-20,
          drop_convergence_test_iteration_coefficient=1,
          max_iterations=1000),
        sites_cart_selection=sites_cart_selection,
        )
      assert minimized.minimizer.iter() > 100
      sites_cart_minimized_1 = sites_cart.deep_copy()
      if (0 or verbose):
        dump_pdb(
          file_name="minimized_1.pdb", sites_cart=sites_cart_minimized_1)
      bond_deltas = geometry_restraints.bond_deltas(
        sites_cart=sites_cart_minimized_1,
        proxies=bond_proxies.simple)
      angle_deltas = geometry_restraints.angle_deltas(
        sites_cart=sites_cart_minimized_1,
        proxies=angle_proxies)
      if (0 or verbose):
        for proxy,delta in zip(bond_proxies.simple, bond_deltas):
          print "bond:", proxy.i_seqs, delta
        for proxy,delta in zip(angle_proxies, angle_deltas):
          print "angle:", proxy.i_seqs, delta
      assert is_below_limit(
        value=flex.max(flex.abs(bond_deltas)), limit=0, eps=1.e-6)
      assert is_below_limit(
        value=flex.max(flex.abs(angle_deltas)), limit=0, eps=2.e-6)
  sites_cart += matrix.col((1,1,0)) - matrix.col(sites_cart.min())
  unit_cell_lengths = list(  matrix.col(sites_cart.max())
                           + matrix.col((1,-1.2,4)))
  unit_cell_lengths[1] *= 2
  unit_cell_lengths[2] *= 2
  xray_structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=unit_cell_lengths,
      space_group_symbol="P112"))
  for serial,site in zip(count(1), sites_cart):
    xray_structure.add_scatterer(xray.scatterer(
      label="C%02d"%serial,
      site=xray_structure.unit_cell().fractionalize(site)))
  if (0 or verbose):
    xray_structure.show_summary().show_scatterers()
  p1_structure = (xray_structure
    .apply_shift((-.5,-.5,0))
    .expand_to_p1()
    .apply_shift((.5,.5,0)))
  for shift in [(1,0,0), (0,1,0), (0,0,1)]:
    p1_structure.add_scatterers(p1_structure.apply_shift(shift).scatterers())
  if (0 or verbose):
    open("p1_structure.pdb", "w").write(p1_structure.as_pdb_file())
  nonbonded_cutoff = 6.5
  asu_mappings = xray_structure.asu_mappings(
    buffer_thickness=nonbonded_cutoff)
  bond_asu_table = crystal.pair_asu_table(asu_mappings=asu_mappings)
  geometry_restraints.add_pairs(bond_asu_table, bond_proxies.simple)
  shell_asu_tables = crystal.coordination_sequences.shell_asu_tables(
    pair_asu_table=bond_asu_table,
    max_shell=3)
  shell_sym_tables = [shell_asu_table.extract_pair_sym_table()
    for shell_asu_table in shell_asu_tables]
  bond_params_table = geometry_restraints.extract_bond_params(
    n_seq=sites_cart.size(),
    bond_simple_proxies=bond_proxies.simple)
  atom_energy_types = flex.std_string(sites_cart.size(), "Default")
  nonbonded_params = geometry_restraints.nonbonded_params(
    factor_1_4_interactions=vdw_1_4_factor,
    const_shrink_1_4_interactions=0,
    default_distance=default_vdw_distance)
  nonbonded_params.distance_table.setdefault(
    "Default")["Default"] = default_vdw_distance
  pair_proxies = geometry_restraints.pair_proxies(
    bond_params_table=bond_params_table,
    shell_asu_tables=shell_asu_tables,
    model_indices=None,
    conformer_indices=None,
    nonbonded_params=nonbonded_params,
    nonbonded_types=atom_energy_types,
    nonbonded_distance_cutoff_plus_buffer=nonbonded_cutoff)
  if (0 or verbose):
    print "pair_proxies.bond_proxies.n_total():", \
           pair_proxies.bond_proxies.n_total(),
    print "simple:", pair_proxies.bond_proxies.simple.size(),
    print "sym:", pair_proxies.bond_proxies.asu.size()
    print "pair_proxies.nonbonded_proxies.n_total():", \
           pair_proxies.nonbonded_proxies.n_total(),
    print "simple:", pair_proxies.nonbonded_proxies.simple.size(),
    print "sym:", pair_proxies.nonbonded_proxies.asu.size()
    print "min_distance_nonbonded: %.2f" % flex.min(
      geometry_restraints.nonbonded_deltas(
        sites_cart=sites_cart,
        sorted_asu_proxies=pair_proxies.nonbonded_proxies))
  s = StringIO()
  pair_proxies.bond_proxies.show_histogram_of_model_distances(
    sites_cart=sites_cart,
    f=s,
    prefix="[]")
  assert s.getvalue().splitlines()[0] == "[]Histogram of bond lengths:"
  assert s.getvalue().splitlines()[5].startswith("[]      1.80 -     1.80:")
  s = StringIO()
  pair_proxies.bond_proxies.show_histogram_of_deltas(
    sites_cart=sites_cart,
    f=s,
    prefix="][")
  assert s.getvalue().splitlines()[0] == "][Histogram of bond deltas:"
  assert s.getvalue().splitlines()[5].startswith("][     0.000 -    0.000:")
  s = StringIO()
  pair_proxies.bond_proxies.show_sorted(
    by_value="residual",
    sites_cart=sites_cart,
    max_items=3,
    f=s,
    prefix=":;")
  l = s.getvalue().splitlines()
  assert l[0] == ":;Bond restraints: 18"
  assert l[1] == ":;Sorted by residual:"
  assert l[2].startswith(":;bond ")
  assert l[3].startswith(":;     ")
  assert l[4] == ":;  ideal  model  delta    sigma   weight residual"
  for i in [5,-2]:
    assert l[i].startswith(":;  1.800  1.800 ")
  assert l[-1] == ":;... (remaining 15 not shown)"
  s = StringIO()
  pair_proxies.nonbonded_proxies.show_histogram_of_model_distances(
    sites_cart=sites_cart,
    f=s,
    prefix="]^")
  assert not show_diff(s.getvalue(), """\
]^Histogram of nonbonded interaction distances:
]^      2.16 -     3.03: 3
]^      3.03 -     3.89: 12
]^      3.89 -     4.75: 28
]^      4.75 -     5.61: 44
]^      5.61 -     6.48: 54
""")
  s = StringIO()
  pair_proxies.nonbonded_proxies.show_sorted(
    by_value="delta",
    sites_cart=sites_cart,
    max_items=7,
    f=s,
    prefix=">,")
  assert not show_diff(s.getvalue(), """\
>,Nonbonded interactions: 141
>,Sorted by model distance:
>,nonbonded 15
>,          15
>,   model   vdw sym.op.
>,   2.164 3.600 -x+2,-y+1,z
...
>,nonbonded 4
>,          8
>,   model   vdw
>,   3.414 3.600
>,... (remaining 134 not shown)
""",
    selections=[range(6), range(-5,0)])
  vdw_1_sticks = []
  vdw_2_sticks = []
  for proxy in pair_proxies.nonbonded_proxies.simple:
    if (proxy.vdw_distance == default_vdw_distance):
      vdw_1_sticks.append(pml_stick(
        begin=sites_cart[proxy.i_seqs[0]],
        end=sites_cart[proxy.i_seqs[1]]))
    else:
      vdw_2_sticks.append(pml_stick(
        begin=sites_cart[proxy.i_seqs[0]],
        end=sites_cart[proxy.i_seqs[1]]))
  mps = asu_mappings.mappings()
  for proxy in pair_proxies.nonbonded_proxies.asu:
    if (proxy.vdw_distance == default_vdw_distance):
      vdw_1_sticks.append(pml_stick(
        begin=mps[proxy.i_seq][0].mapped_site(),
        end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
    else:
      vdw_2_sticks.append(pml_stick(
        begin=mps[proxy.i_seq][0].mapped_site(),
        end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
  if (0 or verbose):
    pml_write(f=open("vdw_1.pml", "w"), label="vdw_1", sticks=vdw_1_sticks)
    pml_write(f=open("vdw_2.pml", "w"), label="vdw_2", sticks=vdw_2_sticks)
  #
  i_pdb = count(2)
  for use_crystal_symmetry in [False, True]:
    if (not use_crystal_symmetry):
      crystal_symmetry = None
      site_symmetry_table = None
    else:
      crystal_symmetry = xray_structure
      site_symmetry_table = xray_structure.site_symmetry_table()
    for sites_cart in [sites_cart_manual.deep_copy(),
                       sites_cart_minimized_1.deep_copy()]:
      manager = geometry_restraints.manager.manager(
        crystal_symmetry=crystal_symmetry,
        site_symmetry_table=site_symmetry_table,
        nonbonded_params=nonbonded_params,
        nonbonded_types=atom_energy_types,
        nonbonded_function=geometry_restraints.prolsq_repulsion_function(),
        bond_params_table=bond_params_table,
        shell_sym_tables=shell_sym_tables,
        nonbonded_distance_cutoff=nonbonded_cutoff,
        nonbonded_buffer=1,
        angle_proxies=angle_proxies,
        plain_pairs_radius=5)
      manager = manager.select(selection=flex.bool(sites_cart.size(), True))
      manager = manager.select(
        iselection=flex.size_t_range(stop=sites_cart.size()))
      pair_proxies = manager.pair_proxies(sites_cart=sites_cart)
      minimized = geometry_restraints.lbfgs.lbfgs(
        sites_cart=sites_cart,
        geometry_restraints_manager=manager,
        lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
          max_iterations=1000))
      if (0 or verbose):
        minimized.final_target_result.show()
        print "number of function evaluations:", minimized.minimizer.nfun()
        print "n_updates_pair_proxies:", manager.n_updates_pair_proxies
      if (not use_crystal_symmetry):
        assert minimized.final_target_result.bond_residual_sum < 1.e-3
        assert minimized.final_target_result.nonbonded_residual_sum < 0.1
      else:
        assert minimized.final_target_result.bond_residual_sum < 1.e-2
        assert minimized.final_target_result.nonbonded_residual_sum < 0.1
      assert minimized.final_target_result.angle_residual_sum < 1.e-3
      if (0 or verbose):
        pdb_file_name = "minimized_%d.pdb" % i_pdb.next()
        print "Writing file:", pdb_file_name
        dump_pdb(file_name=pdb_file_name, sites_cart=sites_cart)
      if (manager.site_symmetry_table is None):
        additional_site_symmetry_table = None
      else:
        additional_site_symmetry_table = sgtbx.site_symmetry_table()
      assert manager.new_including_isolated_sites(
        n_additional_sites=0,
        site_symmetry_table=additional_site_symmetry_table,
        nonbonded_types=flex.std_string()).plain_pairs_radius \
          == manager.plain_pairs_radius
      if (crystal_symmetry is not None):
        assert len(manager.plain_pair_sym_table) == 16
        if (0 or verbose):
          manager.plain_pair_sym_table.show()
  #
  xray_structure.set_u_iso(values=flex.double([
    0.77599982480241358, 0.38745781137212021, 0.20667558236418682,
    0.99759840171302094, 0.8917287406687805, 0.64780251325379845,
    0.24878590382983534, 0.59480621182194615, 0.58695637792905142,
    0.33997130213653637, 0.51258699130743735, 0.79760289141276675,
    0.39996577657875021, 0.4329328819341467, 0.70422156561726479,
    0.87260110626999332]))
  class parameters: pass
  parameters.sphere_radius = 5
  parameters.distance_power = 0.7
  parameters.average_power = 0.9
  parameters.wilson_b_weight = 1.3952
  parameters.wilson_b_weight_auto = False
  adp_energies = adp_restraints.energies_iso(
    geometry_restraints_manager=manager,
    xray_structure=xray_structure,
    parameters=parameters,
    wilson_b=None,
    use_hd=False,
    use_u_local_only = False,
    compute_gradients=False,
    gradients=None,
    normalization=False,
    collect=True)
  assert adp_energies.number_of_restraints == 69
  assert approx_equal(adp_energies.residual_sum, 6.24865382467)
  assert adp_energies.gradients is None
  assert adp_energies.u_i.size() == adp_energies.number_of_restraints
  assert adp_energies.u_j.size() == adp_energies.number_of_restraints
  assert adp_energies.r_ij.size() == adp_energies.number_of_restraints
  for wilson_b in [None, 10, 100]:
    finite_difference_gradients = flex.double()
    eps = 1.e-6
    for i_scatterer in xrange(xray_structure.scatterers().size()):
      rs = []
      for signed_eps in [eps, -eps]:
        xray_structure_eps = xray_structure.deep_copy_scatterers()
        xray_structure_eps.scatterers()[i_scatterer].u_iso += signed_eps
        adp_energies = adp_restraints.energies_iso(
          geometry_restraints_manager=manager,
          xray_structure=xray_structure_eps,
          parameters=parameters,
          wilson_b=wilson_b,
          use_u_local_only = False,
          use_hd=False,
          compute_gradients=True,
          gradients=None,
          normalization=False,
          collect=False)
        rs.append(adp_energies.residual_sum)
        assert adp_energies.gradients.size() \
            == xray_structure.scatterers().size()
        assert adp_energies.u_i == None
        assert adp_energies.u_j == None
        assert adp_energies.r_ij == None
      finite_difference_gradients.append((rs[0]-rs[1])/(2*eps))
    sel = flex.bool(xray_structure.scatterers().size(), True)
    xray_structure.scatterers().flags_set_grad_u_iso(sel.iselection())
    adp_energies = adp_restraints.energies_iso(
      geometry_restraints_manager=manager,
      xray_structure=xray_structure,
      parameters=parameters,
      wilson_b=wilson_b,
      use_u_local_only = False,
      use_hd=False,
      compute_gradients=True,
      gradients=None,
      normalization=False,
      collect=False)
    assert approx_equal(adp_energies.gradients, finite_difference_gradients)
  print "OK"
Example #12
0
def _create_hbond_proxy (
    acceptor_atoms,
    donor_atoms,
    hbond_counts,
    distance_ideal,
    distance_cut,
    remove_outliers,
    weight=1.0,
    sigma=None,
    slack=None,
    top_out=False,
    log=sys.stdout) :
  assert sigma is not None
  assert slack is not None
  donors = []
  acceptors = []
  for atom in acceptor_atoms :
    if (atom.name == ' O  ') :
      acceptors.append(atom)
  for atom in donor_atoms :
    if (atom.name == ' N  ') :
      donors.append(atom)
  if len(donors) > 0 and len(acceptors) > 0:
    # make pairs of connecting atoms
    donor_acceptor_pairs = []
    if len(donors) == 1:
      for acc in acceptors:
        donor_acceptor_pairs.append((donors[0], acc))
    elif len(donors) == 2 and len(acceptors) == 2:
      donor_acceptor_pairs.append((donors[0], acceptors[0]))
      donor_acceptor_pairs.append((donors[1], acceptors[1]))
    elif len(donors) == 2 and len(acceptors) == 1:
      for donor in donors:
        donor_acceptor_pairs.append((donor, acceptors[0]))
    result = []
    for donor, acceptor in donor_acceptor_pairs:
      # print "  linking:", donor.id_str(), acceptor.id_str()
      if (hbond_counts[donor.i_seq] > 0) :
        print >> log, "      WARNING: donor atom is already bonded, skipping"
        print >> log, "    %s" % donor_labels.id_str()
        return None
      elif (hbond_counts[acceptor.i_seq] > 0) :
        print >> log, "      WARNING: acceptor atom is already bonded, skipping"
        print >> log, "    %s" % acceptor_labels.id_str()
        return None
      if (remove_outliers) and (distance_cut > 0) :
        dist = donor.distance(acceptor)
        if (dist > distance_cut) :
          print >> log, "      removed outlier: %.3fA  %s --> %s (cutoff:%.3fA)"%(
              dist, donor.id_str(), acceptor.id_str(), distance_cut)
          return None
      limit = -1
      if (top_out) :
        limit = (distance_cut - distance_ideal)**2 * weight/(sigma**2)
        print "limit: %.2f" % limit
      proxy = geometry_restraints.bond_simple_proxy(
        i_seqs=(donor.i_seq, acceptor.i_seq),
        distance_ideal=distance_ideal,
        weight=weight/(sigma ** 2),
        slack=slack,
        top_out=top_out,
        limit=limit,
        origin_id=1)
      result.append(proxy)
    return result
  else :
    print >> log, "WARNING: missing atoms!"
    return None
Example #13
0
def get_basepair_hbond_proxies(pdb_hierarchy,
                               bp_phil_params,
                               hbond_distance_cutoff=3.4):
    assert pdb_hierarchy is not None
    bond_proxies_result = []
    angle_proxies_result = []
    if len(bp_phil_params) > 0:
        # return bond_proxies_result, angle_proxies_result
        selection_cache = pdb_hierarchy.atom_selection_cache()
        pdb_atoms = pdb_hierarchy.atoms()
        # dashes = open('dashes.pml', 'w')
        pdb_atoms = pdb_hierarchy.atoms()
        for base_pair in bp_phil_params:
            if (base_pair.base1 is not None and base_pair.base2 is not None
                    and base_pair.enabled):
                selected_atoms_1 = selection_cache.iselection(base_pair.base1)
                selected_atoms_2 = selection_cache.iselection(base_pair.base2)
                if len(selected_atoms_1) == 0:
                    raise Sorry(
                        "Selection %s in base_pair retusulted in 0 atoms." %
                        (base_pair.base1))
                if len(selected_atoms_2) == 0:
                    raise Sorry(
                        "Selection %s in base_pair retusulted in 0 atoms." %
                        (base_pair.base2))
                a1 = pdb_atoms[selected_atoms_1[0]]
                a2 = pdb_atoms[selected_atoms_2[0]]
                if base_pair.saenger_class == 0:
                    hbonds, saenger_class = get_h_bonds_for_basepair(
                        a1,
                        a2,
                        distance_cutoff=hbond_distance_cutoff,
                        log=sys.stdout,
                        verbose=-1)
                    base_pair.saenger_class = saenger_class
                hbonds = get_h_bonds_for_particular_basepair(
                    (a1, a2), base_pair.saenger_class)
                for hb in hbonds:
                    if hb[0] is None or hb[1] is None:
                        print "NA hbond rejected because one of the atoms is absent"
                        continue
                    dist = hb[0].distance(hb[1])
                    if dist < hbond_distance_cutoff:
                        if base_pair.restrain_hbonds:
                            hb_target, hb_sigma = get_hb_lenght_targets(hb)
                            p = geometry_restraints.bond_simple_proxy(
                                i_seqs=[hb[0].i_seq, hb[1].i_seq],
                                distance_ideal=hb_target,
                                weight=1.0 / hb_sigma**2,
                                slack=0,
                                top_out=False,
                                limit=1,
                                origin_id=1)
                            bond_proxies_result.append(p)
                            # print "bond:", hb[0].id_str(), hb[1].id_str(), "(%4.2f, %4.2f)" % (hb_target, hb_sigma)
                            # s1 = pdb_atoms[hb[0].i_seq].id_str()
                            # s2 = pdb_atoms[hb[1].i_seq].id_str()
                            # ps = "dist chain \"%s\" and resi %s and name %s, chain \"%s\" and resi %s and name %s\n" % (
                            #   s1[14:15], s1[15:19], s1[5:8], s2[14:15], s2[15:19], s2[5:8])
                            # dashes.write(ps)
                        if base_pair.restrain_hb_angles:
                            angle_proxies_result += get_angle_proxies_for_bond(
                                hb)
                    else:
                        print "NA hbond rejected:", hb[0].id_str(
                        ), hb[1].id_str(), "distance=%.2f" % dist
    # dashes.close()
    return geometry_restraints.shared_bond_simple_proxy(bond_proxies_result), \
        angle_proxies_result
Example #14
0
def _create_hbond_proxy(acceptor_atoms,
                        donor_atoms,
                        hbond_counts,
                        distance_ideal,
                        distance_cut,
                        remove_outliers,
                        weight=1.0,
                        sigma=None,
                        slack=None,
                        top_out=False,
                        log=sys.stdout):
    assert sigma is not None
    assert slack is not None
    donors = []
    acceptors = []
    for atom in acceptor_atoms:
        if (atom.name == ' O  '):
            acceptors.append(atom)
    for atom in donor_atoms:
        if (atom.name == ' N  '):
            donors.append(atom)
    if len(donors) > 0 and len(acceptors) > 0:
        # make pairs of connecting atoms
        donor_acceptor_pairs = []
        if len(donors) == 1:
            for acc in acceptors:
                donor_acceptor_pairs.append((donors[0], acc))
        elif len(donors) == 2 and len(acceptors) == 2:
            donor_acceptor_pairs.append((donors[0], acceptors[0]))
            donor_acceptor_pairs.append((donors[1], acceptors[1]))
        elif len(donors) == 2 and len(acceptors) == 1:
            for donor in donors:
                donor_acceptor_pairs.append((donor, acceptors[0]))
        result = []
        for donor, acceptor in donor_acceptor_pairs:
            # print "  linking:", donor.id_str(), acceptor.id_str()
            if (hbond_counts[donor.i_seq] > 0):
                print >> log, "      WARNING: donor atom is already bonded, skipping"
                print >> log, "    %s" % donor_labels.id_str()
                return None
            elif (hbond_counts[acceptor.i_seq] > 0):
                print >> log, "      WARNING: acceptor atom is already bonded, skipping"
                print >> log, "    %s" % acceptor_labels.id_str()
                return None
            if (remove_outliers) and (distance_cut > 0):
                dist = donor.distance(acceptor)
                if (dist > distance_cut):
                    print >> log, "      removed outlier: %.3fA  %s --> %s (cutoff:%.3fA)" % (
                        dist, donor.id_str(), acceptor.id_str(), distance_cut)
                    return None
            limit = -1
            if (top_out):
                limit = (distance_cut - distance_ideal)**2 * weight / (sigma**
                                                                       2)
                print "limit: %.2f" % limit
            proxy = geometry_restraints.bond_simple_proxy(
                i_seqs=(donor.i_seq, acceptor.i_seq),
                distance_ideal=distance_ideal,
                weight=weight / (sigma**2),
                slack=slack,
                top_out=top_out,
                limit=limit,
                origin_id=1)
            result.append(proxy)
        return result
    else:
        print >> log, "WARNING: missing atoms!"
        return None
def exercise_bond_over_symmetry_2(mon_lib_srv, ener_lib):
  """ This test is to illustrate that bond over symmetry actually
  adds 2 proxies.
  """
  from cctbx.geometry_restraints.linking_class import linking_class
  origin_ids = linking_class()
  pdb_inp = iotbx.pdb.input(source_info=None, lines=raw_records10)
  params = mmtbx.model.manager.get_default_pdb_interpretation_params()
  params.pdb_interpretation.restraints_library.mcl=False
  model = mmtbx.model.manager(
      model_input = pdb_inp,
      pdb_interpretation_params=params,
      log=null_out())
  grm = model.get_restraints_manager().geometry
  simple, asu = grm.get_all_bond_proxies()
  assert (simple.size(), asu.size()) == (0, 0)

  h = model.get_hierarchy()
  sites_cart = h.atoms().extract_xyz()
  site_labels = model.get_xray_structure().scatterers().extract_labels()
  pair_proxies = grm.pair_proxies(flags=None, sites_cart=sites_cart)

  out = StringIO()
  pair_proxies.bond_proxies.show_sorted(
      by_value="residual",
      sites_cart=sites_cart,
      site_labels=site_labels,
      f=out,
      prefix="")
  outtxt = out.getvalue()
  # print(outtxt)

  proxy = geometry_restraints.bond_simple_proxy(
      i_seqs=(0,1),
      distance_ideal=2.9,
      weight=400,
      origin_id=origin_ids.get_origin_id('hydrogen bonds'))
  grm.add_new_bond_restraints_in_place(
      proxies=[proxy],
      sites_cart=h.atoms().extract_xyz())
  simple, asu = grm.get_all_bond_proxies()
  # print(simple.size(), asu.size())
  assert (simple.size(), asu.size()) == (0,2)

  sites_cart = h.atoms().extract_xyz()
  site_labels = model.get_xray_structure().scatterers().extract_labels()
  pair_proxies = grm.pair_proxies(flags=None, sites_cart=sites_cart)

  out = StringIO()
  pair_proxies.bond_proxies.show_sorted(
      by_value="residual",
      sites_cart=sites_cart,
      site_labels=site_labels,
      f=out,
      prefix="")
  outtxt = out.getvalue()
  # print(outtxt)
  assert_lines_in_text(outtxt, """\
bond pdb=" CA  HIS A   2 "
     pdb=" N   MET A   1 "
  ideal  model  delta    sigma   weight residual sym.op.
  2.900  1.998  0.902 5.00e-02 4.00e+02 3.25e+02 x,y+1,z
bond pdb=" N   MET A   1 "
     pdb=" CA  HIS A   2 "
  ideal  model  delta    sigma   weight residual sym.op.
  2.900  1.998  0.902 5.00e-02 4.00e+02 3.25e+02 x,y-1,z
    """)

  es = grm.energies_sites(sites_cart=sites_cart, compute_gradients=True)
  out = StringIO()
  es.show(f=out)
  outtxt = out.getvalue()
  # print(outtxt)
  # do for x coordinate
  # ATOM      1  N   MET A   1       9.821   1.568   5.000  1.00 66.07           N
  # ATOM      2  CA  HIS A   2       9.946  12.171   5.357  1.00 66.55           C

  # calculation is from geometry_restraints/bond.h: gradient_0()
  # weight * 2 * delta_slack * d_distance_d_site_0(epsilon);
  # print("X gradient:", 400*2*0.902*(9.946-9.821)) # 90
  # Note that n=2 but residual sum is 325.349. 349 is chopped off in rounding in
  # cctbx/geometry_restraints/__init__py, def _bond_show_sorted_impl(...)
  # where %6.2e is used. in cctbx/geometry_restraints/energies.py: def show()
  # %.6g is used which is showing more numbers.
  assert_lines_in_text(outtxt, """\
      bond_residual_sum (n=2): 325.349""")
  # print("Gradients:", list(es.gradients))
  # Seems that gradients were splitted in half (note the X gradient is 90 8 lines above)
  assert approx_equal(list(es.gradients),
    [(45.135801792665134, -708.451544937652, 128.90784991984805), (-45.13580179266516, 708.4515449376522, -128.90784991984813)])