Ejemplo n.º 1
0
def exercise_basic():
    t = ramachandran.load_tables()["ala"]
    assert approx_equal(t.get_score(0.0, 0.0), -26.16, eps=0.01)
    assert approx_equal(t.get_score(-60, 120), 10.41, eps=0.01)
    assert approx_equal(t.get_score(90, 90), -7.43, eps=0.01)
    assert approx_equal(t.get_energy(0.0, 0.0), 53.81, eps=0.01)
    assert approx_equal(t.get_energy(-60, 120), 17.24, eps=0.01)
    e1 = t.get_energy(-85.0, 85.0)
    e2 = t.get_energy(-85.000001, 85.000001)
    assert approx_equal(e1, e2, eps=0.000001)
    assert approx_equal(t.get_energy(-85.0, 86.0), 21.3345, eps=0.001)
    assert approx_equal(t.get_energy(-86.0, 85.0), 21.389, eps=0.001)
    ext = bp.import_ext("mmtbx_ramachandran_restraints_ext")
    proxies = ext.shared_phi_psi_proxy()
    proxies.append(
        ext.phi_psi_proxy(i_seqs=[0, 1, 2, 3, 4],
                          residue_type="general",
                          weight=1))
    proxies.append(
        ext.phi_psi_proxy(i_seqs=[4, 5, 6, 7, 8],
                          residue_type="pre-proline",
                          weight=1))
    proxies.append(
        ext.phi_psi_proxy(i_seqs=[8, 9, 10, 11, 12],
                          residue_type="general",
                          weight=1))
    selected = proxies.proxy_select(n_seq=13, iselection=flex.size_t(range(9)))
    assert (selected.size() == 2)
    assert list(selected[0].get_i_seqs()) == [0, 1, 2, 3, 4]
    assert selected[0].residue_type == "general"
    assert list(selected[1].get_i_seqs()) == [4, 5, 6, 7, 8]
    assert selected[1].residue_type == "pre-proline"
Ejemplo n.º 2
0
def add_coordinate_restraints(
      sites_cart,
      selection=None,
      sigma=0.5,
      limit=1.0,
      top_out_potential=False):
  import boost_adaptbx.boost.python as bp
  ext_rcp = bp.import_ext("mmtbx_reference_coordinate_ext")
  result = ext_rcp.shared_reference_coordinate_proxy()
  if (selection is not None):
    if (isinstance(selection, flex.bool)):
      selection = selection.iselection()
  if selection is None:
    selection = flex.bool(
      len(sites_cart),
      True).iselection()
  # Not clear why this assertion should present. What if we want to restrain
  # only part of the molecule?
  assert len(sites_cart) == len(selection)
  weight = 1.0 / (sigma**2)
  for k, i_seq in enumerate(selection):
    i_seqs = [i_seq]
    ref_sites = sites_cart[k]
    proxy = ext_rcp.reference_coordinate_proxy(
              i_seqs=i_seqs,
              ref_sites=ref_sites,
              weight=weight,
              limit=limit,
              top_out=top_out_potential)
    result.append(proxy)
  return result
Ejemplo n.º 3
0
def real_to_complex_3d_in_place(data):
    import boost_adaptbx.boost.python as bp
    ext = bp.import_ext("cudatbx_cufft_ext")
    real_type = type(data).__name__
    if (real_type == "double"):
        return ext.real_to_complex_3d_in_place_dp(data)
    else:
        assert (real_type == "float")
        return ext.real_to_complex_3d_in_place_sp(data)
Ejemplo n.º 4
0
def complex_to_real_3d_in_place(data, n):
    import boost_adaptbx.boost.python as bp
    ext = bp.import_ext("cudatbx_cufft_ext")
    complex_type = type(data).__name__
    if (complex_type == "complex_double"):
        return ext.complex_to_real_3d_in_place_dp(data, n)
    else:
        assert (complex_type == "complex_float")
        return ext.complex_to_real_3d_in_place_sp(data, n)
