def exercise_2():
  inp = iotbx.pdb.input(lines=pdb_str_1, source_info=None)
  model = mmtbx.model.manager(
      model_input = inp)
  model.setup_scattering_dictionaries(scattering_table="wk1995")
  g_stat = model.geometry_statistics()
def run(args, out=None, log=sys.stdout):
    if (len(args) == 0) or (args == ["--help"]):
        print(msg, file=log)
        defaults(log=log, silent=False)
        return
    parsed = defaults(log=log, silent=True)
    #
    processed_args = utils.process_command_line_args(args=args,
                                                     log=log,
                                                     master_params=parsed)
    params = processed_args.params.extract()
    #
    reflection_files = processed_args.reflection_files
    if (len(reflection_files) == 0):
        raise Sorry("No reflection file found.")
    crystal_symmetry = processed_args.crystal_symmetry
    if (crystal_symmetry is None):
        raise Sorry("No crystal symmetry found.")
    if (len(processed_args.pdb_file_names) == 0):
        raise Sorry("No PDB file found.")
    pdb_file_names = processed_args.pdb_file_names
    #
    rfs = reflection_file_server(crystal_symmetry=crystal_symmetry,
                                 reflection_files=reflection_files)
    parameters = extract_xtal_data.data_and_flags_master_params().extract()
    if (params.f_obs_label is not None):
        parameters.labels = params.f_obs_label
    if (params.r_free_flags_label is not None):
        parameters.r_free_flags.label = params.r_free_flags_label
    if (params.high_resolution is not None):
        parameters.high_resolution = params.high_resolution
    determine_data_and_flags_result = extract_xtal_data.run(
        reflection_file_server=rfs,
        parameters=parameters,
        data_parameter_scope="refinement.input.xray_data",
        flags_parameter_scope="refinement.input.xray_data.r_free_flags",
        data_description="X-ray data",
        keep_going=True,
        log=StringIO())
    f_obs = determine_data_and_flags_result.f_obs
    # Data
    show_header(l="Data:", log=log)
    f_obs.show_comprehensive_summary(prefix="  ", f=log)
    # R-free-flags
    show_header(l="R-free-flags:", log=log)
    r_free_flags = determine_data_and_flags_result.r_free_flags
    test_flag_value = determine_data_and_flags_result.test_flag_value
    if (r_free_flags is None):
        r_free_flags = f_obs.array(data=flex.bool(f_obs.data().size(), False))
        test_flag_value = None
        print("  not available", file=log)
    else:
        print("  flag value:", test_flag_value, file=log)
    # Model
    pdb_combined = iotbx.pdb.combine_unique_pdb_files(
        file_names=processed_args.pdb_file_names)
    pdb_combined.report_non_unique(out=log)
    if (len(pdb_combined.unique_file_names) == 0):
        raise Sorry("No coordinate file given.")
    raw_records = pdb_combined.raw_records
    try:
        pdb_inp = iotbx.pdb.input(source_info=None,
                                  lines=flex.std_string(raw_records))
    except ValueError as e:
        raise Sorry("Model format (PDB or mmCIF) error:\n%s" % str(e))
    model = mmtbx.model.manager(model_input=pdb_inp,
                                crystal_symmetry=crystal_symmetry,
                                log=StringIO())
    #
    scattering_table = params.scattering_table
    exptl_method = pdb_inp.get_experiment_type()
    if (exptl_method is not None) and ("NEUTRON" in exptl_method):
        scattering_table = "neutron"
    model.setup_scattering_dictionaries(scattering_table=scattering_table,
                                        d_min=f_obs.d_min())
    #
    # Model vs data
    #
    show_header(l="Model vs Data:", log=log)
    fmodel = mmtbx.f_model.manager(xray_structure=model.get_xray_structure(),
                                   f_obs=f_obs,
                                   r_free_flags=r_free_flags,
                                   twin_law=params.twin_law)
    fmodel.update_all_scales(update_f_part1=True)
    fmodel.show(log=log, show_header=False, show_approx=False)
    print("  r_work: %6.4f" % fmodel.r_work(), file=log)
    if (test_flag_value is not None):
        print("  r_free: %6.4f" % fmodel.r_free(), file=log)
    else:
        print("  r_free: None", file=log)
    print(file=log)
    n_outl = f_obs.data().size() - fmodel.f_obs().data().size()
    print("  Number of F-obs outliers:", n_outl, file=log)
    #
    # Extract information from PDB file header and output (if any)
    #
    pub_r_work = None
    pub_r_free = None
    pub_high = None
    pub_low = None
    pub_sigma = None
    pub_program_name = None
    pub_solv_cont = None
    pub_matthews = None
    published_results = pdb_inp.get_r_rfree_sigma(file_name=pdb_file_names[0])
    if (published_results is not None):
        pub_r_work = published_results.r_work
        pub_r_free = published_results.r_free
        pub_high = published_results.high
        pub_low = published_results.low
        pub_sigma = published_results.sigma
    pub_program_name = pdb_inp.get_program_name()
    pub_solv_cont = pdb_inp.get_solvent_content()
    pub_matthews = pdb_inp.get_matthews_coeff()
    #
    show_header(l="Information extracted from PDB file header:", log=log)
    print("  program_name    : %-s" % format_value("%s", pub_program_name),
          file=log)
    print("  year            : %-s" %
          format_value("%s", pdb_inp.extract_header_year()),
          file=log)
    print("  r_work          : %-s" % format_value("%s", pub_r_work), file=log)
    print("  r_free          : %-s" % format_value("%s", pub_r_free), file=log)
    print("  high_resolution : %-s" % format_value("%s", pub_high), file=log)
    print("  low_resolution  : %-s" % format_value("%s", pub_low), file=log)
    print("  sigma_cutoff    : %-s" % format_value("%s", pub_sigma), file=log)
    print("  matthews_coeff  : %-s" % format_value("%s", pub_matthews),
          file=log)
    print("  solvent_cont    : %-s" % format_value("%s", pub_solv_cont),
          file=log)
    if (exptl_method is not None):
        print("  exptl_method    : %-s" % format_value("%s", exptl_method),
              file=log)
    #
    # Recompute R-factors using published cutoffs
    fmodel_cut = fmodel
    tmp_sel = flex.bool(fmodel.f_obs().data().size(), True)
    if (pub_sigma is not None and fmodel.f_obs().sigmas() is not None):
        tmp_sel &= fmodel.f_obs().data() > fmodel.f_obs().sigmas() * pub_sigma
    if (pub_high is not None
            and abs(pub_high - fmodel.f_obs().d_min()) > 0.03):
        tmp_sel &= fmodel.f_obs().d_spacings().data() > pub_high
    if (pub_low is not None
            and abs(pub_low - fmodel.f_obs().d_max_min()[0]) > 0.03):
        tmp_sel &= fmodel.f_obs().d_spacings().data() < pub_low
    if (tmp_sel.count(True) != tmp_sel.size() and tmp_sel.count(True) > 0):
        show_header(l="After applying resolution and sigma cutoffs:", log=log)
        fmodel = mmtbx.f_model.manager(
            xray_structure=model.get_xray_structure(),
            f_obs=fmodel.f_obs().select(tmp_sel),
            r_free_flags=fmodel.r_free_flags().select(tmp_sel),
            twin_law=params.twin_law)
        fmodel.update_all_scales(update_f_part1=True)
        fmodel.show(log=log, show_header=False, show_approx=False)
        print("  r_work: %6.4f" % fmodel.r_work(), file=log)
        if (test_flag_value is not None):
            print("  r_free: %6.4f" % fmodel.r_free(), file=log)
        else:
            print("  r_free: None", file=log)
        print(file=log)
        n_outl = f_obs.data().size() - fmodel.f_obs().data().size()
        print("  Number of F-obs outliers:", n_outl, file=log)
