def exercise():
    from mmtbx.building.alternate_conformations import density_sampling
    from mmtbx.utils import fmodel_simple
    from mmtbx.monomer_library import server
    from iotbx import file_reader
    import iotbx.pdb.hierarchy
    generate_inputs()
    fmodel_params = """
    high_resolution = 1.2
    r_free_flags_fraction = 0.1
    add_sigmas = True
    pdb_file = ser_frag.pdb
    output {
      label = F
      type = *real complex
      file_name = ser_frag.mtz
    }
    fmodel.k_sol = 0.3
    fmodel.b_sol = 20
    """
    open("ser_frag_fmodel.eff", "w").write(fmodel_params)
    assert (easy_run.fully_buffered("phenix.fmodel ser_frag_fmodel.eff").
            raise_if_errors().return_code == 0)
    assert os.path.isfile("ser_frag.mtz")
    mtz_in = file_reader.any_file("ser_frag.mtz")
    f_obs = mtz_in.file_server.miller_arrays[0]
    flags = mtz_in.file_server.miller_arrays[1]
    flags = flags.customized_copy(data=(flags.data() == 1))
    mon_lib_srv = server.server()
    pdb_in = iotbx.pdb.hierarchy.input(file_name="ser_frag_single.pdb")
    hierarchy = pdb_in.hierarchy
    pdb_atoms = hierarchy.atoms()
    pdb_atoms.reset_i_seq()
    sites_cart = pdb_atoms.extract_xyz()
    xrs = pdb_in.input.xray_structure_simple()
    fmodel = fmodel_simple(f_obs=f_obs,
                           xray_structures=[xrs],
                           scattering_table="n_gaussian",
                           r_free_flags=flags,
                           skip_twin_detection=True)
    models = []
    prev_res = next_res = next_next_res = None
    for chain in hierarchy.only_model().chains():
        residue_groups = chain.residue_groups()
        n_rg = len(residue_groups)
        for i_res, residue_group in enumerate(residue_groups):
            sites_orig = sites_cart.deep_copy()
            next_res = next_next_res = None
            if (i_res < (n_rg - 1)):
                next_res = residue_groups[i_res + 1].atom_groups()[0]
            if (i_res < (n_rg - 2)):
                next_next_res = residue_groups[i_res + 2].atom_groups()[0]
            atom_groups = residue_group.atom_groups()
            primary_conf = atom_groups[0]
            out = StringIO()
            confs = density_sampling.screen_residue(
                residue=primary_conf,
                prev_residue=prev_res,
                next_residue=next_res,
                next_next_residue=next_next_res,
                sites_cart=sites_cart,
                fmodel=fmodel,
                mon_lib_srv=mon_lib_srv,
                params=None,
                backrub=True,
                shear=False,
                verbose=True,
                out=out)
            prev_res = primary_conf
            if (confs is None):
                continue
            # TODO tweak density sampling to allow a backrubbed conformer with a
            # chi1 t rotamer for Ser 99
            if (i_res == 1):
                assert ("""  A SER  99     20.0    None       t"""
                        in out.getvalue())
            for conf in confs:
                sites_new = sites_cart.set_selected(conf.sites_selection,
                                                    conf.sites_selected())
                pdb_atoms.set_xyz(sites_new)
                models.append(hierarchy.only_model().detached_copy())
            confs = density_sampling.screen_residue(
                residue=primary_conf,
                prev_residue=prev_res,
                next_residue=next_res,
                next_next_residue=next_next_res,
                sites_cart=sites_cart,
                fmodel=fmodel,
                mon_lib_srv=mon_lib_srv,
                params=None,
                backrub=False,
                out=out)
            if (i_res == 1):
                print len(confs)
    new_hierarchy = iotbx.pdb.hierarchy.root()
    for i_model, conf in enumerate(models):
        conf.id = str(i_model + 1)
        new_hierarchy.append_model(conf)
    open("ser_frag_guided_ensemble.pdb",
         "w").write(new_hierarchy.as_pdb_string())
   prev_residue = next_residue = None
   residue_groups = chain.residue_groups()
   n_groups = len(residue_groups)
   for i_res, residue_group in enumerate(residue_groups) :
     if (i_res < n_groups - 1) :
       next_residue = residue_groups[i_res+1].atom_groups()[0]
     i_seqs = residue_group.atoms().extract_i_seq()
     if (selection.select(i_seqs).all_eq(True)) :
       atom_group = residue_group.only_atom_group()
       if (get_class(atom_group.resname) != "common_amino_acid") :
         continue
       confs = density_sampling.screen_residue(
         residue=atom_group,
         prev_residue=prev_residue,
         next_residue=next_residue,
         sites_cart=sites_cart,
         fmodel=fmodel,
         mon_lib_srv=mon_lib_srv,
         params=params,
         map_file_name="map_coeffs.mtz",
         out=out)
       ensemble = []
       for conf in confs :
         conf_atoms = conf.set_atom_sites(pdb_atoms)
         pdb_lines = []
         for atom in conf_atoms :
           pdb_lines.append(atom.format_atom_record())
         ensemble.append("\n".join(pdb_lines))
       ensembles.append(ensemble)
     prev_residue = residue_group.atom_groups()[0]
 if (len(ensembles) == 0) :
   raise Sorry("No alternate conformations found.")