Ejemplo n.º 5
0
def get_map_from_map(map_file_object, params, xrs, log):
  print("Processing input CCP4 map file...", file=log)
  map_data = map_file_object.file_content.map_data()
  try:
    # map_cs = map_content.file_object.crystal_symmetry()
    map_cs = map_file_object.crystal_symmetry()
  except NotImplementedError as e:
    pass
  print("Input map min,max,mean: %7.3f %7.3f %7.3f"%\
      map_data.as_1d().min_max_mean().as_tuple(), file=log)
  if map_cs.space_group().type().number() not in [0,1]:
    print(map_cs.space_group().type().number())
    raise Sorry("Only P1 group for maps is supported.")
  map_data = map_data - flex.mean(map_data)
  sd = map_data.sample_standard_deviation()
  map_data = map_data/sd
  print("Rescaled map min,max,mean: %7.3f %7.3f %7.3f"%\
    map_data.as_1d().min_max_mean().as_tuple(), file=log)
  map_file_object.file_content.show_summary(prefix="  ")
  shift_manager = mmtbx.utils.extract_box_around_model_and_map(
      xray_structure = xrs,
      map_data       = map_data.deep_copy(),
      box_cushion    = 5)
  sys.stdout.flush()
  xray_structure = shift_manager.xray_structure_box
  crystal_symmetry = xray_structure.crystal_symmetry()
  map_data = shift_manager.map_box

  if params.mask_and_he_map:
    print("Masking and histogram equalizing...", file=log)
    import boost_adaptbx.boost.python as bp
    cctbx_maptbx_ext = bp.import_ext("cctbx_maptbx_ext")
    xrs_p1 = xray_structure.expand_to_p1(sites_mod_positive=True)
    radii = flex.double(xrs_p1.scatterers().size(), 5.0)
    mask = cctbx_maptbx_ext.mask(
      sites_frac                  = xrs_p1.sites_frac(),
      unit_cell                   = xrs_p1.unit_cell(),
      n_real                      = map_data.all(),
      mask_value_inside_molecule  = 1,
      mask_value_outside_molecule = 0,
      radii                       = radii)
    map_data = mask*map_data
    from phenix.command_line.real_space_refine import write_ccp4_map
    write_ccp4_map(o=xray_structure.crystal_symmetry(), file_name="junk_mask.map",
     map_data=mask)
    del mask
    map_data = maptbx.volume_scale(map = map_data, n_bins = 10000).map_data()
    write_ccp4_map(o=xray_structure.crystal_symmetry(), file_name="junk_map.map",
     map_data=map_data)
  return map_data, map_cs, shift_manager
Ejemplo n.º 6
0
Archivo: dssp.py Proyecto: dials/cctbx
 def process_o_n_interaction(self, o_atom, n_atom):
     import boost_adaptbx.boost.python as bp
     ext = bp.import_ext("mmtbx_dssp_ext")
     energy = ext.get_o_n_hbond_energy(O=o_atom, N=n_atom)
     # TODO incorporate angle filtering - need to ask Jane and/or look at
     # Reduce source code for ideas
     #angle = hbond_base_angle(
     #  c_xyz=c_xyz,
     #  h_xyz=h_xyz,
     #  o_xyz=col(o_atom.xyz),
     #  n_xyz=col(n_atom.xyz))
     if (energy is not None) and (energy < self.params.energy_cutoff):
         return hbond(residue1=o_atom.parent(),
                      residue2=n_atom.parent(),
                      energy=energy)
     return None
