def __init__(
     self,
     restraints_manager,
     pdb_hierarchy,
     correct_special_position_tolerance,
     riding_h_manager=None,
     ncs_restraints_group_list=[],  # These are actually for NCS CONSTRAINTS!
     max_number_of_iterations=500,
     number_of_macro_cycles=5,
     selection=None,
     bond=False,
     nonbonded=False,
     angle=False,
     dihedral=False,
     chirality=False,
     planarity=False,
     parallelity=False,
     rmsd_bonds_termination_cutoff=0,
     rmsd_angles_termination_cutoff=0,
     alternate_nonbonded_off_on=False,
     cdl=False,
     rdl=False,
     correct_hydrogens=False,
     fix_rotamer_outliers=True,
     allow_allowed_rotamers=True,
     states_collector=None,
     log=None,
     mon_lib_srv=None,
     ias_selection=None,
 ):
     self.log = log
     if self.log is None:
         self.log = sys.stdout
     self.pdb_hierarchy = pdb_hierarchy
     self.ias_selection = ias_selection
     self.minimized = None
     self.mon_lib_srv = mon_lib_srv
     if self.mon_lib_srv is None:
         self.mon_lib_srv = monomer_library.server.server()
     self.restraints_manager = restraints_manager
     assert max_number_of_iterations + number_of_macro_cycles > 0
     assert [
         bond, nonbonded, angle, dihedral, chirality, planarity, parallelity
     ].count(False) < 7
     self.cdl_proxies = None
     self.rdl_proxies = None
     self.rotamer_manager = None
     if fix_rotamer_outliers:
         from mmtbx.rotamer.rotamer_eval import RotamerEval
         self.rotamer_manager = RotamerEval(mon_lib_srv=self.mon_lib_srv)
     if (cdl):
         from mmtbx.conformation_dependent_library.cdl_setup import setup_restraints
         self.cdl_proxies = setup_restraints(
             self.restraints_manager.geometry)
     self.correct_hydrogens = correct_hydrogens
     if (alternate_nonbonded_off_on and number_of_macro_cycles % 2 != 0):
         number_of_macro_cycles += 1
     import scitbx.lbfgs
     lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
         max_iterations=max_number_of_iterations)
     exception_handling_params = scitbx.lbfgs.exception_handling_parameters(
         ignore_line_search_failed_step_at_lower_bound=True)
     geometry_restraints_flags = geometry_restraints.flags.flags(
         bond=bond,
         nonbonded=nonbonded,
         angle=angle,
         dihedral=dihedral,
         chirality=chirality,
         planarity=planarity,
         parallelity=parallelity,
         reference_coordinate=True,
         reference_dihedral=True,
         bond_similarity=True,
         ramachandran_restraints=True)
     self.update_cdl_restraints()
     self.show()
     for i_macro_cycle in xrange(number_of_macro_cycles):
         print >> self.log, "  macro-cycle:", i_macro_cycle
         self.restraints_manager.geometry.update_ramachandran_restraints_phi_psi_targets(
             sites_cart=self.pdb_hierarchy.atoms().extract_xyz())
         if (alternate_nonbonded_off_on
                 and i_macro_cycle <= number_of_macro_cycles / 2):
             geometry_restraints_flags.nonbonded = bool(i_macro_cycle % 2)
         self.update_cdl_restraints(macro_cycle=i_macro_cycle)
         if (fix_rotamer_outliers):
             self.pdb_hierarchy, self.restraints_manager = add_rotamer_restraints(
                 pdb_hierarchy=self.pdb_hierarchy,
                 restraints_manager=self.restraints_manager,
                 selection=selection,
                 sigma=10,
                 mode="fix_outliers",
                 accept_allowed=allow_allowed_rotamers,
                 mon_lib_srv=self.mon_lib_srv,
                 rotamer_manager=self.rotamer_manager)
         sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
         if rdl:
             self.updaterdl(prefix="Update RDL restraints")
         if (ncs_restraints_group_list is not None
                 and len(ncs_restraints_group_list)) > 0:
             # do ncs minimization
             print >> self.log, "Using NCS constraints."
             xrs = self.pdb_hierarchy.extract_xray_structure(
             ).deep_copy_scatterers()
             refine_selection = flex.size_t(xrange(xrs.scatterers().size()))
             tfg_obj = mmtbx.refinement.minimization_ncs_constraints.\
                 target_function_and_grads_geometry_minimization(
                     xray_structure=xrs,
                     ncs_restraints_group_list=ncs_restraints_group_list, # CONSTRAINTS
                     refine_selection=refine_selection,
                     restraints_manager=self.restraints_manager.geometry,
                     refine_sites=True,
                     refine_transformations=False,
                     )
             minimized = mmtbx.refinement.minimization_ncs_constraints.lbfgs(
                 target_and_grads_object=tfg_obj,
                 xray_structure=xrs,
                 ncs_restraints_group_list=
                 ncs_restraints_group_list,  # CONSTRAINTS
                 refine_selection=refine_selection,
                 finite_grad_differences_test=False,
                 max_iterations=max_number_of_iterations,
                 refine_sites=True,
                 refine_transformations=False)
             self.pdb_hierarchy.adopt_xray_structure(xrs)
         else:
             sites_cart_orig = sites_cart.deep_copy()
             if ias_selection is not None and ias_selection.count(True) > 0:
                 sites_cart = sites_cart.select(~ias_selection)
             self.minimized = lbfgs(
                 sites_cart=sites_cart,
                 riding_h_manager=riding_h_manager,
                 correct_special_position_tolerance=
                 correct_special_position_tolerance,
                 geometry_restraints_manager=restraints_manager.geometry,
                 geometry_restraints_flags=geometry_restraints_flags,
                 lbfgs_termination_params=lbfgs_termination_params,
                 lbfgs_exception_handling_params=exception_handling_params,
                 sites_cart_selection=selection,
                 rmsd_bonds_termination_cutoff=rmsd_bonds_termination_cutoff,
                 rmsd_angles_termination_cutoff=
                 rmsd_angles_termination_cutoff,
                 states_collector=states_collector,
                 site_labels=None)
             if (ias_selection is not None):
                 for i_seq, ias_s in enumerate(
                         ias_selection
                 ):  # assumes that IAS appended to the back
                     if (not ias_s):
                         sites_cart_orig[i_seq] = sites_cart[i_seq]
             else:
                 sites_cart_orig = sites_cart
             self.pdb_hierarchy.atoms().set_xyz(sites_cart_orig)
         self.show()
         self.log.flush()
         geometry_restraints_flags.nonbonded = nonbonded
         lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
             max_iterations=max_number_of_iterations)