Exemple #3
0
def exercise_2(eps = 1.e-6):
###> Get started from PDB
  mon_lib_srv = monomer_library.server.server()
  ener_lib = monomer_library.server.ener_lib()
  pdb_file = libtbx.env.find_in_repositories(
    relative_path="phenix_regression/pdb/phe_abc_tlsanl_out_geometry_minimized.pdb",
    test=os.path.isfile)
  model = mmtbx.model.manager(
      model_input=iotbx.pdb.input(file_name=pdb_file),
      build_grm=True)
  model.setup_scattering_dictionaries(scattering_table="wk1995")
  model.get_xray_structure().convert_to_isotropic()
  u_iso_start = model.get_xray_structure().extract_u_iso_or_u_equiv()
  model.get_xray_structure().convert_to_anisotropic()

  selections = []
  selection_strings = ["chain A", "chain B", "chain C"]
  for string in selection_strings:
      selections.append(model.selection(string = string))
################
  selection = flex.bool(model.get_number_of_atoms(), True)
  class refinement_flags: pass
  refinement_flags.adp_tls = selections
  model.set_refinement_flags(refinement_flags)
  model.determine_tls_groups(selection_strings=selections, generate_tlsos=selections)
  model.set_refinement_flags(refinement_flags)
  xray_structure = model.get_xray_structure()
