Ejemplo n.º 1
0
    def test_get_list_of_best_ncs_copy_map_correlation(self):
        """
    Verifying that we get a list of chain index for the chain with the best
    map correlation
    """
        # print sys._getframe().f_code.co_name

        d_min = 1.0
        pdb_inp = iotbx.pdb.input(lines=pdb_poor_0, source_info=None)
        ncs_inp = ncs.input(hierarchy=pdb_inp.construct_hierarchy())
        ncs_restraints_group_list = ncs_inp.get_ncs_restraints_group_list()

        pdb_inp_poor = iotbx.pdb.input(lines=pdb_poor_0, source_info=None)
        ph_poor = pdb_inp_poor.construct_hierarchy(sort_atoms=False)
        ph_poor.atoms().reset_i_seq()
        xrs_poor = pdb_inp_poor.xray_structure_simple()

        pdb_inp_answer = iotbx.pdb.input(lines=pdb_answer_0, source_info=None)
        ph_answer = pdb_inp_answer.construct_hierarchy()
        ph_answer.atoms().reset_i_seq()
        xrs_answer = pdb_inp_answer.xray_structure_simple()

        fc = xrs_answer.structure_factors(d_min=d_min,
                                          algorithm="direct").f_calc()
        fft_map = fc.fft_map(resolution_factor=0.25)
        fft_map.apply_sigma_scaling()
        map_data = fft_map.real_map_unpadded()

        selections = [
            flex.size_t([0, 1, 2, 3, 4, 5, 6]),
            flex.size_t([7, 8, 9, 10, 11, 12, 13]),
            flex.size_t([14, 15, 16, 17, 18, 19, 20])
        ]

        mp = mmtbx.maps.correlation.from_map_and_xray_structure_or_fmodel(
            xray_structure=xrs_poor, map_data=map_data, d_min=d_min)

        cc = mp.cc(selections=selections)

        nu.get_list_of_best_ncs_copy_map_correlation(
            ncs_groups=ncs_restraints_group_list,
            xray_structure=xrs_poor,
            map_data=map_data,
            d_min=d_min)
Ejemplo n.º 2
0
  def test_get_list_of_best_ncs_copy_map_correlation(self):
    """
    Verifying that we get a list of chain index for the chain with the best
    map correlation
    """
    # print sys._getframe().f_code.co_name

    d_min = 1.0
    pdb_inp = iotbx.pdb.input(lines=pdb_poor_0,source_info=None)
    ncs_inp = ncs.input(hierarchy=pdb_inp.construct_hierarchy())
    ncs_restraints_group_list = ncs_inp.get_ncs_restraints_group_list()

    pdb_inp_poor = iotbx.pdb.input(lines=pdb_poor_0,source_info=None)
    ph_poor = pdb_inp_poor.construct_hierarchy(sort_atoms=False)
    ph_poor.atoms().reset_i_seq()
    xrs_poor = pdb_inp_poor.xray_structure_simple()

    pdb_inp_answer = iotbx.pdb.input(lines=pdb_answer_0,source_info=None)
    ph_answer = pdb_inp_answer.construct_hierarchy()
    ph_answer.atoms().reset_i_seq()
    xrs_answer = pdb_inp_answer.xray_structure_simple()

    fc = xrs_answer.structure_factors(d_min=d_min, algorithm="direct").f_calc()
    fft_map = fc.fft_map(resolution_factor = 0.25)
    fft_map.apply_sigma_scaling()
    map_data = fft_map.real_map_unpadded()

    selections = [flex.size_t([0,1,2,3,4,5,6]),flex.size_t([7,8,9,10,11,12,13]),
                flex.size_t([14,15,16,17,18,19,20])]

    mp = mmtbx.maps.correlation.from_map_and_xray_structure_or_fmodel(
      xray_structure = xrs_poor,
      map_data       = map_data,
      d_min          = d_min)

    cc = mp.cc(selections=selections)

    nu.get_list_of_best_ncs_copy_map_correlation(
      ncs_groups     = ncs_restraints_group_list,
      xray_structure = xrs_poor,
      map_data       = map_data,
      d_min          = d_min)
