Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move code from boost.* to boost_adaptbx.*, #458 #470

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions boost/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +0,0 @@
from __future__ import absolute_import, division, print_function
import libtbx.forward_compatibility
13 changes: 10 additions & 3 deletions boost/optional.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from __future__ import absolute_import, division, print_function
import boost.python
ext = boost.python.import_ext("boost_optional_ext")
from boost_optional_ext import *
from boost_adaptbx.optional import *
import warnings

warnings.warn(
"importing from boost.optional is deprecated; this module will be removed shortly. "
"import from boost_adaptbx.optional instead. "
"Please see https://github.com/cctbx/cctbx_project/issues/458 for more information.",
FutureWarning,
stacklevel=2
)
266 changes: 10 additions & 256 deletions boost/python.py
Original file line number Diff line number Diff line change
@@ -1,190 +1,14 @@
from __future__ import absolute_import, division, print_function

import inspect
import os
import re
import sys
from boost_adaptbx.python import *
import warnings

from libtbx import cpp_function_name

symbol_not_found_pat = re.compile(
r"[Ss]ymbol[ ]not[ ]found: \s* (\w+) $", re.X | re.M | re.S)

python_libstdcxx_so = None
if (sys.platform.startswith("linux")):
from libtbx import easy_run
for line in easy_run.fully_buffered(
command='/usr/bin/ldd "%s"' % sys.executable).stdout_lines:
if (line.strip().startswith("libstdc++.so")):
python_libstdcxx_so = line.split()[0]
break

def import_ext(name, optional=False):
components = name.split(".")
if (len(components) > 1):
__import__(".".join(components[:-1]))
previous_dlopenflags = None
if (sys.platform.startswith("linux")) :
previous_dlopenflags = sys.getdlopenflags()
sys.setdlopenflags(0x100|0x2)
try: mod = __import__(name)
except ImportError as e:
if (optional): return None
error_msg = str(e)
m = symbol_not_found_pat.search(error_msg)
if m:
error_msg = ( error_msg[:m.start(1)]
+ cpp_function_name.demangle(m.group(1))
+ error_msg[m.end(1):])
raise ImportError(
"\n ".join(['__import__("%s"): %s' % (name, error_msg), "sys.path:"]
+ [" "+p for p in sys.path]))
for comp in components[1:]:
mod = getattr(mod, comp)
if (previous_dlopenflags is not None):
sys.setdlopenflags(previous_dlopenflags)
if (python_libstdcxx_so is not None):
mod_file = getattr(mod, "__file__", None)
if (mod_file is not None):
for line in easy_run.fully_buffered(
command='/usr/bin/ldd "%s"' % mod_file).stdout_lines:
if (line.strip().startswith("libstdc++.so")):
mod_libstdcxx_so = line.split()[0]
if (mod_libstdcxx_so != python_libstdcxx_so):
raise SystemError("""\
FATAL: libstdc++.so mismatch:
%s: %s
%s: %s""" % (sys.executable, python_libstdcxx_so,
mod_file, mod_libstdcxx_so))
break
return mod

ext = import_ext("boost_python_meta_ext")

try: streambuf = ext.streambuf
except AttributeError: pass # XXX backward compatibility 2009-11-24
try: ostream = ext.ostream
except AttributeError: pass

if os.getenv("BOOST_ADAPTBX_ENABLE_TRACE"):
ext.enable_signals_backtrace_if_possible()

class floating_point_exceptions_type(object):
__shared_state = {'initialised': False}

def __init__(self):
self.__dict__ = self.__shared_state
if not self.initialised:
division_by_zero = bool(os.getenv("BOOST_ADAPTBX_TRAP_FPE", self.division_by_zero_trapped))
invalid = bool(os.getenv("BOOST_ADAPTBX_TRAP_INVALID",self.invalid_trapped))
overflow = bool(os.getenv("BOOST_ADAPTBX_TRAP_OVERFLOW",self.overflow_trapped))
ext.trap_exceptions(division_by_zero, invalid, overflow)
self.initialised = True