def run(processed_pdb_file, params=master_params().extract(), log=sys.stdout):
    co = params
    geometry_restraints_flags = geometry_restraints.flags.flags(default=True)
    all_chain_proxies = processed_pdb_file.all_chain_proxies
    reference_manager = None
    if (co.restrain_c_alpha_positions):
        assert 0, "Broken! - rewrite this part first."
        from mmtbx.geometry_restraints import reference
        ca_selection = all_chain_proxies.pdb_hierarchy.get_peptide_c_alpha_selection(
        )
        ca_sites_cart = \
          all_chain_proxies.sites_cart.deep_copy().select(ca_selection)
        reference_manager = reference.manager()
        reference_manager.add_coordinate_restraints(sites_cart=ca_sites_cart,
                                                    selection=ca_selection)
    geometry_restraints_manager = processed_pdb_file.\
      geometry_restraints_manager(show_energies = False,
                                  reference_manager=\
                                    reference_manager)
    special_position_settings = all_chain_proxies.special_position_settings
    sites_cart = all_chain_proxies.sites_cart_exact().deep_copy()
    atom_labels = [atom.id_str() for atom in all_chain_proxies.pdb_atoms]
    geometry_restraints_manager.site_symmetry_table \
      .show_special_position_shifts(
        special_position_settings=special_position_settings,
        site_labels=atom_labels,
        sites_cart_original=all_chain_proxies.sites_cart,
        sites_cart_exact=sites_cart,
        out=log,
        prefix="  ")
    if (co.show_geometry_restraints):
        geometry_restraints_manager.show_sorted(
            flags=geometry_restraints_flags,
            sites_cart=sites_cart,
            site_labels=atom_labels)
    pair_proxies = geometry_restraints_manager.pair_proxies(
        sites_cart=all_chain_proxies.sites_cart,
        flags=geometry_restraints_flags)
    pair_proxies.bond_proxies.show_sorted(by_value="residual",
                                          sites_cart=sites_cart,
                                          site_labels=atom_labels,
                                          f=log,
                                          max_items=10)
    if (pair_proxies.nonbonded_proxies is not None):
        pair_proxies.nonbonded_proxies.show_sorted(by_value="delta",
                                                   sites_cart=sites_cart,
                                                   site_labels=atom_labels,
                                                   f=log,
                                                   max_items=10)
    del pair_proxies
    print >> log
    log.flush()
    if (co.alternate_nonbonded_off_on and co.macro_cycles % 2 != 0):
        co.macro_cycles += 1
        print >> log, "INFO: Number of macro cycles increased by one to ensure use of"
        print >> log, "      nonbonded interactions in last macro cycle."
        print >> log
    for i_macro_cycle in xrange(co.macro_cycles):
        if (co.alternate_nonbonded_off_on):
            geometry_restraints_flags.nonbonded = bool(i_macro_cycle % 2)
            print >> log, "Use nonbonded interactions this macro cycle:", \
              geometry_restraints_flags.nonbonded
        minimized = lbfgs(
            sites_cart=sites_cart,
            geometry_restraints_manager=geometry_restraints_manager,
            geometry_restraints_flags=geometry_restraints_flags,
            lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
                max_iterations=co.max_iterations),
            lbfgs_exception_handling_params=scitbx.lbfgs.
            exception_handling_parameters(
                ignore_line_search_failed_step_at_lower_bound=True))
        print >> log, "Energies at start of minimization:"
        minimized.first_target_result.show(f=log)
        print >> log
        print >> log, "Number of minimization iterations:", minimized.minimizer.iter(
        )
        print >> log, "Root-mean-square coordinate difference: %.3f" % (
            all_chain_proxies.sites_cart.rms_difference(sites_cart))
        print >> log
        print >> log, "Energies at end of minimization:"
        minimized.final_target_result.show(f=log)
        print >> log
        geometry_restraints_manager.pair_proxies(
          sites_cart=sites_cart,
          flags=geometry_restraints_flags) \
            .bond_proxies.show_sorted(
              by_value="residual",
              sites_cart=sites_cart,
              site_labels=atom_labels,
              f=log,
              max_items=10)
        print >> log
    assert geometry_restraints_flags.nonbonded
    return sites_cart