def run (args, out=None ):
  if (out is None) : out = sys.stdout
  from mmtbx.building.alternate_conformations import density_sampling
  import mmtbx.maps.utils
  import mmtbx.utils
  from mmtbx.monomer_library import server
  import iotbx.pdb.hierarchy
  get_class = iotbx.pdb.common_residue_names_get_class
  mon_lib_srv = server.server()
  cmdline = mmtbx.utils.cmdline_load_pdb_and_data(
    args=args,
    master_phil=master_phil,
    process_pdb_file=False,
    scattering_table="n_gaussian")
  params = cmdline.params
  working_phil = master_phil.format(python_object=params)
  master_phil.fetch_diff(source=working_phil).show(out=out)
  fmodel = cmdline.fmodel
  hierarchy = cmdline.pdb_hierarchy
  sele_cache = hierarchy.atom_selection_cache()
  assert (params.selection is not None)
  selection = sele_cache.selection(params.selection)
  assert (selection.count(True) > 0)
  have_results = False
  pdb_atoms = hierarchy.atoms()
  sites_cart = pdb_atoms.extract_xyz()
  ensembles = []
  t1 = time.time()
  for chain in hierarchy.only_model().chains() :
    prev_residue = next_residue = None
    residue_groups = chain.residue_groups()
    n_groups = len(residue_groups)
    for i_res, residue_group in enumerate(residue_groups) :
      if (i_res < n_groups - 1) :
        next_residue = residue_groups[i_res+1].atom_groups()[0]
      i_seqs = residue_group.atoms().extract_i_seq()
      if (selection.select(i_seqs).all_eq(True)) :
        atom_group = residue_group.only_atom_group()
        if (get_class(atom_group.resname) != "common_amino_acid") :
          continue
        confs = density_sampling.screen_residue(
          residue=atom_group,
          prev_residue=prev_residue,
          next_residue=next_residue,
          sites_cart=sites_cart,
          fmodel=fmodel,
          mon_lib_srv=mon_lib_srv,
          params=params,
          map_file_name="map_coeffs.mtz",
          out=out)
        ensemble = []
        for conf in confs :
          conf_atoms = conf.set_atom_sites(pdb_atoms)
          pdb_lines = []
          for atom in conf_atoms :
            pdb_lines.append(atom.format_atom_record())
          ensemble.append("\n".join(pdb_lines))
        ensembles.append(ensemble)
      prev_residue = residue_group.atom_groups()[0]
  if (len(ensembles) == 0) :
    raise Sorry("No alternate conformations found.")
  t2 = time.time()
  print >> out, "search time: %.1fs" % (t2-t1)
  for i_ens, ensemble in enumerate(ensembles) :
    ensemble_hierarchy = iotbx.pdb.hierarchy.root()
    for k, model_str in enumerate(ensemble) :
      input = iotbx.pdb.hierarchy.input(pdb_string=model_str)
      model = input.hierarchy.only_model().detached_copy()
      model.id = str(k+1)
      ensemble_hierarchy.append_model(model)
    f = open("ensemble_%d.pdb" % (i_ens+1), "w")
    f.write(ensemble_hierarchy.as_pdb_string())
    f.close()
    print "wrote ensemble_%d.pdb" % (i_ens+1)
  if (params.coot) :
    easy_run.call("coot --pdb %s --auto map_coeffs.mtz --pdb ensemble.pdb" %
      params.input.pdb.file_name[0])