def exercise_1():
    pdb_in = simple_pdb()
    pdb_hierarchy = pdb_in.construct_hierarchy()
    sites_cart = pdb_hierarchy.atoms().extract_xyz()

    proxies = reference.add_coordinate_restraints(sites_cart=sites_cart)
    assert proxies.size() == 29, "expected 29, got %d" % proxies.size()
    import boost_adaptbx.boost.python as bp
    ext = bp.import_ext("mmtbx_reference_coordinate_ext")
    grads = flex.vec3_double(sites_cart.size(), (0.0, 0.0, 0.0))
    residual = ext.reference_coordinate_residual_sum(sites_cart=sites_cart,
                                                     proxies=proxies,
                                                     gradient_array=grads)
    assert approx_equal(residual, 0.0)

    #test selection
    ca_selection = pdb_hierarchy.get_peptide_c_alpha_selection()
    ca_sites_cart = sites_cart.select(ca_selection)
    proxies = reference.add_coordinate_restraints(sites_cart=ca_sites_cart,
                                                  selection=ca_selection)
    assert proxies.size() == 3, "expected 3, got %d" % proxies.size()
    tst_iselection = flex.size_t()
    for atom in pdb_hierarchy.atoms():
        if atom.name == " CA " or atom.name == " N  ":
            tst_iselection.append(atom.i_seq)
    tst_sites_cart = sites_cart.select(tst_iselection)
    proxies = reference.add_coordinate_restraints(sites_cart=tst_sites_cart,
                                                  selection=tst_iselection)
    assert proxies.size() == 6, "expected 6, got %d" % proxies.size()

    #test remove
    selection = flex.bool([False] * 29)
    proxies = proxies.proxy_remove(selection=selection)
    assert proxies.size() == 6, "expected 6, got %d" % proxies.size()
    proxies = proxies.proxy_remove(selection=ca_selection)
    assert proxies.size() == 3, "expected 3, got %d" % proxies.size()
    selection = flex.bool([True] * 29)
    proxies = proxies.proxy_remove(selection=selection)
    assert proxies.size() == 0, "expected 0, got %d" % proxies.size()
Ejemplo n.º 8
0
from __future__ import absolute_import, division, print_function
import six
import sys, time
import mmtbx.model
import iotbx.pdb
import boost_adaptbx.boost.python as bp
from libtbx.utils import null_out
from libtbx import group_args
from cctbx.array_family import flex
from mmtbx.ligands.ready_set_utils import add_n_terminal_hydrogens_to_residue_group
from cctbx.geometry_restraints.linking_class import linking_class
#
from cctbx.maptbx.box import shift_and_box_model

ext = bp.import_ext("cctbx_geometry_restraints_ext")
get_class = iotbx.pdb.common_residue_names_get_class
# For development
print_time = False

# ==============================================================================


def mon_lib_query(residue, mon_lib_srv):
    md, ani = mon_lib_srv.get_comp_comp_id_and_atom_name_interpretation(
        residue_name=residue.resname,
        atom_names=residue.atoms().extract_name())
    return md


# ==============================================================================
Ejemplo n.º 9
0
from __future__ import absolute_import, division, print_function
import scitbx.array_family.flex
from scitbx.array_family import flex

import boost_adaptbx.boost.python as bp
from six import string_types
from six.moves import zip
from six.moves import range
ext = bp.import_ext("mmtbx_alignment_ext")
"""
Written by Tom Ioerger (http://faculty.cs.tamu.edu/ioerger).
Originally in Python, Oleg Sobolev moved to C++ for better performance.
Send comments or suggestions to: [email protected]

This implementation provides algorithms for aligning two protein
sequences, where each sequence is represented as a string of one-letter
amino-acid codes. The implementation is based on the ideas of Gotoh
(1982) and runs in quadratic time O(M*N), where M and N are the
sequence lengths. It does both global (Needleman & Wunsch, 1970) and
local (Smith & Waterman, 1981) alignments, assuming affine (linear) gap
penalties (for which default gap-cost parameters may be changed by the
user). Alignments are based on maximizing similarity. Similarity scores
between amino acids are specified via symmetric matrices. Similarity
matrices of Dayhoff (1978) and BLOSUM50 (Henikoff & Henikoff (1992),
http://en.wikipedia.org/wiki/BLOSUM) are provided. User-supplied
matrices are also supported (this feature also enables alignment of
non-amino-acid sequences).

Dayhoff, M.O. (1978).
Atlas of Protein Sequence and Structure, Vol. 5 suppl. 3, 345-352.
Ejemplo n.º 10
0
""" Weighting schemes.

They all feature:

  o __str__: a string representation of the weighting scheme in a format
             that is appropriate for the CIF item _refine_ls_weighting_details;

  o type: the kind of weighting scheme,
          that is appropriate for the CIF item _refine_ls_weighting_scheme