예제 #3
0
def run(args):
  assert args in [[], ["--verbose"]]
  if (len(args) != 0):
    cout = sys.stdout
  else:
    cout = null_out()
  edge_list_bonds = [(0,1),(0,4),(1,2),(2,3),(3,4)]
  bond_list = [
    (("C1*", "C2*"), 1.529),
    (("C1*", "O4*"), 1.412),
    (("C2*", "C3*"), 1.526),
    (("C3*", "C4*"), 1.520),
    (("C4*", "O4*"), 1.449)]
  angle_list = [
    (("C1*", "C2*", "C3*"), 101.3),
    (("C2*", "C3*", "C4*"), 102.3),
    (("C3*", "C4*", "O4*"), 104.2),
    (("C4*", "O4*", "C1*"), 110.0)]
  sites_cart, geo_manager = cctbx.geometry_restraints.manager \
    .construct_non_crystallographic_conserving_bonds_and_angles(
      sites_cart=sites_cart_3p,
      edge_list_bonds=edge_list_bonds,
      edge_list_angles=[])
  for bond_atom_names,distance_ideal in bond_list:
    i,j = [atom_names.index(atom_name) for atom_name in bond_atom_names]
    bond_params = geo_manager.bond_params_table[i][j]
    assert approx_equal(bond_params.distance_ideal, distance_ideal, eps=1.e-2)
    bond_params.distance_ideal = distance_ideal
    bond_params.weight = 1/0.02**2
  assert geo_manager.angle_proxies is None
  geo_manager.angle_proxies = cctbx.geometry_restraints.shared_angle_proxy()
  for angle_atom_names,angle_ideal in angle_list:
    i_seqs = [atom_names.index(atom_name) for atom_name in angle_atom_names]
    geo_manager.angle_proxies.append(cctbx.geometry_restraints.angle_proxy(
      i_seqs=i_seqs,
      angle_ideal=angle_ideal,
      weight=1/3**2))
  geo_manager.show_sorted(
    site_labels=atom_names, sites_cart=sites_cart, f=cout)
  def lbfgs(sites_cart):
    for i_lbfgs_restart in xrange(3):
      minimized = cctbx.geometry_restraints.lbfgs.lbfgs(
        sites_cart=sites_cart,
        geometry_restraints_manager=geo_manager)
      assert is_below_limit(value=minimized.final_target_value, limit=1e-10)
    return minimized
  lbfgs(sites_cart=sites_cart_3p)
  lbfgs(sites_cart=sites_cart_2p)
  conformer_counts = [0] * 4
  sites_cart = sites_cart.deep_copy()
  mt = flex.mersenne_twister(seed=0)
  for i_trial in xrange(20):
    while True:
      for i in xrange(sites_cart.size()):
        sites_cart[i] = mt.random_double_point_on_sphere()
      try:
        lbfgs(sites_cart=sites_cart)
      except RuntimeError, e:
        if (not str(e).startswith(
              "Bond distance > max_reasonable_bond_distance: ")):
          raise
      else:
        break
    rmsd_list = flex.double()
    for reference_sites in [
          sites_cart_3p,
          sites_cart_2p,
          sites_cart_a,
          sites_cart_b]:
      sup = scitbx.math.superpose.least_squares_fit(
        reference_sites=reference_sites,
        other_sites=sites_cart)
      rmsd = reference_sites.rms_difference(sup.other_sites_best_fit())
      rmsd_list.append(rmsd)
    oline = " ".join(["%.3f" % rmsd for rmsd in rmsd_list])
    print >> cout, oline
    assert is_below_limit(min(rmsd_list), 1e-3)
    conformer_counts[flex.min_index(rmsd_list)] += 1