################
###> Get TLS <-> Ucart
  T_initial = []
  L_initial = []
  S_initial = []
  T_initial.append([0.11,0.22,0.33,0.12,0.13,0.23])
  L_initial.append([1.11,1.22,1.33,1.12,1.13,1.23])
  S_initial.append([0.11,0.12,0.13,0.21,0.22,0.23,0.31,0.32,-0.33])

  T_initial.append([0.22,0.44,0.66,0.24,0.26,0.46])
  L_initial.append([2.22,2.44,2.66,2.24,2.26,2.46])
  S_initial.append([0.22,0.24,0.26,0.42,0.44,0.46,0.62,0.64,-0.66])

  T_initial.append([0.33,0.66,0.99,0.36,0.39,0.69])
  L_initial.append([2.33,2.66,2.99,2.36,2.39,2.69])
  S_initial.append([0.22,0.24,0.26,0.42,0.44,0.46,0.62,0.64,-0.66])

  tlsosA = tools.generate_tlsos(selections     = selections,
                                xray_structure = xray_structure,
                                T              = T_initial,
                                L              = L_initial,
                                S              = S_initial)

  tlsos = tools.generate_tlsos(selections     = selections,
                               xray_structure = xray_structure,
                               T              = T_initial,
                               L              = L_initial,
                               S              = S_initial)
  tlsos = tools.make_tlso_compatible_with_u_positive_definite(
                  tlsos                                       = tlsos,
                  xray_structure                              = xray_structure.deep_copy_scatterers(),
                  selections                                  = selections,
                  max_iterations                              = 50,
                  number_of_u_nonpositive_definite            = 0,
                  eps                                         = eps,
                  number_of_macro_cycles_for_tls_from_uanisos = 30)

  u_cart_answer = tools.u_cart_from_tls(sites_cart = xray_structure.sites_cart(),
                                         selections = selections,
                                         tlsos      = tlsos)
  xray_structure.scatterers().set_u_cart(xray_structure.unit_cell(),
                                                                 u_cart_answer)

  assert approx_equal(u_cart_answer,
        xray_structure.scatterers().extract_u_cart(xray_structure.unit_cell()))


  tools.show_tls(tlsos = tlsos, text = "ANSWER")

###> Set up fmodel
  sfg_params = mmtbx.f_model.sf_and_grads_accuracy_master_params.extract()
  sfg_params.algorithm = "direct"
  sfg_params.cos_sin_table = False
  dummy = xray_structure.structure_factors(algorithm = sfg_params.algorithm,
                                           d_min     = 2.0).f_calc()
  f_obs = abs(dummy.structure_factors_from_scatterers(
                           xray_structure = xray_structure,
                           algorithm      = sfg_params.algorithm,
                           cos_sin_table  = sfg_params.cos_sin_table).f_calc())
  flags = f_obs.generate_r_free_flags(fraction=0.01, max_free=2000)

  fmodel = mmtbx.f_model.manager(xray_structure    = xray_structure,
                                 f_obs             = f_obs,
                                 r_free_flags      = flags,
                                 target_name       = "ls_wunit_k1",
                                 sf_and_grads_accuracy_params = sfg_params)
  fmodel.info(free_reflections_per_bin=250, max_number_of_bins=30).show_all()
  xray_structure.convert_to_isotropic()
  xray_structure.set_b_iso(value = 25.0)
  fmodel.update_xray_structure(xray_structure = xray_structure,
                               update_f_calc  = True)
  fmodel.info(free_reflections_per_bin=250, max_number_of_bins=30).show_all()
  print("*"*80)