"""


from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
from six.moves import range
ext = bp.import_ext("smtbx_refinement_least_squares_ext")


from cctbx.array_family import flex

import math


@bp.inject_into(ext.mainstream_shelx_weighting)
class _():

  def __str__(self):
    if round(self.a, 4) in (0.1, 0.2):
      a = "%.1f" %self.a
    else:
      a = "%.4f" %self.a
Ejemplo n.º 11
0
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp

ext = bp.import_ext("rwgk_tbx_smart_ptr_private_first_base_ext")
from rwgk_tbx_smart_ptr_private_first_base_ext import *
Ejemplo n.º 12
0
#
# Use the FindExtraAtomInfo() function to get an ExtraAtomInfo structure filled
# based on a specific atom along with a second tuple value that has a list of all
# information in the table for that atom.

from __future__ import print_function, nested_scopes, generators, division
from __future__ import absolute_import, unicode_literals
import sys
import re
import iotbx
from iotbx.map_model_manager import map_model_manager
from iotbx.data_manager import DataManager
import mmtbx

import boost_adaptbx.boost.python as bp
bp.import_ext("mmtbx_probe_ext")
import mmtbx_probe_ext as probe

##################################################################################
# Helper functions.

# Pad the name with spaces on the right to ensure that it is at least as long as
# requested.
def Pad(s, n=4):
  ret = s
  while len(s) < n:
    s += ' '
  return ret

# Gobble up all spaces from the end of the name after non-space characters
def Unpad(n):
Ejemplo n.º 13
0
from __future__ import division
import os
import time
import math
import libtbx.load_env
from scitbx.array_family import flex
from libtbx import easy_pickle
from libtbx.utils import Sorry

import boost_adaptbx.boost.python as bp
ext = bp.import_ext("mmtbx_pair_interaction_ext")

dat_path = libtbx.env.find_in_repositories("qrefine")
qr_unit_tests_data = None
if(dat_path is not None):
  qr_unit_tests_data = os.path.join(dat_path,"tests","unit","data_files")

A2B=1.8897259885789
global results
results=[]
global mol_pair_has_interaction
mol_pair_has_interaction=[]

global wave_functions
wave_functions = []

def load_wfc(element):
  element = element.lower()
  folder = libtbx.env.find_in_repositories("mmtbx/pair_interaction")
  for fn in os.listdir(folder):
    if(fn.startswith(element) and fn.endswith(".pkl")):
Ejemplo n.º 14
0
Archivo: dmtbx.py Proyecto: dials/cctbx
from __future__ import absolute_import, division, print_function
import cctbx.array_family.flex  # import dependency

import boost_adaptbx.boost.python as bp
ext = bp.import_ext("cctbx_dmtbx_ext")
from cctbx_dmtbx_ext import *


@bp.inject_into(weighted_triplet_phase_relation)
class _():
    def format(self, miller_indices, ih=None):
        l = [
            miller_indices[self.ik()],
            self.friedel_flag_k(), miller_indices[self.ihmk()],
            self.friedel_flag_hmk(),
            self.ht_sum(),
            self.weight()
        ]
        if (ih is not None):
            l.insert(0, miller_indices[ih])
        return " ".join([str(item).replace(" ", "") for item in l])


def triplet_generator(miller_set,
                      amplitudes=None,
                      max_relations_per_reflection=0,
                      sigma_2_only=False,
                      discard_weights=False):
    return ext.triplet_generator(miller_set.space_group(),
                                 miller_set.indices(), amplitudes,
                                 max_relations_per_reflection, sigma_2_only,
Ejemplo n.º 15
0
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
import cctbx.uctbx  # possibly implicit
ext = bp.import_ext("simtbx_kokkos_ext")
from simtbx_kokkos_ext import *
Ejemplo n.º 16
0
from __future__ import absolute_import, division, print_function
from cctbx.array_family import flex  # for tuple mappings

import boost_adaptbx.boost.python as bp
ext = bp.import_ext("cctbx_multipolar_ext")
from cctbx_multipolar_ext import *
Ejemplo n.º 17
0
from __future__ import absolute_import, division, print_function

import boost_adaptbx.boost.python as bp
from functools import reduce
ext = bp.import_ext("boost_adaptbx_graph_maximum_clique_ext")
import operator

rascal = ext.rascal
greedy = ext.greedy
bron_kerbosch_all_cliques = ext.bron_kerbosch_all_cliques


def compatibility_graph(
    first,
    second,
    vertex_equality=operator.eq,
    edge_equality=operator.eq,
    output_graph_vertex="vector",
    output_graph_edge="vector",
):

    from boost_adaptbx import graph
    result = graph.adjacency_list(
        graph_type="undirected",
        vertex_type=output_graph_vertex,
        edge_type=output_graph_edge,
    )
    vertex_from = {}

    import itertools
Ejemplo n.º 18
0
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp

bp.import_ext("scitbx_wigner_ext")
from scitbx_wigner_ext import *
Ejemplo n.º 19
0
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
import cctbx.uctbx  # possibly implicit
ext = bp.import_ext("simtbx_pixel_ext")
from simtbx_pixel_ext import *
Ejemplo n.º 20
0
import boost_adaptbx.boost.python as bp

ext = bp.import_ext("tntbx_ext")
from tntbx_ext import *

from scitbx.array_family import flex


class svd(object):
    def __init__(self, m):
        self.n_rows, self.n_columns = m.focus()
        assert self.n_rows > 0
        assert self.n_columns > 0
        if (self.n_rows < self.n_columns):
            m = m.matrix_transpose()
        self.svd_m_ge_n = svd_m_ge_n_double(m=m)

    def singular_values(self):
        result = self.svd_m_ge_n.singular_values()
        if (self.n_rows < self.n_columns):
            result.resize(self.n_columns, 0)
        return result

    def s(self):
        s = self.svd_m_ge_n.s()
        if (self.n_rows < self.n_columns):
            result = flex.double(flex.grid(self.n_columns, self.n_columns), 0)
            result.matrix_paste_block_in_place(block=s, i_row=0, i_column=0)
        return s

    def u(self):
Ejemplo n.º 21
0
from __future__ import absolute_import, division, print_function
import libtbx.load_env
import iotbx.phil
from libtbx import adopt_init_args
import sys
import os, math
import boost_adaptbx.boost.python as bp
from scitbx.array_family import flex
from mmtbx.validation import ramalyze
from mmtbx.conformation_dependent_library import generate_protein_threes
from six.moves import range
from collections import OrderedDict
from mmtbx.rotamer import ramachandran_eval

ext = bp.import_ext("mmtbx_ramachandran_restraints_ext")
from mmtbx_ramachandran_restraints_ext import lookup_table, \
    ramachandran_residual_sum, phi_psi_targets

ext2 = bp.import_ext("mmtbx_validation_ramachandran_ext")
from mmtbx_validation_ramachandran_ext import rama_eval

old_master_phil = iotbx.phil.parse("""
  rama_weight = 1.0
    .type = float
    .short_caption = Ramachandran gradients weight
    .expert_level = 1
    .style = hidden
  scale_allowed = 1.0
    .type = float
    .short_caption = Rescale allowed region pseudo-energy by
    .style = hidden