예제 #4
0
def run(args):
    assert args in [[], ["--verbose"]]
    if (len(args) != 0):
        cout = sys.stdout
    else:
        cout = null_out()
    edge_list_bonds = [(0, 1), (0, 4), (1, 2), (2, 3), (3, 4)]
    bond_list = [(("C1*", "C2*"), 1.529), (("C1*", "O4*"), 1.412),
                 (("C2*", "C3*"), 1.526), (("C3*", "C4*"), 1.520),
                 (("C4*", "O4*"), 1.449)]
    angle_list = [
        (("C1*", "C2*", "C3*"), 101.3), (("C2*", "C3*", "C4*"), 102.3),
        (("C3*", "C4*", "O4*"), 104.2), (("C4*", "O4*", "C1*"), 110.0)
    ]
    sites_cart, geo_manager = cctbx.geometry_restraints.manager \
      .construct_non_crystallographic_conserving_bonds_and_angles(
        sites_cart=sites_cart_3p,
        edge_list_bonds=edge_list_bonds,
        edge_list_angles=[])
    for bond_atom_names, distance_ideal in bond_list:
        i, j = [atom_names.index(atom_name) for atom_name in bond_atom_names]
        bond_params = geo_manager.bond_params_table[i][j]
        assert approx_equal(bond_params.distance_ideal,
                            distance_ideal,
                            eps=1.e-2)
        bond_params.distance_ideal = distance_ideal
        bond_params.weight = 1 / 0.02**2
    assert geo_manager.angle_proxies is None
    geo_manager.angle_proxies = cctbx.geometry_restraints.shared_angle_proxy()
    for angle_atom_names, angle_ideal in angle_list:
        i_seqs = [
            atom_names.index(atom_name) for atom_name in angle_atom_names
        ]
        geo_manager.angle_proxies.append(
            cctbx.geometry_restraints.angle_proxy(i_seqs=i_seqs,
                                                  angle_ideal=angle_ideal,
                                                  weight=1 / 3**2))
    geo_manager.show_sorted(site_labels=atom_names,
                            sites_cart=sites_cart,
                            f=cout)

    def lbfgs(sites_cart):
        for i_lbfgs_restart in range(3):
            minimized = cctbx.geometry_restraints.lbfgs.lbfgs(
                sites_cart=sites_cart, geometry_restraints_manager=geo_manager)
            assert is_below_limit(value=minimized.final_target_value,
                                  limit=1e-10)
        return minimized

    lbfgs(sites_cart=sites_cart_3p)
    lbfgs(sites_cart=sites_cart_2p)
    conformer_counts = [0] * 4
    sites_cart = sites_cart.deep_copy()
    mt = flex.mersenne_twister(seed=0)
    for i_trial in range(20):
        while True:
            for i in range(sites_cart.size()):
                sites_cart[i] = mt.random_double_point_on_sphere()
            try:
                lbfgs(sites_cart=sites_cart)
            except RuntimeError as e:
                if (not str(e).startswith(
                        "Bond distance > max_reasonable_bond_distance: ")):
                    raise
            else:
                break
        rmsd_list = flex.double()
        for reference_sites in [
                sites_cart_3p, sites_cart_2p, sites_cart_a, sites_cart_b
        ]:
            sup = scitbx.math.superpose.least_squares_fit(
                reference_sites=reference_sites, other_sites=sites_cart)
            rmsd = reference_sites.rms_difference(sup.other_sites_best_fit())
            rmsd_list.append(rmsd)
        oline = " ".join(["%.3f" % rmsd for rmsd in rmsd_list])
        print(oline, file=cout)
        assert is_below_limit(min(rmsd_list), 1e-3)
        conformer_counts[flex.min_index(rmsd_list)] += 1
    print("conformer_counts:", conformer_counts)
    #
    if (libtbx.env.has_module("iotbx")):
        import iotbx.pdb.hierarchy
        hierarchy = iotbx.pdb.hierarchy.root()
        model = iotbx.pdb.hierarchy.model(id="")
        chain = iotbx.pdb.hierarchy.chain(id="A")
        model.append_chain(chain)
        hierarchy.append_model(model)
        #
        sites_cart_pentagon = pentagon_sites_cart()
        for i_stack, sites_cart in enumerate(
            [sites_cart_3p, sites_cart_2p, sites_cart_a, sites_cart_b]):
            atom_group = iotbx.pdb.hierarchy.atom_group(resname="  U",
                                                        altloc="")
            sup = scitbx.math.superpose.least_squares_fit(
                reference_sites=sites_cart_pentagon, other_sites=sites_cart)
            sites_cart_out = sup.other_sites_best_fit()
            for site_label, site_cart in zip(atom_names, sites_cart_out):
                atom = iotbx.pdb.hierarchy.atom()
                atom.name = " %-3s" % site_label
                atom.xyz = matrix.col(site_cart) + matrix.col(
                    (0, 0, i_stack * 1.5))
                atom.occ = 1
                atom.b = 20
                atom.element = " " + site_label[0]
                atom_group.append_atom(atom)
            residue_group = iotbx.pdb.hierarchy.residue_group(resseq="%4d" %
                                                              (i_stack + 1),
                                                              icode=" ")
            residue_group.append_atom_group(atom_group)
            chain.append_residue_group(residue_group)
        hierarchy.atoms().reset_serial()
        pdb_str = hierarchy.as_pdb_string(append_end=True)
        file_name = "puckers.pdb"
        print("Writing file:", file_name)
        open(file_name, "w").write("""\
REMARK random_puckers.py
REMARK 1 = 3'
REMARK 2 = 2'
REMARK 3 = A
REMARK 4 = B
""" + pdb_str)
    #
    print("OK")