###> TLS refinement against xray data
  if (not "--comprehensive" in sys.argv[1:]):
          number_of_macro_cycles   = 1
          max_number_of_iterations = 3
  else:
          number_of_macro_cycles   = 100
          max_number_of_iterations = 50

  for start_tls_value in [None]:#[0.0, tlsosA, None]:
  #for start_tls_value in [None]:
      print(" \n "+str(start_tls_value) + " \n ")
      fmodel_cp = fmodel.deep_copy()
      #for sc in fmodel_cp.xray_structure.scatterers():
      #  sc.flags.set_use_u_aniso(True)
      fmodel_cp.xray_structure.convert_to_anisotropic()

      if(start_tls_value is None):
         run_finite_differences_test = True
      else: run_finite_differences_test = False
      model.set_xray_structure(fmodel_cp.xray_structure)
      tls_refinement_manager = tools.tls_refinement(
                     fmodel                      = fmodel_cp,
                     model                       = model,
                     selections                  = selections,
                     selections_1d               = None,
                     refine_T                    = 1,
                     refine_L                    = 1,
                     refine_S                    = 1,
                     number_of_macro_cycles      = number_of_macro_cycles,
                     max_number_of_iterations    = max_number_of_iterations,
                     start_tls_value             = start_tls_value,
                     run_finite_differences_test = run_finite_differences_test,
                     eps                         = eps)
      u_cart = tls_refinement_manager.fmodel.xray_structure.scatterers().extract_u_cart(
                                                        xray_structure.unit_cell())
      if("--comprehensive" in sys.argv[1:]):
         format   = "%10.6f %10.6f %10.6f %10.6f %10.6f %10.6f"
         counter = 0
         if(start_tls_value == tlsosA): tolerance = 1.e-6
         else: tolerance = 0.02
         for m1,m2 in zip(u_cart_answer, u_cart):
             counter += 1
             if(counter < 10):
                print("1=" + format % (m1[0],m1[1],m1[2],m1[3],m1[4],m1[5]))
                print("2=" + format % (m2[0],m2[1],m2[2],m2[3],m2[4],m2[5]))
             assert approx_equal(m1,m2, tolerance)