def division_by_zero_trapped():
def fget(self):
return ext.is_division_by_zero_trapped()
def fset(self, flag):
if flag == self.division_by_zero_trapped: return
ext.trap_exceptions(division_by_zero=flag,
invalid=self.invalid_trapped,
overflow=self.overflow_trapped)
return locals()
division_by_zero_trapped = property(**division_by_zero_trapped())

def invalid_trapped():
def fget(self):
return ext.is_invalid_trapped()
def fset(self, flag):
if flag == self.fget(): return
ext.trap_exceptions(division_by_zero=self.invalid_trapped,
invalid=flag,
overflow=self.overflow_trapped)
return locals()
invalid_trapped = property(**invalid_trapped())

def overflow_trapped():
def fget(self):
return ext.is_overflow_trapped()
def fset(self, flag):
if flag == self.fget(): return
ext.trap_exceptions(division_by_zero=self.overflow_trapped,
invalid=self.invalid_trapped,
overflow=flag)
return locals()
overflow_trapped = property(**overflow_trapped())

floating_point_exceptions = floating_point_exceptions_type()


class trapping(object):
""" Synopsis:

>>> import boost.python
>>> from scitbx.array_family import flex
>>> a = flex.double((0, 0, 0))
>>> with boost.python.trapping(division_by_zero=False):
>>> b = 1/a
>>> tuple(b)
(inf, inf, inf)
>>> 1/a
... CRASH ...
"""
def __init__(self, division_by_zero=True, invalid=True, overflow=True):
self.division_by_zero = ext.is_division_by_zero_trapped()
self.invalid = ext.is_invalid_trapped()
self.overflow = ext.is_overflow_trapped()
ext.trap_exceptions(division_by_zero, invalid, overflow)


def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
ext.trap_exceptions(self.division_by_zero, self.invalid, self.overflow)


meta_class = ext.holder.__class__
platform_info = ext.platform_info()
assert len(platform_info) > 0 # please disable this assertion and send email to cctbx@cci.lbl.gov

def c_sizeof(typename):
pattern = "sizeof(%s) = " % typename
for line in platform_info.splitlines():
if (line.startswith(pattern)):
break
else:
raise RuntimeError('boost.python.platform_info: "%s" not found.' % pattern)
return int(line[len(pattern):])

sizeof_void_ptr = c_sizeof("void*")


class gcc_version(object):

def __init__(self):
pat = r" \s* = \s* (\d+) \s+"
m = re.search("__GNUC__ %s __GNUC_MINOR__ %s __GNUC_PATCHLEVEL__ %s"
% ((pat,)*3),
platform_info, re.X|re.M|re.S)
if not m:
self.major, self.minor, self.patchlevel = None, None, None
else:
self.major, self.minor, self.patchlevel = tuple(
[ int(x) for x in m.groups() ])

def __bool__(self):
return self.major is not None

__nonzero__ = __bool__

def __str__(self):
if self:
return "%i.%i.%i" % (self.major, self.minor, self.patchlevel)
else:
return "GCC, it is not"

warnings.warn(
"importing from boost.python is deprecated; this module will be removed shortly. "
"import from boost_adaptbx.python instead. "
"Please see https://github.com/cctbx/cctbx_project/issues/458 for more information.",
FutureWarning,
stacklevel=2
)

_skip_warning = True
class injector(object):
Expand All @@ -194,7 +18,7 @@ class CrystalExt(boost.python.injector, Crystal):

please use

@boost.python.inject_into(Crystal)
@boost_adaptbx.python.inject_into(Crystal)
class _(object):
'''
class __metaclass__(meta_class):
Expand All @@ -204,7 +28,7 @@ def __init__(self, name, bases, dict):
warnings.warn(
"boost.python.injector is deprecated and does not work on Python 3. "
"Please see https://github.com/cctbx/cctbx_project/pull/386 for more information.",
DeprecationWarning,
FutureWarning,
stacklevel=2
)
if (len(bases) > 1):
Expand All @@ -225,73 +49,3 @@ def setattr_from_dict(d):
setattr_from_dict(b.__dict__)
return type.__init__(self, name, (), {})
_skip_warning = False

def inject(target_class, *mixin_classes):
'''Add entries from python class dictionaries to a boost extension class.