Ejemplo n.º 22
0
from __future__ import absolute_import, division, print_function
from scitbx.lstbx import normal_eqns  # import dependency
import boost_adaptbx.boost.python as bp
ext = bp.import_ext("xes_ext")
from xes_ext import *
Ejemplo n.º 23
0
from __future__ import absolute_import, division, print_function

import boost_adaptbx.boost.python as bp
from boost_adaptbx.boost.python import streambuf, ostream
from six.moves import range
ext = bp.import_ext("boost_adaptbx_python_streambuf_test_ext")
import StringIO
import cStringIO
from libtbx.test_utils import Exception_expected
from libtbx.option_parser import option_parser
import libtbx.object_oriented_patterns as oop
import os


class file_object_debug_proxy(oop.proxy):

  def __init__(self, *args, **kwds):
    super(file_object_debug_proxy, self).__init__(*args, **kwds)
    self.seek_call_log = []
    self.write_call_log = []

  def seek(self, off, mode):
    self.seek_call_log.append((off, mode))
    self.subject.seek(off, mode)

  def write(self, s):
    self.write_call_log.append(s)
    self.subject.write(s)


class io_test_case(object):
Ejemplo n.º 24
0
from __future__ import absolute_import, division, print_function
from six.moves import range
import spotfinder.array_family.flex  # implicit import