Exemple #4
0
def run(args, command_name="phenix.fobs_minus_fobs_map", log=None):
    if (len(args) == 0): args = ["--help"]
    examples = """Examples:

phenix.fobs_minus_fobs_map f_obs_1_file=data1.mtz f_obs_2_file=data2.sca \
f_obs_1_label=FOBS1 f_obs_2_label=FOBS2 model.pdb

phenix.fobs_minus_fobs_map f_obs_1_file=data.mtz f_obs_2_file=data.mtz \
f_obs_1_label=FOBS1 f_obs_2_label=FOBS2 phase_source=model.pdb \
high_res=2.0 sigma_cutoff=2 scattering_table=neutron"""

    command_line = (iotbx_option_parser(
        usage="%s [options]" % command_name,
        description=examples).option("--silent",
                                     action="store_true",
                                     help="Suppress output to the screen.").
                    enable_symmetry_comprehensive()).process(args=args)
    #
    if (log is None):
        log = sys.stdout
    if (not command_line.options.silent):
        utils.print_header("phenix.fobs_minus_fobs_map", out=log)
        print("Command line arguments: ", file=log)
        print(args, file=log)
        print(file=log)
    #
    processed_args = utils.process_command_line_args(
        args=command_line.args,
        cmd_cs=command_line.symmetry,
        master_params=fo_minus_fo_master_params(),
        absolute_angle_tolerance=5,
        absolute_length_tolerance=1,
        log=log,
        suppress_symmetry_related_errors=True)
    working_phil = processed_args.params
    if (not command_line.options.silent):
        print("*** Parameters:", file=log)
        working_phil.show(out=log)
        print(file=log)
    params = working_phil.extract()
    consensus_symmetry = None
    if (params.ignore_non_isomorphous_unit_cells):
        if (None in [
                params.f_obs_1_file_name, params.f_obs_2_file_name,
                params.phase_source
        ]):
            raise Sorry(
                "The file parameters (f_obs_1_file_name, f_obs_2_file_name, " +
                "phase_source) must be specified explicitly when " +
                "ignore_non_isomorphous_unit_cells=True.")
        symm_manager = iotbx.symmetry.manager()
        pdb_in = iotbx.file_reader.any_file(params.phase_source,
                                            force_type="pdb")
        symm_manager.process_pdb_file(pdb_in)
        hkl_in_1 = iotbx.file_reader.any_file(params.f_obs_1_file_name,
                                              force_type="hkl")
        sg_err_1, uc_err_1 = symm_manager.process_reflections_file(hkl_in_1)
        hkl_in_2 = iotbx.file_reader.any_file(params.f_obs_2_file_name,
                                              force_type="hkl")
        sg_err_2, uc_err_2 = symm_manager.process_reflections_file(hkl_in_2)
        out = StringIO()
        symm_manager.show(out=out)
        if (sg_err_1) or (sg_err_2):
            raise Sorry((
                "Incompatible space groups in input files:\n%s\nAll files " +
                "must have the same point group (and ideally the same space group). "
                +
                "Please note that any symmetry information in the PDB file will be "
                + "used first.") % out.getvalue())
        elif (uc_err_1) or (uc_err_2):
            libtbx.call_back(
                message="warn",
                data=
                ("Crystal symmetry mismatch:\n%s\nCalculations will continue "
                 +
                 "using the symmetry in the PDB file (or if not available, the "
                 +
                 "first reflection file), but the maps should be treated with "
                 + "extreme suspicion.") % out.getvalue())
        crystal_symmetry = symm_manager.as_symmetry_object()
    else:
        processed_args = utils.process_command_line_args(
            args=command_line.args,
            cmd_cs=command_line.symmetry,
            master_params=fo_minus_fo_master_params(),
            suppress_symmetry_related_errors=False,
            absolute_angle_tolerance=5,
            absolute_length_tolerance=1,
            log=StringIO())
        crystal_symmetry = processed_args.crystal_symmetry
    #
    pdb_file_names = processed_args.pdb_file_names
    if (len(processed_args.pdb_file_names) == 0):
        if (params.phase_source is not None):
            pdb_file_names = [params.phase_source]
        else:
            raise Sorry("No PDB file found.")
    # Extaract Fobs1, Fobs2
    f_obss = []
    if (len(processed_args.reflection_files) == 2):
        for reflection_file in processed_args.reflection_files:
            reflection_file_server = reflection_file_utils.reflection_file_server(
                crystal_symmetry=crystal_symmetry,
                force_symmetry=True,
                reflection_files=[reflection_file],
                err=null_out())
            # XXX UGLY !!!
            try:
                parameters = utils.data_and_flags_master_params().extract()
                if (params.f_obs_1_label is not None):
                    parameters.labels = [params.f_obs_1_label]
                determine_data_and_flags_result = utils.determine_data_and_flags(
                    reflection_file_server=reflection_file_server,
                    keep_going=True,
                    parameters=parameters,
                    log=null_out())
            except:  # intentional
                parameters = utils.data_and_flags_master_params().extract()
                if (params.f_obs_2_label is not None):
                    parameters.labels = [params.f_obs_2_label]
                determine_data_and_flags_result = utils.determine_data_and_flags(
                    reflection_file_server=reflection_file_server,
                    keep_going=True,
                    parameters=parameters,
                    log=null_out())
            f_obss.append(determine_data_and_flags_result.f_obs)
    else:
        if ([params.f_obs_1_file_name,
             params.f_obs_2_file_name].count(None) == 2):
            raise Sorry("No reflection data file found.")
        for file_name, label in zip(
            [params.f_obs_1_file_name, params.f_obs_2_file_name],
            [params.f_obs_1_label, params.f_obs_2_label]):
            reflection_file = reflection_file_reader.any_reflection_file(
                file_name=file_name, ensure_read_access=False)
            reflection_file_server = reflection_file_utils.reflection_file_server(
                crystal_symmetry=crystal_symmetry,
                force_symmetry=True,
                reflection_files=[reflection_file],
                err=null_out())
            parameters = utils.data_and_flags_master_params().extract()
            if (label is not None):
                parameters.labels = [label]
            determine_data_and_flags_result = utils.determine_data_and_flags(
                reflection_file_server=reflection_file_server,
                parameters=parameters,
                keep_going=True,
                log=null_out())
            f_obss.append(determine_data_and_flags_result.f_obs)
    if (len(f_obss) != 2):
        raise Sorry(" ".join(errors))
    if (not command_line.options.silent):
        for ifobs, fobs in enumerate(f_obss):
            print("*** Summary for data set %d:" % ifobs, file=log)
            fobs.show_comprehensive_summary(f=log)
            print(file=log)
    pdb_combined = combine_unique_pdb_files(file_names=pdb_file_names)
    pdb_combined.report_non_unique(out=log)
    if (len(pdb_combined.unique_file_names) == 0):
        raise Sorry("No coordinate file given.")
    #
    raw_recs = flex.std_string()
    for rec in pdb_combined.raw_records:
        if (rec.upper().count("CRYST1") == 0):
            raw_recs.append(rec)
    raw_recs.append(
        iotbx.pdb.format_cryst1_record(crystal_symmetry=crystal_symmetry))
    #
    pdb_in = iotbx.pdb.input(source_info=None, lines=raw_recs)
    model = mmtbx.model.manager(model_input=pdb_in)
    d_min = min(f_obss[0].d_min(), f_obss[1].d_min())
    model.setup_scattering_dictionaries(
        scattering_table=params.scattering_table, d_min=d_min)
    xray_structure = model.get_xray_structure()
    hierarchy = model.get_hierarchy()
    #
    omit_sel = flex.bool(hierarchy.atoms_size(), False)
    if (params.advanced.omit_selection is not None):
        print("Will omit selection from phasing model:", file=log)
        print("  " + params.advanced.omit_selection, file=log)
        omit_sel = hierarchy.atom_selection_cache().selection(
            params.advanced.omit_selection)
        print("%d atoms selected for removal" % omit_sel.count(True), file=log)
    del hierarchy
    xray_structure = xray_structure.select(~omit_sel)
    if (not command_line.options.silent):
        print("*** Model summary:", file=log)
        xray_structure.show_summary(f=log)
        print(file=log)
    info0 = f_obss[0].info()
    info1 = f_obss[1].info()
    f_obss[0] = f_obss[0].resolution_filter(
        d_min=params.high_resolution,
        d_max=params.low_resolution).set_info(info0)
    f_obss[1] = f_obss[1].resolution_filter(
        d_min=params.high_resolution,
        d_max=params.low_resolution).set_info(info1)
    if (params.sigma_cutoff is not None):
        for i in [0, 1]:
            if (f_obss[i].sigmas() is not None):
                sel = f_obss[i].data(
                ) > f_obss[i].sigmas() * params.sigma_cutoff
                f_obss[i] = f_obss[i].select(sel).set_info(info0)
    for k, f_obs in enumerate(f_obss):
        if (f_obs.indices().size() == 0):
            raise Sorry(
                "No data left in array %d (labels=%s) after filtering!" %
                (k + 1, f_obs.info().label_string()))
    output_file_name = params.output_file
    if (output_file_name is None) and (params.file_name_prefix is not None):
        output_file_name = "%s_%s.mtz" % (params.file_name_prefix,
                                          params.job_id)
    output_files = compute_fo_minus_fo_map(
        data_arrays=f_obss,
        xray_structure=xray_structure,
        log=log,
        silent=command_line.options.silent,
        output_file=output_file_name,
        peak_search=params.find_peaks_holes,
        map_cutoff=params.map_cutoff,
        peak_search_params=params.peak_search,
        multiscale=params.advanced.multiscale,
        anomalous=params.advanced.anomalous).file_names
    return output_files
