Ejemplo n.º 1
0
    def __init__(self, *args, **kwds):
        super(restrained_crystal_structure_builder,
              self).__init__(*args, **kwds)
        geom = geometry_restraints
        adp = adp_restraints
        self._proxies = {}

        self._proxies = {
            'bond':
            geometry_restraints.shared_bond_simple_proxy(),
            'angle':
            geometry_restraints.shared_angle_proxy(),
            'dihedral':
            geometry_restraints.shared_dihedral_proxy(),
            'planarity':
            geometry_restraints.shared_planarity_proxy(),
            'chirality':
            geometry_restraints.shared_chirality_proxy(),
            'bond_similarity':
            geometry_restraints.shared_bond_similarity_proxy(),
            'adp_similarity':
            adp_restraints.shared_adp_similarity_proxy(),
            'rigid_bond':
            adp_restraints.shared_rigid_bond_proxy(),
            'isotropic_adp':
            adp_restraints.shared_isotropic_adp_proxy(),
            'fixed_u_eq_adp':
            adp_restraints.shared_fixed_u_eq_adp_proxy(),
            'adp_u_eq_similarity':
            adp_restraints.shared_adp_u_eq_similarity_proxy(),
            'adp_volume_similarity':
            adp_restraints.shared_adp_volume_similarity_proxy(),
        }
Ejemplo n.º 2
0
class angle_restraint_test_case(geometry_restraints_test_case):
    manager = restraints.manager(
        angle_proxies=geometry_restraints.shared_angle_proxy([
            geom.angle_proxy((30, 0, 19), 115, 1),
            geom.angle_proxy((21, 1, 2), 110, 1)
        ]))
    proxies = manager.angle_proxies
    restraint_t = geom.angle
Ejemplo n.º 3
0
  def __init__(self, *args, **kwds):
    super(restrained_crystal_structure_builder, self).__init__(*args, **kwds)
    geom = geometry_restraints
    adp = adp_restraints
    self._proxies = {}

    self._proxies = {
      'bond': geometry_restraints.shared_bond_simple_proxy(),
      'angle': geometry_restraints.shared_angle_proxy(),
      'dihedral': geometry_restraints.shared_dihedral_proxy(),
      'planarity': geometry_restraints.shared_planarity_proxy(),
      'chirality': geometry_restraints.shared_chirality_proxy(),
      'bond_similarity': geometry_restraints.shared_bond_similarity_proxy(),
      'adp_similarity': adp_restraints.shared_adp_similarity_proxy(),
      'rigid_bond': adp_restraints.shared_rigid_bond_proxy(),
      'isotropic_adp': adp_restraints.shared_isotropic_adp_proxy(),
      'fixed_u_eq_adp': adp_restraints.shared_fixed_u_eq_adp_proxy(),
      'adp_u_eq_similarity': adp_restraints.shared_adp_u_eq_similarity_proxy(),
      'adp_volume_similarity': adp_restraints.shared_adp_volume_similarity_proxy(),
    }
Ejemplo n.º 4
0
    def create_protein_hbond_proxies(self, annotation=None, log=sys.stdout):
        # assert as_regular_bond_proxies=True
        if annotation is None:
            annotation = self.actual_sec_str
        remove_outliers = self.params.secondary_structure.protein.remove_outliers

        from scitbx.array_family import flex
        atoms = self.pdb_hierarchy.atoms()
        hbond_counts = flex.int(atoms.size(), 0)

        distance_ideal = self.params.secondary_structure.protein.distance_ideal_n_o
        distance_cut = self.params.secondary_structure.protein.distance_cut_n_o
        if (distance_cut is None):
            distance_cut = -1
        generated_proxies = geometry_restraints.shared_bond_simple_proxy()
        hb_angle_proxies = []
        if self.params.secondary_structure.protein.enabled:
            for helix in self.params.secondary_structure.protein.helix:
                if helix.selection is not None:
                    print >> log, "    Processing helix ", helix.selection
                    proxies, angle_proxies = proteins.create_helix_hydrogen_bond_proxies(
                        params=helix,
                        pdb_hierarchy=self.pdb_hierarchy,
                        selection_cache=self.selection_cache,
                        weight=1.0,
                        hbond_counts=hbond_counts,
                        distance_ideal=distance_ideal,
                        distance_cut=distance_cut,
                        remove_outliers=remove_outliers,
                        restrain_hbond_angles=self.params.secondary_structure.
                        protein.restrain_hbond_angles,
                        log=log)
                    if (proxies.size() == 0):
                        print >> log, "      No H-bonds generated for '%s'" % helix.selection
                        continue
                    else:
                        generated_proxies.extend(proxies)
                        hb_angle_proxies += angle_proxies
            for k, sheet in enumerate(
                    self.params.secondary_structure.protein.sheet):
                print >> log, "    Processing sheet with id=%s, first strand: %s" % (
                    sheet.sheet_id, sheet.first_strand)
                if sheet.first_strand is not None:
                    proxies, angle_proxies = proteins.create_sheet_hydrogen_bond_proxies(
                        sheet_params=sheet,
                        pdb_hierarchy=self.pdb_hierarchy,
                        selection_cache=self.selection_cache,
                        weight=1.0,
                        hbond_counts=hbond_counts,
                        distance_ideal=distance_ideal,
                        distance_cut=distance_cut,
                        remove_outliers=remove_outliers,
                        restrain_hbond_angles=self.params.secondary_structure.
                        protein.restrain_hbond_angles,
                        log=log)
                    if (proxies.size() == 0):
                        print >> log, \
                            "  No H-bonds generated for sheet with id=%s" % sheet.sheet_id
                        continue
                    else:
                        generated_proxies.extend(proxies)
                        hb_angle_proxies += angle_proxies

        n_proxies = generated_proxies.size()
        print >> log, ""
        if (n_proxies == 0):
            print >> log, "    No hydrogen bonds defined for protein."
        else:
            print >> log, "    %d hydrogen bonds defined for protein." % n_proxies
            print >> log, "    %d hydrogen bond angles defined for protein." % len(
                hb_angle_proxies)
        return generated_proxies, geometry_restraints.shared_angle_proxy(
            hb_angle_proxies)