import boost_adaptbx.boost.python as bp

ext = bp.import_ext("spotfinder_dxtbx_ext")
from spotfinder_dxtbx_ext import *

from libtbx import adopt_init_args


class Distl:
    def __init__(self, params, detector, beam, data):
        adopt_init_args(self, locals())

        npanels = len(detector)
        self.finderlist = []
        for n in range(npanels):
            SF = w_Distl(optionstring="", report_overloads=False)

            panel = detector[n]

            saturation = panel.get_trusted_range()[1]

            SF.setspotimg(panel=panel,
                          beam=beam,
                          rawdata=data,
                          peripheral_margin=params.distl.peripheral_margin,
                          saturation=saturation)
Ejemplo n.º 25
0
from __future__ import absolute_import, division, print_function
from cctbx.array_family import flex
from scitbx import matrix
import math
from libtbx import adopt_init_args
import scitbx.lbfgs
from mmtbx.bulk_solvent import kbu_refinery
from cctbx import maptbx
import mmtbx.masks
import boost_adaptbx.boost.python as bp

asu_map_ext = bp.import_ext("cctbx_asymmetric_map_ext")
from libtbx import group_args
from mmtbx import bulk_solvent
from mmtbx.ncs import tncs
from collections import OrderedDict
import mmtbx.f_model
import sys
from libtbx.test_utils import approx_equal

from mmtbx import masks
from cctbx.masks import vdw_radii_from_xray_structure

ext = bp.import_ext("mmtbx_masks_ext")
mosaic_ext = bp.import_ext("mmtbx_mosaic_ext")

APPLY_SCALE_K1_TO_FOBS = False


def moving_average(x, n):
    r = []
Ejemplo n.º 26
0
from __future__ import absolute_import, division, print_function

import os
import time

import boost_adaptbx.boost.optional  # import dependency
import boost_adaptbx.boost.python as bp
bp.import_ext("scitbx_random_ext")
import scitbx_random_ext


def get_random_seed():
    try:
        result = (os.getpid() * (2**16)) \
               + (time.time() * (2**8))
    except KeyboardInterrupt:
        raise
    except Exception:
        result = time.time()
    return int(result % (2**31 - 1))


def set_random_seed(value):
    mt19937.seed(value)


from scitbx_random_ext import *
mt19937 = mersenne_twister_19937(value=get_random_seed())


class variate_factory(object):
Ejemplo n.º 27
0
from __future__ import absolute_import, division, print_function
import cctbx.array_family.flex  # import dependency

import boost_adaptbx.boost.python as bp
ext = bp.import_ext("mmtbx_tls_ext")
from mmtbx_tls_ext import *
Ejemplo n.º 28
0
from __future__ import absolute_import, division, print_function

import boost_adaptbx.boost.python as bp
ext = bp.import_ext("boost_adaptbx_graph_metric_ext")

from boost_adaptbx_graph_metric_ext import *
Ejemplo n.º 29
0
from __future__ import absolute_import, division, print_function

from cctbx.development import random_structure
from cctbx.sgtbx import space_group_info
import boost_adaptbx.boost.python as bp
from six.moves import range
asu_map_ext = bp.import_ext("cctbx_asymmetric_map_ext")
from cctbx_asymmetric_map_ext import *
from cctbx.array_family import flex
from cctbx import maptbx
import mmtbx.masks
import random

if (1):
  random.seed(0)
  flex.set_random_seed(0)

def run_group(symbol, preprocess_against_shallow):
  group = space_group_info(symbol)
  print("\n== space group %d"%symbol)
  xrs = random_structure.xray_structure(
    space_group_info       = group,
    volume_per_atom        = 15.,
    general_positions_only = False,
    elements               = ('C', 'N', 'O', 'H')*31,
    min_distance           = 1.0)
  sgt = xrs.space_group().type()
  #
  cg = maptbx.crystal_gridding(
    unit_cell        = xrs.unit_cell(),
    space_group_info = xrs.space_group_info(),
Ejemplo n.º 30
0
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
bp.import_ext("cctbx_geometry_ext")
from cctbx_geometry_ext import *