Ejemplo n.º 3
0
 def run_lbfgs(self):
     if (self.model.get_ncs_groups() is None
             or not self.all_params.ncs.constraints.apply_to_adp):
         lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
             max_iterations=self.individual_adp_params.iso.
             max_number_of_iterations)
         is_neutron_scat_table = False
         if (self.all_params.main.scattering_table == "neutron"):
             is_neutron_scat_table = True
         minimized = minimization.lbfgs(
             restraints_manager=self.model.restraints_manager,
             fmodels=self.fmodels,
             model=self.model,
             refine_adp=True,
             is_neutron_scat_table=is_neutron_scat_table,
             lbfgs_termination_params=lbfgs_termination_params,
             iso_restraints=self.adp_restraints_params.iso,
             verbose=0,
             target_weights=self.target_weights,
             h_params=self.h_params)
     elif (self.all_params.ncs.constraints.apply_to_coordinates):
         fmodel = self.fmodels.fmodel_xray()
         # update NCS groups
         import mmtbx.ncs.ncs_utils as nu
         nu.get_list_of_best_ncs_copy_map_correlation(
             ncs_groups=self.model.get_ncs_groups(), fmodel=fmodel)
         assert "individual_adp" in self.all_params.refine.strategy
         minimized = minimization.run_constrained(
             model=self.model,
             fmodel=fmodel,
             target_weight=self.target_weights.xyz_weights_result.wx,
             log=self.log,
             params=self.all_params,
             refine_u_iso=True,
             prefix="NCS constrained ADP refinement").minimized
         self.model.set_xray_structure(fmodel.xray_structure)
     else:
         raise RuntimeError("Bad ncs options.")
Ejemplo n.º 4
0
 def run_lbfgs(self):
   if(self.model.ncs_groups is None or
      not self.all_params.ncs.constraints.apply_to_adp):
     lbfgs_termination_params = scitbx.lbfgs.termination_parameters(
       max_iterations = self.individual_adp_params.iso.max_number_of_iterations)
     is_neutron_scat_table = False
     if(self.all_params.main.scattering_table == "neutron"):
       is_neutron_scat_table = True
     minimized = minimization.lbfgs(
       restraints_manager       = self.model.restraints_manager,
       fmodels                  = self.fmodels,
       model                    = self.model,
       refine_adp               = True,
       is_neutron_scat_table    = is_neutron_scat_table,
       lbfgs_termination_params = lbfgs_termination_params,
       iso_restraints           = self.adp_restraints_params.iso,
       verbose                  = 0,
       target_weights           = self.target_weights,
       h_params                 = self.h_params)
   elif(self.all_params.ncs.constraints.apply_to_coordinates):
     fmodel = self.fmodels.fmodel_xray()
     # update NCS groups
     import mmtbx.ncs.ncs_utils as nu
     nu.get_list_of_best_ncs_copy_map_correlation(
       ncs_groups = self.model.ncs_groups,
       fmodel     = fmodel)
     assert "individual_adp" in self.all_params.refine.strategy
     minimized = minimization.run_constrained(
       model         = self.model,
       fmodel        = fmodel,
       target_weight = self.target_weights.xyz_weights_result.wx,
       log           = self.log,
       params        = self.all_params,
       refine_u_iso  = True,
       prefix        = "NCS constrained ADP refinement").minimized
     self.model.xray_structure = fmodel.xray_structure
   else: raise RuntimeError("Bad ncs options.")