def run(args, out=None):
    if (out is None): out = sys.stdout
    from mmtbx.building.alternate_conformations import density_sampling
    import mmtbx.maps.utils
    import mmtbx.utils
    from mmtbx.monomer_library import server
    import iotbx.pdb.hierarchy
    get_class = iotbx.pdb.common_residue_names_get_class
    mon_lib_srv = server.server()
    cmdline = mmtbx.utils.cmdline_load_pdb_and_data(
        args=args,
        master_phil=master_phil,
        process_pdb_file=False,
        scattering_table="n_gaussian")
    params = cmdline.params
    working_phil = master_phil.format(python_object=params)
    master_phil.fetch_diff(source=working_phil).show(out=out)
    fmodel = cmdline.fmodel
    hierarchy = cmdline.pdb_hierarchy
    sele_cache = hierarchy.atom_selection_cache()
    assert (params.selection is not None)
    selection = sele_cache.selection(params.selection)
    assert (selection.count(True) > 0)
    have_results = False
    pdb_atoms = hierarchy.atoms()
    sites_cart = pdb_atoms.extract_xyz()
    ensembles = []
    t1 = time.time()
    for chain in hierarchy.only_model().chains():
        prev_residue = next_residue = None
        residue_groups = chain.residue_groups()
        n_groups = len(residue_groups)
        for i_res, residue_group in enumerate(residue_groups):
            if (i_res < n_groups - 1):
                next_residue = residue_groups[i_res + 1].atom_groups()[0]
            i_seqs = residue_group.atoms().extract_i_seq()
            if (selection.select(i_seqs).all_eq(True)):
                atom_group = residue_group.only_atom_group()
                if (get_class(atom_group.resname) != "common_amino_acid"):
                    continue
                confs = density_sampling.screen_residue(
                    residue=atom_group,
                    prev_residue=prev_residue,
                    next_residue=next_residue,
                    sites_cart=sites_cart,
                    fmodel=fmodel,
                    mon_lib_srv=mon_lib_srv,
                    params=params,
                    map_file_name="map_coeffs.mtz",
                    out=out)
                ensemble = []
                for conf in confs:
                    conf_atoms = conf.set_atom_sites(pdb_atoms)
                    pdb_lines = []
                    for atom in conf_atoms:
                        pdb_lines.append(atom.format_atom_record())
                    ensemble.append("\n".join(pdb_lines))
                ensembles.append(ensemble)
            prev_residue = residue_group.atom_groups()[0]
    if (len(ensembles) == 0):
        raise Sorry("No alternate conformations found.")
    t2 = time.time()
    print("search time: %.1fs" % (t2 - t1), file=out)
    for i_ens, ensemble in enumerate(ensembles):
        ensemble_hierarchy = iotbx.pdb.hierarchy.root()
        for k, model_str in enumerate(ensemble):
            input = iotbx.pdb.hierarchy.input(pdb_string=model_str)
            model = input.hierarchy.only_model().detached_copy()
            model.id = str(k + 1)
            ensemble_hierarchy.append_model(model)
        f = open("ensemble_%d.pdb" % (i_ens + 1), "w")
        f.write(ensemble_hierarchy.as_pdb_string())
        f.close()
        print("wrote ensemble_%d.pdb" % (i_ens + 1))
    if (params.coot):
        easy_run.call(
            "coot --pdb %s --auto map_coeffs.mtz --pdb ensemble.pdb" %
            params.input.pdb.file_name[0])