It is used as follows:

class _():
def method(...):
...
boost.python.inject(extension_class, _)

instead of the previous mechanism of

class _(boost.python.injector, extension_class):
def method(...):
...

which does not work in python 3.
'''
for m in mixin_classes:
for key, value in m.__dict__.items():
if key not in ("__init__",
"__del__",
"__module__",
"__file__",
"__dict__") and (key != '__doc__' or value):
setattr(target_class, key, value)

def inject_into(target_class, *mixin_classes):
'''Add entries from python class dictionaries to a boost extension class.

It is used as follows:

@boost.python.inject_into(extension_class)
class _():
def method(...):
...
'''
def _inject(c):
if inspect.isclass(c):
inject(target_class, c, *mixin_classes)
else:
setattr(target_class, c.__name__, c)
class empty_class:
pass
inject(target_class, empty_class, *mixin_classes)
return _inject

def process_docstring_options(env_var="BOOST_ADAPTBX_DOCSTRING_OPTIONS"):
from_env = os.environ.get(env_var)
if (from_env is None): return None
try:
return eval(
"docstring_options(%s)" % from_env,
{},
{"docstring_options": ext.docstring_options})
except KeyboardInterrupt: raise
except Exception as e:
from libtbx.str_utils import show_string
raise RuntimeError(
"Error processing %s=%s\n" % (env_var, show_string(from_env))
+ " Exception: %s\n" % str(e)
+ " Valid example:\n"
+ ' %s="show_user_defined=True,show_signatures=False"' % env_var)

docstring_options = process_docstring_options()

class py3_make_iterator:
def __next__(obj):
return obj.next()
39 changes: 10 additions & 29 deletions boost/rational.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,11 @@
from __future__ import absolute_import, division, print_function
import boost.python
from six.moves import range
ext = boost.python.import_ext("boost_rational_ext")
from boost_rational_ext import *

builtin_int = __builtins__["int"]

def from_string(s):
flds = [builtin_int(i) for i in s.split("/")]
assert len(flds) in (1,2)
if (len(flds) == 1):
return int(flds[0])
return int(flds[0], flds[1])

def vector(numerators, denominators):
if (isinstance(denominators, builtin_int)):
denominators = [denominators] * len(numerators)
else:
assert len(numerators) == len(denominators)
result = []
for i in range(len(numerators)):
result.append(int(numerators[i], denominators[i]))
return result

def lcm_denominators(array):
l = 1
for r in array:
l = lcm(l, r.denominator())
return l
from boost_adaptbx.rational import *
import warnings

warnings.warn(
"importing from boost.rational is deprecated; this module will be removed shortly. "
"import from boost_adaptbx.rational instead. "
"Please see https://github.com/cctbx/cctbx_project/issues/458 for more information.",
FutureWarning,
stacklevel=2
)
13 changes: 10 additions & 3 deletions boost/std_pair.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from __future__ import absolute_import, division, print_function
import boost.python
ext = boost.python.import_ext("std_pair_ext")
from std_pair_ext import *
from boost_adaptbx.std_pair import *
import warnings

warnings.warn(
"importing from boost.std_pair is deprecated; this module will be removed shortly. "
"import from boost_adaptbx.std_pair instead. "
"Please see https://github.com/cctbx/cctbx_project/issues/458 for more information.",
FutureWarning,
stacklevel=2
)
13 changes: 10 additions & 3 deletions boost/tuple.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
from __future__ import absolute_import, division, print_function
import boost.python
ext = boost.python.import_ext("boost_tuple_ext")
from boost_tuple_ext import *
from boost_adaptbx.tuple import *
import warnings

warnings.warn(
"importing from boost.tuple is deprecated; this module will be removed shortly. "
"import from boost_adaptbx.tuple instead. "
"Please see https://github.com/cctbx/cctbx_project/issues/458 for more information.",
FutureWarning,
stacklevel=2
)
2 changes: 2 additions & 0 deletions boost_adaptbx/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from __future__ import absolute_import, division, print_function
import libtbx.forward_compatibility
Loading