Ejemplo n.º 5
0
  def __init__(self,
      model,
      target_map,
      refine_ncs_operators=False,
      number_of_cycles=1,
      log=None):
    from mmtbx.refinement.geometry_minimization import add_rotamer_restraints
    from mmtbx.refinement.minimization_monitor import minimization_monitor
    self.model = model
    self.log = log
    print >> self.log, "Minimizing using reference map..."
    self.log.flush()

    # copy-paste from cctbx_project/mmtbx/refinement/geometry_minimization.py:
    # minimize_wrapper_for_ramachandran
    self.model.get_restraints_manager().geometry.pair_proxies(
        sites_cart=self.model.get_sites_cart())
    if self.model.get_restraints_manager().geometry.ramachandran_manager is not None:
      self.model.get_restraints_manager().geometry.ramachandran_manager.update_phi_psi_targets(
          sites_cart=self.model.get_sites_cart())

    ncs_restraints_group_list = self.model.get_ncs_groups()
    if ncs_restraints_group_list is None:
      ncs_restraints_group_list = []
    ncs_groups=None
    if len(ncs_restraints_group_list) > 0:
      ncs_groups=ncs_restraints_group_list

    min_monitor = minimization_monitor(
        number_of_cycles=number_of_cycles,
        max_number_of_cycles=20,
        mode="no_outliers")
    selection_real_space = None
    import mmtbx.refinement.real_space.weight
    self.w = 1
    print >> log, "number_of_cycles", number_of_cycles
    print >> log, "Stats before minimization:"
    ms = self.model.geometry_statistics()
    ms.show(log=log)

    while min_monitor.need_more_cycles():
      print >> self.log, "Cycle number", min_monitor.get_current_cycle_n()
      print >> self.log, "  Updating rotamer restraints..."
      add_rotamer_restraints(
        pdb_hierarchy      = self.model.get_hierarchy(),
        restraints_manager = self.model.get_restraints_manager(),
        selection          = None,
        sigma              = 5,
        mode               = "fix_outliers",
        accept_allowed     = False,
        mon_lib_srv        = self.model.get_mon_lib_srv(),
        rotamer_manager    = self.model.get_rotamer_manager())
      self.model.set_sites_cart_from_hierarchy()

      if min_monitor.need_weight_optimization():
        # if self.w is None:
        print >> self.log, "  Determining weight..."
        self.log.flush()
        self.weight = mmtbx.refinement.real_space.weight.run(
            map_data                    = target_map,
            xray_structure              = self.model.get_xray_structure(),
            pdb_hierarchy               = self.model.get_hierarchy(),
            geometry_restraints_manager = self.model.get_restraints_manager(),
            rms_bonds_limit             = 0.015,
            rms_angles_limit            = 1.0,
            ncs_groups                  = ncs_groups)

        # division is to put more weight onto restraints. Checked. Works.
        self.w = self.weight.weight/3.0
        # self.w = self.weight.weight/15.0
        # self.w = 0
        # self.w = self.weight.weight
        for s in self.weight.msg_strings:
          print >> self.log, s

      if ncs_restraints_group_list is None or len(ncs_restraints_group_list)==0:
        #No NCS
        print >> self.log, "  Minimizing..."
        print >> self.log, "     with weight %f" % self.w
        self.log.flush()
        refine_object = simple(
            target_map                  = target_map,
            selection                   = None,
            max_iterations              = 150,
            geometry_restraints_manager = self.model.get_restraints_manager().geometry,
            selection_real_space        = selection_real_space,
            states_accumulator          = None,
            ncs_groups                  = ncs_groups)
        refine_object.refine(weight = self.w, xray_structure = self.model.get_xray_structure())
        self.rmsd_bonds_final, self.rmsd_angles_final = refine_object.rmsds()
        print >> log, "RMSDS:", self.rmsd_bonds_final, self.rmsd_angles_final
        # print >> log, "sizes:", len(refine_object.sites_cart()), len(self.xrs.scatterers())
        self.model.set_sites_cart(refine_object.sites_cart(), update_grm=True)
        # print >> log, "sizes", self.xrs.scatterers()
      else:
        # Yes NCS
        # copy-paste from macro_cycle_real_space.py
        import mmtbx.ncs.ncs_utils as nu
        nu.get_list_of_best_ncs_copy_map_correlation(
            ncs_groups     = ncs_restraints_group_list,
            xray_structure = self.model.get_xray_structure(),
            map_data       = target_map,
            d_min          = 3)
        print >> self.log, "  Minimizing... (NCS)"
        tfg_obj = mmtbx.refinement.minimization_ncs_constraints.\
          target_function_and_grads_real_space(
            map_data                   = target_map,
            xray_structure             = self.model.get_xray_structure(),
            ncs_restraints_group_list  = ncs_restraints_group_list,
            refine_selection           = None,
            real_space_gradients_delta = 1,
            restraints_manager         = self.model.get_restraints_manager(),
            data_weight                = self.w,
            refine_sites               = True)
        minimized = mmtbx.refinement.minimization_ncs_constraints.lbfgs(
          target_and_grads_object      = tfg_obj,
          xray_structure               = self.model.get_xray_structure(),
          ncs_restraints_group_list    = ncs_restraints_group_list,
          refine_selection             = None,
          finite_grad_differences_test = False,
          max_iterations               = 100,
          refine_sites                 = True)
        self.model.set_sites_cart(tfg_obj.xray_structure.sites_cart())
      ms = self.model.geometry_statistics()
      min_monitor.save_cycle_results(geometry=ms)
      ms.show(log=log)