def exercise () :
  from mmtbx.building.alternate_conformations import density_sampling
  from mmtbx.utils import fmodel_simple
  from mmtbx.monomer_library import server
  from iotbx import file_reader
  import iotbx.pdb.hierarchy
  generate_inputs()
  fmodel_params = """
    high_resolution = 1.2
    r_free_flags_fraction = 0.1
    add_sigmas = True
    pdb_file = shear_frag.pdb
    output {
      label = F
      type = *real complex
      file_name = shear_frag.mtz
    }
    fmodel.k_sol = 0.3
    fmodel.b_sol = 20
    """
  open("shear_frag_fmodel.eff", "w").write(fmodel_params)
  assert (easy_run.fully_buffered("phenix.fmodel shear_frag_fmodel.eff"
    ).raise_if_errors().return_code == 0)
  assert os.path.isfile("shear_frag.mtz")
  mtz_in = file_reader.any_file("shear_frag.mtz")
  f_obs = mtz_in.file_server.miller_arrays[0]
  flags = mtz_in.file_server.miller_arrays[1]
  flags = flags.customized_copy(data=(flags.data()==1))
  mon_lib_srv = server.server()
  pdb_in = iotbx.pdb.hierarchy.input(file_name="shear_frag_single.pdb")
  hierarchy = pdb_in.hierarchy
  pdb_atoms = hierarchy.atoms()
  pdb_atoms.reset_i_seq()
  sites_cart = pdb_atoms.extract_xyz()
  xrs = pdb_in.input.xray_structure_simple()
  fmodel = fmodel_simple(
    f_obs=f_obs,
    xray_structures=[xrs],
    scattering_table="n_gaussian",
    r_free_flags=flags,
    skip_twin_detection=True)
  models = []
  prev_res = next_res = next_next_res = None
  for chain in hierarchy.only_model().chains() :
    residue_groups = chain.residue_groups()
    n_rg = len(residue_groups) # should be 4
    for i_res, residue_group in enumerate(residue_groups) :
      sites_orig = sites_cart.deep_copy()
      next_res = next_next_res = None
      if (i_res < (n_rg - 1)) :
        next_res = residue_groups[i_res+1].atom_groups()[0]
      if (i_res < (n_rg - 2)) :
        next_next_res = residue_groups[i_res+2].atom_groups()[0]
      atom_groups = residue_group.atom_groups()
      primary_conf = atom_groups[0]
      out = StringIO()
      confs = density_sampling.screen_residue(
        residue=primary_conf,
        prev_residue=prev_res,
        next_residue=next_res,
        next_next_residue=next_next_res,
        sites_cart=sites_cart,
        fmodel=fmodel,
        mon_lib_srv=mon_lib_srv,
        params=None,
        backrub=True,
        shear=True,
        verbose=True,
        out=out)
      prev_res = primary_conf
      if (confs is None) :
        continue
      if (i_res == 1) :
        assert ("""  A ILE   7     None     4.0      mt""")
      for conf in confs :
        sites_new = sites_cart.set_selected(conf.sites_selection,
          conf.sites_selected())
        pdb_atoms.set_xyz(sites_new)
        models.append(hierarchy.only_model().detached_copy())
  new_hierarchy = iotbx.pdb.hierarchy.root()
  for i_model, conf in enumerate(models) :
    conf.id = str(i_model + 1)
    new_hierarchy.append_model(conf)
  open("shear_frag_naive_ensemble.pdb", "w").write(
    new_hierarchy.as_pdb_string())