def run(args, log=sys.stdout):
    print >> log, "-" * 79
    print >> log, legend
    print >> log, "-" * 79
    inputs = mmtbx.utils.process_command_line_args(
        args=args, master_params=master_params())
    params = inputs.params.extract()
    # estimate resolution
    d_min = params.resolution
    broadcast(m="Map resolution:", log=log)
    if (d_min is None):
        raise Sorry("Resolution is required.")
    print >> log, "  d_min: %6.4f" % d_min
    # model
    broadcast(m="Input PDB:", log=log)
    file_names = inputs.pdb_file_names
    if (len(file_names) != 1): raise Sorry("PDB file has to given.")
    if (inputs.crystal_symmetry is None):
        raise Sorry("No crystal symmetry defined.")
    pdb_inp = iotbx.pdb.input(file_name=file_names[0])
    model = mmtbx.model.manager(model_input=pdb_inp,
                                crystal_symmetry=inputs.crystal_symmetry,
                                build_grm=True)
    if model.get_number_of_models() > 1:
        raise Sorry("Only one model allowed.")
    model.setup_scattering_dictionaries(
        scattering_table=params.scattering_table)
    model.get_xray_structure().show_summary(f=log, prefix="  ")
    broadcast(m="Input map:", log=log)
    if (inputs.ccp4_map is None): raise Sorry("Map file has to given.")
    inputs.ccp4_map.show_summary(prefix="  ")
    map_data = inputs.ccp4_map.map_data()
    print >> log, "  Actual map (min,max,mean):", \
      map_data.as_1d().min_max_mean().as_tuple()
    make_sub_header("Histogram of map values", out=log)
    md = map_data.as_1d()
    show_histogram(data=md,
                   n_slots=10,
                   data_min=flex.min(md),
                   data_max=flex.max(md),
                   log=log)
    # shift origin if needed
    soin = maptbx.shift_origin_if_needed(
        map_data=map_data,
        sites_cart=model.get_sites_cart(),
        crystal_symmetry=model.crystal_symmetry())
    map_data = soin.map_data
    model.set_sites_cart(soin.sites_cart, update_grm=True)
    ####
    # Compute and show all stats
    ####
    broadcast(m="Model statistics:", log=log)
    make_sub_header("Overall", out=log)
    info = mmtbx.model.statistics.info(model=model)
    info.geometry.show()

    # XXX - these are not available anymore due to refactoring
    # make_sub_header("Histogram of devations from ideal bonds", out=log)
    # show_histogram(data=ms.bond_deltas, n_slots=10, data_min=0, data_max=0.2,
    #   log=log)
    # #
    # make_sub_header("Histogram of devations from ideal angles", out=log)
    # show_histogram(data=ms.angle_deltas, n_slots=10, data_min=0, data_max=30.,
    #   log=log)
    # #
    # make_sub_header("Histogram of non-bonded distances", out=log)
    # show_histogram(data=ms.nonbonded_distances, n_slots=10, data_min=0,
    #   data_max=5., log=log)
    #
    make_sub_header("Histogram of ADPs", out=log)
    info.adp.show(log=log)
    # bs = xrs.extract_u_iso_or_u_equiv()*adptbx.u_as_b(1.)
    # show_histogram(data=bs, n_slots=10, data_min=flex.min(bs),
    #   data_max=flex.max(bs), log=log)
    #
    # Compute CC
    broadcast(m="Map-model CC (overall):", log=log)
    five_cc_result = mmtbx.maps.correlation.five_cc(
        map=map_data, xray_structure=model.get_xray_structure(), d_min=d_min)
    atom_radius = five_cc_result.atom_radius
    if atom_radius is None:
        atom_radius = five_cc_result._atom_radius()
    print >> log, "  CC_mask  : %6.4f" % five_cc_result.result.cc_mask
    print >> log, "  CC_volume: %6.4f" % five_cc_result.result.cc_volume
    print >> log, "  CC_peaks : %6.4f" % five_cc_result.result.cc_peaks
    # Compute FSC(map, model)
    broadcast(m="Model-map FSC:", log=log)
    fsc = mmtbx.maps.correlation.fsc_model_vs_map(
        xray_structure=model.get_xray_structure(),
        map=map_data,
        atom_radius=atom_radius,
        d_min=d_min)
    fsc.show(prefix="  ")
    # Local CC
    cc_calculator = mmtbx.maps.correlation.from_map_and_xray_structure_or_fmodel(
        xray_structure=model.get_xray_structure(),
        map_data=map_data,
        d_min=d_min)
    broadcast(m="Map-model CC (local):", log=log)
    # per residue
    print >> log, "Per residue:"
    residue_results = list()
    ph = model.get_hierarchy()
    xrs = model.get_xray_structure()
    for rg in ph.residue_groups():
        cc = cc_calculator.cc(selection=rg.atoms().extract_i_seq())
        chain_id = rg.parent().id
        print >> log, "  chain id: %s resid %s: %6.4f" % (chain_id, rg.resid(),
                                                          cc)
    # per chain
    print >> log, "Per chain:"
    for chain in ph.chains():
        print >> log, "  chain %s: %6.4f" % (
            chain.id,
            cc_calculator.cc(selection=chain.atoms().extract_i_seq()))
    # per residue detailed counts
    print >> log, "Per residue (histogram):"
    crystal_gridding = maptbx.crystal_gridding(
        unit_cell=xrs.unit_cell(),
        space_group_info=xrs.space_group_info(),
        pre_determined_n_real=map_data.accessor().all())
    f_calc = xrs.structure_factors(d_min=d_min).f_calc()
    fft_map = miller.fft_map(crystal_gridding=crystal_gridding,
                             fourier_coefficients=f_calc)
    fft_map.apply_sigma_scaling()
    map_model = fft_map.real_map_unpadded()
    sites_cart = xrs.sites_cart()
    cc_per_residue = flex.double()
    for rg in ph.residue_groups():
        cc = mmtbx.maps.correlation.from_map_map_atoms(
            map_1=map_data,
            map_2=map_model,
            sites_cart=sites_cart.select(rg.atoms().extract_i_seq()),
            unit_cell=xrs.unit_cell(),
            radius=2.)
        cc_per_residue.append(cc)
    show_histogram(data=cc_per_residue,
                   n_slots=10,
                   data_min=-1.,
                   data_max=1.0,
                   log=log)
     raise Sorry("No coordinate file given.")
 raw_records = pdb_combined.raw_records
 try:
     pdb_inp = iotbx.pdb.input(source_info=None,
                               lines=flex.std_string(raw_records))
 except ValueError, e:
     raise Sorry("Model format (PDB or mmCIF) error:\n%s" % str(e))
 model = mmtbx.model.manager(model_input=pdb_inp,
                             crystal_symmetry=crystal_symmetry,
                             log=StringIO())
 #
 scattering_table = params.scattering_table
 exptl_method = pdb_inp.get_experiment_type()
 if (exptl_method is not None) and ("NEUTRON" in exptl_method):
     scattering_table = "neutron"
 model.setup_scattering_dictionaries(scattering_table=scattering_table,
                                     d_min=f_obs.d_min())
 #
 # Model vs data
 #
 show_header(l="Model vs Data:", log=log)
 fmodel = mmtbx.f_model.manager(xray_structure=model.get_xray_structure(),
                                f_obs=f_obs,
                                r_free_flags=r_free_flags,
                                twin_law=params.twin_law)
 fmodel.update_all_scales(update_f_part1=True)
 fmodel.show(log=log, show_header=False, show_approx=False)
 print >> log, "  r_work: %6.4f" % fmodel.r_work()
 if (test_flag_value is not None):
     print >> log, "  r_free: %6.4f" % fmodel.r_free()
 else:
     print >> log, "  r_free: None"