Ejemplo n.º 6
0
  def __init__(self,
      pdb_h,
      xrs,
      target_map,
      grm=None,
      ncs_restraints_group_list=[],
      mon_lib_srv=None,
      rotamer_manager=None,
      ss_annotation=None,
      refine_ncs_operators=False,
      number_of_cycles=1,
      log=None):
    assert grm is not None
    from mmtbx.refinement.geometry_minimization import add_rotamer_restraints
    from mmtbx.model_statistics import geometry_no_grm
    from mmtbx.refinement.minimization_monitor import minimization_monitor
    self.pdb_h = pdb_h
    self.xrs = xrs
    self.log = log
    # self.cs = self.xrs.crystal_symmetry()
    self.cs = crystal.symmetry(
        unit_cell=self.xrs.crystal_symmetry().unit_cell(),
        space_group=1)
    print >> self.log, "Minimizing using reference map..."
    self.log.flush()
    self.grm = grm
    # copy-paste from cctbx_project/mmtbx/refinement/geometry_minimization.py:
    # minimize_wrapper_for_ramachandran

    self.grm.geometry.pair_proxies(
        sites_cart=self.pdb_h.atoms().extract_xyz())
    if self.grm.geometry.ramachandran_manager is not None:
      self.grm.geometry.ramachandran_manager.update_phi_psi_targets(
          sites_cart=self.pdb_h.atoms().extract_xyz())

    ncs_groups=None
    if len(ncs_restraints_group_list) > 0:
      ncs_groups=ncs_restraints_group_list

    if rotamer_manager is None:
      from mmtbx.rotamer.rotamer_eval import RotamerEval
      rotamer_manager = RotamerEval(mon_lib_srv=mon_lib_srv)

    # self.pdb_h.write_pdb_file(file_name="rsr_before_rot_fix.pdb",
    #     crystal_symmetry=self.xrs.crystal_symmetry())
    # STOP()

    # selection_real_space = xrs.backbone_selection() # XXX What is it???
    min_monitor = minimization_monitor(
        number_of_cycles=number_of_cycles,
        max_number_of_cycles=20,
        mode="no_outliers")
    selection_real_space = None
    import mmtbx.refinement.real_space.weight
    self.w = 1
    print >> log, "number_of_cycles", number_of_cycles
    print >> log, "Stats before minimization:"
    ms = geometry_no_grm(
        pdb_hierarchy=self.pdb_h,
        molprobity_scores=True)
    print >> self.log, ms.format_molprobity_scores(prefix="    ")

    while min_monitor.need_more_cycles():
      # for x in xrange(number_of_cycles):
      print >> self.log, "Cycle number", min_monitor.get_current_cycle_n()
      print >> self.log, "  Updating rotamer restraints..."
      self.pdb_h, grm = add_rotamer_restraints(
        pdb_hierarchy      = self.pdb_h,
        restraints_manager = grm,
        selection          = None,
        sigma              = 5,
        mode               = "fix_outliers",
        accept_allowed     = False,
        mon_lib_srv        = mon_lib_srv,
        rotamer_manager    = rotamer_manager)
      self.xrs = self.pdb_h.extract_xray_structure(crystal_symmetry=self.cs)
      # self.pdb_h.write_pdb_file(file_name="rsr_after_rot_fix.pdb",
      #     crystal_symmetry=self.xrs.crystal_symmetry())
      # if True:
      if ncs_restraints_group_list is None or len(ncs_restraints_group_list)==0:
        #No NCS
        if min_monitor.need_weight_optimization():
          # if self.w is None:
          print >> self.log, "  Determining weight..."
          self.log.flush()
          self.weight = mmtbx.refinement.real_space.weight.run(
              map_data                    = target_map,
              xray_structure              = self.xrs,
              pdb_hierarchy               = self.pdb_h,
              geometry_restraints_manager = grm,
              rms_bonds_limit             = 0.015,
              rms_angles_limit            = 1.0)
          # for s in self.weight.msg_strings:
          #   print >> self.log, s

          # division is to put more weight onto restraints. Checked. Works.
          self.w = self.weight.weight/3.0
          # self.w = self.weight.weight/15.0
          # self.w = 0
          # self.w = self.weight.weight
          # print >> self.log, self.w
        print >> self.log, "  Minimizing..."
        print >> self.log, "     with weight %f" % self.w
        self.log.flush()
        refine_object = simple(
            target_map                  = target_map,
            selection                   = None,
            max_iterations              = 150,
            geometry_restraints_manager = grm.geometry,
            selection_real_space        = selection_real_space,
            states_accumulator          = None,
            ncs_groups                  = ncs_groups)
        refine_object.refine(weight = self.w, xray_structure = self.xrs)
        self.rmsd_bonds_final, self.rmsd_angles_final = refine_object.rmsds()
        print >> log, "RMSDS:", self.rmsd_bonds_final, self.rmsd_angles_final
        # print >> log, "sizes:", len(refine_object.sites_cart()), len(self.xrs.scatterers())
        self.xrs=self.xrs.replace_sites_cart(
            new_sites=refine_object.sites_cart(), selection=None)
        # print >> log, "sizes", self.xrs.scatterers()
      else:
        # Yes NCS
        # copy-paste from macro_cycle_real_space.py
        import mmtbx.ncs.ncs_utils as nu
        nu.get_list_of_best_ncs_copy_map_correlation(
            ncs_groups     = ncs_restraints_group_list,
            xray_structure = self.xrs,
            map_data       = target_map,
            d_min          = 3)
        if min_monitor.need_weight_optimization():
          # if self.w is None:
          print >> self.log, "  Determining weight... (NCS)",
          self.weight = mmtbx.refinement.real_space.weight.run(
              map_data                    = target_map,
              xray_structure              = self.xrs,#.select(sel_master),
              pdb_hierarchy               = self.pdb_h,#.select(sel_master),
              geometry_restraints_manager = grm,
              rms_bonds_limit             = 0.01,
              rms_angles_limit            = 1.0,
              ncs_groups                  = ncs_restraints_group_list)
          # division supposed to put more weight onto restraints. Need checking.
          self.w = self.weight.weight/3.0
          for s in self.weight.msg_strings:
            print >> self.log, s
        print >> self.log, "  Minimizing... (NCS)"
        tfg_obj = mmtbx.refinement.minimization_ncs_constraints.\
          target_function_and_grads_real_space(
            map_data                   = target_map,
            xray_structure             = self.xrs,
            ncs_restraints_group_list  = ncs_restraints_group_list,
            refine_selection           = None,
            real_space_gradients_delta = 1,
            restraints_manager         = grm,
            data_weight                = self.w,
            refine_sites               = True)
        minimized = mmtbx.refinement.minimization_ncs_constraints.lbfgs(
          target_and_grads_object      = tfg_obj,
          xray_structure               = self.xrs,
          ncs_restraints_group_list    = ncs_restraints_group_list,
          refine_selection             = None,
          finite_grad_differences_test = False,
          max_iterations               = 100,
          refine_sites                 = True)
        self.xrs = tfg_obj.xray_structure
          # self.structure_monitor.update(
          #   xray_structure = tfg_obj.xray_structure,
          #   accept_as_is   = True)
      self.pdb_h.adopt_xray_structure(self.xrs)
      ms = geometry_no_grm(
          pdb_hierarchy=self.pdb_h,
          molprobity_scores=True)
      min_monitor.save_cycle_results(geometry=ms)
      print >> self.log, ms.format_molprobity_scores(prefix="    ")