Ejemplo n.º 5
0
def exercise(verbose=0):
    distance_ideal = 1.8
    default_vdw_distance = 3.6
    vdw_1_4_factor = 3.5 / 3.6
    sites_cart_manual = flex.vec3_double([(1, 3, 0), (2, 3, 0), (3, 2, 0),
                                          (3, 1, 0), (4, 1, 0), (3, 4, 0),
                                          (4, 3, 0), (5, 3, 0), (6, 2, 0),
                                          (7, 2, 0), (8, 3, 0), (7, 4, 0),
                                          (6, 4, 0), (7, 5, 0), (6, 6, 0),
                                          (8, 6, 0)])
    bond_proxies = geometry_restraints.bond_sorted_asu_proxies(
        asu_mappings=None)
    for i_seqs in [(0, 1), (1, 2), (2, 3), (3, 4), (1, 5), (2, 6), (5, 6),
                   (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12),
                   (12, 7), (11, 13), (13, 14), (14, 15), (15, 13)]:
        bond_proxies.process(
            geometry_restraints.bond_simple_proxy(
                i_seqs=i_seqs, distance_ideal=distance_ideal, weight=100))
    angle_proxies = geometry_restraints.shared_angle_proxy()
    for i_seqs, angle_ideal in [[(0, 1, 2), 135], [(0, 1, 5), 135],
                                [(1, 2, 3), 135], [(3, 2, 6), 135],
                                [(2, 3, 4), 120], [(1, 2, 6), 90],
                                [(2, 6, 5), 90], [(6, 5, 1), 90],
                                [(5, 1, 2), 90], [(2, 6, 7), 135],
                                [(5, 6, 7), 135], [(6, 7, 8), 120],
                                [(6, 7, 12), 120], [(7, 8, 9), 120],
                                [(8, 9, 10), 120], [(9, 10, 11), 120],
                                [(10, 11, 12), 120], [(11, 12, 7), 120],
                                [(12, 7, 8), 120], [(10, 11, 13), 120],
                                [(12, 11, 13), 120], [(11, 13, 15), 150],
                                [(11, 13, 14), 150], [(13, 15, 14), 60],
                                [(15, 14, 13), 60], [(14, 13, 15), 60]]:
        angle_proxies.append(
            geometry_restraints.angle_proxy(i_seqs=i_seqs,
                                            angle_ideal=angle_ideal,
                                            weight=1))
    if (0 or verbose):
        dump_pdb(file_name="manual.pdb", sites_cart=sites_cart_manual)
    for traditional_convergence_test in [True, False]:
        for sites_cart_selection in [True, False]:
            sites_cart = sites_cart_manual.deep_copy()
            if sites_cart_selection:
                sites_cart_selection = flex.bool(sites_cart.size(), True)
                sites_cart_selection[1] = False
            assert bond_proxies.asu.size() == 0
            bond_params_table = geometry_restraints.extract_bond_params(
                n_seq=sites_cart.size(),
                bond_simple_proxies=bond_proxies.simple)
            manager = geometry_restraints.manager.manager(
                bond_params_table=bond_params_table,
                angle_proxies=angle_proxies)
            minimized = geometry_restraints.lbfgs.lbfgs(
                sites_cart=sites_cart,
                geometry_restraints_manager=manager,
                lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
                    traditional_convergence_test=traditional_convergence_test,
                    drop_convergence_test_max_drop_eps=1.e-20,
                    drop_convergence_test_iteration_coefficient=1,
                    max_iterations=1000),
                sites_cart_selection=sites_cart_selection,
            )
            assert minimized.minimizer.iter() > 100
            sites_cart_minimized_1 = sites_cart.deep_copy()
            if (0 or verbose):
                dump_pdb(file_name="minimized_1.pdb",
                         sites_cart=sites_cart_minimized_1)
            bond_deltas = geometry_restraints.bond_deltas(
                sites_cart=sites_cart_minimized_1, proxies=bond_proxies.simple)
            angle_deltas = geometry_restraints.angle_deltas(
                sites_cart=sites_cart_minimized_1, proxies=angle_proxies)
            if (0 or verbose):
                for proxy, delta in zip(bond_proxies.simple, bond_deltas):
                    print "bond:", proxy.i_seqs, delta
                for proxy, delta in zip(angle_proxies, angle_deltas):
                    print "angle:", proxy.i_seqs, delta
            assert is_below_limit(value=flex.max(flex.abs(bond_deltas)),
                                  limit=0,
                                  eps=1.e-6)
            assert is_below_limit(value=flex.max(flex.abs(angle_deltas)),
                                  limit=0,
                                  eps=2.e-6)
    sites_cart += matrix.col((1, 1, 0)) - matrix.col(sites_cart.min())
    unit_cell_lengths = list(
        matrix.col(sites_cart.max()) + matrix.col((1, -1.2, 4)))
    unit_cell_lengths[1] *= 2
    unit_cell_lengths[2] *= 2
    xray_structure = xray.structure(crystal_symmetry=crystal.symmetry(
        unit_cell=unit_cell_lengths, space_group_symbol="P112"))
    for serial, site in zip(count(1), sites_cart):
        xray_structure.add_scatterer(
            xray.scatterer(
                label="C%02d" % serial,
                site=xray_structure.unit_cell().fractionalize(site)))
    if (0 or verbose):
        xray_structure.show_summary().show_scatterers()
    p1_structure = (xray_structure.apply_shift(
        (-.5, -.5, 0)).expand_to_p1().apply_shift((.5, .5, 0)))
    for shift in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]:
        p1_structure.add_scatterers(
            p1_structure.apply_shift(shift).scatterers())
    if (0 or verbose):
        open("p1_structure.pdb", "w").write(p1_structure.as_pdb_file())
    nonbonded_cutoff = 6.5
    asu_mappings = xray_structure.asu_mappings(
        buffer_thickness=nonbonded_cutoff)
    bond_asu_table = crystal.pair_asu_table(asu_mappings=asu_mappings)
    geometry_restraints.add_pairs(bond_asu_table, bond_proxies.simple)
    shell_asu_tables = crystal.coordination_sequences.shell_asu_tables(
        pair_asu_table=bond_asu_table, max_shell=3)
    shell_sym_tables = [
        shell_asu_table.extract_pair_sym_table()
        for shell_asu_table in shell_asu_tables
    ]
    bond_params_table = geometry_restraints.extract_bond_params(
        n_seq=sites_cart.size(), bond_simple_proxies=bond_proxies.simple)
    atom_energy_types = flex.std_string(sites_cart.size(), "Default")
    nonbonded_params = geometry_restraints.nonbonded_params(
        factor_1_4_interactions=vdw_1_4_factor,
        const_shrink_1_4_interactions=0,
        default_distance=default_vdw_distance)
    nonbonded_params.distance_table.setdefault(
        "Default")["Default"] = default_vdw_distance
    pair_proxies = geometry_restraints.pair_proxies(
        bond_params_table=bond_params_table,
        shell_asu_tables=shell_asu_tables,
        model_indices=None,
        conformer_indices=None,
        nonbonded_params=nonbonded_params,
        nonbonded_types=atom_energy_types,
        nonbonded_distance_cutoff_plus_buffer=nonbonded_cutoff)
    if (0 or verbose):
        print "pair_proxies.bond_proxies.n_total():", \
               pair_proxies.bond_proxies.n_total(),
        print "simple:", pair_proxies.bond_proxies.simple.size(),
        print "sym:", pair_proxies.bond_proxies.asu.size()
        print "pair_proxies.nonbonded_proxies.n_total():", \
               pair_proxies.nonbonded_proxies.n_total(),
        print "simple:", pair_proxies.nonbonded_proxies.simple.size(),
        print "sym:", pair_proxies.nonbonded_proxies.asu.size()
        print "min_distance_nonbonded: %.2f" % flex.min(
            geometry_restraints.nonbonded_deltas(
                sites_cart=sites_cart,
                sorted_asu_proxies=pair_proxies.nonbonded_proxies))
    s = StringIO()
    pair_proxies.bond_proxies.show_histogram_of_model_distances(
        sites_cart=sites_cart, f=s, prefix="[]")
    assert s.getvalue().splitlines()[0] == "[]Histogram of bond lengths:"
    assert s.getvalue().splitlines()[5].startswith("[]      1.80 -     1.80:")
    s = StringIO()
    pair_proxies.bond_proxies.show_histogram_of_deltas(sites_cart=sites_cart,
                                                       f=s,
                                                       prefix="][")
    assert s.getvalue().splitlines()[0] == "][Histogram of bond deltas:"
    assert s.getvalue().splitlines()[5].startswith("][     0.000 -    0.000:")
    s = StringIO()
    pair_proxies.bond_proxies.show_sorted(by_value="residual",
                                          sites_cart=sites_cart,
                                          max_items=3,
                                          f=s,
                                          prefix=":;")
    l = s.getvalue().splitlines()
    assert l[0] == ":;Bond restraints: 18"
    assert l[1] == ":;Sorted by residual:"
    assert l[2].startswith(":;bond ")
    assert l[3].startswith(":;     ")
    assert l[4] == ":;  ideal  model  delta    sigma   weight residual"
    for i in [5, -2]:
        assert l[i].startswith(":;  1.800  1.800 ")
    assert l[-1] == ":;... (remaining 15 not shown)"
    s = StringIO()
    pair_proxies.nonbonded_proxies.show_histogram_of_model_distances(
        sites_cart=sites_cart, f=s, prefix="]^")
    assert not show_diff(
        s.getvalue(), """\
]^Histogram of nonbonded interaction distances:
]^      2.16 -     3.03: 3
]^      3.03 -     3.89: 12
]^      3.89 -     4.75: 28
]^      4.75 -     5.61: 44
]^      5.61 -     6.48: 54
""")
    s = StringIO()
    pair_proxies.nonbonded_proxies.show_sorted(by_value="delta",
                                               sites_cart=sites_cart,
                                               max_items=7,
                                               f=s,
                                               prefix=">,")
    assert not show_diff(s.getvalue(),
                         """\
>,Nonbonded interactions: 141
>,Sorted by model distance:
>,nonbonded 15
>,          15
>,   model   vdw sym.op.
>,   2.164 3.600 -x+2,-y+1,z
...
>,nonbonded 4
>,          8
>,   model   vdw
>,   3.414 3.600
>,... (remaining 134 not shown)
""",
                         selections=[range(6), range(-5, 0)])
    vdw_1_sticks = []
    vdw_2_sticks = []
    for proxy in pair_proxies.nonbonded_proxies.simple:
        if (proxy.vdw_distance == default_vdw_distance):
            vdw_1_sticks.append(
                pml_stick(begin=sites_cart[proxy.i_seqs[0]],
                          end=sites_cart[proxy.i_seqs[1]]))
        else:
            vdw_2_sticks.append(
                pml_stick(begin=sites_cart[proxy.i_seqs[0]],
                          end=sites_cart[proxy.i_seqs[1]]))
    mps = asu_mappings.mappings()
    for proxy in pair_proxies.nonbonded_proxies.asu:
        if (proxy.vdw_distance == default_vdw_distance):
            vdw_1_sticks.append(
                pml_stick(begin=mps[proxy.i_seq][0].mapped_site(),
                          end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
        else:
            vdw_2_sticks.append(
                pml_stick(begin=mps[proxy.i_seq][0].mapped_site(),
                          end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
    if (0 or verbose):
        pml_write(f=open("vdw_1.pml", "w"), label="vdw_1", sticks=vdw_1_sticks)
        pml_write(f=open("vdw_2.pml", "w"), label="vdw_2", sticks=vdw_2_sticks)
    #
    i_pdb = count(2)
    for use_crystal_symmetry in [False, True]:
        if (not use_crystal_symmetry):
            crystal_symmetry = None
            site_symmetry_table = None
        else:
            crystal_symmetry = xray_structure
            site_symmetry_table = xray_structure.site_symmetry_table()
        for sites_cart in [
                sites_cart_manual.deep_copy(),
                sites_cart_minimized_1.deep_copy()
        ]:
            manager = geometry_restraints.manager.manager(
                crystal_symmetry=crystal_symmetry,
                site_symmetry_table=site_symmetry_table,
                nonbonded_params=nonbonded_params,
                nonbonded_types=atom_energy_types,
                nonbonded_function=geometry_restraints.
                prolsq_repulsion_function(),
                bond_params_table=bond_params_table,
                shell_sym_tables=shell_sym_tables,
                nonbonded_distance_cutoff=nonbonded_cutoff,
                nonbonded_buffer=1,
                angle_proxies=angle_proxies,
                plain_pairs_radius=5)
            manager = manager.select(
                selection=flex.bool(sites_cart.size(), True))
            manager = manager.select(iselection=flex.size_t_range(
                stop=sites_cart.size()))
            pair_proxies = manager.pair_proxies(sites_cart=sites_cart)
            minimized = geometry_restraints.lbfgs.lbfgs(
                sites_cart=sites_cart,
                geometry_restraints_manager=manager,
                lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
                    max_iterations=1000))
            if (0 or verbose):
                minimized.final_target_result.show()
                print "number of function evaluations:", minimized.minimizer.nfun(
                )
                print "n_updates_pair_proxies:", manager.n_updates_pair_proxies
            if (not use_crystal_symmetry):
                assert minimized.final_target_result.bond_residual_sum < 1.e-3
                assert minimized.final_target_result.nonbonded_residual_sum < 0.1
            else:
                assert minimized.final_target_result.bond_residual_sum < 1.e-2
                assert minimized.final_target_result.nonbonded_residual_sum < 0.1
            assert minimized.final_target_result.angle_residual_sum < 1.e-3
            if (0 or verbose):
                pdb_file_name = "minimized_%d.pdb" % i_pdb.next()
                print "Writing file:", pdb_file_name
                dump_pdb(file_name=pdb_file_name, sites_cart=sites_cart)
            if (manager.site_symmetry_table is None):
                additional_site_symmetry_table = None
            else:
                additional_site_symmetry_table = sgtbx.site_symmetry_table()
            assert manager.new_including_isolated_sites(
              n_additional_sites=0,
              site_symmetry_table=additional_site_symmetry_table,
              nonbonded_types=flex.std_string()).plain_pairs_radius \
                == manager.plain_pairs_radius
            if (crystal_symmetry is not None):
                assert len(manager.plain_pair_sym_table) == 16
                if (0 or verbose):
                    manager.plain_pair_sym_table.show()
    #
    xray_structure.set_u_iso(values=flex.double([
        0.77599982480241358, 0.38745781137212021, 0.20667558236418682,
        0.99759840171302094, 0.8917287406687805, 0.64780251325379845,
        0.24878590382983534, 0.59480621182194615, 0.58695637792905142,
        0.33997130213653637, 0.51258699130743735, 0.79760289141276675,
        0.39996577657875021, 0.4329328819341467, 0.70422156561726479,
        0.87260110626999332
    ]))

    class parameters:
        pass

    parameters.sphere_radius = 5
    parameters.distance_power = 0.7
    parameters.average_power = 0.9
    parameters.wilson_b_weight = 1.3952
    parameters.wilson_b_weight_auto = False
    adp_energies = adp_restraints.energies_iso(
        geometry_restraints_manager=manager,
        xray_structure=xray_structure,
        parameters=parameters,
        wilson_b=None,
        use_hd=False,
        use_u_local_only=False,
        compute_gradients=False,
        gradients=None,
        normalization=False,
        collect=True)
    assert adp_energies.number_of_restraints == 69
    assert approx_equal(adp_energies.residual_sum, 6.24865382467)
    assert adp_energies.gradients is None
    assert adp_energies.u_i.size() == adp_energies.number_of_restraints
    assert adp_energies.u_j.size() == adp_energies.number_of_restraints
    assert adp_energies.r_ij.size() == adp_energies.number_of_restraints
    for wilson_b in [None, 10, 100]:
        finite_difference_gradients = flex.double()
        eps = 1.e-6
        for i_scatterer in xrange(xray_structure.scatterers().size()):
            rs = []
            for signed_eps in [eps, -eps]:
                xray_structure_eps = xray_structure.deep_copy_scatterers()
                xray_structure_eps.scatterers(
                )[i_scatterer].u_iso += signed_eps
                adp_energies = adp_restraints.energies_iso(
                    geometry_restraints_manager=manager,
                    xray_structure=xray_structure_eps,
                    parameters=parameters,
                    wilson_b=wilson_b,
                    use_u_local_only=False,
                    use_hd=False,
                    compute_gradients=True,
                    gradients=None,
                    normalization=False,
                    collect=False)
                rs.append(adp_energies.residual_sum)
                assert adp_energies.gradients.size() \
                    == xray_structure.scatterers().size()
                assert adp_energies.u_i == None
                assert adp_energies.u_j == None
                assert adp_energies.r_ij == None
            finite_difference_gradients.append((rs[0] - rs[1]) / (2 * eps))
        sel = flex.bool(xray_structure.scatterers().size(), True)
        xray_structure.scatterers().flags_set_grad_u_iso(sel.iselection())
        adp_energies = adp_restraints.energies_iso(
            geometry_restraints_manager=manager,
            xray_structure=xray_structure,
            parameters=parameters,
            wilson_b=wilson_b,
            use_u_local_only=False,
            use_hd=False,
            compute_gradients=True,
            gradients=None,
            normalization=False,
            collect=False)
        assert approx_equal(adp_energies.gradients,
                            finite_difference_gradients)
    print "OK"
def read_pdb():

    pdbstring = """\
ATOM      0  CA  GLY A   3       5.804  -2.100   7.324  1.00  1.36           C
ATOM      1  C   GLY A   3       4.651  -1.149   7.578  1.00  1.01           C
ATOM      2  O   GLY A   3       3.598  -1.553   8.071  1.00  1.38           O
ATOM      3  N   GLY A   3       6.706  -1.622   6.294  1.00  1.11           N
ATOM      4  CA  PHE A   4       3.819   1.134   7.419  1.00  0.89           C
ATOM      5  CB  PHE A   4       4.397   2.380   8.094  1.00  1.13           C
ATOM      6  C   PHE A   4       3.185   1.509   6.084  1.00  0.94           C
ATOM      7  N   PHE A   4       4.852   0.121   7.242  1.00  0.88           N
ATOM      8  O   PHE A   4       2.361   2.421   6.010  1.00  1.47           O
ATOM      9  CA  LEU A   5       3.055   1.059   3.693  1.00  0.87           C
ATOM     10  CB  LEU A   5       3.965   0.435   2.634  1.00  1.13           C
ATOM     11  C   LEU A   5       1.634   0.527   3.541  1.00  0.87           C
ATOM     12  N   LEU A   5       3.576   0.800   5.030  1.00  0.92           N
ATOM     13  O   LEU A   5       1.246  -0.440   4.196  1.00  1.23           O
"""

    pdb_inp = iotbx.pdb.input(lines=flex.split_lines(pdbstring),
                              source_info=None)

    sites_cart = pdb_inp.atoms().extract_xyz()

    # TRANS    phi      1 C      2 N      2 CA     2 C        60.00  20.0 3
    # TRANS    psi      1 N      1 CA     1 C      2 N       160.00  30.0 2

    dihedral_proxies = geometry_restraints.shared_dihedral_proxy()

    # residue 1
    psi = geometry_restraints.dihedral_proxy(i_seqs=[3, 0, 1, 7],
                                             angle_ideal=160.0,
                                             weight=1 / 30.0**2,
                                             periodicity=3)
    dihedral_proxies.append(psi)

    # residue 2
    phi = geometry_restraints.dihedral_proxy(i_seqs=[1, 7, 4, 6],
                                             angle_ideal=60.0,
                                             weight=1 / 20.0**2,
                                             periodicity=3)
    dihedral_proxies.append(phi)

    psi = geometry_restraints.dihedral_proxy(i_seqs=[7, 4, 6, 8],
                                             angle_ideal=160.0,
                                             weight=1 / 30.0**2,
                                             periodicity=3)
    dihedral_proxies.append(psi)

    # residue 3
    phi = geometry_restraints.dihedral_proxy(i_seqs=[6, 12, 9, 11],
                                             angle_ideal=60.0,
                                             weight=1 / 20.0**2,
                                             periodicity=3)
    dihedral_proxies.append(phi)

    angle_proxies = geometry_restraints.shared_angle_proxy()

    ## Residue 1
    # a3
    a = geometry_restraints.angle_proxy(i_seqs=[3, 0, 1],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    # a7
    a = geometry_restraints.angle_proxy(i_seqs=[2, 1, 7],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    ## Residue 2
    # a1
    a = geometry_restraints.angle_proxy(i_seqs=[1, 7, 4],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    # a3
    a = geometry_restraints.angle_proxy(i_seqs=[7, 4, 6],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    # a7
    a = geometry_restraints.angle_proxy(i_seqs=[8, 6, 12],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    ## Residue 3
    # a1
    a = geometry_restraints.angle_proxy(i_seqs=[6, 12, 9],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    # a3
    a = geometry_restraints.angle_proxy(i_seqs=[12, 9, 11],
                                        angle_ideal=0,
                                        weight=1)
    angle_proxies.append(a)

    # compute dihedral
    #dihedral = geometry_restraints.dihedral(
    #    sites_cart=sites_cart,
    #    proxy=dihedral_proxies[0])

    # Shows real dihedral value
    #print dihedral.angle_model, dihedral.delta
    cfd_list = []

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='GLY',
        next_residue_name='PHE',
        conformation_proxies=None,
        i_phi_proxy=None,  # index into dihedral_proxies
        i_psi_proxy=0,
        i_dynamic_angles=[None, None, 0, None, None, None,
                          1],  # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None)
    cfd_list.append(cfd)

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='PHE',
        next_residue_name='LEU',
        conformation_proxies=None,
        i_phi_proxy=1,  # index into dihedral_proxies
        i_psi_proxy=2,
        i_dynamic_angles=[2, None, 3, None, None, None,
                          4],  # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None)
    cfd_list.append(cfd)

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='LEU',
        next_residue_name=None,
        conformation_proxies=None,
        i_phi_proxy=3,  # index into dihedral_proxies
        i_psi_proxy=None,
        i_dynamic_angles=[5, None, 6, None, None, None,
                          None],  # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None)
    cfd_list.append(cfd)

    for x in range(1, 4):
        print
        print 'Starting cycle', x
        print
        for cfd in cfd_list:
            cfd.update_restraints(sites_cart, dihedral_proxies, angle_proxies)
Ejemplo n.º 7
0
def exercise_geometry_restraints_as_cif():
    quartz = xray.structure(crystal_symmetry=crystal.symmetry(
        (5.01, 5.01, 5.47, 90, 90, 120), "P6222"),
                            scatterers=flex.xray_scatterer([
                                xray.scatterer("Si", (1 / 2., 1 / 2., 1 / 3.)),
                                xray.scatterer("O", (0.197, -0.197, 0.83333))
                            ]))
    bond_proxies = geometry_restraints.shared_bond_simple_proxy((
        geometry_restraints.bond_simple_proxy(
            i_seqs=[0, 1],
            rt_mx_ji=sgtbx.rt_mx("x-y,x,z-2/3"),
            distance_ideal=1.6,
            weight=3.2),
        geometry_restraints.bond_simple_proxy(i_seqs=[0, 1],
                                              distance_ideal=1.7,
                                              weight=1.8),
    ))
    dihedral_proxies = geometry_restraints.shared_dihedral_proxy((
        geometry_restraints.dihedral_proxy(
            i_seqs=[1, 0, 1, 0],
            sym_ops=(sgtbx.rt_mx("1+y,1-x+y, z-1/3"), sgtbx.rt_mx(),
                     sgtbx.rt_mx("x-y,x,z-2/3"), sgtbx.rt_mx("1-x,y-x,1/3-z")),
            angle_ideal=-30,
            weight=2),
        geometry_restraints.dihedral_proxy(
            i_seqs=[1, 0, 1, 0],
            sym_ops=(sgtbx.rt_mx("1+y,1-x+y, z-1/3"), sgtbx.rt_mx(),
                     sgtbx.rt_mx("-y,x-y,z-1/3"), sgtbx.rt_mx("x-y,x,1/3+z")),
            angle_ideal=90,
            weight=3),
    ))
    angle_proxies = geometry_restraints.shared_angle_proxy((
        geometry_restraints.angle_proxy(i_seqs=[1, 0, 1],
                                        sym_ops=(sgtbx.rt_mx("x-y,x,z-2/3"),
                                                 sgtbx.rt_mx(),
                                                 sgtbx.rt_mx("-y,x-y,z-1/3")),
                                        angle_ideal=103,
                                        weight=2),
        geometry_restraints.angle_proxy(
            i_seqs=[1, 0, 1],
            sym_ops=(sgtbx.rt_mx("y+1,-x+y+1,z-1/3"), sgtbx.rt_mx(),
                     sgtbx.rt_mx("-y,x-y,z-1/3")),
            angle_ideal=110,
            weight=5),
        geometry_restraints.angle_proxy(i_seqs=[0, 1, 0],
                                        sym_ops=(sgtbx.rt_mx("y,-x+y,z+2/3"),
                                                 sgtbx.rt_mx(),
                                                 sgtbx.rt_mx("-x+y,-x,z+1/3")),
                                        angle_ideal=150,
                                        weight=5),
    ))
    bond_similarity_proxies = geometry_restraints.shared_bond_similarity_proxy(
        (geometry_restraints.bond_similarity_proxy(
            i_seqs=[(0, 1), (0, 1), (0, 1)],
            sym_ops=(sgtbx.rt_mx("x-y,x,z-2/3"), sgtbx.rt_mx("-y,x-y,z-1/3"),
                     sgtbx.rt_mx("y+1,-x+y+1,z-1/3")),
            weights=(1, 1, 1)), ))
    cif_block = iotbx.cif.model.block()
    iotbx.cif.restraints.add_to_cif_block(
        cif_block,
        quartz,
        bond_proxies=bond_proxies,
        angle_proxies=angle_proxies,
        dihedral_proxies=dihedral_proxies,
        bond_similarity_proxies=bond_similarity_proxies)
    s = StringIO()
    cif_block.show(out=s)
    assert not show_diff(
        s.getvalue(), """\
loop_
  _restr_distance_atom_site_label_1
  _restr_distance_atom_site_label_2
  _restr_distance_site_symmetry_2
  _restr_distance_target
  _restr_distance_target_weight_param
  _restr_distance_diff
  Si  O  2_554  1.6000  0.5590  -0.0160
  Si  O  1      1.7000  0.7454  -2.3838

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

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

loop_
  _restr_equal_distance_class_class_id
  _restr_equal_distance_class_target_weight_param
  _restr_equal_distance_class_average
  _restr_equal_distance_class_esd
  _restr_equal_distance_class_diff_max
  1  1.0000  1.6160  0.0000  0.0000

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

""")
def read_pdb():

    pdbstring = """\
ATOM      0  CA  GLY A   3       5.804  -2.100   7.324  1.00  1.36           C
ATOM      1  C   GLY A   3       4.651  -1.149   7.578  1.00  1.01           C
ATOM      2  O   GLY A   3       3.598  -1.553   8.071  1.00  1.38           O
ATOM      3  N   GLY A   3       6.706  -1.622   6.294  1.00  1.11           N
ATOM      4  CA  PHE A   4       3.819   1.134   7.419  1.00  0.89           C
ATOM      5  CB  PHE A   4       4.397   2.380   8.094  1.00  1.13           C
ATOM      6  C   PHE A   4       3.185   1.509   6.084  1.00  0.94           C
ATOM      7  N   PHE A   4       4.852   0.121   7.242  1.00  0.88           N
ATOM      8  O   PHE A   4       2.361   2.421   6.010  1.00  1.47           O
ATOM      9  CA  LEU A   5       3.055   1.059   3.693  1.00  0.87           C
ATOM     10  CB  LEU A   5       3.965   0.435   2.634  1.00  1.13           C
ATOM     11  C   LEU A   5       1.634   0.527   3.541  1.00  0.87           C
ATOM     12  N   LEU A   5       3.576   0.800   5.030  1.00  0.92           N
ATOM     13  O   LEU A   5       1.246  -0.440   4.196  1.00  1.23           O
"""

    pdb_inp = iotbx.pdb.input(
        lines=flex.split_lines(pdbstring), source_info=None)

    sites_cart = pdb_inp.atoms().extract_xyz()

# TRANS    phi      1 C      2 N      2 CA     2 C        60.00  20.0 3
# TRANS    psi      1 N      1 CA     1 C      2 N       160.00  30.0 2

    dihedral_proxies = geometry_restraints.shared_dihedral_proxy()

    # residue 1
    psi = geometry_restraints.dihedral_proxy(
        i_seqs=[3, 0, 1, 7],
        angle_ideal=160.0,
        weight=1/30.0**2,
        periodicity=3
        )
    dihedral_proxies.append(psi)

    # residue 2
    phi = geometry_restraints.dihedral_proxy(
        i_seqs=[1, 7, 4, 6],
        angle_ideal=60.0,
        weight=1/20.0**2,
        periodicity=3
        )
    dihedral_proxies.append(phi)

    psi = geometry_restraints.dihedral_proxy(
        i_seqs=[7, 4, 6, 8],
        angle_ideal=160.0,
        weight=1/30.0**2,
        periodicity=3
        )
    dihedral_proxies.append(psi)

    # residue 3
    phi = geometry_restraints.dihedral_proxy(
        i_seqs=[6, 12, 9, 11],
        angle_ideal=60.0,
        weight=1/20.0**2,
        periodicity=3
        )
    dihedral_proxies.append(phi)

    angle_proxies = geometry_restraints.shared_angle_proxy()

    ## Residue 1
    # a3
    a = geometry_restraints.angle_proxy(
        i_seqs=[3, 0, 1],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    # a7
    a = geometry_restraints.angle_proxy(
        i_seqs=[2, 1, 7],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    ## Residue 2
    # a1
    a = geometry_restraints.angle_proxy(
        i_seqs=[1, 7, 4],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    # a3
    a = geometry_restraints.angle_proxy(
        i_seqs=[7, 4, 6],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    # a7
    a = geometry_restraints.angle_proxy(
        i_seqs=[8, 6, 12],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    ## Residue 3
    # a1
    a = geometry_restraints.angle_proxy(
        i_seqs=[6, 12, 9],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    # a3
    a = geometry_restraints.angle_proxy(
        i_seqs=[12, 9, 11],
        angle_ideal=0,
        weight=1
        )
    angle_proxies.append(a)

    # compute dihedral
    #dihedral = geometry_restraints.dihedral(
    #    sites_cart=sites_cart,
    #    proxy=dihedral_proxies[0])

    # Shows real dihedral value
    #print dihedral.angle_model, dihedral.delta
    cfd_list = []

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='GLY',
        next_residue_name='PHE',
        conformation_proxies=None,
        i_phi_proxy=None, # index into dihedral_proxies
        i_psi_proxy=0,
        i_dynamic_angles=[None, None, 0, None, None, None, 1], # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None
        )
    cfd_list.append(cfd)

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='PHE',
        next_residue_name='LEU',
        conformation_proxies=None,
        i_phi_proxy=1, # index into dihedral_proxies
        i_psi_proxy=2,
        i_dynamic_angles=[2, None, 3, None, None, None, 4], # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None
        )
    cfd_list.append(cfd)

    cfd = conformation_dependent_restraints.conformation_dependent_restraints(
        residue_name='LEU',
        next_residue_name=None,
        conformation_proxies=None,
        i_phi_proxy=3, # index into dihedral_proxies
        i_psi_proxy=None,
        i_dynamic_angles=[5, None, 6, None, None, None, None], # indexes into angles in angle_proxies
        i_dynamic_dihedrals=None
        )
    cfd_list.append(cfd)

    for x in range(1, 4):
        print
        print 'Starting cycle', x
        print
        for cfd in cfd_list:
            cfd.update_restraints(sites_cart, dihedral_proxies, angle_proxies)
Ejemplo n.º 9
0
def exercise_geometry_restraints_as_cif():
  quartz = xray.structure(
    crystal_symmetry=crystal.symmetry(
      (5.01,5.01,5.47,90,90,120), "P6222"),
    scatterers=flex.xray_scatterer([
      xray.scatterer("Si", (1/2.,1/2.,1/3.)),
      xray.scatterer("O", (0.197,-0.197,0.83333))]))
  bond_proxies = geometry_restraints.shared_bond_simple_proxy((
    geometry_restraints.bond_simple_proxy(
      i_seqs=[0,1],
      rt_mx_ji=sgtbx.rt_mx("x-y,x,z-2/3"),
      distance_ideal=1.6,
      weight=3.2),
    geometry_restraints.bond_simple_proxy(
      i_seqs=[0,1],
      distance_ideal=1.7,
      weight=1.8),
  ))
  dihedral_proxies = geometry_restraints.shared_dihedral_proxy((
    geometry_restraints.dihedral_proxy(
      i_seqs = [1,0,1,0],
      sym_ops = (sgtbx.rt_mx("1+y,1-x+y, z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("x-y,x,z-2/3"),
                 sgtbx.rt_mx("1-x,y-x,1/3-z")),
      angle_ideal=-30,
      weight=2),
    geometry_restraints.dihedral_proxy(
      i_seqs = [1,0,1,0],
      sym_ops = (sgtbx.rt_mx("1+y,1-x+y, z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3"),
                 sgtbx.rt_mx("x-y,x,1/3+z")),
      angle_ideal=90,
      weight=3),
  ))
  angle_proxies = geometry_restraints.shared_angle_proxy((
    geometry_restraints.angle_proxy(
      i_seqs = [1,0,1],
      sym_ops = (sgtbx.rt_mx("x-y,x,z-2/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3")),
      angle_ideal=103,
      weight=2),
    geometry_restraints.angle_proxy(
      i_seqs = [1,0,1],
      sym_ops = (sgtbx.rt_mx("y+1,-x+y+1,z-1/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-y,x-y,z-1/3")),
      angle_ideal=110,
      weight=5),
    geometry_restraints.angle_proxy(
      i_seqs = [0,1,0],
      sym_ops = (sgtbx.rt_mx("y,-x+y,z+2/3"),
                 sgtbx.rt_mx(),
                 sgtbx.rt_mx("-x+y,-x,z+1/3")),
      angle_ideal=150,
      weight=5),
  ))
  bond_similarity_proxies = geometry_restraints.shared_bond_similarity_proxy((
    geometry_restraints.bond_similarity_proxy(
      i_seqs=[(0,1),(0,1),(0,1)],
      sym_ops=(sgtbx.rt_mx("x-y,x,z-2/3"),
               sgtbx.rt_mx("-y,x-y,z-1/3"),
               sgtbx.rt_mx("y+1,-x+y+1,z-1/3")),
      weights=(1,1,1)),
  ))
  cif_block = iotbx.cif.model.block()
  iotbx.cif.restraints.add_to_cif_block(
    cif_block, quartz,
    bond_proxies=bond_proxies,
    angle_proxies=angle_proxies,
    dihedral_proxies=dihedral_proxies,
    bond_similarity_proxies=bond_similarity_proxies)
  s = StringIO()
  cif_block.show(out=s)
  assert not show_diff(s.getvalue(), """\
loop_
  _restr_distance_atom_site_label_1
  _restr_distance_atom_site_label_2
  _restr_distance_site_symmetry_2
  _restr_distance_target
  _restr_distance_target_weight_param
  _restr_distance_diff
  Si  O  2_554  1.6000  0.5590  -0.0160
  Si  O  1      1.7000  0.7454  -2.3838

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

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

loop_
  _restr_equal_distance_class_class_id
  _restr_equal_distance_class_target_weight_param
  _restr_equal_distance_class_average
  _restr_equal_distance_class_esd
  _restr_equal_distance_class_diff_max
  1  1.0000  1.6160  0.0000  0.0000

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

""")
def exercise(verbose=0):
  distance_ideal = 1.8
  default_vdw_distance = 3.6
  vdw_1_4_factor = 3.5/3.6
  sites_cart_manual = flex.vec3_double([
    (1,3,0), (2,3,0), (3,2,0), (3,1,0), (4,1,0), (3,4,0), (4,3,0), (5,3,0),
    (6,2,0), (7,2,0), (8,3,0), (7,4,0), (6,4,0), (7,5,0), (6,6,0), (8,6,0)])
  bond_proxies = geometry_restraints.bond_sorted_asu_proxies(asu_mappings=None)
  for i_seqs in [(0,1),(1,2),(2,3),(3,4),(1,5),(2,6),(5,6),
                 (6,7),(7,8),(8,9),(9,10),(10,11),(11,12),
                 (12,7),(11,13),(13,14),(14,15),(15,13)]:
    bond_proxies.process(geometry_restraints.bond_simple_proxy(
      i_seqs=i_seqs, distance_ideal=distance_ideal, weight=100))
  angle_proxies = geometry_restraints.shared_angle_proxy()
  for i_seqs,angle_ideal in [[(0,1,2),135],
                             [(0,1,5),135],
                             [(1,2,3),135],
                             [(3,2,6),135],
                             [(2,3,4),120],
                             [(1,2,6),90],
                             [(2,6,5),90],
                             [(6,5,1),90],
                             [(5,1,2),90],
                             [(2,6,7),135],
                             [(5,6,7),135],
                             [(6,7,8),120],
                             [(6,7,12),120],
                             [(7,8,9),120],
                             [(8,9,10),120],
                             [(9,10,11),120],
                             [(10,11,12),120],
                             [(11,12,7),120],
                             [(12,7,8),120],
                             [(10,11,13),120],
                             [(12,11,13),120],
                             [(11,13,15),150],
                             [(11,13,14),150],
                             [(13,15,14),60],
                             [(15,14,13),60],
                             [(14,13,15),60]]:
    angle_proxies.append(geometry_restraints.angle_proxy(
      i_seqs=i_seqs, angle_ideal=angle_ideal, weight=1))
  if (0 or verbose):
    dump_pdb(file_name="manual.pdb", sites_cart=sites_cart_manual)
  for traditional_convergence_test in [True,False]:
    for sites_cart_selection in [True, False]:
      sites_cart = sites_cart_manual.deep_copy()
      if sites_cart_selection:
        sites_cart_selection = flex.bool(sites_cart.size(), True)
        sites_cart_selection[1] = False
      assert bond_proxies.asu.size() == 0
      bond_params_table = geometry_restraints.extract_bond_params(
        n_seq=sites_cart.size(),
        bond_simple_proxies=bond_proxies.simple)
      manager = geometry_restraints.manager.manager(
        bond_params_table=bond_params_table,
        angle_proxies=angle_proxies)
      minimized = geometry_restraints.lbfgs.lbfgs(
        sites_cart=sites_cart,
        geometry_restraints_manager=manager,
        lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
          traditional_convergence_test=traditional_convergence_test,
          drop_convergence_test_max_drop_eps=1.e-20,
          drop_convergence_test_iteration_coefficient=1,
          max_iterations=1000),
        sites_cart_selection=sites_cart_selection,
        )
      assert minimized.minimizer.iter() > 100
      sites_cart_minimized_1 = sites_cart.deep_copy()
      if (0 or verbose):
        dump_pdb(
          file_name="minimized_1.pdb", sites_cart=sites_cart_minimized_1)
      bond_deltas = geometry_restraints.bond_deltas(
        sites_cart=sites_cart_minimized_1,
        proxies=bond_proxies.simple)
      angle_deltas = geometry_restraints.angle_deltas(
        sites_cart=sites_cart_minimized_1,
        proxies=angle_proxies)
      if (0 or verbose):
        for proxy,delta in zip(bond_proxies.simple, bond_deltas):
          print "bond:", proxy.i_seqs, delta
        for proxy,delta in zip(angle_proxies, angle_deltas):
          print "angle:", proxy.i_seqs, delta
      assert is_below_limit(
        value=flex.max(flex.abs(bond_deltas)), limit=0, eps=1.e-6)
      assert is_below_limit(
        value=flex.max(flex.abs(angle_deltas)), limit=0, eps=2.e-6)
  sites_cart += matrix.col((1,1,0)) - matrix.col(sites_cart.min())
  unit_cell_lengths = list(  matrix.col(sites_cart.max())
                           + matrix.col((1,-1.2,4)))
  unit_cell_lengths[1] *= 2
  unit_cell_lengths[2] *= 2
  xray_structure = xray.structure(
    crystal_symmetry=crystal.symmetry(
      unit_cell=unit_cell_lengths,
      space_group_symbol="P112"))
  for serial,site in zip(count(1), sites_cart):
    xray_structure.add_scatterer(xray.scatterer(
      label="C%02d"%serial,
      site=xray_structure.unit_cell().fractionalize(site)))
  if (0 or verbose):
    xray_structure.show_summary().show_scatterers()
  p1_structure = (xray_structure
    .apply_shift((-.5,-.5,0))
    .expand_to_p1()
    .apply_shift((.5,.5,0)))
  for shift in [(1,0,0), (0,1,0), (0,0,1)]:
    p1_structure.add_scatterers(p1_structure.apply_shift(shift).scatterers())
  if (0 or verbose):
    open("p1_structure.pdb", "w").write(p1_structure.as_pdb_file())
  nonbonded_cutoff = 6.5
  asu_mappings = xray_structure.asu_mappings(
    buffer_thickness=nonbonded_cutoff)
  bond_asu_table = crystal.pair_asu_table(asu_mappings=asu_mappings)
  geometry_restraints.add_pairs(bond_asu_table, bond_proxies.simple)
  shell_asu_tables = crystal.coordination_sequences.shell_asu_tables(
    pair_asu_table=bond_asu_table,
    max_shell=3)
  shell_sym_tables = [shell_asu_table.extract_pair_sym_table()
    for shell_asu_table in shell_asu_tables]
  bond_params_table = geometry_restraints.extract_bond_params(
    n_seq=sites_cart.size(),
    bond_simple_proxies=bond_proxies.simple)
  atom_energy_types = flex.std_string(sites_cart.size(), "Default")
  nonbonded_params = geometry_restraints.nonbonded_params(
    factor_1_4_interactions=vdw_1_4_factor,
    const_shrink_1_4_interactions=0,
    default_distance=default_vdw_distance)
  nonbonded_params.distance_table.setdefault(
    "Default")["Default"] = default_vdw_distance
  pair_proxies = geometry_restraints.pair_proxies(
    bond_params_table=bond_params_table,
    shell_asu_tables=shell_asu_tables,
    model_indices=None,
    conformer_indices=None,
    nonbonded_params=nonbonded_params,
    nonbonded_types=atom_energy_types,
    nonbonded_distance_cutoff_plus_buffer=nonbonded_cutoff)
  if (0 or verbose):
    print "pair_proxies.bond_proxies.n_total():", \
           pair_proxies.bond_proxies.n_total(),
    print "simple:", pair_proxies.bond_proxies.simple.size(),
    print "sym:", pair_proxies.bond_proxies.asu.size()
    print "pair_proxies.nonbonded_proxies.n_total():", \
           pair_proxies.nonbonded_proxies.n_total(),
    print "simple:", pair_proxies.nonbonded_proxies.simple.size(),
    print "sym:", pair_proxies.nonbonded_proxies.asu.size()
    print "min_distance_nonbonded: %.2f" % flex.min(
      geometry_restraints.nonbonded_deltas(
        sites_cart=sites_cart,
        sorted_asu_proxies=pair_proxies.nonbonded_proxies))
  s = StringIO()
  pair_proxies.bond_proxies.show_histogram_of_model_distances(
    sites_cart=sites_cart,
    f=s,
    prefix="[]")
  assert s.getvalue().splitlines()[0] == "[]Histogram of bond lengths:"
  assert s.getvalue().splitlines()[5].startswith("[]      1.80 -     1.80:")
  s = StringIO()
  pair_proxies.bond_proxies.show_histogram_of_deltas(
    sites_cart=sites_cart,
    f=s,
    prefix="][")
  assert s.getvalue().splitlines()[0] == "][Histogram of bond deltas:"
  assert s.getvalue().splitlines()[5].startswith("][     0.000 -    0.000:")
  s = StringIO()
  pair_proxies.bond_proxies.show_sorted(
    by_value="residual",
    sites_cart=sites_cart,
    max_items=3,
    f=s,
    prefix=":;")
  l = s.getvalue().splitlines()
  assert l[0] == ":;Bond restraints: 18"
  assert l[1] == ":;Sorted by residual:"
  assert l[2].startswith(":;bond ")
  assert l[3].startswith(":;     ")
  assert l[4] == ":;  ideal  model  delta    sigma   weight residual"
  for i in [5,-2]:
    assert l[i].startswith(":;  1.800  1.800 ")
  assert l[-1] == ":;... (remaining 15 not shown)"
  s = StringIO()
  pair_proxies.nonbonded_proxies.show_histogram_of_model_distances(
    sites_cart=sites_cart,
    f=s,
    prefix="]^")
  assert not show_diff(s.getvalue(), """\
]^Histogram of nonbonded interaction distances:
]^      2.16 -     3.03: 3
]^      3.03 -     3.89: 12
]^      3.89 -     4.75: 28
]^      4.75 -     5.61: 44
]^      5.61 -     6.48: 54
""")
  s = StringIO()
  pair_proxies.nonbonded_proxies.show_sorted(
    by_value="delta",
    sites_cart=sites_cart,
    max_items=7,
    f=s,
    prefix=">,")
  assert not show_diff(s.getvalue(), """\
>,Nonbonded interactions: 141
>,Sorted by model distance:
>,nonbonded 15
>,          15
>,   model   vdw sym.op.
>,   2.164 3.600 -x+2,-y+1,z
...
>,nonbonded 4
>,          8
>,   model   vdw
>,   3.414 3.600
>,... (remaining 134 not shown)
""",
    selections=[range(6), range(-5,0)])
  vdw_1_sticks = []
  vdw_2_sticks = []
  for proxy in pair_proxies.nonbonded_proxies.simple:
    if (proxy.vdw_distance == default_vdw_distance):
      vdw_1_sticks.append(pml_stick(
        begin=sites_cart[proxy.i_seqs[0]],
        end=sites_cart[proxy.i_seqs[1]]))
    else:
      vdw_2_sticks.append(pml_stick(
        begin=sites_cart[proxy.i_seqs[0]],
        end=sites_cart[proxy.i_seqs[1]]))
  mps = asu_mappings.mappings()
  for proxy in pair_proxies.nonbonded_proxies.asu:
    if (proxy.vdw_distance == default_vdw_distance):
      vdw_1_sticks.append(pml_stick(
        begin=mps[proxy.i_seq][0].mapped_site(),
        end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
    else:
      vdw_2_sticks.append(pml_stick(
        begin=mps[proxy.i_seq][0].mapped_site(),
        end=mps[proxy.j_seq][proxy.j_sym].mapped_site()))
  if (0 or verbose):
    pml_write(f=open("vdw_1.pml", "w"), label="vdw_1", sticks=vdw_1_sticks)
    pml_write(f=open("vdw_2.pml", "w"), label="vdw_2", sticks=vdw_2_sticks)
  #
  i_pdb = count(2)
  for use_crystal_symmetry in [False, True]:
    if (not use_crystal_symmetry):
      crystal_symmetry = None
      site_symmetry_table = None
    else:
      crystal_symmetry = xray_structure
      site_symmetry_table = xray_structure.site_symmetry_table()
    for sites_cart in [sites_cart_manual.deep_copy(),
                       sites_cart_minimized_1.deep_copy()]:
      manager = geometry_restraints.manager.manager(
        crystal_symmetry=crystal_symmetry,
        site_symmetry_table=site_symmetry_table,
        nonbonded_params=nonbonded_params,
        nonbonded_types=atom_energy_types,
        nonbonded_function=geometry_restraints.prolsq_repulsion_function(),
        bond_params_table=bond_params_table,
        shell_sym_tables=shell_sym_tables,
        nonbonded_distance_cutoff=nonbonded_cutoff,
        nonbonded_buffer=1,
        angle_proxies=angle_proxies,
        plain_pairs_radius=5)
      manager = manager.select(selection=flex.bool(sites_cart.size(), True))
      manager = manager.select(
        iselection=flex.size_t_range(stop=sites_cart.size()))
      pair_proxies = manager.pair_proxies(sites_cart=sites_cart)
      minimized = geometry_restraints.lbfgs.lbfgs(
        sites_cart=sites_cart,
        geometry_restraints_manager=manager,
        lbfgs_termination_params=scitbx.lbfgs.termination_parameters(
          max_iterations=1000))
      if (0 or verbose):
        minimized.final_target_result.show()
        print "number of function evaluations:", minimized.minimizer.nfun()
        print "n_updates_pair_proxies:", manager.n_updates_pair_proxies
      if (not use_crystal_symmetry):
        assert minimized.final_target_result.bond_residual_sum < 1.e-3
        assert minimized.final_target_result.nonbonded_residual_sum < 0.1
      else:
        assert minimized.final_target_result.bond_residual_sum < 1.e-2
        assert minimized.final_target_result.nonbonded_residual_sum < 0.1
      assert minimized.final_target_result.angle_residual_sum < 1.e-3
      if (0 or verbose):
        pdb_file_name = "minimized_%d.pdb" % i_pdb.next()
        print "Writing file:", pdb_file_name
        dump_pdb(file_name=pdb_file_name, sites_cart=sites_cart)
      if (manager.site_symmetry_table is None):
        additional_site_symmetry_table = None
      else:
        additional_site_symmetry_table = sgtbx.site_symmetry_table()
      assert manager.new_including_isolated_sites(
        n_additional_sites=0,
        site_symmetry_table=additional_site_symmetry_table,
        nonbonded_types=flex.std_string()).plain_pairs_radius \
          == manager.plain_pairs_radius
      if (crystal_symmetry is not None):
        assert len(manager.plain_pair_sym_table) == 16
        if (0 or verbose):
          manager.plain_pair_sym_table.show()
  #
  xray_structure.set_u_iso(values=flex.double([
    0.77599982480241358, 0.38745781137212021, 0.20667558236418682,
    0.99759840171302094, 0.8917287406687805, 0.64780251325379845,
    0.24878590382983534, 0.59480621182194615, 0.58695637792905142,
    0.33997130213653637, 0.51258699130743735, 0.79760289141276675,
    0.39996577657875021, 0.4329328819341467, 0.70422156561726479,
    0.87260110626999332]))
  class parameters: pass
  parameters.sphere_radius = 5
  parameters.distance_power = 0.7
  parameters.average_power = 0.9
  parameters.wilson_b_weight = 1.3952
  parameters.wilson_b_weight_auto = False
  adp_energies = adp_restraints.energies_iso(
    geometry_restraints_manager=manager,
    xray_structure=xray_structure,
    parameters=parameters,
    wilson_b=None,
    use_hd=False,
    use_u_local_only = False,
    compute_gradients=False,
    gradients=None,
    normalization=False,
    collect=True)
  assert adp_energies.number_of_restraints == 69
  assert approx_equal(adp_energies.residual_sum, 6.24865382467)
  assert adp_energies.gradients is None
  assert adp_energies.u_i.size() == adp_energies.number_of_restraints
  assert adp_energies.u_j.size() == adp_energies.number_of_restraints
  assert adp_energies.r_ij.size() == adp_energies.number_of_restraints
  for wilson_b in [None, 10, 100]:
    finite_difference_gradients = flex.double()
    eps = 1.e-6
    for i_scatterer in xrange(xray_structure.scatterers().size()):
      rs = []
      for signed_eps in [eps, -eps]:
        xray_structure_eps = xray_structure.deep_copy_scatterers()
        xray_structure_eps.scatterers()[i_scatterer].u_iso += signed_eps
        adp_energies = adp_restraints.energies_iso(
          geometry_restraints_manager=manager,
          xray_structure=xray_structure_eps,
          parameters=parameters,
          wilson_b=wilson_b,
          use_u_local_only = False,
          use_hd=False,
          compute_gradients=True,
          gradients=None,
          normalization=False,
          collect=False)
        rs.append(adp_energies.residual_sum)
        assert adp_energies.gradients.size() \
            == xray_structure.scatterers().size()
        assert adp_energies.u_i == None
        assert adp_energies.u_j == None
        assert adp_energies.r_ij == None
      finite_difference_gradients.append((rs[0]-rs[1])/(2*eps))
    sel = flex.bool(xray_structure.scatterers().size(), True)
    xray_structure.scatterers().flags_set_grad_u_iso(sel.iselection())
    adp_energies = adp_restraints.energies_iso(
      geometry_restraints_manager=manager,
      xray_structure=xray_structure,
      parameters=parameters,
      wilson_b=wilson_b,
      use_u_local_only = False,
      use_hd=False,
      compute_gradients=True,
      gradients=None,
      normalization=False,
      collect=False)
    assert approx_equal(adp_energies.gradients, finite_difference_gradients)
  print "OK"