def run(processed_pdb_file, params=master_params().extract(), log=sys.stdout):
  co = params
  geometry_restraints_flags = geometry_restraints.flags.flags(default=True)
  all_chain_proxies = processed_pdb_file.all_chain_proxies
  reference_manager = None
  if (co.restrain_c_alpha_positions):
    assert 0, "Broken! - rewrite this part first."
    from mmtbx.geometry_restraints import reference
    ca_selection=all_chain_proxies.pdb_hierarchy.get_peptide_c_alpha_selection()
    ca_sites_cart = \
      all_chain_proxies.sites_cart.deep_copy().select(ca_selection)
    reference_manager = reference.manager()
    reference_manager.add_coordinate_restraints(
      sites_cart=ca_sites_cart,
      selection=ca_selection)
  geometry_restraints_manager = processed_pdb_file.\
    geometry_restraints_manager(show_energies = False,
                                reference_manager=\
                                  reference_manager)
  special_position_settings = all_chain_proxies.special_position_settings
  sites_cart = all_chain_proxies.sites_cart_exact().deep_copy()
  atom_labels = [atom.id_str() for atom in all_chain_proxies.pdb_atoms]
  geometry_restraints_manager.site_symmetry_table \
    .show_special_position_shifts(
      special_position_settings=special_position_settings,
      site_labels=atom_labels,
      sites_cart_original=all_chain_proxies.sites_cart,
      sites_cart_exact=sites_cart,
      out=log,
      prefix="  ")
  if (co.show_geometry_restraints):
    geometry_restraints_manager.show_sorted(
      flags=geometry_restraints_flags,
      sites_cart=sites_cart,
      site_labels=atom_labels)
  pair_proxies =  geometry_restraints_manager.pair_proxies(
    sites_cart=all_chain_proxies.sites_cart,
    flags=geometry_restraints_flags)
  pair_proxies.bond_proxies.show_sorted(
    by_value="residual",
    sites_cart=sites_cart,
    site_labels=atom_labels,
    f=log,
    max_items=10)
  if (pair_proxies.nonbonded_proxies is not None):
    pair_proxies.nonbonded_proxies.show_sorted(
      by_value="delta",
      sites_cart=sites_cart,
      site_labels=atom_labels,
      f=log,
      max_items=10)
  del pair_proxies
  print >> log
  log.flush()
  if (co.alternate_nonbonded_off_on and co.macro_cycles % 2 != 0):
    co.macro_cycles += 1
    print >> log, "INFO: Number of macro cycles increased by one to ensure use of"
    print >> log, "      nonbonded interactions in last macro cycle."
    print >> log
  for i_macro_cycle in xrange(co.macro_cycles):
    if (co.alternate_nonbonded_off_on):
      geometry_restraints_flags.nonbonded = bool(i_macro_cycle % 2)
      print >> log, "Use nonbonded interactions this macro cycle:", \
        geometry_restraints_flags.nonbonded
    minimized = lbfgs(
      sites_cart=sites_cart,
      geometry_restraints_manager=geometry_restraints_manager,
      geometry_restraints_flags=geometry_restraints_flags,
      lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
        max_iterations=co.max_iterations),
      lbfgs_exception_handling_params=
        scitbx.lbfgs.exception_handling_parameters(
          ignore_line_search_failed_step_at_lower_bound=True))
    print >> log, "Energies at start of minimization:"
    minimized.first_target_result.show(f=log)
    print >> log
    print >> log, "Number of minimization iterations:", minimized.minimizer.iter()
    print >> log, "Root-mean-square coordinate difference: %.3f" % (
      all_chain_proxies.sites_cart.rms_difference(sites_cart))
    print >> log
    print >> log, "Energies at end of minimization:"
    minimized.final_target_result.show(f=log)
    print >> log
    geometry_restraints_manager.pair_proxies(
      sites_cart=sites_cart,
      flags=geometry_restraints_flags) \
        .bond_proxies.show_sorted(
          by_value="residual",
          sites_cart=sites_cart,
          site_labels=atom_labels,
          f=log,
          max_items=10)
    print >> log
  assert geometry_restraints_flags.nonbonded
  return sites_cart
 def __init__(self,
              restraints_manager,
              pdb_hierarchy,
              correct_special_position_tolerance,
              ncs_restraints_group_list      = [],
              max_number_of_iterations       = 500,
              number_of_macro_cycles         = 5,
              selection                      = None,
              bond                           = False,
              nonbonded                      = False,
              angle                          = False,
              dihedral                       = False,
              chirality                      = False,
              planarity                      = False,
              parallelity                    = False,
              rmsd_bonds_termination_cutoff  = 0,
              rmsd_angles_termination_cutoff = 0,
              alternate_nonbonded_off_on     = False,
              cdl                            = False,
              rdl                            = False,
              correct_hydrogens              = False,
              fix_rotamer_outliers           = True,
              allow_allowed_rotamers         = True,
              states_collector               = None,
              log                            = None,
              mon_lib_srv                    = None):
   self.log = log
   if self.log is None:
     self.log = sys.stdout
   self.pdb_hierarchy = pdb_hierarchy
   self.minimized = None
   self.mon_lib_srv = mon_lib_srv
   if self.mon_lib_srv is None:
     self.mon_lib_srv = monomer_library.server.server()
   self.restraints_manager = restraints_manager
   assert max_number_of_iterations+number_of_macro_cycles > 0
   assert [bond,nonbonded,angle,dihedral,chirality,planarity,
           parallelity].count(False) < 7
   self.cdl_proxies = None
   self.rdl_proxies = None
   self.rotamer_manager = None
   if fix_rotamer_outliers:
     from mmtbx.rotamer.rotamer_eval import RotamerEval
     self.rotamer_manager = RotamerEval(mon_lib_srv=self.mon_lib_srv)
   if(cdl):
     from mmtbx.conformation_dependent_library.cdl_setup import setup_restraints
     self.cdl_proxies = setup_restraints(self.restraints_manager.geometry)
   self.correct_hydrogens = correct_hydrogens
   if(alternate_nonbonded_off_on and number_of_macro_cycles % 2 != 0):
     number_of_macro_cycles += 1
   import scitbx.lbfgs
   lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
     max_iterations = max_number_of_iterations)
   exception_handling_params = scitbx.lbfgs.exception_handling_parameters(
     ignore_line_search_failed_step_at_lower_bound = True)
   geometry_restraints_flags = geometry_restraints.flags.flags(
     bond               = bond,
     nonbonded          = nonbonded,
     angle              = angle,
     dihedral           = dihedral,
     chirality          = chirality,
     planarity          = planarity,
     parallelity        = parallelity,
     reference_coordinate = True,
     reference_dihedral = True,
     bond_similarity    = True,
     ramachandran_restraints = True)
   self.update_cdl_restraints()
   self.show()
   for i_macro_cycle in xrange(number_of_macro_cycles):
     print >> self.log, "  macro-cycle:", i_macro_cycle
     self.restraints_manager.geometry.update_ramachandran_restraints_phi_psi_targets(
       sites_cart=self.pdb_hierarchy.atoms().extract_xyz())
     if(alternate_nonbonded_off_on and i_macro_cycle<=number_of_macro_cycles/2):
       geometry_restraints_flags.nonbonded = bool(i_macro_cycle % 2)
     self.correct_hydrogen_geometries(self.log)
     self.update_cdl_restraints(macro_cycle=i_macro_cycle)
     if(fix_rotamer_outliers):
       self.pdb_hierarchy, self.restraints_manager = add_rotamer_restraints(
         pdb_hierarchy      = self.pdb_hierarchy,
         restraints_manager = self.restraints_manager,
         selection          = selection,
         sigma              = 10,
         mode               = "fix_outliers",
         accept_allowed     = allow_allowed_rotamers,
         mon_lib_srv        = self.mon_lib_srv,
         rotamer_manager    = self.rotamer_manager)
     sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
     if rdl:
       self.updaterdl(prefix="Update RDL restraints")
     # self.pdb_hierarchy.write_pdb_file("after_fix_%d.pdb" % i_macro_cycle)
     # self.restraints_manager.write_geo_file(
     #     sites_cart=self.pdb_hierarchy.atoms().extract_xyz(),
     #     site_labels= [atom.id_str() for atom in self.pdb_hierarchy.atoms()],
     #     file_name="after_fix_%d.geo" % i_macro_cycle)
     if (ncs_restraints_group_list is not None
         and len(ncs_restraints_group_list)) > 0:
       # do ncs minimization
       print >> self.log, "Using NCS constraints."
       xrs = self.pdb_hierarchy.extract_xray_structure().deep_copy_scatterers()
       refine_selection = flex.size_t(xrange(xrs.scatterers().size()))
       tfg_obj = mmtbx.refinement.minimization_ncs_constraints.\
           target_function_and_grads_geometry_minimization(
               xray_structure=xrs,
               ncs_restraints_group_list=ncs_restraints_group_list,
               refine_selection=refine_selection,
               restraints_manager=self.restraints_manager.geometry,
               refine_sites=True,
               refine_transformations=False,
               )
       minimized = mmtbx.refinement.minimization_ncs_constraints.lbfgs(
         target_and_grads_object      = tfg_obj,
         xray_structure               = xrs,
         ncs_restraints_group_list    = ncs_restraints_group_list,
         refine_selection             = refine_selection,
         finite_grad_differences_test = False,
         max_iterations               = max_number_of_iterations,
         refine_sites                 = True,
         refine_transformations       = False)
       self.pdb_hierarchy.adopt_xray_structure(xrs)
     else:
       self.minimized = lbfgs(
         sites_cart                      = sites_cart,
         correct_special_position_tolerance=correct_special_position_tolerance,
         geometry_restraints_manager     = restraints_manager.geometry,
         geometry_restraints_flags       = geometry_restraints_flags,
         lbfgs_termination_params        = lbfgs_termination_params,
         lbfgs_exception_handling_params = exception_handling_params,
         sites_cart_selection            = selection,
         rmsd_bonds_termination_cutoff   = rmsd_bonds_termination_cutoff,
         rmsd_angles_termination_cutoff  = rmsd_angles_termination_cutoff,
         states_collector                = states_collector,
         site_labels                     = None)
       self.pdb_hierarchy.atoms().set_xyz(sites_cart)
     self.show()
     self.log.flush()
     geometry_restraints_flags.nonbonded = nonbonded
     lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
         max_iterations = max_number_of_iterations)
 def __init__(self,
              restraints_manager,
              pdb_hierarchy,
              correct_special_position_tolerance,
              max_number_of_iterations       = 500,
              number_of_macro_cycles         = 5,
              selection                      = None,
              bond                           = False,
              nonbonded                      = False,
              angle                          = False,
              dihedral                       = False,
              chirality                      = False,
              planarity                      = False,
              parallelity                    = False,
              rmsd_bonds_termination_cutoff  = 0,
              rmsd_angles_termination_cutoff = 0,
              alternate_nonbonded_off_on     = False,
              cdl                            = False,
              correct_hydrogens              = False,
              fix_rotamer_outliers           = True,
              states_collector               = None,
              log                            = None):
   self.log = log
   if self.log is None:
     self.log = sys.stdout
   self.pdb_hierarchy = pdb_hierarchy
   self.minimized = None
   self.restraints_manager = restraints_manager
   assert max_number_of_iterations+number_of_macro_cycles > 0
   assert [bond,nonbonded,angle,dihedral,chirality,planarity,
           parallelity].count(False) < 7
   self.cdl_proxies = None
   if(cdl):
     from mmtbx.conformation_dependent_library.cdl_setup import setup_restraints
     self.cdl_proxies = setup_restraints(restraints_manager.geometry)
   self.correct_hydrogens = correct_hydrogens
   if(alternate_nonbonded_off_on and number_of_macro_cycles % 2 != 0):
     number_of_macro_cycles += 1
   import scitbx.lbfgs
   lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
     max_iterations = max_number_of_iterations)
   exception_handling_params = scitbx.lbfgs.exception_handling_parameters(
     ignore_line_search_failed_step_at_lower_bound = True)
   geometry_restraints_flags = geometry_restraints.flags.flags(
     bond               = bond,
     nonbonded          = nonbonded,
     angle              = angle,
     dihedral           = dihedral,
     chirality          = chirality,
     planarity          = planarity,
     parallelity        = parallelity,
     reference_coordinate = True,
     reference_dihedral = True,
     bond_similarity    = True,
     ramachandran_restraints = True)
   self.update_cdl_restraints()
   self.show()
   for i_macro_cycle in xrange(number_of_macro_cycles):
     print >> self.log, "  macro-cycle:", i_macro_cycle
     if(alternate_nonbonded_off_on and i_macro_cycle<=number_of_macro_cycles/2):
       geometry_restraints_flags.nonbonded = bool(i_macro_cycle % 2)
     self.correct_hydrogen_geometries(log)
     self.update_cdl_restraints(macro_cycle=i_macro_cycle)
     if(fix_rotamer_outliers):
       self.pdb_hierarchy, self.restraints_manager = add_rotamer_restraints(
         pdb_hierarchy      = self.pdb_hierarchy,
         restraints_manager = self.restraints_manager,
         selection          = selection,
         sigma              = 10,
         mode               = "fix_outliers")
     sites_cart = self.pdb_hierarchy.atoms().extract_xyz()
     self.minimized = lbfgs(
       sites_cart                      = sites_cart,
       correct_special_position_tolerance=correct_special_position_tolerance,
       geometry_restraints_manager     = restraints_manager.geometry,
       geometry_restraints_flags       = geometry_restraints_flags,
       lbfgs_termination_params        = lbfgs_termination_params,
       lbfgs_exception_handling_params = exception_handling_params,
       sites_cart_selection            = selection,
       rmsd_bonds_termination_cutoff   = rmsd_bonds_termination_cutoff,
       rmsd_angles_termination_cutoff  = rmsd_angles_termination_cutoff,
       states_collector                = states_collector,
       site_labels                     = None)
     self.pdb_hierarchy.atoms().set_xyz(sites_cart)
     self.show()
     geometry_restraints_flags.nonbonded = nonbonded
     lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
         max_iterations = max_number_of_iterations)