Ejemplo n.º 7
0
  def __init__(self,
      pdb_h,
      xrs,
      target_map,
      grm=None,
      ncs_restraints_group_list=[],
      mon_lib_srv=None,
      rotamer_manager=None,
      ss_annotation=None,
      refine_ncs_operators=False,
      number_of_cycles=1,
      log=None):
    from mmtbx.refinement.geometry_minimization import add_rotamer_restraints
    from mmtbx.model_statistics import geometry_no_grm
    self.pdb_h = pdb_h
    self.xrs = xrs
    self.log = log
    self.cs = self.xrs.crystal_symmetry()
    print >> self.log, "Minimizing using reference map..."
    self.log.flush()
    self.grm = grm
    # create a new one
    # copy-paste from cctbx_project/mmtbx/refinement/geometry_minimization.py:
    # minimize_wrapper_for_ramachandran
    if self.grm is None:
      from mmtbx.monomer_library.pdb_interpretation import grand_master_phil_str
      from mmtbx.geometry_restraints import reference
      from mmtbx.command_line.geometry_minimization import \
          get_geometry_restraints_manager
      from libtbx.utils import null_out
      from scitbx.array_family import flex
      import mmtbx.utils
      if self.log is None:
        self.log = null_out()
      params_line = grand_master_phil_str
      import iotbx.phil
      params = iotbx.phil.parse(
          input_string=params_line, process_includes=True).extract()
      params.pdb_interpretation.clash_guard.nonbonded_distance_threshold=None
      params.pdb_interpretation.peptide_link.ramachandran_restraints = True
      params.pdb_interpretation.peptide_link.oldfield.weight_scale=3
      params.pdb_interpretation.peptide_link.oldfield.plot_cutoff=0.03
      params.pdb_interpretation.nonbonded_weight = 500
      params.pdb_interpretation.c_beta_restraints=True
      params.pdb_interpretation.max_reasonable_bond_distance = None
      params.pdb_interpretation.peptide_link.apply_peptide_plane = True
      params.pdb_interpretation.ncs_search.enabled = True
      params.pdb_interpretation.restraints_library.rdl = True
      processed_pdb_files_srv = mmtbx.utils.\
          process_pdb_file_srv(
              crystal_symmetry= self.cs,
              pdb_interpretation_params = params.pdb_interpretation,
              stop_for_unknowns         = False,
              log=self.log,
              cif_objects=None)
      processed_pdb_file, junk = processed_pdb_files_srv.\
          process_pdb_files(raw_records=flex.split_lines(self.pdb_h.as_pdb_string()))
      mon_lib_srv = processed_pdb_files_srv.mon_lib_srv
      ener_lib = processed_pdb_files_srv.ener_lib
      ncs_restraints_group_list = []
      if processed_pdb_file.ncs_obj is not None:
        ncs_restraints_group_list = processed_pdb_file.ncs_obj.get_ncs_restraints_group_list()
      grm = get_geometry_restraints_manager(
          processed_pdb_file, xrs, params=params)
      # dealing with SS
      if ss_annotation is not None:
        from mmtbx.secondary_structure import manager
        ss_manager = manager(
            pdb_hierarchy=self.pdb_h,
            geometry_restraints_manager=grm.geometry,
            sec_str_from_pdb_file=ss_annotation,
            params=None,
            mon_lib_srv=mon_lib_srv,
            verbose=-1,
            log=self.log)
        grm.geometry.set_secondary_structure_restraints(
            ss_manager=ss_manager,
            hierarchy=self.pdb_h,
            log=self.log)
    else:
      self.grm.geometry.pair_proxies(
          sites_cart=self.pdb_h.atoms().extract_xyz())
      if self.grm.geometry.ramachandran_manager is not None:
        self.grm.geometry.ramachandran_manager.update_phi_psi_targets(
            sites_cart=self.pdb_h.atoms().extract_xyz())

    ncs_groups=None
    if len(ncs_restraints_group_list) > 0:
      ncs_groups=ncs_restraints_group_list

    if rotamer_manager is None:
      from mmtbx.rotamer.rotamer_eval import RotamerEval
      rotamer_manager = RotamerEval(mon_lib_srv=mon_lib_srv)

    self.pdb_h.write_pdb_file(file_name="rsr_before_rot_fix.pdb",
        crystal_symmetry=self.xrs.crystal_symmetry())
    # STOP()

    selection_real_space = xrs.backbone_selection()
    # selection_real_space = None
    import mmtbx.refinement.real_space.weight
    self.w = None
    for x in xrange(number_of_cycles):
      print >> self.log, "  Updating rotamer restraints..."
      self.pdb_h, grm = add_rotamer_restraints(
        pdb_hierarchy      = self.pdb_h,
        restraints_manager = grm,
        selection          = None,
        sigma              = 5,
        mode               = "fix_outliers",
        accept_allowed     = False,
        mon_lib_srv        = mon_lib_srv,
        rotamer_manager    = rotamer_manager)
      self.xrs = self.pdb_h.extract_xray_structure(crystal_symmetry=self.cs)
      self.pdb_h.write_pdb_file(file_name="rsr_after_rot_fix.pdb",
          crystal_symmetry=self.xrs.crystal_symmetry())
      # if True:
      if ncs_restraints_group_list is None or len(ncs_restraints_group_list)==0:
        #No NCS
        if self.w is None:
          print >> self.log, "  Determining weight..."
          self.log.flush()
          self.weight = mmtbx.refinement.real_space.weight.run(
              map_data                    = target_map,
              xray_structure              = self.xrs,
              pdb_hierarchy               = self.pdb_h,
              geometry_restraints_manager = grm,
              rms_bonds_limit             = 0.015,
              rms_angles_limit            = 1.0)
          # division is to put more weight onto restraints. Checked. Works.
          self.w = self.weight.weight/3.0
          # self.w = self.weight.weight
          # self.w =2
          # print >> self.log, self.w
          for s in self.weight.msg_strings:
            print >> self.log, s
        print >> self.log, "  Minimizing..."
        print >> self.log, "     with weight %f" % self.w
        self.log.flush()
        refine_object = simple(
            target_map                  = target_map,
            selection                   = None,
            max_iterations              = 150,
            geometry_restraints_manager = grm.geometry,
            selection_real_space        = selection_real_space,
            states_accumulator          = None,
            ncs_groups                  = ncs_groups)
        refine_object.refine(weight = self.w, xray_structure = self.xrs)
        self.rmsd_bonds_final, self.rmsd_angles_final = refine_object.rmsds()
        print >> log, "RMSDS:", self.rmsd_bonds_final, self.rmsd_angles_final
        # print >> log, "sizes:", len(refine_object.sites_cart()), len(self.xrs.scatterers())
        self.xrs=self.xrs.replace_sites_cart(
            new_sites=refine_object.sites_cart(), selection=None)
        # print >> log, "sizes", self.xrs.scatterers()
      else:
        # Yes NCS
        # copy-paste from macro_cycle_real_space.py
        import mmtbx.ncs.ncs_utils as nu
        nu.get_list_of_best_ncs_copy_map_correlation(
            ncs_groups     = ncs_restraints_group_list,
            xray_structure = self.xrs,
            map_data       = target_map,
            d_min          = 3)
        if self.w is None:
          print >> self.log, "  Determining weight... (NCS)",
          self.weight = mmtbx.refinement.real_space.weight.run(
              map_data                    = target_map,
              xray_structure              = self.xrs,#.select(sel_master),
              pdb_hierarchy               = self.pdb_h,#.select(sel_master),
              geometry_restraints_manager = grm,
              rms_bonds_limit             = 0.01,
              rms_angles_limit            = 1.0,
              ncs_groups                  = ncs_restraints_group_list)
          # division supposed to put more weight onto restraints. Need checking.
          self.w = self.weight.weight/3.0
          for s in self.weight.msg_strings:
            print >> self.log, s
        print >> self.log, "  Minimizing... (NCS)"

        actions = [[True, False], ]
        if refine_ncs_operators:
          actions = [[False, True], [True, False]]
        for action in actions:
          refine_sites, refine_transformations = action
          tfg_obj = mmtbx.refinement.minimization_ncs_constraints.\
            target_function_and_grads_real_space(
              map_data                   = target_map,
              xray_structure             = self.xrs,
              ncs_restraints_group_list  = ncs_restraints_group_list,
              refine_selection           = None,
              real_space_gradients_delta = 1,
              restraints_manager         = grm,
              data_weight                = self.w,
              refine_sites               = refine_sites,
              refine_transformations     = refine_transformations)
          minimized = mmtbx.refinement.minimization_ncs_constraints.lbfgs(
            target_and_grads_object      = tfg_obj,
            xray_structure               = self.xrs,
            ncs_restraints_group_list    = ncs_restraints_group_list,
            refine_selection             = None,
            finite_grad_differences_test = False,
            max_iterations               = 100,
            refine_sites                 = refine_sites,
            refine_transformations       = refine_transformations)
          self.xrs = tfg_obj.xray_structure
          # self.structure_monitor.update(
          #   xray_structure = tfg_obj.xray_structure,
          #   accept_as_is   = True)
      self.pdb_h.adopt_xray_structure(self.xrs)
      # ms = geometry_no_grm(
      #     pdb_hierarchy=self.pdb_h,
      #     molprobity_scores=True)
      # print >> self.log, ms.format_molprobity_scores(prefix="    ")


    # print >> log, "pdb_h", self.pdb_h.atoms_size()
    self.pdb_h.write_pdb_file("after_map_min.pdb")