├── holoprot ├── __init__.py ├── models │ └── __init__.py ├── data │ ├── __init__.py │ └── base.py ├── layers │ ├── __init__.py │ └── mpn │ │ └── __init__.py ├── graphs │ ├── __init__.py │ └── complex.py ├── utils │ ├── backbone.py │ ├── metrics.py │ └── tensor.py └── feat │ └── __init__.py ├── superpixel ├── ers │ ├── __init__.py │ ├── ers.so │ ├── setup.py │ └── demo_ers.py ├── pybind11 │ ├── docs │ │ ├── requirements.txt │ │ ├── pybind11-logo.png │ │ ├── pybind11_vs_boost_python1.png │ │ ├── pybind11_vs_boost_python2.png │ │ ├── _static │ │ │ └── theme_overrides.css │ │ ├── advanced │ │ │ ├── pycpp │ │ │ │ ├── index.rst │ │ │ │ ├── object.rst │ │ │ │ └── utilities.rst │ │ │ └── cast │ │ │ │ ├── index.rst │ │ │ │ ├── custom.rst │ │ │ │ ├── chrono.rst │ │ │ │ └── functional.rst │ │ ├── Doxyfile │ │ ├── index.rst │ │ ├── limitations.rst │ │ ├── release.rst │ │ ├── reference.rst │ │ ├── benchmark.py │ │ ├── benchmark.rst │ │ └── intro.rst │ ├── .readthedocs.yml │ ├── MANIFEST.in │ ├── .gitmodules │ ├── pybind11 │ │ ├── _version.py │ │ ├── __init__.py │ │ └── __main__.py │ ├── include │ │ └── pybind11 │ │ │ ├── common.h │ │ │ ├── detail │ │ │ ├── typeid.h │ │ │ └── descr.h │ │ │ ├── complex.h │ │ │ ├── options.h │ │ │ ├── functional.h │ │ │ ├── eval.h │ │ │ └── buffer_info.h │ ├── setup.cfg │ ├── .github │ │ └── workflows │ │ │ ├── format.yml │ │ │ └── configure.yml │ ├── CMakeLists │ ├── .gitignore │ ├── tests │ │ ├── pytest.ini │ │ ├── requirements.txt │ │ ├── cross_module_gil_utils.cpp │ │ ├── local_bindings.h │ │ ├── pybind11_tests.h │ │ ├── pybind11_tests.cpp │ │ └── pybind11_cross_module_tests.cpp │ ├── tools │ │ ├── cmake_uninstall.cmake.in │ │ ├── libsize.py │ │ ├── check-style.sh │ │ ├── FindCatch.cmake │ │ ├── FindEigen3.cmake │ │ └── pybind11Config.cmake.in │ ├── .pre-commit-config.yaml │ ├── ISSUE_TEMPLATE.md │ ├── .appveyor.yml │ ├── LICENSE │ ├── .cmake-format.yaml │ ├── CONTRIBUTING.md │ └── setup.py ├── cmake │ ├── Macros │ │ └── set_if_empty.cmake │ └── Modules │ │ └── Findpybind11.cmake ├── MERCLazyGreedy.h ├── ers.cpp ├── MERCOutput.h ├── MERCInput.h ├── MERCInputGraph.h ├── MERCClustering.h ├── MERCOutput.cpp ├── MERCDisjointSet.h ├── MERCFunctions.h ├── Edge.h ├── MERCCInput.cpp ├── CMakeLists.txt ├── MERCDisjointSet.cpp ├── MERCEdge.h ├── MERCFunctions.cpp ├── MList.h ├── MERCLazyGreedy.cpp └── MSubmodularHeap.h ├── .gitattributes ├── assets └── holoprot.png ├── configs ├── preprocess │ ├── enzyme │ │ ├── surface.json │ │ ├── patch2backbone.json │ │ └── surface2backbone.json │ └── pdbbind │ │ ├── surface.json │ │ ├── patch2backbone.json │ │ └── surface2backbone.json └── train │ ├── enzyme │ └── default_config.yaml │ └── pdbbind │ ├── identity30.yaml │ ├── identity60.yaml │ └── scaffold.yaml ├── environment.yml ├── .gitignore ├── setup.py ├── install_dependencies.sh ├── LICENSE.md └── scripts └── preprocess ├── prepare_graphs.py ├── generate_patches.py ├── resize_meshes.py └── splits.py /holoprot/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /superpixel/ers/__init__.py: -------------------------------------------------------------------------------- 1 | from .ers import * 2 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/requirements.txt: -------------------------------------------------------------------------------- 1 | breathe == 4.5.0 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.cpp linguist-vendored 2 | *.h linguist-vendored 3 | -------------------------------------------------------------------------------- /holoprot/models/__init__.py: -------------------------------------------------------------------------------- 1 | from holoprot.models.trainer import Trainer 2 | -------------------------------------------------------------------------------- /assets/holoprot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsomnath/holoprot/HEAD/assets/holoprot.png -------------------------------------------------------------------------------- /superpixel/ers/ers.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsomnath/holoprot/HEAD/superpixel/ers/ers.so -------------------------------------------------------------------------------- /configs/preprocess/enzyme/surface.json: -------------------------------------------------------------------------------- 1 | {"msms_bin": "/path/to/msms", 2 | "sigma": 18.0} 3 | -------------------------------------------------------------------------------- /configs/preprocess/pdbbind/surface.json: -------------------------------------------------------------------------------- 1 | {"msms_bin": "/path/to/msms", 2 | "sigma": 18.0} 3 | -------------------------------------------------------------------------------- /superpixel/pybind11/.readthedocs.yml: -------------------------------------------------------------------------------- 1 | python: 2 | version: 3 3 | requirements_file: docs/requirements.txt 4 | -------------------------------------------------------------------------------- /superpixel/pybind11/MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include include/pybind11 *.h 2 | include LICENSE README.md CONTRIBUTING.md 3 | -------------------------------------------------------------------------------- /superpixel/pybind11/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tools/clang"] 2 | path = tools/clang 3 | url = ../../wjakob/clang-cindex-python3.git 4 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/pybind11-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsomnath/holoprot/HEAD/superpixel/pybind11/docs/pybind11-logo.png -------------------------------------------------------------------------------- /configs/preprocess/enzyme/patch2backbone.json: -------------------------------------------------------------------------------- 1 | {"max_num_neighbors": 128, 2 | "mode": "ca", 3 | "radius": 12.0, 4 | "sigma": 18.0 5 | } 6 | -------------------------------------------------------------------------------- /configs/preprocess/enzyme/surface2backbone.json: -------------------------------------------------------------------------------- 1 | {"max_num_neighbors": 128, 2 | "mode": "ca", 3 | "radius": 12.0, 4 | "sigma": 18.0 5 | } 6 | -------------------------------------------------------------------------------- /configs/preprocess/pdbbind/patch2backbone.json: -------------------------------------------------------------------------------- 1 | {"max_num_neighbors": 128, 2 | "mode": "ca", 3 | "radius": 12.0, 4 | "sigma": 18.0 5 | } 6 | -------------------------------------------------------------------------------- /configs/preprocess/pdbbind/surface2backbone.json: -------------------------------------------------------------------------------- 1 | {"max_num_neighbors": 128, 2 | "mode": "ca", 3 | "radius": 12.0, 4 | "sigma": 18.0 5 | } 6 | -------------------------------------------------------------------------------- /superpixel/pybind11/pybind11/_version.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | version_info = (2, 5, 'dev1') 3 | __version__ = '.'.join(map(str, version_info)) 4 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/pybind11_vs_boost_python1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsomnath/holoprot/HEAD/superpixel/pybind11/docs/pybind11_vs_boost_python1.png -------------------------------------------------------------------------------- /superpixel/pybind11/docs/pybind11_vs_boost_python2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vsomnath/holoprot/HEAD/superpixel/pybind11/docs/pybind11_vs_boost_python2.png -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/common.h: -------------------------------------------------------------------------------- 1 | #include "detail/common.h" 2 | #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." 3 | -------------------------------------------------------------------------------- /holoprot/data/__init__.py: -------------------------------------------------------------------------------- 1 | from holoprot.data.datasets import PDBBindDataset, EnzymeDataset 2 | 3 | DATASETS = {'pdbbind': PDBBindDataset, 4 | 'enzyme': EnzymeDataset} 5 | -------------------------------------------------------------------------------- /holoprot/layers/__init__.py: -------------------------------------------------------------------------------- 1 | from holoprot.layers.mpn import (WLNConv, WLNResConv, GRUConv, 2 | LSTMConv, mpn_layer_from_config) 3 | from holoprot.layers.mpn.prot_mpn import ProtMPN 4 | -------------------------------------------------------------------------------- /holoprot/graphs/__init__.py: -------------------------------------------------------------------------------- 1 | from holoprot.graphs.backbone import Backbone 2 | from holoprot.graphs.surface import Surface 3 | from holoprot.graphs.patch import Patch 4 | from holoprot.graphs.hier_graph import Surface2Backbone, Patch2Backbone 5 | from holoprot.graphs.complex import Complex 6 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | channels: 2 | - pytorch 3 | - omnia 4 | - conda-forge 5 | - defaults 6 | dependencies: 7 | - openmm 8 | - pdbfixer 9 | - rdkit 10 | - pytorch=1.7.0 11 | - cudatoolkit=10.1.243 12 | - pip 13 | - pip: 14 | - networkx 15 | - biopython 16 | - h5py 17 | - pot 18 | - wandb 19 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/_static/theme_overrides.css: -------------------------------------------------------------------------------- 1 | .wy-table-responsive table td, 2 | .wy-table-responsive table th { 3 | white-space: initial !important; 4 | } 5 | .rst-content table.docutils td { 6 | vertical-align: top !important; 7 | } 8 | div[class^='highlight'] pre { 9 | white-space: pre; 10 | white-space: pre-wrap; 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | 3 | notebooks/ 4 | misc/ 5 | wandb/ 6 | *experiments/ 7 | test_* 8 | 9 | *.egg-info* 10 | *~ 11 | lsf* 12 | *.log 13 | **/log* 14 | 15 | scripts/depreceated/ 16 | 17 | .idea/ 18 | .vscode/ 19 | .DS_Store 20 | 21 | binaries/ 22 | build/ 23 | datasets/ 24 | dist/ 25 | *.tar.gz 26 | 27 | .ipynb_checkpoints 28 | masif_pymol_plugin/ 29 | __pycache__/* 30 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/pycpp/index.rst: -------------------------------------------------------------------------------- 1 | Python C++ interface 2 | #################### 3 | 4 | pybind11 exposes Python types and functions using thin C++ wrappers, which 5 | makes it possible to conveniently call Python code from C++ without resorting 6 | to Python's C API. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | object 12 | numpy 13 | utilities 14 | -------------------------------------------------------------------------------- /superpixel/pybind11/setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [flake8] 5 | max-line-length = 99 6 | show_source = True 7 | exclude = .git, __pycache__, build, dist, docs, tools, venv 8 | ignore = 9 | # required for pretty matrix formatting: multiple spaces after `,` and `[` 10 | E201, E241, W504, 11 | # camelcase 'cPickle' imported as lowercase 'pickle' 12 | N813 13 | -------------------------------------------------------------------------------- /superpixel/ers/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | import sys 4 | if sys.version_info < (3,0): 5 | sys.exit('Sorry, Python < 3.0 is not supported') 6 | 7 | setup( 8 | name = 'superpixel', 9 | version = '${PACKAGE_VERSION}', 10 | packages = [ 'ers' ], 11 | package_dir = { 12 | '': '${CMAKE_CURRENT_BINARY_DIR}' 13 | }, 14 | package_data = { 15 | '': ['ers.so'] 16 | } 17 | ) 18 | -------------------------------------------------------------------------------- /superpixel/pybind11/.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | name: Format 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | push: 7 | branches: 8 | - master 9 | - stable 10 | - "v*" 11 | 12 | jobs: 13 | pre-commit: 14 | name: Format 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v2 18 | - uses: actions/setup-python@v2 19 | - uses: pre-commit/action@v2.0.0 20 | -------------------------------------------------------------------------------- /superpixel/pybind11/CMakeLists: -------------------------------------------------------------------------------- 1 | # Generate python module library 2 | if(PYBIND_LIB) 3 | message("GENERATING PYBIND LIBRARY") 4 | 5 | add_definitions(-DPYBIND) 6 | 7 | find_package(PythonLibs) 8 | include_directories(${PYTHON_INCLUDE_DIRS}) 9 | 10 | add_subdirectory(pybind11) 11 | pybind11_add_module(ers src/pugixml.cpp src/functions.cpp src/musicxml.cpp) 12 | target_include_directories(maialib PUBLIC include) 13 | endif() 14 | -------------------------------------------------------------------------------- /superpixel/cmake/Macros/set_if_empty.cmake: -------------------------------------------------------------------------------- 1 | # Module: set_if_empty 2 | # Author: Matthias Maier 3 | # Bastian Rieck 4 | # 5 | # Provides macro SET_IF_EMPTY. Given a variable and a value, the variable is 6 | # set to the value if it is still empty. 7 | 8 | MACRO( SET_IF_EMPTY variable value ) 9 | IF( "${${variable}}" STREQUAL "" ) 10 | SET( ${variable} ${value} ) 11 | ENDIF() 12 | ENDMACRO() 13 | -------------------------------------------------------------------------------- /superpixel/pybind11/pybind11/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from ._version import version_info, __version__ # noqa: F401 imported but unused 3 | 4 | 5 | def get_include(user=False): 6 | import os 7 | d = os.path.dirname(__file__) 8 | if os.path.exists(os.path.join(d, "include")): 9 | # Package is installed 10 | return os.path.join(d, "include") 11 | else: 12 | # Package is from a source directory 13 | return os.path.join(os.path.dirname(d), "include") 14 | -------------------------------------------------------------------------------- /superpixel/pybind11/.gitignore: -------------------------------------------------------------------------------- 1 | CMakeCache.txt 2 | CMakeFiles 3 | Makefile 4 | cmake_install.cmake 5 | cmake_uninstall.cmake 6 | .DS_Store 7 | *.so 8 | *.pyd 9 | *.dll 10 | *.sln 11 | *.sdf 12 | *.opensdf 13 | *.vcxproj 14 | *.vcxproj.user 15 | *.filters 16 | example.dir 17 | Win32 18 | x64 19 | Release 20 | Debug 21 | .vs 22 | CTestTestfile.cmake 23 | Testing 24 | autogen 25 | MANIFEST 26 | /.ninja_* 27 | /*.ninja 28 | /docs/.build 29 | *.py[co] 30 | *.egg-info 31 | *~ 32 | .*.swp 33 | .DS_Store 34 | /dist 35 | /build 36 | .cache/ 37 | sosize-*.txt 38 | pybind11Config*.cmake 39 | pybind11Targets.cmake 40 | /*env* 41 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from setuptools import setup, find_packages 4 | import os 5 | 6 | 7 | datadir = os.path.join('data') 8 | datafiles = [(d, [os.path.join(d, f) for f in files]) 9 | for d, folders, files in os.walk(datadir)] 10 | 11 | setup(name='holoprot', 12 | version='0.1', 13 | description='Multi-Scale Representation Learning on Proteins', 14 | license='MIT', 15 | packages=find_packages(), 16 | install_requires=['numpy', 17 | 'scipy', 18 | 'pandas', 19 | 'torch'], 20 | zip_safe=False, 21 | data_files=datafiles, 22 | ) 23 | -------------------------------------------------------------------------------- /superpixel/pybind11/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | minversion = 3.0 3 | norecursedirs = test_cmake_build test_embed 4 | addopts = 5 | # show summary of skipped tests 6 | -rs 7 | # capture only Python print and C++ py::print, but not C output (low-level Python errors) 8 | --capture=sys 9 | filterwarnings = 10 | # make warnings into errors but ignore certain third-party extension issues 11 | error 12 | # importing scipy submodules on some version of Python 13 | ignore::ImportWarning 14 | # bogus numpy ABI warning (see numpy/#432) 15 | ignore:.*numpy.dtype size changed.*:RuntimeWarning 16 | ignore:.*numpy.ufunc size changed.*:RuntimeWarning 17 | -------------------------------------------------------------------------------- /superpixel/pybind11/tests/requirements.txt: -------------------------------------------------------------------------------- 1 | --extra-index-url https://antocuni.github.io/pypy-wheels/manylinux2010/ 2 | numpy==1.16.6; python_version<"3.6" 3 | numpy==1.18.0; platform_python_implementation=="PyPy" and sys_platform=="darwin" and python_version>="3.6" 4 | numpy==1.19.1; (platform_python_implementation!="PyPy" or sys_platform!="darwin") and python_version>="3.6" 5 | pytest==4.6.9; python_version<"3.5" 6 | pytest==5.4.3; python_version>="3.5" 7 | scipy==1.2.3; (platform_python_implementation!="PyPy" or sys_platform!="darwin") and python_version<"3.6" 8 | scipy==1.5.2; (platform_python_implementation!="PyPy" or sys_platform!="darwin") and python_version>="3.6" and python_version<"3.9" 9 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/Doxyfile: -------------------------------------------------------------------------------- 1 | PROJECT_NAME = pybind11 2 | INPUT = ../include/pybind11/ 3 | RECURSIVE = YES 4 | 5 | GENERATE_HTML = NO 6 | GENERATE_LATEX = NO 7 | GENERATE_XML = YES 8 | XML_OUTPUT = .build/doxygenxml 9 | XML_PROGRAMLISTING = YES 10 | 11 | MACRO_EXPANSION = YES 12 | EXPAND_ONLY_PREDEF = YES 13 | EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION 14 | 15 | ALIASES = "rst=\verbatim embed:rst" 16 | ALIASES += "endrst=\endverbatim" 17 | 18 | QUIET = YES 19 | WARNINGS = YES 20 | WARN_IF_UNDOCUMENTED = NO 21 | PREDEFINED = DOXYGEN_SHOULD_SKIP_THIS \ 22 | PY_MAJOR_VERSION=3 23 | -------------------------------------------------------------------------------- /superpixel/cmake/Modules/Findpybind11.cmake: -------------------------------------------------------------------------------- 1 | # Module: Findpybind11.cmake 2 | # Author: Bastian Rieck 3 | # 4 | # CMake find module for pybind11. 5 | 6 | INCLUDE( FindPackageHandleStandardArgs ) 7 | 8 | SET_IF_EMPTY( PYBIND11_DIR "$ENV{PYBIND11_DIR}" ) 9 | 10 | FIND_PATH( 11 | PYBIND11_INCLUDE_DIR 12 | pybind11/pybind11.h 13 | HINTS 14 | ${PYBIND11_DIR} 15 | ) 16 | 17 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( PYBIND11 DEFAULT_MSG 18 | PYBIND11_INCLUDE_DIR 19 | ) 20 | 21 | IF( PYBIND11_FOUND ) 22 | SET( PYBIND11_INCLUDE_DIRS ${PYBIND11_INCLUDE_DIR} ) 23 | 24 | MARK_AS_ADVANCED( 25 | PYBIND11_INCLUDE_DIR 26 | PYBIND11_DIR 27 | ) 28 | ELSE() 29 | SET( PYBIND11_DIR "" CACHE STRING 30 | "An optional hint to a pybind11 directory" 31 | ) 32 | ENDIF() 33 | -------------------------------------------------------------------------------- /superpixel/ers/demo_ers.py: -------------------------------------------------------------------------------- 1 | from ers import ERS 2 | import cv2 3 | import numpy as np 4 | 5 | def colormap(input,colors): 6 | height = input.shape[0] 7 | width = input.shape[1] 8 | output = np.zeros([height, width, 3], np.uint8) 9 | for y in range(0, height): 10 | for x in range(0, width): 11 | id = int(input[y, x]) 12 | for k in range(0, 3): 13 | output[y,x,k] = colors[id, k] 14 | return output 15 | 16 | nC = 20 17 | img = cv2.imread("../images/242078.jpg") 18 | 19 | grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 20 | 21 | e = ERS(0.5, 5.0) 22 | segmentation = e.computeSegmentation(np.uint8(grayImg), nC) 23 | 24 | colors = np.uint8(np.random.rand(nC, 3) * 255) 25 | output = colormap(segmentation, colors) 26 | cv2.imshow("img", img) 27 | cv2.imshow("segmentation",output) 28 | cv2.waitKey() 29 | cv2.destroyAllWindows() 30 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/index.rst: -------------------------------------------------------------------------------- 1 | .. only: not latex 2 | 3 | .. image:: pybind11-logo.png 4 | 5 | pybind11 --- Seamless operability between C++11 and Python 6 | ========================================================== 7 | 8 | .. only: not latex 9 | 10 | Contents: 11 | 12 | .. toctree:: 13 | :maxdepth: 1 14 | 15 | intro 16 | changelog 17 | upgrade 18 | 19 | .. toctree:: 20 | :caption: The Basics 21 | :maxdepth: 2 22 | 23 | basics 24 | classes 25 | compiling 26 | 27 | .. toctree:: 28 | :caption: Advanced Topics 29 | :maxdepth: 2 30 | 31 | advanced/functions 32 | advanced/classes 33 | advanced/exceptions 34 | advanced/smart_ptrs 35 | advanced/cast/index 36 | advanced/pycpp/index 37 | advanced/embedding 38 | advanced/misc 39 | 40 | .. toctree:: 41 | :caption: Extra Information 42 | :maxdepth: 1 43 | 44 | faq 45 | benchmark 46 | limitations 47 | reference 48 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/limitations.rst: -------------------------------------------------------------------------------- 1 | Limitations 2 | ########### 3 | 4 | pybind11 strives to be a general solution to binding generation, but it also has 5 | certain limitations: 6 | 7 | - pybind11 casts away ``const``-ness in function arguments and return values. 8 | This is in line with the Python language, which has no concept of ``const`` 9 | values. This means that some additional care is needed to avoid bugs that 10 | would be caught by the type checker in a traditional C++ program. 11 | 12 | - The NumPy interface ``pybind11::array`` greatly simplifies accessing 13 | numerical data from C++ (and vice versa), but it's not a full-blown array 14 | class like ``Eigen::Array`` or ``boost.multi_array``. 15 | 16 | These features could be implemented but would lead to a significant increase in 17 | complexity. I've decided to draw the line here to keep this project simple and 18 | compact. Users who absolutely require these features are encouraged to fork 19 | pybind11. 20 | -------------------------------------------------------------------------------- /install_dependencies.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | source $(conda info --root)/etc/profile.d/conda.sh 4 | 5 | conda create -y --name prot python=3.7.3 6 | conda activate prot 7 | conda env update --file $PWD/environment.yml 8 | 9 | CUDA=cu101 10 | pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.7.0+${CUDA}.html 11 | pip install torch-sparse -f https://pytorch-geometric.com/whl/torch-1.7.0+${CUDA}.html 12 | pip install torch-cluster -f https://pytorch-geometric.com/whl/torch-1.7.0+${CUDA}.html 13 | pip install torch-spline-conv -f https://pytorch-geometric.com/whl/torch-1.7.0+${CUDA}.html 14 | pip install torch-geometric 15 | 16 | if [[ "$OSTYPE" == "linux-gnu"* ]]; then 17 | pip install "https://github.com/PyMesh/PyMesh/releases/download/v0.3/pymesh2-0.3-cp37-cp37m-linux_x86_64.whl" 18 | elif [[ "$OSTYPE" == "darwin"* ]]; then 19 | pip install "https://github.com/PyMesh/PyMesh/releases/download/v0.3/pymesh2-0.3-cp37-cp37m-macosx_10_15_x86_64.whl" 20 | else 21 | echo "$OSTYPE" 22 | fi 23 | 24 | python setup.py develop 25 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/release.rst: -------------------------------------------------------------------------------- 1 | To release a new version of pybind11: 2 | 3 | - Update the version number and push to pypi 4 | - Update ``pybind11/_version.py`` (set release version, remove 'dev'). 5 | - Update ``PYBIND11_VERSION_MAJOR`` etc. in ``include/pybind11/detail/common.h``. 6 | - Ensure that all the information in ``setup.py`` is up-to-date. 7 | - Update version in ``docs/conf.py``. 8 | - Tag release date in ``docs/changelog.rst``. 9 | - ``git add`` and ``git commit``. 10 | - if new minor version: ``git checkout -b vX.Y``, ``git push -u origin vX.Y`` 11 | - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``. 12 | - ``git push`` 13 | - ``git push --tags``. 14 | - ``python setup.py sdist upload``. 15 | - ``python setup.py bdist_wheel upload``. 16 | - Get back to work 17 | - Update ``_version.py`` (add 'dev' and increment minor). 18 | - Update version in ``docs/conf.py`` 19 | - Update version macros in ``include/pybind11/common.h`` 20 | - ``git add`` and ``git commit``. 21 | ``git push`` 22 | -------------------------------------------------------------------------------- /superpixel/pybind11/pybind11/__main__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function 3 | 4 | import argparse 5 | import sys 6 | import sysconfig 7 | 8 | from . import get_include 9 | 10 | 11 | def print_includes(): 12 | dirs = [sysconfig.get_path('include'), 13 | sysconfig.get_path('platinclude'), 14 | get_include()] 15 | 16 | # Make unique but preserve order 17 | unique_dirs = [] 18 | for d in dirs: 19 | if d not in unique_dirs: 20 | unique_dirs.append(d) 21 | 22 | print(' '.join('-I' + d for d in unique_dirs)) 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser(prog='python -m pybind11') 27 | parser.add_argument('--includes', action='store_true', 28 | help='Include flags for both pybind11 and Python headers.') 29 | args = parser.parse_args() 30 | if not sys.argv[1:]: 31 | parser.print_help() 32 | if args.includes: 33 | print_includes() 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /superpixel/pybind11/tools/cmake_uninstall.cmake.in: -------------------------------------------------------------------------------- 1 | # Source: https://gitlab.kitware.com/cmake/community/-/wikis/FAQ#can-i-do-make-uninstall-with-cmake 2 | 3 | if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt") 4 | message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt") 5 | endif() 6 | 7 | file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files) 8 | string(REGEX REPLACE "\n" ";" files "${files}") 9 | foreach(file ${files}) 10 | message(STATUS "Uninstalling $ENV{DESTDIR}${file}") 11 | if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 12 | exec_program( 13 | "@CMAKE_COMMAND@" ARGS 14 | "-E remove \"$ENV{DESTDIR}${file}\"" 15 | OUTPUT_VARIABLE rm_out 16 | RETURN_VALUE rm_retval) 17 | if(NOT "${rm_retval}" STREQUAL 0) 18 | message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}") 19 | endif() 20 | else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") 21 | message(STATUS "File $ENV{DESTDIR}${file} does not exist.") 22 | endif() 23 | endforeach() 24 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Vignesh Ram Somnath 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /configs/train/enzyme/default_config.yaml: -------------------------------------------------------------------------------- 1 | split: 2 | value: base 3 | dataset: 4 | value: enzyme 5 | prot_mode: 6 | value: patch2backbone 7 | encoder: 8 | value: wln 9 | hsize: 10 | value: 512 11 | bhsize: 12 | value: 150 13 | shsize: 14 | value: 150 15 | bdepth: 16 | value: 5 17 | sdepth: 18 | value: 4 19 | n_classes: 20 | value: 384 21 | dropout_mlp: 22 | value: 0.3 23 | dropout_mpn: 24 | value: 0.15 25 | lr: 26 | value: 0.0005 27 | clip_norm: 28 | value: 10.0 29 | epochs: 30 | value: 300 31 | num_workers: 32 | value: 6 33 | batch_size: 34 | value: 8 35 | step_after: 36 | value: 50 37 | scheduler_type: 38 | value: plateau 39 | accum_every: 40 | value: null 41 | metric_thresh: 42 | value: 0.01 43 | patience: 44 | value: 10 45 | anneal_rate: 46 | value: 0.6 47 | use_doubles: 48 | value: False 49 | use_concat: 50 | value: False 51 | use_grad_noise: 52 | value: True 53 | use_attn: 54 | value: False 55 | print_every: 56 | value: 500 57 | eval_every: 58 | value: 1500 59 | activation: 60 | value: lrelu 61 | jk_pool: 62 | value: null 63 | use_mpn_in_patch: 64 | value: False 65 | -------------------------------------------------------------------------------- /superpixel/pybind11/.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v3.1.0 4 | hooks: 5 | - id: check-added-large-files 6 | - id: check-case-conflict 7 | - id: check-merge-conflict 8 | - id: check-symlinks 9 | - id: check-yaml 10 | - id: debug-statements 11 | - id: end-of-file-fixer 12 | - id: mixed-line-ending 13 | - id: requirements-txt-fixer 14 | - id: trailing-whitespace 15 | - id: fix-encoding-pragma 16 | 17 | - repo: https://github.com/Lucas-C/pre-commit-hooks 18 | rev: v1.1.9 19 | hooks: 20 | - id: remove-tabs 21 | 22 | - repo: https://gitlab.com/pycqa/flake8 23 | rev: 3.8.3 24 | hooks: 25 | - id: flake8 26 | additional_dependencies: [flake8-bugbear, pep8-naming] 27 | exclude: ^(docs/.*|tools/.*)$ 28 | 29 | - repo: https://github.com/cheshirekow/cmake-format-precommit 30 | rev: v0.6.11 31 | hooks: 32 | - id: cmake-format 33 | additional_dependencies: [pyyaml] 34 | types: [file] 35 | files: (\.cmake|CMakeLists.txt)(.in)?$ 36 | 37 | - repo: local 38 | hooks: 39 | - id: check-style 40 | name: Classic check-style 41 | language: system 42 | types: 43 | - c++ 44 | entry: ./tools/check-style.sh 45 | -------------------------------------------------------------------------------- /configs/train/pdbbind/identity30.yaml: -------------------------------------------------------------------------------- 1 | split: 2 | value: identity30 3 | dataset: 4 | value: pdbbind 5 | prot_mode: 6 | value: surface2backbone 7 | encoder: 8 | value: wln 9 | hsize: 10 | value: 512 11 | bhsize: 12 | value: 200 13 | shsize: 14 | value: 150 15 | bdepth: 16 | value: 5 17 | sdepth: 18 | value: 6 19 | lig_hsize: 20 | value: 300 21 | lig_depth: 22 | value: 4 23 | dropout_mlp: 24 | value: 0.3 25 | dropout_mpn: 26 | value: 0.15 27 | lr: 28 | value: 0.001 29 | clip_norm: 30 | value: 10.0 31 | weight_decay: 32 | value: 0.001 33 | epochs: 34 | value: 200 35 | num_workers: 36 | value: 6 37 | batch_size: 38 | value: 1 39 | step_after: 40 | value: 50 41 | scheduler_type: 42 | value: plateau 43 | accum_every: 44 | value: null 45 | metric_thresh: 46 | value: 0.01 47 | patience: 48 | value: 5 49 | accum_every: 50 | value: 32 51 | anneal_rate: 52 | value: 0.9 53 | use_doubles: 54 | value: False 55 | use_concat: 56 | value: False 57 | use_grad_noise: 58 | value: True 59 | use_attn: 60 | value: False 61 | print_every: 62 | value: 500 63 | eval_every: 64 | value: 1900 65 | ligand_only: 66 | value: False 67 | use_mpn_in_patch: 68 | value: False 69 | -------------------------------------------------------------------------------- /configs/train/pdbbind/identity60.yaml: -------------------------------------------------------------------------------- 1 | split: 2 | value: identity60 3 | dataset: 4 | value: pdbbind 5 | prot_mode: 6 | value: surface2backbone 7 | encoder: 8 | value: wln 9 | hsize: 10 | value: 512 11 | bhsize: 12 | value: 200 13 | shsize: 14 | value: 150 15 | bdepth: 16 | value: 5 17 | sdepth: 18 | value: 6 19 | lig_hsize: 20 | value: 300 21 | lig_depth: 22 | value: 4 23 | dropout_mlp: 24 | value: 0.3 25 | dropout_mpn: 26 | value: 0.15 27 | lr: 28 | value: 0.001 29 | clip_norm: 30 | value: 10.0 31 | weight_decay: 32 | value: 0.001 33 | epochs: 34 | value: 200 35 | num_workers: 36 | value: 6 37 | batch_size: 38 | value: 1 39 | step_after: 40 | value: 50 41 | scheduler_type: 42 | value: plateau 43 | accum_every: 44 | value: null 45 | metric_thresh: 46 | value: 0.01 47 | patience: 48 | value: 5 49 | accum_every: 50 | value: 32 51 | anneal_rate: 52 | value: 0.9 53 | use_doubles: 54 | value: False 55 | use_concat: 56 | value: False 57 | use_grad_noise: 58 | value: True 59 | use_attn: 60 | value: False 61 | print_every: 62 | value: 500 63 | eval_every: 64 | value: 1900 65 | ligand_only: 66 | value: False 67 | use_mpn_in_patch: 68 | value: False 69 | -------------------------------------------------------------------------------- /configs/train/pdbbind/scaffold.yaml: -------------------------------------------------------------------------------- 1 | split: 2 | value: scaffold 3 | dataset: 4 | value: pdbbind 5 | prot_mode: 6 | value: surface2backbone 7 | encoder: 8 | value: wln 9 | hsize: 10 | value: 512 11 | bhsize: 12 | value: 200 13 | shsize: 14 | value: 150 15 | bdepth: 16 | value: 5 17 | sdepth: 18 | value: 6 19 | lig_hsize: 20 | value: 300 21 | lig_depth: 22 | value: 4 23 | dropout_mlp: 24 | value: 0.3 25 | dropout_mpn: 26 | value: 0.15 27 | lr: 28 | value: 0.001 29 | clip_norm: 30 | value: 10.0 31 | weight_decay: 32 | value: 0.001 33 | epochs: 34 | value: 200 35 | num_workers: 36 | value: 6 37 | batch_size: 38 | value: 1 39 | step_after: 40 | value: 50 41 | scheduler_type: 42 | value: plateau 43 | accum_every: 44 | value: null 45 | metric_thresh: 46 | value: 0.01 47 | patience: 48 | value: 5 49 | accum_every: 50 | value: 32 51 | anneal_rate: 52 | value: 0.9 53 | use_doubles: 54 | value: False 55 | use_concat: 56 | value: False 57 | use_grad_noise: 58 | value: True 59 | use_attn: 60 | value: False 61 | print_every: 62 | value: 500 63 | eval_every: 64 | value: 1900 65 | ligand_only: 66 | value: False 67 | use_mpn_in_patch: 68 | value: False 69 | -------------------------------------------------------------------------------- /superpixel/pybind11/tools/libsize.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import print_function, division 3 | import os 4 | import sys 5 | 6 | # Internal build script for generating debugging test .so size. 7 | # Usage: 8 | # python libsize.py file.so save.txt -- displays the size of file.so and, if save.txt exists, compares it to the 9 | # size in it, then overwrites save.txt with the new size for future runs. 10 | 11 | if len(sys.argv) != 3: 12 | sys.exit("Invalid arguments: usage: python libsize.py file.so save.txt") 13 | 14 | lib = sys.argv[1] 15 | save = sys.argv[2] 16 | 17 | if not os.path.exists(lib): 18 | sys.exit("Error: requested file ({}) does not exist".format(lib)) 19 | 20 | libsize = os.path.getsize(lib) 21 | 22 | print("------", os.path.basename(lib), "file size:", libsize, end='') 23 | 24 | if os.path.exists(save): 25 | with open(save) as sf: 26 | oldsize = int(sf.readline()) 27 | 28 | if oldsize > 0: 29 | change = libsize - oldsize 30 | if change == 0: 31 | print(" (no change)") 32 | else: 33 | print(" (change of {:+} bytes = {:+.2%})".format(change, change / oldsize)) 34 | else: 35 | print() 36 | 37 | with open(save, 'w') as sf: 38 | sf.write(str(libsize)) 39 | -------------------------------------------------------------------------------- /superpixel/pybind11/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Make sure you've completed the following steps before submitting your issue -- thank you! 2 | 3 | 1. Check if your question has already been answered in the [FAQ](http://pybind11.readthedocs.io/en/latest/faq.html) section. 4 | 2. Make sure you've read the [documentation](http://pybind11.readthedocs.io/en/latest/). Your issue may be addressed there. 5 | 3. If those resources didn't help and you only have a short question (not a bug report), consider asking in the [Gitter chat room](https://gitter.im/pybind/Lobby). 6 | 4. If you have a genuine bug report or a more complex question which is not answered in the previous items (or not suitable for chat), please fill in the details below. 7 | 5. Include a self-contained and minimal piece of code that reproduces the problem. If that's not possible, try to make the description as clear as possible. 8 | 9 | *After reading, remove this checklist and the template text in parentheses below.* 10 | 11 | ## Issue description 12 | 13 | (Provide a short description, state the expected behavior and what actually happens.) 14 | 15 | ## Reproducible example code 16 | 17 | (The code should be minimal, have no external dependencies, isolate the function(s) that cause breakage. Submit matched and complete C++ and Python snippets that can be easily compiled and run to diagnose the issue.) 18 | -------------------------------------------------------------------------------- /superpixel/pybind11/.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: 3 | - Visual Studio 2015 4 | test: off 5 | skip_branch_with_pr: true 6 | build: 7 | parallel: true 8 | platform: 9 | - x86 10 | environment: 11 | matrix: 12 | - PYTHON: 36 13 | CONFIG: Debug 14 | - PYTHON: 27 15 | CONFIG: Debug 16 | install: 17 | - ps: | 18 | $env:CMAKE_GENERATOR = "Visual Studio 14 2015" 19 | if ($env:PLATFORM -eq "x64") { $env:PYTHON = "$env:PYTHON-x64" } 20 | $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts\;$env:PATH" 21 | python -W ignore -m pip install --upgrade pip wheel 22 | python -W ignore -m pip install pytest numpy --no-warn-script-location 23 | - ps: | 24 | Start-FileDownload 'http://bitbucket.org/eigen/eigen/get/3.3.3.zip' 25 | 7z x 3.3.3.zip -y > $null 26 | $env:CMAKE_INCLUDE_PATH = "eigen-eigen-67e894c6cd8f;$env:CMAKE_INCLUDE_PATH" 27 | build_script: 28 | - cmake -G "%CMAKE_GENERATOR%" -A "%CMAKE_ARCH%" 29 | -DCMAKE_CXX_STANDARD=14 30 | -DPYBIND11_WERROR=ON 31 | -DDOWNLOAD_CATCH=ON 32 | -DCMAKE_SUPPRESS_REGENERATION=1 33 | . 34 | - set MSBuildLogger="C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" 35 | - cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger% 36 | - cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger% 37 | on_failure: if exist "tests\test_cmake_build" type tests\test_cmake_build\*.log* 38 | -------------------------------------------------------------------------------- /superpixel/MERCLazyGreedy.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erclustering_lazy_greedy_h_ 24 | #define _m_erclustering_lazy_greedy_h_ 25 | 26 | #include "MERCClustering.h" 27 | 28 | class MERCLazyGreedy: public MERCClustering 29 | { 30 | public: 31 | 32 | // clustering with the cylce-free constraint 33 | MERCDisjointSet* ClusteringTree(int nVertices,MERCInput &edges,int kernel,double lambda,int nC); 34 | }; 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /superpixel/ers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "MERCLazyGreedy.h" 5 | #include "MERCInputGraph.h" 6 | #include "MERCOutput.h" 7 | 8 | namespace py = pybind11; 9 | 10 | using namespace std; 11 | 12 | class ERS { 13 | public: 14 | ERS( double lam) { lambda_ = lam;} 15 | double lambda_; 16 | 17 | py::array_t computeSegmentation(py::array_t edgeList, py::array_t edgeSim, int numNodes, int nC) { 18 | MERCInputGraph input; 19 | int kernel = 0; 20 | 21 | // read the graph for segmentation 22 | input.ReadGraph(edgeList, edgeSim, numNodes); 23 | 24 | // entropy rate superpixel segmentation 25 | MERCLazyGreedy merc; 26 | merc.ClusteringTreeIF(input.nNodes_, input, kernel, lambda_*1.0*nC, nC); 27 | vector label = MERCOutput::DisjointSetToLabel(merc.disjointSet_); 28 | 29 | py::array_t result = py::array_t(input.nNodes_); 30 | py::buffer_info buf_out = result.request(); 31 | float *out = (float *) buf_out.ptr; 32 | 33 | for (int num = 0; num < input.nNodes_; num++){ 34 | out[num] = (float)label[num]; 35 | } 36 | return result; 37 | } 38 | }; 39 | 40 | 41 | PYBIND11_MODULE(ers, m) { 42 | m.doc() = "Python Bindings for Entropy Rate Superpixel"; 43 | 44 | py::class_(m, "ERS") 45 | .def(py::init()) 46 | .def("computeSegmentation", &ERS::computeSegmentation); 47 | } 48 | -------------------------------------------------------------------------------- /superpixel/MERCOutput.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_output_h_ 24 | #define _m_erc_output_h_ 25 | 26 | #include 27 | #include 28 | #include 29 | #include "MERCDisjointSet.h" 30 | using namespace std; 31 | 32 | class MERCOutput 33 | { 34 | public: 35 | 36 | // Convert disjoint the set structure to a label array 37 | static vector DisjointSetToLabel(MERCDisjointSet *u); 38 | 39 | // Store the clustering map 40 | static void StoreClusteringMap(vector &label,const char *filename); 41 | }; 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /scripts/preprocess/prepare_graphs.py: -------------------------------------------------------------------------------- 1 | import os 2 | import argparse 3 | import torch 4 | torch.multiprocessing.set_sharing_strategy('file_system') 5 | 6 | from holoprot.utils import str2bool 7 | from holoprot.data.handlers import PDBBind, Enzyme 8 | 9 | HANDLERS = {'pdbbind': PDBBind, 'enzyme': Enzyme} 10 | DATA_DIR = os.path.join(os.environ['PROT'], "datasets") 11 | 12 | 13 | def main(): 14 | parser = argparse.ArgumentParser() 15 | parser.add_argument("--data_dir", type=str, default=DATA_DIR, help="Data Directory") 16 | parser.add_argument("--prot_mode", default='surface2backbone') 17 | parser.add_argument("--dataset", default='pdbbind', help="Dataset for which we prepare graphs.") 18 | parser.add_argument("--exp_name", default="PatchPointCloud_06-01-2021--20-20-00") 19 | parser.add_argument("--use_mp", default=True, type=str2bool) 20 | parser.add_argument("--pdb_ids", nargs="+", default=None) 21 | parser.add_argument("--n_segments", type=int, default=20, help="Number of patches ") 22 | args = parser.parse_args() 23 | 24 | handler_cls = HANDLERS.get(args.dataset) 25 | 26 | kwargs = {} 27 | if args.prot_mode in ['backbone2patch', 'patch2backbone']: 28 | kwargs['exp_name'] = args.exp_name 29 | kwargs['n_segments'] = args.n_segments 30 | 31 | handler = handler_cls(dataset=args.dataset, 32 | data_dir=args.data_dir, 33 | prot_mode=args.prot_mode, 34 | use_mp=args.use_mp, **kwargs) 35 | handler.process_ids(pdb_ids=args.pdb_ids) 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /holoprot/layers/mpn/__init__.py: -------------------------------------------------------------------------------- 1 | from holoprot.layers.mpn.wln import WLNConv, WLNResConv 2 | from holoprot.layers.mpn.rnn import GRUConv, LSTMConv 3 | 4 | WLNs = {'wln': WLNConv, 'wlnres': WLNResConv} 5 | RNNs = {'gru': GRUConv, 'lstm': LSTMConv} 6 | 7 | def mpn_layer_from_config(config, encoder): 8 | if encoder in WLNs: 9 | layer_class = WLNs.get(encoder) 10 | mpn_layer = layer_class(node_fdim=config['node_fdim'], 11 | edge_fdim=config['edge_fdim'], 12 | hsize=config['hsize'], 13 | depth=config['depth'], 14 | dropout=config['dropout_p'], 15 | activation=config['activation'], 16 | jk_pool=config.get("jk_pool", None)) 17 | elif encoder in RNNs: 18 | raise NotImplementedError("RNN layers currently do not work with the codebase") 19 | layer_class = RNNs.get(encoder) 20 | mpn_layer = layer_class(node_fdim=config['node_fdim'], 21 | edge_fdim=config['edge_fdim'], 22 | hsize=config['hsize'], 23 | depth=config['depth'], 24 | dropout=config['dropout_p'], 25 | rnn_agg=config.get("rnn_agg", None), 26 | activation=config['activation']) 27 | elif encoder == 'gtrans': 28 | raise NotImplementedError() 29 | 30 | else: 31 | raise ValueError(f"Encoder {encoder} is not supported yet.") 32 | return mpn_layer 33 | -------------------------------------------------------------------------------- /superpixel/MERCInput.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_input_h_ 24 | #define _m_erc_input_h_ 25 | 26 | #include 27 | #include 28 | #include "Edge.h" 29 | 30 | using namespace std; 31 | 32 | class MERCInput 33 | { 34 | public: 35 | MERCInput(); 36 | ~MERCInput(); 37 | void Release(); 38 | void Write(const char* filename); 39 | void Read(const char* filename); 40 | void ReadFromMatlab(double *pI,double *pJ,double *pW,int nEdges,int nNodes); 41 | 42 | public: 43 | Edge *edges_; 44 | int nEdges_; 45 | int nNodes_; 46 | 47 | }; 48 | 49 | #endif -------------------------------------------------------------------------------- /superpixel/pybind11/tools/check-style.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Script to check include/test code for common pybind11 code style errors. 4 | # 5 | # This script currently checks for 6 | # 7 | # 1. missing space between keyword and parenthesis, e.g.: for(, if(, while( 8 | # 2. Missing space between right parenthesis and brace, e.g. 'for (...){' 9 | # 3. opening brace on its own line. It should always be on the same line as the 10 | # if/while/for/do statement. 11 | # 12 | # Invoke as: tools/check-style.sh 13 | # 14 | 15 | check_style_errors=0 16 | IFS=$'\n' 17 | 18 | 19 | found="$(grep '\<\(if\|for\|while\|catch\)(\|){' $@ -rn --color=always)" 20 | if [ -n "$found" ]; then 21 | echo -e '\033[31;01mError: found the following coding style problems:\033[0m' 22 | check_style_errors=1 23 | echo "$found" | sed -e 's/^/ /' 24 | fi 25 | 26 | found="$(awk ' 27 | function prefix(filename, lineno) { 28 | return " \033[35m" filename "\033[36m:\033[32m" lineno "\033[36m:\033[0m" 29 | } 30 | function mark(pattern, string) { sub(pattern, "\033[01;31m&\033[0m", string); return string } 31 | last && /^\s*{/ { 32 | print prefix(FILENAME, FNR-1) mark("\\)\\s*$", last) 33 | print prefix(FILENAME, FNR) mark("^\\s*{", $0) 34 | last="" 35 | } 36 | { last = /(if|for|while|catch|switch)\s*\(.*\)\s*$/ ? $0 : "" } 37 | ' $(find include -type f) $@)" 38 | if [ -n "$found" ]; then 39 | check_style_errors=1 40 | echo -e '\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\033[0m' 41 | echo "$found" 42 | fi 43 | 44 | exit $check_style_errors 45 | -------------------------------------------------------------------------------- /superpixel/pybind11/.github/workflows/configure.yml: -------------------------------------------------------------------------------- 1 | name: Config 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | push: 7 | branches: 8 | - master 9 | - stable 10 | - v* 11 | 12 | jobs: 13 | cmake: 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | runs-on: [ubuntu-latest, macos-latest] 18 | arch: [x64] 19 | cmake: [3.7, 3.18] 20 | 21 | include: 22 | - runs-on: windows-latest 23 | arch: x64 24 | cmake: 3.18 25 | 26 | # TODO: 3.8 27 | - runs-on: windows-2016 28 | arch: x86 29 | cmake: 3.11 30 | 31 | - runs-on: windows-2016 32 | arch: x86 33 | cmake: 3.18 34 | 35 | name: 🐍 3.7 • CMake ${{ matrix.cmake }} • ${{ matrix.runs-on }} 36 | runs-on: ${{ matrix.runs-on }} 37 | 38 | steps: 39 | - uses: actions/checkout@v2 40 | 41 | - name: Setup Python 3.7 42 | uses: actions/setup-python@v2 43 | with: 44 | python-version: 3.7 45 | architecture: ${{ matrix.arch }} 46 | 47 | - name: Prepare env 48 | run: python -m pip install -r tests/requirements.txt 49 | 50 | - name: Setup CMake ${{ matrix.cmake }} 51 | uses: jwlawson/actions-setup-cmake@v1.3 52 | with: 53 | cmake-version: ${{ matrix.cmake }} 54 | 55 | - name: Make build directories 56 | run: mkdir "build dir" 57 | 58 | - name: Configure 59 | working-directory: build dir 60 | shell: bash 61 | run: > 62 | cmake .. 63 | -DPYBIND11_WERROR=ON 64 | -DDOWNLOAD_CATCH=ON 65 | -DPYTHON_EXECUTABLE=$(python -c "import sys; print(sys.executable)") 66 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/cast/index.rst: -------------------------------------------------------------------------------- 1 | Type conversions 2 | ################ 3 | 4 | Apart from enabling cross-language function calls, a fundamental problem 5 | that a binding tool like pybind11 must address is to provide access to 6 | native Python types in C++ and vice versa. There are three fundamentally 7 | different ways to do this—which approach is preferable for a particular type 8 | depends on the situation at hand. 9 | 10 | 1. Use a native C++ type everywhere. In this case, the type must be wrapped 11 | using pybind11-generated bindings so that Python can interact with it. 12 | 13 | 2. Use a native Python type everywhere. It will need to be wrapped so that 14 | C++ functions can interact with it. 15 | 16 | 3. Use a native C++ type on the C++ side and a native Python type on the 17 | Python side. pybind11 refers to this as a *type conversion*. 18 | 19 | Type conversions are the most "natural" option in the sense that native 20 | (non-wrapped) types are used everywhere. The main downside is that a copy 21 | of the data must be made on every Python ↔ C++ transition: this is 22 | needed since the C++ and Python versions of the same type generally won't 23 | have the same memory layout. 24 | 25 | pybind11 can perform many kinds of conversions automatically. An overview 26 | is provided in the table ":ref:`conversion_table`". 27 | 28 | The following subsections discuss the differences between these options in more 29 | detail. The main focus in this section is on type conversions, which represent 30 | the last case of the above list. 31 | 32 | .. toctree:: 33 | :maxdepth: 1 34 | 35 | overview 36 | strings 37 | stl 38 | functional 39 | chrono 40 | eigen 41 | custom 42 | -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/detail/typeid.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/typeid.h: Compiler-independent access to type identifiers 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include 13 | #include 14 | 15 | #if defined(__GNUG__) 16 | #include 17 | #endif 18 | 19 | #include "common.h" 20 | 21 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 22 | PYBIND11_NAMESPACE_BEGIN(detail) 23 | /// Erase all occurrences of a substring 24 | inline void erase_all(std::string &string, const std::string &search) { 25 | for (size_t pos = 0;;) { 26 | pos = string.find(search, pos); 27 | if (pos == std::string::npos) break; 28 | string.erase(pos, search.length()); 29 | } 30 | } 31 | 32 | PYBIND11_NOINLINE inline void clean_type_id(std::string &name) { 33 | #if defined(__GNUG__) 34 | int status = 0; 35 | std::unique_ptr res { 36 | abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free }; 37 | if (status == 0) 38 | name = res.get(); 39 | #else 40 | detail::erase_all(name, "class "); 41 | detail::erase_all(name, "struct "); 42 | detail::erase_all(name, "enum "); 43 | #endif 44 | detail::erase_all(name, "pybind11::"); 45 | } 46 | PYBIND11_NAMESPACE_END(detail) 47 | 48 | /// Return a string representation of a C++ type 49 | template static std::string type_id() { 50 | std::string name(typeid(T).name()); 51 | detail::clean_type_id(name); 52 | return name; 53 | } 54 | 55 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 56 | -------------------------------------------------------------------------------- /superpixel/pybind11/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Wenzel Jakob , All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | 3. Neither the name of the copyright holder nor the names of its contributors 14 | may be used to endorse or promote products derived from this software 15 | without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 21 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | 28 | Please also refer to the file CONTRIBUTING.md, which clarifies licensing of 29 | external contributions to this project including patches, pull requests, etc. 30 | -------------------------------------------------------------------------------- /holoprot/utils/backbone.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utility functions for computing residue depth. 3 | """ 4 | 5 | import numpy as np 6 | from Bio.PDB.Residue import Residue 7 | 8 | 9 | def get_res_depth(residue: Residue, vertices: np.ndarray) -> np.ndarray: 10 | """ 11 | Computes depth (distance from surface) for each residue, computed as an 12 | average of the depths of each atom in the residue. 13 | 14 | Parameters 15 | ---------- 16 | residue: Residue 17 | residue whose c-alpha atom we compute depth for 18 | vertices: np.ndarray, 19 | 20 | Returns 21 | ------- 22 | d: np.ndarray, 23 | Minimum distance of the c-alpha atom and the vertices 24 | """ 25 | d_list = [min_dist(atom.get_coord(), vertices) for atom in residue] 26 | d = sum(d_list) 27 | d = d / len(d_list) 28 | return d 29 | 30 | 31 | def get_ca_depth(residue: Residue, vertices: np.ndarray) -> np.ndarray: 32 | """Computes depth (distance from surface) for C-alpha atoms in each residue. 33 | 34 | Parameters 35 | ---------- 36 | residue: Residue 37 | residue whose c-alpha atom we compute depth for 38 | vertices: np.ndarray, 39 | Vertex coordinates of the surface. 40 | 41 | Returns 42 | ------- 43 | dist: np.ndarray, 44 | Minimum distance of the c-alpha atom and the vertices 45 | """ 46 | if not residue.has_id("CA"): 47 | return None 48 | ca = residue["CA"] 49 | coord = ca.get_coord() 50 | dist = min_dist(coord, vertices) 51 | return dist 52 | 53 | 54 | def min_dist(coord: np.ndarray, vertices: np.ndarray) -> np.ndarray: 55 | """Computes minimum distance from coord to surface. 56 | 57 | Parameters 58 | ---------- 59 | coord: np.ndarray, 60 | Coordinate vector for point 61 | vertices: np.ndarray, 62 | Surface vertices coordinates 63 | 64 | Returns 65 | ------- 66 | minimum distance of coordinate to vertices. 67 | """ 68 | d = vertices - coord 69 | d2 = np.sum(d * d, 1) 70 | return np.sqrt(min(d2)) 71 | -------------------------------------------------------------------------------- /superpixel/MERCInputGraph.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_input_graph_h_ 24 | #define _m_erc_input_graph_h_ 25 | 26 | #include "MERCInput.h" 27 | #include 28 | 29 | namespace py = pybind11; 30 | 31 | using namespace std; 32 | 33 | template 34 | class MERCInputGraph: public MERCInput 35 | { 36 | public: 37 | void ReadGraph(py::array_t edgeList, py::array_t edgeSim, int numNodes); 38 | }; 39 | 40 | template 41 | void MERCInputGraph::ReadGraph(py::array_t edgeList, py::array_t edgeSim, int numNodes){ 42 | auto bufList = edgeList.unchecked<2>(); 43 | py::buffer_info bufSim = edgeSim.request(); 44 | double *bufSimPtr = (double *) bufSim.ptr; 45 | 46 | nEdges_ = bufList.shape(0); 47 | nNodes_ = numNodes; 48 | edges_ = new Edge [nEdges_]; 49 | 50 | for (int num = 0; num < nEdges_; num++){ 51 | edges_[num].a_ = bufList(num, 0); 52 | edges_[num].b_ = bufList(num, 1); 53 | edges_[num].w_ = bufSimPtr[num]; 54 | } 55 | 56 | } 57 | 58 | #endif 59 | -------------------------------------------------------------------------------- /superpixel/MERCClustering.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erclustering_h_ 24 | #define _m_erclustering_h_ 25 | 26 | #include "MERCDisjointSet.h" 27 | #include "MERCInput.h" 28 | #include "MERCEdge.h" 29 | #include "MSubmodularHeap.h" 30 | #include "MERCFunctions.h" 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | using namespace std; 39 | 40 | 41 | class MERCClustering 42 | { 43 | public: 44 | 45 | void ClusteringTreeIF(int nVertices,MERCInput &edges,int kernel,double lambda,int nC) 46 | { 47 | disjointSet_ = ClusteringTree(nVertices,edges,kernel,lambda,nC); 48 | }; 49 | 50 | virtual MERCDisjointSet* ClusteringTree(int nVertices,MERCInput &edges,int kernel,double lambda,int nC) = 0; 51 | 52 | MERCClustering() 53 | { 54 | disjointSet_ = NULL; 55 | }; 56 | 57 | ~MERCClustering() 58 | { 59 | Release(); 60 | }; 61 | 62 | void Release() 63 | { 64 | if(disjointSet_) 65 | delete disjointSet_; 66 | }; 67 | 68 | MERCDisjointSet *disjointSet_; 69 | 70 | }; 71 | 72 | #endif 73 | -------------------------------------------------------------------------------- /holoprot/feat/__init__.py: -------------------------------------------------------------------------------- 1 | from rdkit import Chem 2 | 3 | #Kyte-Doolittle scale for hydrophobicity 4 | KD_SCALE = {} 5 | KD_SCALE["ILE"] = 4.5 6 | KD_SCALE["VAL"] = 4.2 7 | KD_SCALE["LEU"] = 3.8 8 | KD_SCALE["PHE"] = 2.8 9 | KD_SCALE["CYS"] = 2.5 10 | KD_SCALE["MET"] = 1.9 11 | KD_SCALE["ALA"] = 1.8 12 | KD_SCALE["GLY"] = -0.4 13 | KD_SCALE["THR"] = -0.7 14 | KD_SCALE["SER"] = -0.8 15 | KD_SCALE["TRP"] = -0.9 16 | KD_SCALE["TYR"] = -1.3 17 | KD_SCALE["PRO"] = -1.6 18 | KD_SCALE["HIS"] = -3.2 19 | KD_SCALE["GLU"] = -3.5 20 | KD_SCALE["GLN"] = -3.5 21 | KD_SCALE["ASP"] = -3.5 22 | KD_SCALE["ASN"] = -3.5 23 | KD_SCALE["LYS"] = -3.9 24 | KD_SCALE["ARG"] = -4.5 25 | 26 | # Symbols for different atoms 27 | ATOM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', \ 28 | 'As', 'Al', 'I', 'B', 'V', 'K', 'Tl', 'Yb', 'Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se', 'Ti', \ 29 | 'Zn', 'H', 'Li', 'Ge', 'Cu', 'Au', 'Ni', 'Cd', 'In', 'Mn', 'Zr', 'Cr', 'Pt', 'Hg', 'Pb', \ 30 | 'W', 'Ru', 'Nb', 'Re', 'Te', 'Rh', 'Ta', 'Tc', 'Ba', 'Bi', 'Hf', 'Mo', 'U', 'Sm', 'Os', 'Ir', \ 31 | 'Ce','Gd','Ga','Cs', '*', 'unk'] 32 | 33 | AMINO_ACIDS = [ 34 | 'ALA', 'CYS', 'ASP', 'GLU', 'PHE', 'GLY', 'HIS', 'ILE', 'LYS', 'LEU', 'MET', 35 | 'ASN', 'PYL', 'PRO', 'GLN', 'ARG', 'SER', 'THR', 'SEC', 'VAL', 'TRP', 'TYR', 36 | 'unk' 37 | ] 38 | 39 | SECONDARY_STRUCTS = ['H', 'G', 'I', 'E', 'B', 'T', 'C', 'unk'] 40 | 41 | MAX_NB = 10 42 | DEGREES = list(range(MAX_NB)) 43 | EXP_VALENCE = [1, 2, 3, 4, 5, 6] 44 | IMP_VALENCE = [0, 1, 2, 3, 4, 5] 45 | 46 | BOND_TYPES = [None, Chem.rdchem.BondType.SINGLE, Chem.rdchem.BondType.DOUBLE, \ 47 | Chem.rdchem.BondType.TRIPLE, Chem.rdchem.BondType.AROMATIC] 48 | BOND_FLOAT_TO_TYPE = { 49 | 0.0: BOND_TYPES[0], 50 | 1.0: BOND_TYPES[1], 51 | 2.0: BOND_TYPES[2], 52 | 3.0: BOND_TYPES[3], 53 | 1.5: BOND_TYPES[4], 54 | } 55 | 56 | BOND_FLOATS = [0.0, 1.0, 2.0, 3.0, 1.5] 57 | 58 | ATOM_FDIM = len(ATOM_LIST) + len(DEGREES) + len(EXP_VALENCE) + len( 59 | IMP_VALENCE) + 1 60 | BOND_FDIM = 6 61 | CONTACT_FDIM = 2 62 | SURFACE_NODE_FDIM = 4 63 | SURFACE_EDGE_FDIM = 5 64 | PATCH_NODE_FDIM = 4 65 | PATCH_EDGE_FDIM = 4 66 | -------------------------------------------------------------------------------- /superpixel/pybind11/tests/cross_module_gil_utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module 3 | 4 | Copyright (c) 2019 Google LLC 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | #include 10 | #include 11 | 12 | // This file mimics a DSO that makes pybind11 calls but does not define a 13 | // PYBIND11_MODULE. The purpose is to test that such a DSO can create a 14 | // py::gil_scoped_acquire when the running thread is in a GIL-released state. 15 | // 16 | // Note that we define a Python module here for convenience, but in general 17 | // this need not be the case. The typical scenario would be a DSO that implements 18 | // shared logic used internally by multiple pybind11 modules. 19 | 20 | namespace { 21 | 22 | namespace py = pybind11; 23 | void gil_acquire() { py::gil_scoped_acquire gil; } 24 | 25 | constexpr char kModuleName[] = "cross_module_gil_utils"; 26 | 27 | #if PY_MAJOR_VERSION >= 3 28 | struct PyModuleDef moduledef = { 29 | PyModuleDef_HEAD_INIT, 30 | kModuleName, 31 | NULL, 32 | 0, 33 | NULL, 34 | NULL, 35 | NULL, 36 | NULL, 37 | NULL 38 | }; 39 | #else 40 | PyMethodDef module_methods[] = { 41 | {NULL, NULL, 0, NULL} 42 | }; 43 | #endif 44 | 45 | } // namespace 46 | 47 | extern "C" PYBIND11_EXPORT 48 | #if PY_MAJOR_VERSION >= 3 49 | PyObject* PyInit_cross_module_gil_utils() 50 | #else 51 | void initcross_module_gil_utils() 52 | #endif 53 | { 54 | 55 | PyObject* m = 56 | #if PY_MAJOR_VERSION >= 3 57 | PyModule_Create(&moduledef); 58 | #else 59 | Py_InitModule(kModuleName, module_methods); 60 | #endif 61 | 62 | if (m != NULL) { 63 | static_assert( 64 | sizeof(&gil_acquire) == sizeof(void*), 65 | "Function pointer must have the same size as void*"); 66 | PyModule_AddObject(m, "gil_acquire_funcaddr", 67 | PyLong_FromVoidPtr(reinterpret_cast(&gil_acquire))); 68 | } 69 | 70 | #if PY_MAJOR_VERSION >= 3 71 | return m; 72 | #endif 73 | } 74 | -------------------------------------------------------------------------------- /superpixel/MERCOutput.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCOutput.h" 24 | 25 | void MERCOutput::StoreClusteringMap(vector &label,const char *filename) 26 | { 27 | std::ofstream file; 28 | file.open(filename); 29 | 30 | for(int i=0;i MERCOutput::DisjointSetToLabel(MERCDisjointSet *u) 39 | { 40 | int nSegments=0; 41 | int segIndex = 0; 42 | int nVertices = u->rNumVertices(); 43 | std::vector *sarray = new std::vector [nVertices]; 44 | vector labeling(nVertices); 45 | 46 | for (int k=0; kFind(k); 49 | sarray[comp].push_back(k); 50 | } 51 | 52 | for(int k=0;k 0) 55 | { 56 | nSegments++; 57 | } 58 | } 59 | 60 | for(int k=0;k 0) 63 | { 64 | for(unsigned int j=0;j 27 | #include 28 | #include 29 | #include 30 | #include "MList.h" 31 | 32 | 33 | class MERCDisjointSet 34 | { 35 | public: 36 | MERCDisjointSet(int nElements); 37 | ~MERCDisjointSet(); 38 | virtual void Release(); 39 | 40 | // set the pixel x with label l 41 | virtual void Set(int x,int l); 42 | 43 | // find the cluster ID for a given vertex 44 | virtual int Find(int x); 45 | 46 | // joint the cluster contains vertex y and the cluster contains vertex x 47 | virtual int Join(int x,int y); 48 | 49 | // return the cluster size containing the vertex x 50 | int rSize(int x) {return size_[Find(x)];}; 51 | 52 | // return the number of connected components in the set 53 | int rNumSets() const {return nElements_;}; 54 | 55 | // return the total number of vertices in the set 56 | int rNumVertices() const {return nVertices_;}; 57 | 58 | private: 59 | 60 | int *p_; 61 | int *size_; 62 | MList *lists_; 63 | int nElements_; 64 | int nVertices_; 65 | }; 66 | 67 | 68 | 69 | 70 | #endif 71 | 72 | -------------------------------------------------------------------------------- /superpixel/MERCFunctions.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_functions_h_ 24 | #define _m_erc_functions_h_ 25 | 26 | #include "MERCInput.h" 27 | #include 28 | #include 29 | 30 | // Note the potential numerical error. Don't use a very small sigma value. 31 | class MERCFunctions 32 | { 33 | public: 34 | 35 | // compute the similarity scores 36 | static void ComputeSimilarity(MERCInput &edges,double sigma,int kernel=0); 37 | 38 | // compute the similarity scores with the Gaussian kernel. 39 | static void ComputeSimilarityGaussian(MERCInput &edges,double sigma); 40 | 41 | // compute the initial loop weight 42 | static double* ComputeLoopWeight(int nVertices,MERCInput &edges); 43 | 44 | // compute the total weight in the graph 45 | static double ComputeTotalWeight(double *loop,int nVertices); 46 | 47 | // normalize the edge similarity scores 48 | static void NormalizeEdgeWeight(MERCInput &edges,double *loop,double wT); 49 | 50 | // compute the edge gain in the entropy rate 51 | static double ComputeERGain(double wij,double ci,double cj); 52 | 53 | // compute the edge gain in the balancing term 54 | static double ComputeBGain(int nVertices, int si,int sj); 55 | 56 | }; 57 | 58 | #endif -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/complex.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/complex.h: Complex number support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | /// glibc defines I as a macro which breaks things, e.g., boost template names 16 | #ifdef I 17 | # undef I 18 | #endif 19 | 20 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 21 | 22 | template struct format_descriptor, detail::enable_if_t::value>> { 23 | static constexpr const char c = format_descriptor::c; 24 | static constexpr const char value[3] = { 'Z', c, '\0' }; 25 | static std::string format() { return std::string(value); } 26 | }; 27 | 28 | #ifndef PYBIND11_CPP17 29 | 30 | template constexpr const char format_descriptor< 31 | std::complex, detail::enable_if_t::value>>::value[3]; 32 | 33 | #endif 34 | 35 | PYBIND11_NAMESPACE_BEGIN(detail) 36 | 37 | template struct is_fmt_numeric, detail::enable_if_t::value>> { 38 | static constexpr bool value = true; 39 | static constexpr int index = is_fmt_numeric::index + 3; 40 | }; 41 | 42 | template class type_caster> { 43 | public: 44 | bool load(handle src, bool convert) { 45 | if (!src) 46 | return false; 47 | if (!convert && !PyComplex_Check(src.ptr())) 48 | return false; 49 | Py_complex result = PyComplex_AsCComplex(src.ptr()); 50 | if (result.real == -1.0 && PyErr_Occurred()) { 51 | PyErr_Clear(); 52 | return false; 53 | } 54 | value = std::complex((T) result.real, (T) result.imag); 55 | return true; 56 | } 57 | 58 | static handle cast(const std::complex &src, return_value_policy /* policy */, handle /* parent */) { 59 | return PyComplex_FromDoubles((double) src.real(), (double) src.imag()); 60 | } 61 | 62 | PYBIND11_TYPE_CASTER(std::complex, _("complex")); 63 | }; 64 | PYBIND11_NAMESPACE_END(detail) 65 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/options.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/options.h: global settings that are configurable at runtime. 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "detail/common.h" 13 | 14 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | 16 | class options { 17 | public: 18 | 19 | // Default RAII constructor, which leaves settings as they currently are. 20 | options() : previous_state(global_state()) {} 21 | 22 | // Class is non-copyable. 23 | options(const options&) = delete; 24 | options& operator=(const options&) = delete; 25 | 26 | // Destructor, which restores settings that were in effect before. 27 | ~options() { 28 | global_state() = previous_state; 29 | } 30 | 31 | // Setter methods (affect the global state): 32 | 33 | options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; } 34 | 35 | options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; } 36 | 37 | options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; } 38 | 39 | options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; } 40 | 41 | // Getter methods (return the global state): 42 | 43 | static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; } 44 | 45 | static bool show_function_signatures() { return global_state().show_function_signatures; } 46 | 47 | // This type is not meant to be allocated on the heap. 48 | void* operator new(size_t) = delete; 49 | 50 | private: 51 | 52 | struct state { 53 | bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings. 54 | bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings. 55 | }; 56 | 57 | static state &global_state() { 58 | static state instance; 59 | return instance; 60 | } 61 | 62 | state previous_state; 63 | }; 64 | 65 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /superpixel/Edge.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _edge_h_ 24 | #define _edge_h_ 25 | 26 | class Edge 27 | { 28 | public: 29 | int a_; 30 | int b_; 31 | double w_; 32 | double gain_; 33 | inline Edge &operator=(const Edge &rhs); 34 | inline bool operator==(const Edge &other) const; 35 | inline bool operator!=(const Edge &other) const; 36 | inline bool operator>=(const Edge &other) const; 37 | inline bool operator<=(const Edge &other) const; 38 | inline bool operator>(const Edge &other) const; 39 | inline bool operator<(const Edge &other) const; 40 | }; 41 | #endif 42 | 43 | Edge &Edge::operator=(const Edge &rhs) 44 | { 45 | a_ = rhs.a_; 46 | b_ = rhs.b_; 47 | w_ = rhs.w_; 48 | gain_ = rhs.gain_; 49 | return *this; 50 | } 51 | 52 | bool Edge::operator==(const Edge &other) const 53 | { 54 | return w_ == other.w_; 55 | } 56 | 57 | bool Edge::operator!=(const Edge &other) const 58 | { 59 | return w_ != other.w_; 60 | } 61 | 62 | bool Edge::operator>=(const Edge &other) const 63 | { 64 | return w_ >= other.w_; 65 | } 66 | 67 | bool Edge::operator<=(const Edge &other) const 68 | { 69 | return w_ <= other.w_; 70 | } 71 | 72 | bool Edge::operator>(const Edge &other) const 73 | { 74 | return w_ > other.w_; 75 | } 76 | 77 | bool Edge::operator<(const Edge &other) const 78 | { 79 | return w_ < other.w_; 80 | } -------------------------------------------------------------------------------- /superpixel/pybind11/tests/local_bindings.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pybind11_tests.h" 3 | 4 | /// Simple class used to test py::local: 5 | template class LocalBase { 6 | public: 7 | LocalBase(int i) : i(i) { } 8 | int i = -1; 9 | }; 10 | 11 | /// Registered with py::module_local in both main and secondary modules: 12 | using LocalType = LocalBase<0>; 13 | /// Registered without py::module_local in both modules: 14 | using NonLocalType = LocalBase<1>; 15 | /// A second non-local type (for stl_bind tests): 16 | using NonLocal2 = LocalBase<2>; 17 | /// Tests within-module, different-compilation-unit local definition conflict: 18 | using LocalExternal = LocalBase<3>; 19 | /// Mixed: registered local first, then global 20 | using MixedLocalGlobal = LocalBase<4>; 21 | /// Mixed: global first, then local 22 | using MixedGlobalLocal = LocalBase<5>; 23 | 24 | /// Registered with py::module_local only in the secondary module: 25 | using ExternalType1 = LocalBase<6>; 26 | using ExternalType2 = LocalBase<7>; 27 | 28 | using LocalVec = std::vector; 29 | using LocalVec2 = std::vector; 30 | using LocalMap = std::unordered_map; 31 | using NonLocalVec = std::vector; 32 | using NonLocalVec2 = std::vector; 33 | using NonLocalMap = std::unordered_map; 34 | using NonLocalMap2 = std::unordered_map; 35 | 36 | PYBIND11_MAKE_OPAQUE(LocalVec); 37 | PYBIND11_MAKE_OPAQUE(LocalVec2); 38 | PYBIND11_MAKE_OPAQUE(LocalMap); 39 | PYBIND11_MAKE_OPAQUE(NonLocalVec); 40 | //PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 41 | PYBIND11_MAKE_OPAQUE(NonLocalMap); 42 | PYBIND11_MAKE_OPAQUE(NonLocalMap2); 43 | 44 | 45 | // Simple bindings (used with the above): 46 | template 47 | py::class_ bind_local(Args && ...args) { 48 | return py::class_(std::forward(args)...) 49 | .def(py::init()) 50 | .def("get", [](T &i) { return i.i + Adjust; }); 51 | }; 52 | 53 | // Simulate a foreign library base class (to match the example in the docs): 54 | namespace pets { 55 | class Pet { 56 | public: 57 | Pet(std::string name) : name_(name) {} 58 | std::string name_; 59 | const std::string &name() { return name_; } 60 | }; 61 | } 62 | 63 | struct MixGL { int i; MixGL(int i) : i{i} {} }; 64 | struct MixGL2 { int i; MixGL2(int i) : i{i} {} }; 65 | -------------------------------------------------------------------------------- /holoprot/utils/metrics.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import stats 3 | from sklearn import metrics 4 | 5 | def accuracy_fn(y_true, y_pred): 6 | if not isinstance(y_pred, np.ndarray): 7 | y_pred = np.asarray(y_pred).astype(int) 8 | y_true = np.asarray(y_true).astype(int) 9 | return np.mean(y_true == y_pred) 10 | 11 | def pearsonr_fn(y_true, y_pred): 12 | r, pval = stats.pearsonr(y_true, y_pred) 13 | return r 14 | 15 | def rmse_fn(y_true, y_pred): 16 | mse = metrics.mean_squared_error(y_true, y_pred) 17 | rmse = np.sqrt(mse) 18 | return rmse 19 | 20 | def r2_fn(y_true, y_pred): 21 | return metrics.r2_score(y_true, y_pred) 22 | 23 | def mae_fn(y_true, y_pred): 24 | return metrics.mean_absolute_error(y_true, y_pred) 25 | 26 | def spearmanr_fn(y_true, y_pred): 27 | return stats.spearmanr(y_true, y_pred)[0] 28 | 29 | 30 | METRICS = {'accuracy': (accuracy_fn, 0.0, np.greater), 31 | 'pearsonr': (pearsonr_fn, 0.0, np.greater), 32 | 'loss': (None, np.inf, np.less), 33 | 'rmse': (rmse_fn, np.inf, np.less), 34 | 'mae': (mae_fn, np.inf, np.less), 35 | 'r2': (r2_fn, 0.0, np.greater), 36 | 'spearmanr': (spearmanr_fn, 0.0, np.greater)} 37 | 38 | DATASET_METRICS = {'pdbbind': ['rmse', 'pearsonr', 'mae', 'r2', 'spearmanr'], 39 | 'reacbio': ['rmse', 'pearsonr', 'mae', 'r2', 'spearmanr'], 40 | 'scope': 'accuracy', 41 | 'enzyme': 'accuracy'} 42 | 43 | EVAL_METRICS = {'pdbbind': {'patch': 'loss', 'backbone': 'rmse', 'surface': 'rmse', 'backbone2surface': 'rmse', 44 | 'surface2backbone': 'rmse', 'backbone2patch': 'rmse', 'patch2backbone': 'rmse'}, 45 | 'reacbio': {'patch': 'loss', 'backbone': 'rmse', 'surface': 'rmse', 'backbone2surface': 'rmse', 46 | 'surface2backbone': 'rmse', 'backbone2patch': 'rmse', 'patch2backbone': 'rmse'}, 47 | 'scope': {'patch': 'loss', 'backbone': 'accuracy', 'surface': 'accuracy', 48 | 'backbone2surface': 'accuracy', 'surface2backbone': 'accuracy', 'patch2backbone': 'accuracy'}, 49 | 'enzyme': {'patch': 'loss', 'backbone': 'accuracy', 'surface': 'accuracy', 50 | 'backbone2surface': 'accuracy', 'backbone2patch': 'accuracy', 51 | 'surface2backbone': 'accuracy', 'patch2backbone': 'accuracy'}} 52 | -------------------------------------------------------------------------------- /superpixel/pybind11/tools/FindCatch.cmake: -------------------------------------------------------------------------------- 1 | # - Find the Catch test framework or download it (single header) 2 | # 3 | # This is a quick module for internal use. It assumes that Catch is 4 | # REQUIRED and that a minimum version is provided (not EXACT). If 5 | # a suitable version isn't found locally, the single header file 6 | # will be downloaded and placed in the build dir: PROJECT_BINARY_DIR. 7 | # 8 | # This code sets the following variables: 9 | # CATCH_INCLUDE_DIR - path to catch.hpp 10 | # CATCH_VERSION - version number 11 | 12 | if(NOT Catch_FIND_VERSION) 13 | message(FATAL_ERROR "A version number must be specified.") 14 | elseif(Catch_FIND_REQUIRED) 15 | message(FATAL_ERROR "This module assumes Catch is not required.") 16 | elseif(Catch_FIND_VERSION_EXACT) 17 | message(FATAL_ERROR "Exact version numbers are not supported, only minimum.") 18 | endif() 19 | 20 | # Extract the version number from catch.hpp 21 | function(_get_catch_version) 22 | file( 23 | STRINGS "${CATCH_INCLUDE_DIR}/catch.hpp" version_line 24 | REGEX "Catch v.*" 25 | LIMIT_COUNT 1) 26 | if(version_line MATCHES "Catch v([0-9]+)\\.([0-9]+)\\.([0-9]+)") 27 | set(CATCH_VERSION 28 | "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}" 29 | PARENT_SCOPE) 30 | endif() 31 | endfunction() 32 | 33 | # Download the single-header version of Catch 34 | function(_download_catch version destination_dir) 35 | message(STATUS "Downloading catch v${version}...") 36 | set(url https://github.com/philsquared/Catch/releases/download/v${version}/catch.hpp) 37 | file(DOWNLOAD ${url} "${destination_dir}/catch.hpp" STATUS status) 38 | list(GET status 0 error) 39 | if(error) 40 | message(FATAL_ERROR "Could not download ${url}") 41 | endif() 42 | set(CATCH_INCLUDE_DIR 43 | "${destination_dir}" 44 | CACHE INTERNAL "") 45 | endfunction() 46 | 47 | # Look for catch locally 48 | find_path( 49 | CATCH_INCLUDE_DIR 50 | NAMES catch.hpp 51 | PATH_SUFFIXES catch2) 52 | if(CATCH_INCLUDE_DIR) 53 | _get_catch_version() 54 | endif() 55 | 56 | # Download the header if it wasn't found or if it's outdated 57 | if(NOT CATCH_VERSION OR CATCH_VERSION VERSION_LESS ${Catch_FIND_VERSION}) 58 | if(DOWNLOAD_CATCH) 59 | _download_catch(${Catch_FIND_VERSION} "${PROJECT_BINARY_DIR}/catch/") 60 | _get_catch_version() 61 | else() 62 | set(CATCH_FOUND FALSE) 63 | return() 64 | endif() 65 | endif() 66 | 67 | set(CATCH_FOUND TRUE) 68 | -------------------------------------------------------------------------------- /superpixel/pybind11/tests/pybind11_tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | #if defined(_MSC_VER) && _MSC_VER < 1910 5 | // We get some really long type names here which causes MSVC 2015 to emit warnings 6 | # pragma warning(disable: 4503) // warning C4503: decorated name length exceeded, name was truncated 7 | #endif 8 | 9 | namespace py = pybind11; 10 | using namespace pybind11::literals; 11 | 12 | class test_initializer { 13 | using Initializer = void (*)(py::module &); 14 | 15 | public: 16 | test_initializer(Initializer init); 17 | test_initializer(const char *submodule_name, Initializer init); 18 | }; 19 | 20 | #define TEST_SUBMODULE(name, variable) \ 21 | void test_submodule_##name(py::module &); \ 22 | test_initializer name(#name, test_submodule_##name); \ 23 | void test_submodule_##name(py::module &variable) 24 | 25 | 26 | /// Dummy type which is not exported anywhere -- something to trigger a conversion error 27 | struct UnregisteredType { }; 28 | 29 | /// A user-defined type which is exported and can be used by any test 30 | class UserType { 31 | public: 32 | UserType() = default; 33 | UserType(int i) : i(i) { } 34 | 35 | int value() const { return i; } 36 | void set(int set) { i = set; } 37 | 38 | private: 39 | int i = -1; 40 | }; 41 | 42 | /// Like UserType, but increments `value` on copy for quick reference vs. copy tests 43 | class IncType : public UserType { 44 | public: 45 | using UserType::UserType; 46 | IncType() = default; 47 | IncType(const IncType &other) : IncType(other.value() + 1) { } 48 | IncType(IncType &&) = delete; 49 | IncType &operator=(const IncType &) = delete; 50 | IncType &operator=(IncType &&) = delete; 51 | }; 52 | 53 | /// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context. 54 | /// Used to test recursive casters (e.g. std::tuple, stl containers). 55 | struct RValueCaster {}; 56 | PYBIND11_NAMESPACE_BEGIN(pybind11) 57 | PYBIND11_NAMESPACE_BEGIN(detail) 58 | template<> class type_caster { 59 | public: 60 | PYBIND11_TYPE_CASTER(RValueCaster, _("RValueCaster")); 61 | static handle cast(RValueCaster &&, return_value_policy, handle) { return py::str("rvalue").release(); } 62 | static handle cast(const RValueCaster &, return_value_policy, handle) { return py::str("lvalue").release(); } 63 | }; 64 | PYBIND11_NAMESPACE_END(detail) 65 | PYBIND11_NAMESPACE_END(pybind11) 66 | -------------------------------------------------------------------------------- /superpixel/MERCCInput.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCInput.h" 24 | #include 25 | 26 | MERCInput::MERCInput() 27 | { 28 | edges_ = NULL; 29 | } 30 | 31 | MERCInput::~MERCInput() 32 | { 33 | Release(); 34 | } 35 | 36 | void MERCInput::Release() 37 | { 38 | if(edges_) 39 | delete [] edges_; 40 | edges_ = NULL; 41 | } 42 | 43 | void MERCInput::ReadFromMatlab(double *pI,double *pJ,double *pW,int nEdges,int nNodes) 44 | { 45 | nEdges_ = nEdges; 46 | nNodes_ = nNodes; 47 | edges_ = new Edge [nEdges_]; 48 | for(int i=0;i> nNodes_; 67 | file >> nEdges_; 68 | edges_ = new Edge [nEdges_]; 69 | for(int i=0;i>edges_[i].a_>>edges_[i].b_>>edges_[i].w_; 71 | file.close(); 72 | } 73 | 74 | 75 | void MERCInput::Write(const char* filename) 76 | { 77 | std::ofstream file; 78 | file.open(filename); 79 | file.precision(6); 80 | file< [nElements_]; 33 | 34 | 35 | int reservedSize = (int)std::sqrt( 1.0*nElements ); 36 | // Initialization with the cluster size and id 37 | for (int i = 0; i < nElements; i++) 38 | { 39 | p_[i] = i; 40 | size_[i] = 1; 41 | lists_[i].PushBack(i); 42 | } 43 | } 44 | 45 | MERCDisjointSet::~MERCDisjointSet() 46 | { 47 | Release(); 48 | } 49 | 50 | void MERCDisjointSet::Release() 51 | { 52 | delete [] p_; 53 | delete [] size_; 54 | delete [] lists_; 55 | p_ = NULL; 56 | size_ = NULL; 57 | lists_ = NULL; 58 | 59 | } 60 | 61 | void MERCDisjointSet::Set(int x,int l) 62 | { 63 | p_[x] = l; 64 | } 65 | 66 | int MERCDisjointSet::Find(int x) 67 | { 68 | // return the cluster ID 69 | return p_[x]; 70 | } 71 | 72 | int MERCDisjointSet::Join(int x, int y) 73 | { 74 | int aID = Find(x); 75 | int bID = Find(y); 76 | 77 | // The size is only maintained for cluster ID. 78 | int aSize = size_[aID]; 79 | int bSize = size_[bID]; 80 | 81 | 82 | int newID,delID; 83 | if( bSize < aSize ) 84 | { 85 | newID = aID; 86 | delID = bID; 87 | } 88 | else 89 | { 90 | newID = bID; 91 | delID = aID; 92 | } 93 | 94 | size_[newID] = aSize+bSize; 95 | size_[delID] = 0; 96 | 97 | MListNode *iter; 98 | for(iter=lists_[delID].first_;iter!=NULL;iter=iter->next_) 99 | p_[iter->data_] = newID; 100 | lists_[newID].Append(lists_[delID]); 101 | 102 | nElements_--; 103 | return newID; 104 | } -------------------------------------------------------------------------------- /superpixel/MERCEdge.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_edge_h_ 24 | #define _m_erc_edge_h_ 25 | 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | 31 | class MERCEdge 32 | { 33 | public: 34 | int a_; 35 | int b_; 36 | double w_; 37 | double gain_; 38 | 39 | inline MERCEdge &operator=(const MERCEdge &rhs); 40 | inline bool operator==(const MERCEdge &other) const; 41 | inline bool operator!=(const MERCEdge &other) const; 42 | inline bool operator>=(const MERCEdge &other) const; 43 | inline bool operator<=(const MERCEdge &other) const; 44 | inline bool operator>(const MERCEdge &other) const; 45 | inline bool operator<(const MERCEdge &other) const; 46 | 47 | inline friend ostream &operator<<(ostream &output,MERCEdge &e); 48 | }; 49 | 50 | 51 | 52 | ostream &operator<<(ostream &output,MERCEdge &e) 53 | { 54 | output<< "(" << e.a_ <<", " << e.b_ <<", " << e.w_ <<", " << e.gain_ <<")"; 55 | return output; 56 | } 57 | 58 | 59 | MERCEdge &MERCEdge::operator=(const MERCEdge &rhs) 60 | { 61 | a_ = rhs.a_; 62 | b_ = rhs.b_; 63 | w_ = rhs.w_; 64 | gain_ = rhs.gain_; 65 | return *this; 66 | } 67 | 68 | bool MERCEdge::operator==(const MERCEdge &other) const 69 | { 70 | return gain_ == other.gain_; 71 | } 72 | 73 | bool MERCEdge::operator!=(const MERCEdge &other) const 74 | { 75 | return gain_ != other.gain_; 76 | } 77 | 78 | bool MERCEdge::operator>=(const MERCEdge &other) const 79 | { 80 | return gain_ >= other.gain_; 81 | } 82 | 83 | bool MERCEdge::operator<=(const MERCEdge &other) const 84 | { 85 | return gain_ <= other.gain_; 86 | } 87 | 88 | bool MERCEdge::operator>(const MERCEdge &other) const 89 | { 90 | return gain_ > other.gain_; 91 | } 92 | 93 | bool MERCEdge::operator<(const MERCEdge &other) const 94 | { 95 | return gain_ < other.gain_; 96 | } 97 | 98 | #endif -------------------------------------------------------------------------------- /superpixel/pybind11/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Thank you for your interest in this project! Please refer to the following 2 | sections on how to contribute code and bug reports. 3 | 4 | ### Reporting bugs 5 | 6 | At the moment, this project is run in the spare time of a single person 7 | ([Wenzel Jakob](http://rgl.epfl.ch/people/wjakob)) with very limited resources 8 | for issue tracker tickets. Thus, before submitting a question or bug report, 9 | please take a moment of your time and ensure that your issue isn't already 10 | discussed in the project documentation provided at 11 | [http://pybind11.readthedocs.org/en/latest](http://pybind11.readthedocs.org/en/latest). 12 | 13 | Assuming that you have identified a previously unknown problem or an important 14 | question, it's essential that you submit a self-contained and minimal piece of 15 | code that reproduces the problem. In other words: no external dependencies, 16 | isolate the function(s) that cause breakage, submit matched and complete C++ 17 | and Python snippets that can be easily compiled and run on my end. 18 | 19 | ## Pull requests 20 | Contributions are submitted, reviewed, and accepted using Github pull requests. 21 | Please refer to [this 22 | article](https://help.github.com/articles/using-pull-requests) for details and 23 | adhere to the following rules to make the process as smooth as possible: 24 | 25 | * Make a new branch for every feature you're working on. 26 | * Make small and clean pull requests that are easy to review but make sure they 27 | do add value by themselves. 28 | * Add tests for any new functionality and run the test suite (``make pytest``) 29 | to ensure that no existing features break. 30 | * Please run [``pre-commit``][pre-commit] to check your code matches the 31 | project style. (Note that ``gawk`` is required.) Use `pre-commit run 32 | --all-files` before committing (or use installed-mode, check pre-commit docs) 33 | to verify your code passes before pushing to save time. 34 | * This project has a strong focus on providing general solutions using a 35 | minimal amount of code, thus small pull requests are greatly preferred. 36 | 37 | [pre-commit]: https://pre-commit.com 38 | 39 | ### Licensing of contributions 40 | 41 | pybind11 is provided under a BSD-style license that can be found in the 42 | ``LICENSE`` file. By using, distributing, or contributing to this project, you 43 | agree to the terms and conditions of this license. 44 | 45 | You are under no obligation whatsoever to provide any bug fixes, patches, or 46 | upgrades to the features, functionality or performance of the source code 47 | ("Enhancements") to anyone; however, if you choose to make your Enhancements 48 | available either publicly, or directly to the author of this software, without 49 | imposing a separate written license agreement for such Enhancements, then you 50 | hereby grant the following license: a non-exclusive, royalty-free perpetual 51 | license to install, use, modify, prepare derivative works, incorporate into 52 | other computer software, distribute, and sublicense such enhancements or 53 | derivative works thereof, in binary and source code form. 54 | -------------------------------------------------------------------------------- /scripts/preprocess/generate_patches.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import numpy as np 4 | import networkx as nx 5 | import torch 6 | 7 | DATA_DIR = os.path.join(os.environ["PROT"], "datasets") 8 | 9 | 10 | def ers_segment(args): 11 | from superpixel.ers import ERS 12 | exp_name = "ERS" 13 | exp_name += f"_balance={args.balance_fac}_n_segments={args.n_segments}" 14 | 15 | assignments_dir = f"{args.data_dir}/assignments/{args.dataset}/{exp_name}" 16 | os.makedirs(assignments_dir, exist_ok=True) 17 | processed_dir = f"{args.data_dir}/processed/{args.dataset}" 18 | pdb_files = os.listdir(f"{processed_dir}/surface") 19 | 20 | for pdb_file in pdb_files: 21 | pdb_id = pdb_file.split(".")[0] 22 | fullpath = f"{processed_dir}/surface/{pdb_file}" 23 | target_dict = torch.load(fullpath) 24 | 25 | if 'prot' not in target_dict: 26 | print(f"prot not found for {pdb_id}") 27 | continue 28 | data = target_dict['prot'] 29 | 30 | model = ERS(args.balance_fac) 31 | G = nx.Graph() 32 | n = len(data.pos) 33 | G.add_nodes_from(np.arange(n)) 34 | 35 | # Extract edges from triangular faces of mesh 36 | f = np.array(data.face.numpy(), dtype = int) 37 | rowi = np.concatenate([f[:,0], f[:,0], f[:,1], f[:,1], f[:,2], f[:,2]], axis = 0) 38 | rowj = np.concatenate([f[:,1], f[:,2], f[:,0], f[:,2], f[:,0], f[:,1]], axis = 0) 39 | edges = np.stack([rowi, rowj]).T 40 | 41 | G.add_edges_from(edges) 42 | edge_list = np.array(list(G.edges()), dtype=np.int) 43 | 44 | feats = data.x.numpy() 45 | edge_sim = np.sum(feats[edge_list[:, 0]] * feats[edge_list[:, 1]], axis=1) 46 | edge_sim = edge_sim.astype(np.double) 47 | 48 | patch_labels = model.computeSegmentation(edge_list, edge_sim, len(G.nodes), 49 | args.n_segments) 50 | if patch_labels is None: 51 | print(f"Assignments for {pdb_id} could not be generated. Edges: {len(G.edges())}, Nodes: {len(G.nodes())}", flush=True) 52 | 53 | assert len(patch_labels) == len(data.pos) 54 | if len(np.unique(patch_labels)) > 1: 55 | torch.save(patch_labels, f"{assignments_dir}/{pdb_id}.pth") 56 | #print(f"Saved assignments for {pdb_id}, Edges: {len(G.edges())}, Nodes: {len(G.nodes())}", flush=True) 57 | else: 58 | print(f"No unique labels for {pdb_id}. Edges: {len(G.edges())}, Nodes: {len(G.nodes())}") 59 | 60 | 61 | def main(): 62 | parser = argparse.ArgumentParser() 63 | 64 | parser.add_argument("--data_dir", default=DATA_DIR, type=str) 65 | parser.add_argument("--exp_name", type=str, default=None) 66 | parser.add_argument("--ckpt_id", type=str, default=None) 67 | parser.add_argument("--seg_mode", default='ers', help="Which function to use for segmentation") 68 | parser.add_argument("--dataset", default="pdbbind") 69 | parser.add_argument("--balance_fac", type=float, default=0.5) 70 | parser.add_argument("--n_segments", type=int, default=20) 71 | args = parser.parse_args() 72 | 73 | SEG_FNS = {'ers': ers_segment} 74 | segmentation_fn = SEG_FNS.get(args.seg_mode) 75 | segmentation_fn(args) 76 | 77 | if __name__ == "__main__": 78 | main() 79 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/benchmark.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import random 3 | import os 4 | import time 5 | import datetime as dt 6 | 7 | nfns = 4 # Functions per class 8 | nargs = 4 # Arguments per function 9 | 10 | 11 | def generate_dummy_code_pybind11(nclasses=10): 12 | decl = "" 13 | bindings = "" 14 | 15 | for cl in range(nclasses): 16 | decl += "class cl%03i;\n" % cl 17 | decl += '\n' 18 | 19 | for cl in range(nclasses): 20 | decl += "class cl%03i {\n" % cl 21 | decl += "public:\n" 22 | bindings += ' py::class_(m, "cl%03i")\n' % (cl, cl) 23 | for fn in range(nfns): 24 | ret = random.randint(0, nclasses - 1) 25 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 26 | decl += " cl%03i *fn_%03i(" % (ret, fn) 27 | decl += ", ".join("cl%03i *" % p for p in params) 28 | decl += ");\n" 29 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % \ 30 | (fn, cl, fn) 31 | decl += "};\n\n" 32 | bindings += ' ;\n' 33 | 34 | result = "#include \n\n" 35 | result += "namespace py = pybind11;\n\n" 36 | result += decl + '\n' 37 | result += "PYBIND11_MODULE(example, m) {\n" 38 | result += bindings 39 | result += "}" 40 | return result 41 | 42 | 43 | def generate_dummy_code_boost(nclasses=10): 44 | decl = "" 45 | bindings = "" 46 | 47 | for cl in range(nclasses): 48 | decl += "class cl%03i;\n" % cl 49 | decl += '\n' 50 | 51 | for cl in range(nclasses): 52 | decl += "class cl%03i {\n" % cl 53 | decl += "public:\n" 54 | bindings += ' py::class_("cl%03i")\n' % (cl, cl) 55 | for fn in range(nfns): 56 | ret = random.randint(0, nclasses - 1) 57 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 58 | decl += " cl%03i *fn_%03i(" % (ret, fn) 59 | decl += ", ".join("cl%03i *" % p for p in params) 60 | decl += ");\n" 61 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy())\n' % \ 62 | (fn, cl, fn) 63 | decl += "};\n\n" 64 | bindings += ' ;\n' 65 | 66 | result = "#include \n\n" 67 | result += "namespace py = boost::python;\n\n" 68 | result += decl + '\n' 69 | result += "BOOST_PYTHON_MODULE(example) {\n" 70 | result += bindings 71 | result += "}" 72 | return result 73 | 74 | 75 | for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: 76 | print ("{") 77 | for i in range(0, 10): 78 | nclasses = 2 ** i 79 | with open("test.cpp", "w") as f: 80 | f.write(codegen(nclasses)) 81 | n1 = dt.datetime.now() 82 | os.system("g++ -Os -shared -rdynamic -undefined dynamic_lookup " 83 | "-fvisibility=hidden -std=c++14 test.cpp -I include " 84 | "-I /System/Library/Frameworks/Python.framework/Headers -o test.so") 85 | n2 = dt.datetime.now() 86 | elapsed = (n2 - n1).total_seconds() 87 | size = os.stat('test.so').st_size 88 | print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) 89 | print ("}") 90 | -------------------------------------------------------------------------------- /superpixel/pybind11/tools/FindEigen3.cmake: -------------------------------------------------------------------------------- 1 | # - Try to find Eigen3 lib 2 | # 3 | # This module supports requiring a minimum version, e.g. you can do 4 | # find_package(Eigen3 3.1.2) 5 | # to require version 3.1.2 or newer of Eigen3. 6 | # 7 | # Once done this will define 8 | # 9 | # EIGEN3_FOUND - system has eigen lib with correct version 10 | # EIGEN3_INCLUDE_DIR - the eigen include directory 11 | # EIGEN3_VERSION - eigen version 12 | 13 | # Copyright (c) 2006, 2007 Montel Laurent, 14 | # Copyright (c) 2008, 2009 Gael Guennebaud, 15 | # Copyright (c) 2009 Benoit Jacob 16 | # Redistribution and use is allowed according to the terms of the 2-clause BSD license. 17 | 18 | if(NOT Eigen3_FIND_VERSION) 19 | if(NOT Eigen3_FIND_VERSION_MAJOR) 20 | set(Eigen3_FIND_VERSION_MAJOR 2) 21 | endif(NOT Eigen3_FIND_VERSION_MAJOR) 22 | if(NOT Eigen3_FIND_VERSION_MINOR) 23 | set(Eigen3_FIND_VERSION_MINOR 91) 24 | endif(NOT Eigen3_FIND_VERSION_MINOR) 25 | if(NOT Eigen3_FIND_VERSION_PATCH) 26 | set(Eigen3_FIND_VERSION_PATCH 0) 27 | endif(NOT Eigen3_FIND_VERSION_PATCH) 28 | 29 | set(Eigen3_FIND_VERSION 30 | "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") 31 | endif(NOT Eigen3_FIND_VERSION) 32 | 33 | macro(_eigen3_check_version) 34 | file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) 35 | 36 | string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match 37 | "${_eigen3_version_header}") 38 | set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") 39 | string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match 40 | "${_eigen3_version_header}") 41 | set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") 42 | string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match 43 | "${_eigen3_version_header}") 44 | set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") 45 | 46 | set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) 47 | if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 48 | set(EIGEN3_VERSION_OK FALSE) 49 | else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 50 | set(EIGEN3_VERSION_OK TRUE) 51 | endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 52 | 53 | if(NOT EIGEN3_VERSION_OK) 54 | 55 | message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " 56 | "but at least version ${Eigen3_FIND_VERSION} is required") 57 | endif(NOT EIGEN3_VERSION_OK) 58 | endmacro(_eigen3_check_version) 59 | 60 | if(EIGEN3_INCLUDE_DIR) 61 | 62 | # in cache already 63 | _eigen3_check_version() 64 | set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) 65 | 66 | else(EIGEN3_INCLUDE_DIR) 67 | 68 | find_path( 69 | EIGEN3_INCLUDE_DIR 70 | NAMES signature_of_eigen3_matrix_library 71 | PATHS ${CMAKE_INSTALL_PREFIX}/include ${KDE4_INCLUDE_DIR} 72 | PATH_SUFFIXES eigen3 eigen) 73 | 74 | if(EIGEN3_INCLUDE_DIR) 75 | _eigen3_check_version() 76 | endif(EIGEN3_INCLUDE_DIR) 77 | 78 | include(FindPackageHandleStandardArgs) 79 | find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) 80 | 81 | mark_as_advanced(EIGEN3_INCLUDE_DIR) 82 | 83 | endif(EIGEN3_INCLUDE_DIR) 84 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/benchmark.rst: -------------------------------------------------------------------------------- 1 | Benchmark 2 | ========= 3 | 4 | The following is the result of a synthetic benchmark comparing both compilation 5 | time and module size of pybind11 against Boost.Python. A detailed report about a 6 | Boost.Python to pybind11 conversion of a real project is available here: [#f1]_. 7 | 8 | .. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 9 | 10 | Setup 11 | ----- 12 | 13 | A python script (see the ``docs/benchmark.py`` file) was used to generate a set 14 | of files with dummy classes whose count increases for each successive benchmark 15 | (between 1 and 2048 classes in powers of two). Each class has four methods with 16 | a randomly generated signature with a return value and four arguments. (There 17 | was no particular reason for this setup other than the desire to generate many 18 | unique function signatures whose count could be controlled in a simple way.) 19 | 20 | Here is an example of the binding code for one class: 21 | 22 | .. code-block:: cpp 23 | 24 | ... 25 | class cl034 { 26 | public: 27 | cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); 28 | cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); 29 | cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); 30 | cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); 31 | }; 32 | ... 33 | 34 | PYBIND11_MODULE(example, m) { 35 | ... 36 | py::class_(m, "cl034") 37 | .def("fn_000", &cl034::fn_000) 38 | .def("fn_001", &cl034::fn_001) 39 | .def("fn_002", &cl034::fn_002) 40 | .def("fn_003", &cl034::fn_003) 41 | ... 42 | } 43 | 44 | The Boost.Python version looks almost identical except that a return value 45 | policy had to be specified as an argument to ``def()``. For both libraries, 46 | compilation was done with 47 | 48 | .. code-block:: bash 49 | 50 | Apple LLVM version 7.0.2 (clang-700.1.81) 51 | 52 | and the following compilation flags 53 | 54 | .. code-block:: bash 55 | 56 | g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14 57 | 58 | Compilation time 59 | ---------------- 60 | 61 | The following log-log plot shows how the compilation time grows for an 62 | increasing number of class and function declarations. pybind11 includes many 63 | fewer headers, which initially leads to shorter compilation times, but the 64 | performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for 65 | the largest largest file with 2048 classes and a total of 8192 methods -- a 66 | modest **1.2x** speedup relative to Boost.Python, which required 116.35 67 | seconds). 68 | 69 | .. only:: not latex 70 | 71 | .. image:: pybind11_vs_boost_python1.svg 72 | 73 | .. only:: latex 74 | 75 | .. image:: pybind11_vs_boost_python1.png 76 | 77 | Module size 78 | ----------- 79 | 80 | Differences between the two libraries become much more pronounced when 81 | considering the file size of the generated Python plugin: for the largest file, 82 | the binary generated by Boost.Python required 16.8 MiB, which was **2.17 83 | times** / **9.1 megabytes** larger than the output generated by pybind11. For 84 | very small inputs, Boost.Python has an edge in the plot below -- however, note 85 | that it stores many definitions in an external library, whose size was not 86 | included here, hence the comparison is slightly shifted in Boost.Python's 87 | favor. 88 | 89 | .. only:: not latex 90 | 91 | .. image:: pybind11_vs_boost_python2.svg 92 | 93 | .. only:: latex 94 | 95 | .. image:: pybind11_vs_boost_python2.png 96 | -------------------------------------------------------------------------------- /scripts/preprocess/resize_meshes.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import argparse 5 | ''' 6 | Simplifies mesh to target number of faces 7 | Requires Blender 2.8 8 | Author: Rana Hanocka 9 | 10 | @input: 11 | 12 | number of target faces 13 | name of simplified .obj file 14 | 15 | @output: 16 | simplified mesh .obj 17 | to run it from cmd line: 18 | /opt/blender/blender --background --python blender_process.py /home/rana/koala.obj 1000 /home/rana/koala_1000.obj 19 | ''' 20 | 21 | class Process: 22 | def __init__(self, obj_file, target_faces, export_name): 23 | mesh = self.load_obj(obj_file) 24 | self.simplify(mesh, target_faces) 25 | self.export_obj(mesh, export_name) 26 | 27 | def load_obj(self, obj_file): 28 | bpy.ops.import_scene.obj(filepath=obj_file, axis_forward='-Z', axis_up='Y', filter_glob="*.obj;*.mtl", use_edges=True, 29 | use_smooth_groups=True, use_split_objects=False, use_split_groups=False, 30 | use_groups_as_vgroups=False, use_image_search=True, split_mode='ON') 31 | ob = bpy.context.selected_objects[0] 32 | return ob 33 | 34 | def subsurf(self, mesh): 35 | # subdivide mesh 36 | bpy.context.view_layer.objects.active = mesh 37 | mod = mesh.modifiers.new(name='Subsurf', type='SUBSURF') 38 | mod.subdivision_type = 'SIMPLE' 39 | bpy.ops.object.modifier_apply(modifier=mod.name) 40 | # now triangulate 41 | mod = mesh.modifiers.new(name='Triangluate', type='TRIANGULATE') 42 | bpy.ops.object.modifier_apply(modifier=mod.name) 43 | 44 | def simplify(self, mesh, target_faces): 45 | bpy.context.view_layer.objects.active = mesh 46 | mod = mesh.modifiers.new(name='Decimate', type='DECIMATE') 47 | bpy.context.object.modifiers['Decimate'].use_collapse_triangulate = True 48 | # 49 | nfaces = len(mesh.data.polygons) 50 | if nfaces < target_faces: 51 | self.subsurf(mesh) 52 | nfaces = len(mesh.data.polygons) 53 | ratio = target_faces / float(nfaces) 54 | mod.ratio = float('%s' % ('%.6g' % (ratio))) 55 | print('faces: ', mod.face_count, mod.ratio) 56 | bpy.ops.object.modifier_apply(modifier=mod.name) 57 | 58 | 59 | def export_obj(self, mesh, export_name): 60 | outpath = os.path.dirname(export_name) 61 | if not os.path.isdir(outpath): os.makedirs(outpath) 62 | print('EXPORTING', export_name) 63 | bpy.ops.object.select_all(action='DESELECT') 64 | mesh.select_set(state=True) 65 | bpy.ops.export_scene.obj(filepath=export_name, check_existing=False, filter_glob="*.obj;*.mtl", 66 | use_selection=True, use_animation=False, use_mesh_modifiers=True, use_edges=True, 67 | use_smooth_groups=False, use_smooth_groups_bitflags=False, use_normals=True, 68 | use_uvs=False, use_materials=False, use_triangles=True, use_nurbs=False, 69 | use_vertex_groups=False, use_blen_objects=True, group_by_object=False, 70 | group_by_material=False, keep_vertex_order=True, global_scale=1, path_mode='AUTO', 71 | axis_forward='-Z', axis_up='Y') 72 | 73 | if __name__ == "__main__": 74 | obj_file = sys.argv[-3] 75 | target_faces = int(sys.argv[-2]) 76 | export_name = sys.argv[-1] 77 | 78 | blender = Process(obj_file, target_faces, export_name) 79 | -------------------------------------------------------------------------------- /superpixel/MERCFunctions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCFunctions.h" 24 | 25 | using namespace std; 26 | 27 | double MERCFunctions::ComputeERGain(double wij,double ci,double cj) 28 | { 29 | double er = ((wij+ci)*log(wij+ci) + (wij+cj)*log(wij+cj) - ci*log(ci) - cj*log(cj) - 2*wij*log(wij) )/log(2.0); 30 | if( er!=er ) 31 | return 0; 32 | else 33 | return er; 34 | } 35 | 36 | double MERCFunctions::ComputeBGain(int nVertices, int si,int sj) 37 | { 38 | double Si = si*1.0/nVertices; 39 | double Sj = sj*1.0/nVertices; 40 | double b = (-(Si+Sj)*log(Si+Sj) + Si*log(Si) + Sj*log(Sj))/log(2.0) + 1.0; 41 | return b; 42 | } 43 | 44 | void MERCFunctions::NormalizeEdgeWeight(MERCInput &edges,double *loop,double wT) 45 | { 46 | int nEdges = edges.nEdges_; 47 | int nVertices = edges.nNodes_; 48 | for(int i=0;i`` template. 34 | Although this is an implementation detail, adding partial overloads to this 35 | type is explicitly allowed. 36 | 37 | .. code-block:: cpp 38 | 39 | namespace pybind11 { namespace detail { 40 | template <> struct type_caster { 41 | public: 42 | /** 43 | * This macro establishes the name 'inty' in 44 | * function signatures and declares a local variable 45 | * 'value' of type inty 46 | */ 47 | PYBIND11_TYPE_CASTER(inty, _("inty")); 48 | 49 | /** 50 | * Conversion part 1 (Python->C++): convert a PyObject into a inty 51 | * instance or return false upon failure. The second argument 52 | * indicates whether implicit conversions should be applied. 53 | */ 54 | bool load(handle src, bool) { 55 | /* Extract PyObject from handle */ 56 | PyObject *source = src.ptr(); 57 | /* Try converting into a Python integer value */ 58 | PyObject *tmp = PyNumber_Long(source); 59 | if (!tmp) 60 | return false; 61 | /* Now try to convert into a C++ int */ 62 | value.long_value = PyLong_AsLong(tmp); 63 | Py_DECREF(tmp); 64 | /* Ensure return code was OK (to avoid out-of-range errors etc) */ 65 | return !(value.long_value == -1 && !PyErr_Occurred()); 66 | } 67 | 68 | /** 69 | * Conversion part 2 (C++ -> Python): convert an inty instance into 70 | * a Python object. The second and third arguments are used to 71 | * indicate the return value policy and parent object (for 72 | * ``return_value_policy::reference_internal``) and are generally 73 | * ignored by implicit casters. 74 | */ 75 | static handle cast(inty src, return_value_policy /* policy */, handle /* parent */) { 76 | return PyLong_FromLong(src.long_value); 77 | } 78 | }; 79 | }} // namespace pybind11::detail 80 | 81 | .. note:: 82 | 83 | A ``type_caster`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires 84 | that ``T`` is default-constructible (``value`` is first default constructed 85 | and then ``load()`` assigns to it). 86 | 87 | .. warning:: 88 | 89 | When using custom type casters, it's important to declare them consistently 90 | in every compilation unit of the Python extension module. Otherwise, 91 | undefined behavior can ensue. 92 | -------------------------------------------------------------------------------- /superpixel/MList.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_list_h_ 24 | #define _m_list_h_ 25 | 26 | template 27 | class MListNode 28 | { 29 | public: 30 | T data_; 31 | MListNode *next_; 32 | }; 33 | 34 | 35 | template 36 | class MList 37 | { 38 | 39 | public: 40 | MList() { 41 | size_ = 0; 42 | first_ = NULL; 43 | last_ = NULL; 44 | }; 45 | ~MList() 46 | { 47 | Clear(); 48 | }; 49 | 50 | // Clear everything in the list 51 | void Clear(); 52 | 53 | // Push a new node to the end of the list 54 | void PushBack(T &data); 55 | 56 | // Append a list to the end of this list 57 | void Append(MList &other); 58 | //void Append(MList *other); 59 | 60 | // Return the number of elements in the list 61 | unsigned int rSize() {return size_;}; 62 | 63 | // Copy the list 64 | inline MList &operator=(const MList &rhs); 65 | 66 | 67 | MListNode *first_; 68 | MListNode *last_; 69 | unsigned int size_; 70 | }; 71 | 72 | template 73 | MList& MList::operator=(const MList &rhs) 74 | { 75 | MListNode *tmp; 76 | for(tmp=rhs.first_;tmp!=NULL;tmp=tmp->next_) 77 | { 78 | this->PushBack(tmp->data_); 79 | } 80 | return *this; 81 | } 82 | 83 | template 84 | void MList::Append(MList &other) 85 | { 86 | if(size_==0) 87 | { 88 | size_ = other.size_; 89 | first_ = other.first_; 90 | last_ = other.last_; 91 | } 92 | else 93 | { 94 | size_ += other.rSize(); 95 | last_->next_ = other.first_; 96 | last_ = other.last_; 97 | } 98 | 99 | // We should not release the dynamic memory at this place 100 | // since they are appended to the end of the other list. 101 | other.first_ = NULL; 102 | other.last_ = NULL; 103 | other.size_ = 0; 104 | } 105 | 106 | 107 | template 108 | void MList::Clear() 109 | { 110 | if(size_ == 0 ) 111 | return; 112 | 113 | MListNode *node = first_; 114 | while(node!=NULL) 115 | { 116 | // pointer to the next 117 | MListNode *tmp = node->next_; 118 | // delete the current one 119 | delete node; 120 | // link to the next 121 | node = tmp; 122 | } 123 | 124 | first_ = NULL; 125 | last_ = NULL; 126 | size_ = 0; 127 | } 128 | 129 | template 130 | void MList::PushBack(T &data) 131 | { 132 | // copy the content 133 | MListNode *node = new MListNode [1]; 134 | node->data_ = data; 135 | node->next_ = NULL; 136 | 137 | // if the list is empty 138 | if(last_==NULL) 139 | { 140 | // update the first node 141 | first_ = node; 142 | // update the last node 143 | last_ = node; 144 | // increase the size by one 145 | size_++; 146 | } 147 | else 148 | { 149 | // insert to the end of the list 150 | last_->next_ = node; 151 | // update the last node 152 | last_ = node; 153 | // increase the size by one 154 | size_++; 155 | } 156 | } 157 | 158 | 159 | #endif -------------------------------------------------------------------------------- /superpixel/pybind11/tests/pybind11_tests.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/pybind11_tests.cpp -- pybind example plugin 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include "constructor_stats.h" 12 | 13 | #include 14 | #include 15 | 16 | /* 17 | For testing purposes, we define a static global variable here in a function that each individual 18 | test .cpp calls with its initialization lambda. It's convenient here because we can just not 19 | compile some test files to disable/ignore some of the test code. 20 | 21 | It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will 22 | be essentially random, which is okay for our test scripts (there are no dependencies between the 23 | individual pybind11 test .cpp files), but most likely not what you want when using pybind11 24 | productively. 25 | 26 | Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" 27 | section of the documentation for good practice on splitting binding code over multiple files. 28 | */ 29 | std::list> &initializers() { 30 | static std::list> inits; 31 | return inits; 32 | } 33 | 34 | test_initializer::test_initializer(Initializer init) { 35 | initializers().push_back(init); 36 | } 37 | 38 | test_initializer::test_initializer(const char *submodule_name, Initializer init) { 39 | initializers().push_back([=](py::module &parent) { 40 | auto m = parent.def_submodule(submodule_name); 41 | init(m); 42 | }); 43 | } 44 | 45 | void bind_ConstructorStats(py::module &m) { 46 | py::class_(m, "ConstructorStats") 47 | .def("alive", &ConstructorStats::alive) 48 | .def("values", &ConstructorStats::values) 49 | .def_readwrite("default_constructions", &ConstructorStats::default_constructions) 50 | .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) 51 | .def_readwrite("move_assignments", &ConstructorStats::move_assignments) 52 | .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) 53 | .def_readwrite("move_constructions", &ConstructorStats::move_constructions) 54 | .def_static("get", (ConstructorStats &(*)(py::object)) &ConstructorStats::get, py::return_value_policy::reference_internal) 55 | 56 | // Not exactly ConstructorStats, but related: expose the internal pybind number of registered instances 57 | // to allow instance cleanup checks (invokes a GC first) 58 | .def_static("detail_reg_inst", []() { 59 | ConstructorStats::gc(); 60 | return py::detail::get_internals().registered_instances.size(); 61 | }) 62 | ; 63 | } 64 | 65 | PYBIND11_MODULE(pybind11_tests, m) { 66 | m.doc() = "pybind11 test module"; 67 | 68 | bind_ConstructorStats(m); 69 | 70 | #if !defined(NDEBUG) 71 | m.attr("debug_enabled") = true; 72 | #else 73 | m.attr("debug_enabled") = false; 74 | #endif 75 | 76 | py::class_(m, "UserType", "A `py::class_` type for testing") 77 | .def(py::init<>()) 78 | .def(py::init()) 79 | .def("get_value", &UserType::value, "Get value using a method") 80 | .def("set_value", &UserType::set, "Set value using a method") 81 | .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") 82 | .def("__repr__", [](const UserType& u) { return "UserType({})"_s.format(u.value()); }); 83 | 84 | py::class_(m, "IncType") 85 | .def(py::init<>()) 86 | .def(py::init()) 87 | .def("__repr__", [](const IncType& u) { return "IncType({})"_s.format(u.value()); }); 88 | 89 | for (const auto &initializer : initializers()) 90 | initializer(m); 91 | 92 | if (!py::hasattr(m, "have_eigen")) m.attr("have_eigen") = false; 93 | } 94 | -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/detail/descr.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "common.h" 13 | 14 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | PYBIND11_NAMESPACE_BEGIN(detail) 16 | 17 | #if !defined(_MSC_VER) 18 | # define PYBIND11_DESCR_CONSTEXPR static constexpr 19 | #else 20 | # define PYBIND11_DESCR_CONSTEXPR const 21 | #endif 22 | 23 | /* Concatenate type signatures at compile time */ 24 | template 25 | struct descr { 26 | char text[N + 1]; 27 | 28 | constexpr descr() : text{'\0'} { } 29 | constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence()) { } 30 | 31 | template 32 | constexpr descr(char const (&s)[N+1], index_sequence) : text{s[Is]..., '\0'} { } 33 | 34 | template 35 | constexpr descr(char c, Chars... cs) : text{c, static_cast(cs)..., '\0'} { } 36 | 37 | static constexpr std::array types() { 38 | return {{&typeid(Ts)..., nullptr}}; 39 | } 40 | }; 41 | 42 | template 43 | constexpr descr plus_impl(const descr &a, const descr &b, 44 | index_sequence, index_sequence) { 45 | return {a.text[Is1]..., b.text[Is2]...}; 46 | } 47 | 48 | template 49 | constexpr descr operator+(const descr &a, const descr &b) { 50 | return plus_impl(a, b, make_index_sequence(), make_index_sequence()); 51 | } 52 | 53 | template 54 | constexpr descr _(char const(&text)[N]) { return descr(text); } 55 | constexpr descr<0> _(char const(&)[1]) { return {}; } 56 | 57 | template struct int_to_str : int_to_str { }; 58 | template struct int_to_str<0, Digits...> { 59 | static constexpr auto digits = descr(('0' + Digits)...); 60 | }; 61 | 62 | // Ternary description (like std::conditional) 63 | template 64 | constexpr enable_if_t> _(char const(&text1)[N1], char const(&)[N2]) { 65 | return _(text1); 66 | } 67 | template 68 | constexpr enable_if_t> _(char const(&)[N1], char const(&text2)[N2]) { 69 | return _(text2); 70 | } 71 | 72 | template 73 | constexpr enable_if_t _(const T1 &d, const T2 &) { return d; } 74 | template 75 | constexpr enable_if_t _(const T1 &, const T2 &d) { return d; } 76 | 77 | template auto constexpr _() -> decltype(int_to_str::digits) { 78 | return int_to_str::digits; 79 | } 80 | 81 | template constexpr descr<1, Type> _() { return {'%'}; } 82 | 83 | constexpr descr<0> concat() { return {}; } 84 | 85 | template 86 | constexpr descr concat(const descr &descr) { return descr; } 87 | 88 | template 89 | constexpr auto concat(const descr &d, const Args &...args) 90 | -> decltype(std::declval>() + concat(args...)) { 91 | return d + _(", ") + concat(args...); 92 | } 93 | 94 | template 95 | constexpr descr type_descr(const descr &descr) { 96 | return _("{") + descr + _("}"); 97 | } 98 | 99 | PYBIND11_NAMESPACE_END(detail) 100 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 101 | -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/functional.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/functional.h: std::function<> support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 16 | PYBIND11_NAMESPACE_BEGIN(detail) 17 | 18 | template 19 | struct type_caster> { 20 | using type = std::function; 21 | using retval_type = conditional_t::value, void_type, Return>; 22 | using function_type = Return (*) (Args...); 23 | 24 | public: 25 | bool load(handle src, bool convert) { 26 | if (src.is_none()) { 27 | // Defer accepting None to other overloads (if we aren't in convert mode): 28 | if (!convert) return false; 29 | return true; 30 | } 31 | 32 | if (!isinstance(src)) 33 | return false; 34 | 35 | auto func = reinterpret_borrow(src); 36 | 37 | /* 38 | When passing a C++ function as an argument to another C++ 39 | function via Python, every function call would normally involve 40 | a full C++ -> Python -> C++ roundtrip, which can be prohibitive. 41 | Here, we try to at least detect the case where the function is 42 | stateless (i.e. function pointer or lambda function without 43 | captured variables), in which case the roundtrip can be avoided. 44 | */ 45 | if (auto cfunc = func.cpp_function()) { 46 | auto c = reinterpret_borrow(PyCFunction_GET_SELF(cfunc.ptr())); 47 | auto rec = (function_record *) c; 48 | 49 | if (rec && rec->is_stateless && 50 | same_type(typeid(function_type), *reinterpret_cast(rec->data[1]))) { 51 | struct capture { function_type f; }; 52 | value = ((capture *) &rec->data)->f; 53 | return true; 54 | } 55 | } 56 | 57 | // ensure GIL is held during functor destruction 58 | struct func_handle { 59 | function f; 60 | func_handle(function&& f_) : f(std::move(f_)) {} 61 | func_handle(const func_handle&) = default; 62 | ~func_handle() { 63 | gil_scoped_acquire acq; 64 | function kill_f(std::move(f)); 65 | } 66 | }; 67 | 68 | // to emulate 'move initialization capture' in C++11 69 | struct func_wrapper { 70 | func_handle hfunc; 71 | func_wrapper(func_handle&& hf): hfunc(std::move(hf)) {} 72 | Return operator()(Args... args) const { 73 | gil_scoped_acquire acq; 74 | object retval(hfunc.f(std::forward(args)...)); 75 | /* Visual studio 2015 parser issue: need parentheses around this expression */ 76 | return (retval.template cast()); 77 | } 78 | }; 79 | 80 | value = func_wrapper(func_handle(std::move(func))); 81 | return true; 82 | } 83 | 84 | template 85 | static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { 86 | if (!f_) 87 | return none().inc_ref(); 88 | 89 | auto result = f_.template target(); 90 | if (result) 91 | return cpp_function(*result, policy).release(); 92 | else 93 | return cpp_function(std::forward(f_), policy).release(); 94 | } 95 | 96 | PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster::name...) + _("], ") 97 | + make_caster::name + _("]")); 98 | }; 99 | 100 | PYBIND11_NAMESPACE_END(detail) 101 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 102 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/cast/chrono.rst: -------------------------------------------------------------------------------- 1 | Chrono 2 | ====== 3 | 4 | When including the additional header file :file:`pybind11/chrono.h` conversions 5 | from C++11 chrono datatypes to python datetime objects are automatically enabled. 6 | This header also enables conversions of python floats (often from sources such 7 | as ``time.monotonic()``, ``time.perf_counter()`` and ``time.process_time()``) 8 | into durations. 9 | 10 | An overview of clocks in C++11 11 | ------------------------------ 12 | 13 | A point of confusion when using these conversions is the differences between 14 | clocks provided in C++11. There are three clock types defined by the C++11 15 | standard and users can define their own if needed. Each of these clocks have 16 | different properties and when converting to and from python will give different 17 | results. 18 | 19 | The first clock defined by the standard is ``std::chrono::system_clock``. This 20 | clock measures the current date and time. However, this clock changes with to 21 | updates to the operating system time. For example, if your time is synchronised 22 | with a time server this clock will change. This makes this clock a poor choice 23 | for timing purposes but good for measuring the wall time. 24 | 25 | The second clock defined in the standard is ``std::chrono::steady_clock``. 26 | This clock ticks at a steady rate and is never adjusted. This makes it excellent 27 | for timing purposes, however the value in this clock does not correspond to the 28 | current date and time. Often this clock will be the amount of time your system 29 | has been on, although it does not have to be. This clock will never be the same 30 | clock as the system clock as the system clock can change but steady clocks 31 | cannot. 32 | 33 | The third clock defined in the standard is ``std::chrono::high_resolution_clock``. 34 | This clock is the clock that has the highest resolution out of the clocks in the 35 | system. It is normally a typedef to either the system clock or the steady clock 36 | but can be its own independent clock. This is important as when using these 37 | conversions as the types you get in python for this clock might be different 38 | depending on the system. 39 | If it is a typedef of the system clock, python will get datetime objects, but if 40 | it is a different clock they will be timedelta objects. 41 | 42 | Provided conversions 43 | -------------------- 44 | 45 | .. rubric:: C++ to Python 46 | 47 | - ``std::chrono::system_clock::time_point`` → ``datetime.datetime`` 48 | System clock times are converted to python datetime instances. They are 49 | in the local timezone, but do not have any timezone information attached 50 | to them (they are naive datetime objects). 51 | 52 | - ``std::chrono::duration`` → ``datetime.timedelta`` 53 | Durations are converted to timedeltas, any precision in the duration 54 | greater than microseconds is lost by rounding towards zero. 55 | 56 | - ``std::chrono::[other_clocks]::time_point`` → ``datetime.timedelta`` 57 | Any clock time that is not the system clock is converted to a time delta. 58 | This timedelta measures the time from the clocks epoch to now. 59 | 60 | .. rubric:: Python to C++ 61 | 62 | - ``datetime.datetime`` or ``datetime.date`` or ``datetime.time`` → ``std::chrono::system_clock::time_point`` 63 | Date/time objects are converted into system clock timepoints. Any 64 | timezone information is ignored and the type is treated as a naive 65 | object. 66 | 67 | - ``datetime.timedelta`` → ``std::chrono::duration`` 68 | Time delta are converted into durations with microsecond precision. 69 | 70 | - ``datetime.timedelta`` → ``std::chrono::[other_clocks]::time_point`` 71 | Time deltas that are converted into clock timepoints are treated as 72 | the amount of time from the start of the clocks epoch. 73 | 74 | - ``float`` → ``std::chrono::duration`` 75 | Floats that are passed to C++ as durations be interpreted as a number of 76 | seconds. These will be converted to the duration using ``duration_cast`` 77 | from the float. 78 | 79 | - ``float`` → ``std::chrono::[other_clocks]::time_point`` 80 | Floats that are passed to C++ as time points will be interpreted as the 81 | number of seconds from the start of the clocks epoch. 82 | -------------------------------------------------------------------------------- /superpixel/MERCLazyGreedy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCLazyGreedy.h" 24 | 25 | MERCDisjointSet* MERCLazyGreedy::ClusteringTree(int nVertices,MERCInput &edges,int kernel,double lambda,int nC) 26 | { 27 | //LARGE_INTEGER t1, t2, f; 28 | //QueryPerformanceFrequency(&f); 29 | //QueryPerformanceCounter(&t1); 30 | 31 | 32 | int nEdges = edges.nEdges_; 33 | MERCDisjointSet *u = new MERCDisjointSet(nVertices); 34 | 35 | // MERCFunctions::ComputeSimilarity(edges,sigma,kernel); 36 | double *loop = MERCFunctions::ComputeLoopWeight(nVertices,edges); 37 | double wT = MERCFunctions::ComputeTotalWeight(loop,nVertices); 38 | MERCFunctions::NormalizeEdgeWeight(edges,loop,wT); 39 | 40 | // 41 | // Compute initial gain and decide the weighting on the balancing term 42 | // 43 | double *erGainArr = new double [nEdges];// gain in entropy rate term 44 | double *bGainArr = new double [nEdges]; // gain in balancing term 45 | double maxERGain=0,maxBGain=1e-20; 46 | for(int i=0;iFind( edges.edges_[i].a_ ); 53 | int b = u->Find( edges.edges_[i].b_ ); 54 | if(a!=b) 55 | bGainArr[i] = MERCFunctions::ComputeBGain(nVertices, u->rSize(a), u->rSize(b) ); 56 | else 57 | bGainArr[i] = 0; 58 | if(erGainArr[i]>maxERGain) 59 | maxERGain = erGainArr[i]; 60 | if(bGainArr[i]>maxBGain) 61 | maxBGain = bGainArr[i]; 62 | } 63 | double balancing = lambda*maxERGain/std::abs(maxBGain); 64 | //double balancing = lambda* log( 1.0*nVertices )/ log( 1.0*nC ); 65 | 66 | /* 67 | std::cout.precision(8); 68 | std::cout.setf(ios::fixed,ios::floatfield); 69 | std::cout<<"maxERGain = "<Find( bestEdge.a_ ); 108 | b = u->Find( bestEdge.b_ ); 109 | 110 | if(a!=b) 111 | { 112 | u->Join(a,b); 113 | cc--; 114 | loop[bestEdge.a_] -= bestEdge.w_; 115 | loop[bestEdge.b_] -= bestEdge.w_; 116 | } 117 | 118 | heap.EasyPartialUpdateTree(u,balancing,loop); 119 | } 120 | 121 | 122 | delete [] loop; 123 | //QueryPerformanceCounter(&t2); 124 | //std::cout.precision(6); 125 | //std::cout< Data: 24 | mol = Chem.MolFromSmiles(lig_smi) 25 | if mol is None: 26 | print(f"Mol is None {lig_smi}", flush=True) 27 | return None 28 | 29 | data = {} 30 | G = nx.DiGraph(Chem.rdmolops.GetAdjacencyMatrix(mol)) 31 | G = nx.convert_node_labels_to_integers(G) 32 | edge_index = torch.tensor(list(G.edges)).t().contiguous() 33 | 34 | x = [] 35 | for atom in mol.GetAtoms(): 36 | x.append(get_atom_features(AtomProp(atom))) 37 | data['x'] = torch.tensor(x).float() 38 | 39 | edge_attr = [] 40 | mess_idx, edge_dict = [[]], {} 41 | 42 | for a1, a2 in G.edges(): 43 | bond = mol.GetBondBetweenAtoms(a1, a2) 44 | bond_feat = get_bond_features(BondProp(bond)) 45 | edge_attr.append(bond_feat) 46 | edge_dict[(a1, a2)] = eid = len(edge_dict) + 1 47 | mess_idx.append([]) 48 | 49 | data['edge_attr'] = torch.tensor(edge_attr).float() 50 | data['edge_index'] = edge_index 51 | 52 | for u, v in G.edges: 53 | eid = edge_dict[(u, v)] 54 | for w in G.predecessors(u): 55 | if w == v: continue 56 | mess_idx[eid].append(edge_dict[(w, u)]) 57 | mess_idx = create_pad_tensor(mess_idx) 58 | data['mess_idx'] = mess_idx 59 | 60 | def finite_check(x): 61 | return torch.isfinite(x).all().item() 62 | 63 | data = Data.from_dict(data) 64 | checks = [finite_check(data.x), finite_check(data.edge_attr)] 65 | if target is not None: 66 | target = torch.tensor(target) 67 | if not len(target.shape): 68 | target = target.unsqueeze(0) 69 | data.y = target 70 | checks += [finite_check(data.y)] 71 | 72 | if not all(checks): 73 | print(f"Nan checks failed for ligand: {lig_smi}", flush=True) 74 | return None 75 | 76 | return data 77 | 78 | 79 | class Complex: 80 | 81 | def __init__(self, 82 | prot_builder, 83 | **kwargs): 84 | self.prot_builder = prot_builder 85 | self.mol_builder = LigandMol() 86 | 87 | def __call__(self, pdb_file: str, lig_smi: str, 88 | target: Union[float, np.ndarray], **kwargs) -> Union[Data, Tuple[Data]]: 89 | return self.build(pdb_file=pdb_file, lig_smi=lig_smi, target=target, **kwargs) 90 | 91 | def build(self, pdb_file: str, lig_smi: str, target: Union[float, np.ndarray], 92 | **kwargs) -> Union[Data, Tuple[Data]]: 93 | ligand = self.mol_builder.build(lig_smi) 94 | if ligand is None: 95 | return None 96 | 97 | if 'build_prot' in kwargs and kwargs.get('build_prot'): 98 | prot_kwargs = {'pdb_file': pdb_file} 99 | if 'mesh_file' in kwargs: 100 | prot_kwargs['mesh_file'] = kwargs['mesh_file'] 101 | if 'assignments_file' in kwargs: 102 | prot_kwargs['assignments_file'] = kwargs['assignments_file'] 103 | 104 | protein = self.prot_builder(**prot_kwargs) 105 | if protein is None: 106 | return None 107 | 108 | if target is not None: 109 | y = torch.tensor(target) 110 | if not len(y.shape): 111 | y = y.unsqueeze(0) 112 | ligand.y = y 113 | 114 | if 'build_prot' in kwargs and kwargs.get('build_prot'): 115 | return (protein, ligand) 116 | return ligand -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/cast/functional.rst: -------------------------------------------------------------------------------- 1 | Functional 2 | ########## 3 | 4 | The following features must be enabled by including :file:`pybind11/functional.h`. 5 | 6 | 7 | Callbacks and passing anonymous functions 8 | ========================================= 9 | 10 | The C++11 standard brought lambda functions and the generic polymorphic 11 | function wrapper ``std::function<>`` to the C++ programming language, which 12 | enable powerful new ways of working with functions. Lambda functions come in 13 | two flavors: stateless lambda function resemble classic function pointers that 14 | link to an anonymous piece of code, while stateful lambda functions 15 | additionally depend on captured variables that are stored in an anonymous 16 | *lambda closure object*. 17 | 18 | Here is a simple example of a C++ function that takes an arbitrary function 19 | (stateful or stateless) with signature ``int -> int`` as an argument and runs 20 | it with the value 10. 21 | 22 | .. code-block:: cpp 23 | 24 | int func_arg(const std::function &f) { 25 | return f(10); 26 | } 27 | 28 | The example below is more involved: it takes a function of signature ``int -> int`` 29 | and returns another function of the same kind. The return value is a stateful 30 | lambda function, which stores the value ``f`` in the capture object and adds 1 to 31 | its return value upon execution. 32 | 33 | .. code-block:: cpp 34 | 35 | std::function func_ret(const std::function &f) { 36 | return [f](int i) { 37 | return f(i) + 1; 38 | }; 39 | } 40 | 41 | This example demonstrates using python named parameters in C++ callbacks which 42 | requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining 43 | methods of classes: 44 | 45 | .. code-block:: cpp 46 | 47 | py::cpp_function func_cpp() { 48 | return py::cpp_function([](int i) { return i+1; }, 49 | py::arg("number")); 50 | } 51 | 52 | After including the extra header file :file:`pybind11/functional.h`, it is almost 53 | trivial to generate binding code for all of these functions. 54 | 55 | .. code-block:: cpp 56 | 57 | #include 58 | 59 | PYBIND11_MODULE(example, m) { 60 | m.def("func_arg", &func_arg); 61 | m.def("func_ret", &func_ret); 62 | m.def("func_cpp", &func_cpp); 63 | } 64 | 65 | The following interactive session shows how to call them from Python. 66 | 67 | .. code-block:: pycon 68 | 69 | $ python 70 | >>> import example 71 | >>> def square(i): 72 | ... return i * i 73 | ... 74 | >>> example.func_arg(square) 75 | 100L 76 | >>> square_plus_1 = example.func_ret(square) 77 | >>> square_plus_1(4) 78 | 17L 79 | >>> plus_1 = func_cpp() 80 | >>> plus_1(number=43) 81 | 44L 82 | 83 | .. warning:: 84 | 85 | Keep in mind that passing a function from C++ to Python (or vice versa) 86 | will instantiate a piece of wrapper code that translates function 87 | invocations between the two languages. Naturally, this translation 88 | increases the computational cost of each function call somewhat. A 89 | problematic situation can arise when a function is copied back and forth 90 | between Python and C++ many times in a row, in which case the underlying 91 | wrappers will accumulate correspondingly. The resulting long sequence of 92 | C++ -> Python -> C++ -> ... roundtrips can significantly decrease 93 | performance. 94 | 95 | There is one exception: pybind11 detects case where a stateless function 96 | (i.e. a function pointer or a lambda function without captured variables) 97 | is passed as an argument to another C++ function exposed in Python. In this 98 | case, there is no overhead. Pybind11 will extract the underlying C++ 99 | function pointer from the wrapped function to sidestep a potential C++ -> 100 | Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`. 101 | 102 | .. note:: 103 | 104 | This functionality is very useful when generating bindings for callbacks in 105 | C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.). 106 | 107 | The file :file:`tests/test_callbacks.cpp` contains a complete example 108 | that demonstrates how to work with callbacks and anonymous functions in 109 | more detail. 110 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/intro.rst: -------------------------------------------------------------------------------- 1 | .. image:: pybind11-logo.png 2 | 3 | About this project 4 | ================== 5 | **pybind11** is a lightweight header-only library that exposes C++ types in Python 6 | and vice versa, mainly to create Python bindings of existing C++ code. Its 7 | goals and syntax are similar to the excellent `Boost.Python`_ library by David 8 | Abrahams: to minimize boilerplate code in traditional extension modules by 9 | inferring type information using compile-time introspection. 10 | 11 | .. _Boost.Python: http://www.boost.org/doc/libs/release/libs/python/doc/index.html 12 | 13 | The main issue with Boost.Python—and the reason for creating such a similar 14 | project—is Boost. Boost is an enormously large and complex suite of utility 15 | libraries that works with almost every C++ compiler in existence. This 16 | compatibility has its cost: arcane template tricks and workarounds are 17 | necessary to support the oldest and buggiest of compiler specimens. Now that 18 | C++11-compatible compilers are widely available, this heavy machinery has 19 | become an excessively large and unnecessary dependency. 20 | Think of this library as a tiny self-contained version of Boost.Python with 21 | everything stripped away that isn't relevant for binding generation. Without 22 | comments, the core header files only require ~4K lines of code and depend on 23 | Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This 24 | compact implementation was possible thanks to some of the new C++11 language 25 | features (specifically: tuples, lambda functions and variadic templates). Since 26 | its creation, this library has grown beyond Boost.Python in many ways, leading 27 | to dramatically simpler binding code in many common situations. 28 | 29 | Core features 30 | ************* 31 | The following core C++ features can be mapped to Python 32 | 33 | - Functions accepting and returning custom data structures per value, reference, or pointer 34 | - Instance methods and static methods 35 | - Overloaded functions 36 | - Instance attributes and static attributes 37 | - Arbitrary exception types 38 | - Enumerations 39 | - Callbacks 40 | - Iterators and ranges 41 | - Custom operators 42 | - Single and multiple inheritance 43 | - STL data structures 44 | - Smart pointers with reference counting like ``std::shared_ptr`` 45 | - Internal references with correct reference counting 46 | - C++ classes with virtual (and pure virtual) methods can be extended in Python 47 | 48 | Goodies 49 | ******* 50 | In addition to the core functionality, pybind11 provides some extra goodies: 51 | 52 | - Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7) are supported with an 53 | implementation-agnostic interface. 54 | 55 | - It is possible to bind C++11 lambda functions with captured variables. The 56 | lambda capture data is stored inside the resulting Python function object. 57 | 58 | - pybind11 uses C++11 move constructors and move assignment operators whenever 59 | possible to efficiently transfer custom data types. 60 | 61 | - It's easy to expose the internal storage of custom data types through 62 | Pythons' buffer protocols. This is handy e.g. for fast conversion between 63 | C++ matrix classes like Eigen and NumPy without expensive copy operations. 64 | 65 | - pybind11 can automatically vectorize functions so that they are transparently 66 | applied to all entries of one or more NumPy array arguments. 67 | 68 | - Python's slice-based access and assignment operations can be supported with 69 | just a few lines of code. 70 | 71 | - Everything is contained in just a few header files; there is no need to link 72 | against any additional libraries. 73 | 74 | - Binaries are generally smaller by a factor of at least 2 compared to 75 | equivalent bindings generated by Boost.Python. A recent pybind11 conversion 76 | of `PyRosetta`_, an enormous Boost.Python binding project, reported a binary 77 | size reduction of **5.4x** and compile time reduction by **5.8x**. 78 | 79 | - Function signatures are precomputed at compile time (using ``constexpr``), 80 | leading to smaller binaries. 81 | 82 | - With little extra effort, C++ types can be pickled and unpickled similar to 83 | regular Python objects. 84 | 85 | .. _PyRosetta: http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 86 | 87 | Supported compilers 88 | ******************* 89 | 90 | 1. Clang/LLVM (any non-ancient version with C++11 support) 91 | 2. GCC 4.8 or newer 92 | 3. Microsoft Visual Studio 2015 or newer 93 | 4. Intel C++ compiler v17 or newer (v16 with pybind11 v2.0 and v15 with pybind11 v2.0 and a `workaround `_ ) 94 | -------------------------------------------------------------------------------- /superpixel/pybind11/tools/pybind11Config.cmake.in: -------------------------------------------------------------------------------- 1 | #[=============================================================================[.rst 2 | 3 | pybind11Config.cmake 4 | -------------------- 5 | 6 | PYBIND11 cmake module. 7 | This module sets the following variables in your project:: 8 | 9 | pybind11_FOUND - true if pybind11 and all required components found on the system 10 | pybind11_VERSION - pybind11 version in format Major.Minor.Release 11 | pybind11_INCLUDE_DIRS - Directories where pybind11 and python headers are located. 12 | pybind11_INCLUDE_DIR - Directory where pybind11 headers are located. 13 | pybind11_DEFINITIONS - Definitions necessary to use pybind11, namely USING_pybind11. 14 | pybind11_LIBRARIES - compile flags and python libraries (as needed) to link against. 15 | pybind11_LIBRARY - empty. 16 | 17 | 18 | Available components: None 19 | 20 | 21 | Exported targets:: 22 | 23 | If pybind11 is found, this module defines the following :prop_tgt:`IMPORTED` 24 | interface library targets:: 25 | 26 | pybind11::module - for extension modules 27 | pybind11::embed - for embedding the Python interpreter 28 | 29 | Python headers, libraries (as needed by platform), and the C++ standard 30 | are attached to the target. 31 | Classic mode:: 32 | 33 | Set PythonLibsNew variables to influence python detection and 34 | CMAKE_CXX_STANDARD to influence standard setting. :: 35 | 36 | find_package(pybind11 CONFIG REQUIRED) 37 | message(STATUS "Found pybind11 v${pybind11_VERSION} ${pybind11_VERSION_TYPE}: ${pybind11_INCLUDE_DIRS}") 38 | 39 | # Create an extension module 40 | add_library(mylib MODULE main.cpp) 41 | target_link_libraries(mylib pybind11::module) 42 | 43 | # Or embed the Python interpreter into an executable 44 | add_executable(myexe main.cpp) 45 | target_link_libraries(myexe pybind11::embed) 46 | 47 | Suggested usage:: 48 | 49 | find_package with version info is not recommended except for release versions. :: 50 | 51 | find_package(pybind11 CONFIG) 52 | find_package(pybind11 2.0 EXACT CONFIG REQUIRED) 53 | 54 | 55 | The following variables can be set to guide the search for this package:: 56 | 57 | pybind11_DIR - CMake variable, set to directory containing this Config file 58 | CMAKE_PREFIX_PATH - CMake variable, set to root directory of this package 59 | PATH - environment variable, set to bin directory of this package 60 | CMAKE_DISABLE_FIND_PACKAGE_pybind11 - CMake variable, disables 61 | find_package(pybind11) when not REQUIRED, perhaps to force internal build 62 | #]=============================================================================] 63 | 64 | @PACKAGE_INIT@ 65 | 66 | # Location of pybind11/pybind11.h 67 | set(pybind11_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/@CMAKE_INSTALL_INCLUDEDIR@") 68 | 69 | set(pybind11_LIBRARY "") 70 | set(pybind11_DEFINITIONS USING_pybind11) 71 | set(pybind11_VERSION_TYPE "@pybind11_VERSION_TYPE@") 72 | 73 | check_required_components(pybind11) 74 | 75 | include("${CMAKE_CURRENT_LIST_DIR}/pybind11Tools.cmake") 76 | 77 | #----------------------------------------------------------------------------- 78 | # Don't include targets if this file is being picked up by another 79 | # project which has already built this as a subproject 80 | #----------------------------------------------------------------------------- 81 | if(NOT TARGET pybind11::pybind11) 82 | include("${CMAKE_CURRENT_LIST_DIR}/pybind11Targets.cmake") 83 | 84 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}") 85 | find_package(PythonLibsNew ${PYBIND11_PYTHON_VERSION} MODULE REQUIRED) 86 | list(REMOVE_AT CMAKE_MODULE_PATH -1) 87 | 88 | set_property( 89 | TARGET pybind11::pybind11 90 | APPEND 91 | PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS}) 92 | set_property( 93 | TARGET pybind11::pybind11 94 | APPEND 95 | PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS}) 96 | 97 | set_property( 98 | TARGET pybind11::embed 99 | APPEND 100 | PROPERTY INTERFACE_LINK_LIBRARIES ${PYTHON_LIBRARIES}) 101 | set_property( 102 | TARGET pybind11::module 103 | APPEND 104 | PROPERTY 105 | INTERFACE_LINK_LIBRARIES 106 | "$<$,$>:$>" 107 | ) 108 | 109 | get_property( 110 | _iid 111 | TARGET pybind11::pybind11 112 | PROPERTY INTERFACE_INCLUDE_DIRECTORIES) 113 | get_property( 114 | _ill 115 | TARGET pybind11::module 116 | PROPERTY INTERFACE_LINK_LIBRARIES) 117 | set(pybind11_INCLUDE_DIRS ${_iid}) 118 | set(pybind11_LIBRARIES ${_ico} ${_ill}) 119 | 120 | include("${CMAKE_CURRENT_LIST_DIR}/pybind11Tools.cmake") 121 | endif() 122 | -------------------------------------------------------------------------------- /superpixel/MSubmodularHeap.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_submodular_heap_h_ 24 | #define _m_submodular_heap_h_ 25 | #include "MMFunctions.h" 26 | #include "MHeap.h" 27 | #include "MERCDisjointSet.h" 28 | #include "MERCFunctions.h" 29 | 30 | using namespace std; 31 | 32 | template 33 | class MSubmodularHeap: public MHeap 34 | { 35 | public: 36 | 37 | MSubmodularHeap(int length); 38 | MSubmodularHeap(T *inarr,int length); 39 | 40 | // An easy update version for tree structure 41 | void EasyPartialUpdateTree(MERCDisjointSet *u,double balancingTerm,double *loop); 42 | 43 | 44 | private: 45 | 46 | MERCDisjointSet *u_; 47 | double *loop_; 48 | double balancingTerm_; 49 | 50 | // An easy update version for tree structure 51 | int EasyUpdateValueTree(int i); 52 | void EasySubmodularMaxHeapifyTree(); 53 | 54 | }; 55 | 56 | 57 | template 58 | MSubmodularHeap::MSubmodularHeap(int length): MHeap(length) {} 59 | 60 | template 61 | MSubmodularHeap::MSubmodularHeap(T *inarr,int length): MHeap(inarr,length) {} 62 | 63 | //============================================================================== 64 | // Fast update for tree structure 65 | //============================================================================== 66 | template 67 | void MSubmodularHeap::EasyPartialUpdateTree(MERCDisjointSet *u,double balancingTerm,double *loop) 68 | { 69 | // access to the disjoint set structure 70 | u_ = u; 71 | // keep track the loop value 72 | loop_ = loop; 73 | // copy the balancing parameter value. 74 | balancingTerm_ = balancingTerm; 75 | 76 | // A special heap update structure that utilize the submodular property. 77 | EasySubmodularMaxHeapifyTree(); 78 | } 79 | 80 | template 81 | void MSubmodularHeap::EasySubmodularMaxHeapifyTree() 82 | { 83 | //If the root node value is not updated, then update it 84 | //If the root node value is updated, then it is the maximum value in the current heap. 85 | //We don't need to update the other nodes because the dimnishing return property guarantees that the value can only be smaller. 86 | while(EasyUpdateValueTree(1)==0) 87 | { 88 | // If the edge form a loop, remove it from the loop and update the heap. 89 | if(this->array_[1].gain_ == 0) 90 | this->HeapExtractMax(); 91 | // Let insert the value into some correct place in the heap. 92 | else 93 | this->MaxHeapify(1); // find the maximum one through maxheapify 94 | } 95 | } 96 | 97 | 98 | template 99 | int MSubmodularHeap::EasyUpdateValueTree(int i) 100 | { 101 | double erGain,bGain; 102 | // store the old gain 103 | double oldGain = this->array_[i].gain_; 104 | 105 | int a,b; 106 | a = u_->Find( this->array_[i].a_ ); 107 | b = u_->Find( this->array_[i].b_ ); 108 | 109 | 110 | 111 | // If the edge forms a cycle, makes the gain zero. 112 | // Later, we will remove the zero edges from the heap. 113 | if( a==b ) 114 | { 115 | this->array_[i].gain_ = 0; 116 | } 117 | else 118 | { 119 | // recompute the entropy rate gain 120 | erGain = MERCFunctions::ComputeERGain( this->array_[i].w_, loop_[this->array_[i].a_]-this->array_[i].w_, loop_[this->array_[i].b_]-this->array_[i].w_); 121 | 122 | // recomptue the balancing gain 123 | bGain = MERCFunctions::ComputeBGain(u_->rNumVertices(), u_->rSize(a), u_->rSize(b) ); 124 | 125 | 126 | // compute the overall gain 127 | this->array_[i].gain_ = erGain+balancingTerm_*bGain; 128 | //array_[i].erGain_ = erGain; 129 | //array_[i].bGain_ = bGain; 130 | } 131 | 132 | // If the value is uptodate, we return one. (It will exit the while loop.) 133 | if(oldGain==this->array_[i].gain_) 134 | return 1; 135 | 136 | // If it is not, then we return zero. (It will trigger another MaxHeapify.) 137 | return 0; 138 | } 139 | 140 | 141 | 142 | #endif -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/eval.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/exec.h: Support for evaluating Python expressions and statements 3 | from strings and files 4 | 5 | Copyright (c) 2016 Klemens Morgenstern and 6 | Wenzel Jakob 7 | 8 | All rights reserved. Use of this source code is governed by a 9 | BSD-style license that can be found in the LICENSE file. 10 | */ 11 | 12 | #pragma once 13 | 14 | #include "pybind11.h" 15 | 16 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 17 | 18 | enum eval_mode { 19 | /// Evaluate a string containing an isolated expression 20 | eval_expr, 21 | 22 | /// Evaluate a string containing a single statement. Returns \c none 23 | eval_single_statement, 24 | 25 | /// Evaluate a string containing a sequence of statement. Returns \c none 26 | eval_statements 27 | }; 28 | 29 | template 30 | object eval(str expr, object global = globals(), object local = object()) { 31 | if (!local) 32 | local = global; 33 | 34 | /* PyRun_String does not accept a PyObject / encoding specifier, 35 | this seems to be the only alternative */ 36 | std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr; 37 | 38 | int start; 39 | switch (mode) { 40 | case eval_expr: start = Py_eval_input; break; 41 | case eval_single_statement: start = Py_single_input; break; 42 | case eval_statements: start = Py_file_input; break; 43 | default: pybind11_fail("invalid evaluation mode"); 44 | } 45 | 46 | PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); 47 | if (!result) 48 | throw error_already_set(); 49 | return reinterpret_steal(result); 50 | } 51 | 52 | template 53 | object eval(const char (&s)[N], object global = globals(), object local = object()) { 54 | /* Support raw string literals by removing common leading whitespace */ 55 | auto expr = (s[0] == '\n') ? str(module::import("textwrap").attr("dedent")(s)) 56 | : str(s); 57 | return eval(expr, global, local); 58 | } 59 | 60 | inline void exec(str expr, object global = globals(), object local = object()) { 61 | eval(expr, global, local); 62 | } 63 | 64 | template 65 | void exec(const char (&s)[N], object global = globals(), object local = object()) { 66 | eval(s, global, local); 67 | } 68 | 69 | #if defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x3000000 70 | template 71 | object eval_file(str, object, object) { 72 | pybind11_fail("eval_file not supported in PyPy3. Use eval"); 73 | } 74 | template 75 | object eval_file(str, object) { 76 | pybind11_fail("eval_file not supported in PyPy3. Use eval"); 77 | } 78 | template 79 | object eval_file(str) { 80 | pybind11_fail("eval_file not supported in PyPy3. Use eval"); 81 | } 82 | #else 83 | template 84 | object eval_file(str fname, object global = globals(), object local = object()) { 85 | if (!local) 86 | local = global; 87 | 88 | int start; 89 | switch (mode) { 90 | case eval_expr: start = Py_eval_input; break; 91 | case eval_single_statement: start = Py_single_input; break; 92 | case eval_statements: start = Py_file_input; break; 93 | default: pybind11_fail("invalid evaluation mode"); 94 | } 95 | 96 | int closeFile = 1; 97 | std::string fname_str = (std::string) fname; 98 | #if PY_VERSION_HEX >= 0x03040000 99 | FILE *f = _Py_fopen_obj(fname.ptr(), "r"); 100 | #elif PY_VERSION_HEX >= 0x03000000 101 | FILE *f = _Py_fopen(fname.ptr(), "r"); 102 | #else 103 | /* No unicode support in open() :( */ 104 | auto fobj = reinterpret_steal(PyFile_FromString( 105 | const_cast(fname_str.c_str()), 106 | const_cast("r"))); 107 | FILE *f = nullptr; 108 | if (fobj) 109 | f = PyFile_AsFile(fobj.ptr()); 110 | closeFile = 0; 111 | #endif 112 | if (!f) { 113 | PyErr_Clear(); 114 | pybind11_fail("File \"" + fname_str + "\" could not be opened!"); 115 | } 116 | 117 | #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) 118 | PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), 119 | local.ptr()); 120 | (void) closeFile; 121 | #else 122 | PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), 123 | local.ptr(), closeFile); 124 | #endif 125 | 126 | if (!result) 127 | throw error_already_set(); 128 | return reinterpret_steal(result); 129 | } 130 | #endif 131 | 132 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 133 | -------------------------------------------------------------------------------- /superpixel/pybind11/include/pybind11/buffer_info.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/buffer_info.h: Python buffer object interface 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "detail/common.h" 13 | 14 | PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | 16 | /// Information record describing a Python buffer object 17 | struct buffer_info { 18 | void *ptr = nullptr; // Pointer to the underlying storage 19 | ssize_t itemsize = 0; // Size of individual items in bytes 20 | ssize_t size = 0; // Total number of entries 21 | std::string format; // For homogeneous buffers, this should be set to format_descriptor::format() 22 | ssize_t ndim = 0; // Number of dimensions 23 | std::vector shape; // Shape of the tensor (1 entry per dimension) 24 | std::vector strides; // Number of bytes between adjacent entries (for each per dimension) 25 | bool readonly = false; // flag to indicate if the underlying storage may be written to 26 | 27 | buffer_info() { } 28 | 29 | buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, 30 | detail::any_container shape_in, detail::any_container strides_in, bool readonly=false) 31 | : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim), 32 | shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) { 33 | if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) 34 | pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length"); 35 | for (size_t i = 0; i < (size_t) ndim; ++i) 36 | size *= shape[i]; 37 | } 38 | 39 | template 40 | buffer_info(T *ptr, detail::any_container shape_in, detail::any_container strides_in, bool readonly=false) 41 | : buffer_info(private_ctr_tag(), ptr, sizeof(T), format_descriptor::format(), static_cast(shape_in->size()), std::move(shape_in), std::move(strides_in), readonly) { } 42 | 43 | buffer_info(void *ptr, ssize_t itemsize, const std::string &format, ssize_t size, bool readonly=false) 44 | : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) { } 45 | 46 | template 47 | buffer_info(T *ptr, ssize_t size, bool readonly=false) 48 | : buffer_info(ptr, sizeof(T), format_descriptor::format(), size, readonly) { } 49 | 50 | template 51 | buffer_info(const T *ptr, ssize_t size, bool readonly=true) 52 | : buffer_info(const_cast(ptr), sizeof(T), format_descriptor::format(), size, readonly) { } 53 | 54 | explicit buffer_info(Py_buffer *view, bool ownview = true) 55 | : buffer_info(view->buf, view->itemsize, view->format, view->ndim, 56 | {view->shape, view->shape + view->ndim}, {view->strides, view->strides + view->ndim}, view->readonly) { 57 | this->m_view = view; 58 | this->ownview = ownview; 59 | } 60 | 61 | buffer_info(const buffer_info &) = delete; 62 | buffer_info& operator=(const buffer_info &) = delete; 63 | 64 | buffer_info(buffer_info &&other) { 65 | (*this) = std::move(other); 66 | } 67 | 68 | buffer_info& operator=(buffer_info &&rhs) { 69 | ptr = rhs.ptr; 70 | itemsize = rhs.itemsize; 71 | size = rhs.size; 72 | format = std::move(rhs.format); 73 | ndim = rhs.ndim; 74 | shape = std::move(rhs.shape); 75 | strides = std::move(rhs.strides); 76 | std::swap(m_view, rhs.m_view); 77 | std::swap(ownview, rhs.ownview); 78 | readonly = rhs.readonly; 79 | return *this; 80 | } 81 | 82 | ~buffer_info() { 83 | if (m_view && ownview) { PyBuffer_Release(m_view); delete m_view; } 84 | } 85 | 86 | Py_buffer *view() const { return m_view; } 87 | Py_buffer *&view() { return m_view; } 88 | private: 89 | struct private_ctr_tag { }; 90 | 91 | buffer_info(private_ctr_tag, void *ptr, ssize_t itemsize, const std::string &format, ssize_t ndim, 92 | detail::any_container &&shape_in, detail::any_container &&strides_in, bool readonly) 93 | : buffer_info(ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) { } 94 | 95 | Py_buffer *m_view = nullptr; 96 | bool ownview = false; 97 | }; 98 | 99 | PYBIND11_NAMESPACE_BEGIN(detail) 100 | 101 | template struct compare_buffer_info { 102 | static bool compare(const buffer_info& b) { 103 | return b.format == format_descriptor::format() && b.itemsize == (ssize_t) sizeof(T); 104 | } 105 | }; 106 | 107 | template struct compare_buffer_info::value>> { 108 | static bool compare(const buffer_info& b) { 109 | return (size_t) b.itemsize == sizeof(T) && (b.format == format_descriptor::value || 110 | ((sizeof(T) == sizeof(long)) && b.format == (std::is_unsigned::value ? "L" : "l")) || 111 | ((sizeof(T) == sizeof(size_t)) && b.format == (std::is_unsigned::value ? "N" : "n"))); 112 | } 113 | }; 114 | 115 | PYBIND11_NAMESPACE_END(detail) 116 | PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) 117 | -------------------------------------------------------------------------------- /scripts/preprocess/splits.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import random 3 | import copy 4 | 5 | 6 | def generate_scaffold(mol, include_chirality=False): 7 | """Compute the Bemis-Murcko scaffold for a SMILES string. 8 | Note 9 | ---- 10 | This function requires `rdkit` to be installed. 11 | """ 12 | from rdkit.Chem.Scaffolds import MurckoScaffold 13 | scaffold_smiles = MurckoScaffold.MurckoScaffoldSmiles( 14 | mol=mol, includeChirality=include_chirality) 15 | return scaffold_smiles 16 | 17 | 18 | def scaffold_split(dataset, 19 | seed: int = None, 20 | frac_valid: float = 0.1, 21 | frac_test: float = 0.1, 22 | **kwargs): 23 | """Scaffold split for dataset. 24 | 25 | Parameters 26 | ---------- 27 | dataset: 28 | Blah blah 29 | seed: int (default None), 30 | Seed to ensure reproducibility in splits 31 | frac_valid: float (default 0.1), 32 | Valid fraction 33 | frac_test: float (default 0.1), 34 | Test fraction 35 | """ 36 | frac_train = 1 - frac_valid - frac_test 37 | scaffolds = {} 38 | 39 | for id, mol in dataset.items(): 40 | try: 41 | scaffold = generate_scaffold(mol) 42 | if scaffold not in scaffolds: 43 | scaffolds[scaffold] = [id] 44 | else: 45 | scaffolds[scaffold].append(id) 46 | except Exception as e: 47 | print(e, flush=True) 48 | continue 49 | 50 | scaffolds = {key: sorted(value) for key, value in scaffolds.items()} 51 | scaffold_sets = [ 52 | scaffold_set for (scaffold, scaffold_set) in sorted( 53 | scaffolds.items(), key=lambda x: (len(x[1]), x[1][0]), reverse=True) 54 | ] 55 | 56 | train_cutoff = int(frac_train * len(dataset)) 57 | valid_cutoff = int((frac_train + frac_valid) * len(dataset)) 58 | train_ids, valid_ids, test_ids = [], [], [] 59 | 60 | for scaffold_set in scaffold_sets: 61 | if len(train_ids) + len(scaffold_set) > train_cutoff: 62 | if len(train_ids) + len(scaffold_set) + len( 63 | valid_ids) > valid_cutoff: 64 | test_ids += scaffold_set 65 | else: 66 | valid_ids += scaffold_set 67 | else: 68 | train_ids += scaffold_set 69 | print(f"Train: {len(train_ids)}, Valid: {len(valid_ids)}, Test: {len(test_ids)}", flush=True) 70 | return train_ids, valid_ids, test_ids 71 | 72 | 73 | def random_split(dataset, 74 | seed: int = None, 75 | frac_valid: float = 0.1, 76 | frac_test: float = 0.1, 77 | **kwargs): 78 | """Random split for dataset. 79 | 80 | Parameters 81 | ---------- 82 | dataset: 83 | Blah blah 84 | seed: int (default None), 85 | Seed to ensure reproducibility in splits 86 | frac_valid: float (default 0.1), 87 | Valid fraction 88 | frac_test: float (default 0.1), 89 | Test fraction 90 | """ 91 | ids_copy = list(dataset.keys()) 92 | frac_train = 1 - frac_valid - frac_test 93 | train_cutoff = int(frac_train * len(dataset)) 94 | valid_cutoff = int((frac_train + frac_valid) * len(dataset)) 95 | random.shuffle(ids_copy) 96 | 97 | train_ids = ids_copy[:train_cutoff] 98 | valid_ids = ids_copy[train_cutoff:valid_cutoff] 99 | test_ids = ids_copy[valid_cutoff:] 100 | print(f"Train: {len(train_ids)}, Valid: {len(valid_ids)}, Test: {len(test_ids)}", flush=True) 101 | return train_ids, valid_ids, test_ids 102 | 103 | 104 | def stratified_split(dataset, 105 | seed: int = None, 106 | frac_valid: float = 0.1, 107 | frac_test: float = 0.1): 108 | """Stratified split for dataset. 109 | 110 | Parameters 111 | ---------- 112 | dataset: 113 | Blah blah 114 | seed: int (default None), 115 | Seed to ensure reproducibility in splits 116 | frac_valid: float (default 0.1), 117 | Valid fraction 118 | frac_test: float (default 0.1), 119 | Test fraction 120 | """ 121 | frac_train = 1 - frac_valid - frac_test 122 | activities = list(dataset.values()) 123 | sort_idxs = np.argsort(activities) 124 | 125 | train_ids, valid_ids, test_ids = [], [], [] 126 | sorted_ids = np.array(list(dataset.keys()))[sort_idxs] 127 | sorted_ids = sorted_ids.tolist() 128 | 129 | cutoff = 10 130 | train_cutoff = int(frac_train * cutoff) 131 | valid_cutoff = int((frac_train + frac_valid) * cutoff) 132 | 133 | start_idxs = np.arange(0, len(sorted_ids), cutoff) 134 | for idx in start_idxs: 135 | ids_batch = sorted_ids[idx:idx + cutoff].copy() 136 | random.shuffle(ids_batch) 137 | 138 | train_cutoff = int(frac_train * len(ids_batch)) 139 | valid_cutoff = int((frac_train + frac_valid) * len(ids_batch)) 140 | 141 | train_ids.extend(ids_batch[:train_cutoff]) 142 | valid_ids.extend(ids_batch[train_cutoff: valid_cutoff]) 143 | test_ids.extend(ids_batch[valid_cutoff:]) 144 | 145 | print(f"Train: {len(train_ids)}, Valid: {len(valid_ids)}, Test: {len(test_ids)}", flush=True) 146 | return train_ids, valid_ids, test_ids 147 | 148 | 149 | def agglomerative_split(dataset, 150 | seed: int = None, 151 | frac_valid: float = 0.1, 152 | frac_test: float = 0.1): 153 | pass 154 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/pycpp/object.rst: -------------------------------------------------------------------------------- 1 | Python types 2 | ############ 3 | 4 | Available wrappers 5 | ================== 6 | 7 | All major Python types are available as thin C++ wrapper classes. These 8 | can also be used as function parameters -- see :ref:`python_objects_as_args`. 9 | 10 | Available types include :class:`handle`, :class:`object`, :class:`bool_`, 11 | :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`, 12 | :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`, 13 | :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`, 14 | :class:`array`, and :class:`array_t`. 15 | 16 | Casting back and forth 17 | ====================== 18 | 19 | In this kind of mixed code, it is often necessary to convert arbitrary C++ 20 | types to Python, which can be done using :func:`py::cast`: 21 | 22 | .. code-block:: cpp 23 | 24 | MyClass *cls = ..; 25 | py::object obj = py::cast(cls); 26 | 27 | The reverse direction uses the following syntax: 28 | 29 | .. code-block:: cpp 30 | 31 | py::object obj = ...; 32 | MyClass *cls = obj.cast(); 33 | 34 | When conversion fails, both directions throw the exception :class:`cast_error`. 35 | 36 | .. _python_libs: 37 | 38 | Accessing Python libraries from C++ 39 | =================================== 40 | 41 | It is also possible to import objects defined in the Python standard 42 | library or available in the current Python environment (``sys.path``) and work 43 | with these in C++. 44 | 45 | This example obtains a reference to the Python ``Decimal`` class. 46 | 47 | .. code-block:: cpp 48 | 49 | // Equivalent to "from decimal import Decimal" 50 | py::object Decimal = py::module::import("decimal").attr("Decimal"); 51 | 52 | .. code-block:: cpp 53 | 54 | // Try to import scipy 55 | py::object scipy = py::module::import("scipy"); 56 | return scipy.attr("__version__"); 57 | 58 | .. _calling_python_functions: 59 | 60 | Calling Python functions 61 | ======================== 62 | 63 | It is also possible to call Python classes, functions and methods 64 | via ``operator()``. 65 | 66 | .. code-block:: cpp 67 | 68 | // Construct a Python object of class Decimal 69 | py::object pi = Decimal("3.14159"); 70 | 71 | .. code-block:: cpp 72 | 73 | // Use Python to make our directories 74 | py::object os = py::module::import("os"); 75 | py::object makedirs = os.attr("makedirs"); 76 | makedirs("/tmp/path/to/somewhere"); 77 | 78 | One can convert the result obtained from Python to a pure C++ version 79 | if a ``py::class_`` or type conversion is defined. 80 | 81 | .. code-block:: cpp 82 | 83 | py::function f = <...>; 84 | py::object result_py = f(1234, "hello", some_instance); 85 | MyClass &result = result_py.cast(); 86 | 87 | .. _calling_python_methods: 88 | 89 | Calling Python methods 90 | ======================== 91 | 92 | To call an object's method, one can again use ``.attr`` to obtain access to the 93 | Python method. 94 | 95 | .. code-block:: cpp 96 | 97 | // Calculate e^π in decimal 98 | py::object exp_pi = pi.attr("exp")(); 99 | py::print(py::str(exp_pi)); 100 | 101 | In the example above ``pi.attr("exp")`` is a *bound method*: it will always call 102 | the method for that same instance of the class. Alternately one can create an 103 | *unbound method* via the Python class (instead of instance) and pass the ``self`` 104 | object explicitly, followed by other arguments. 105 | 106 | .. code-block:: cpp 107 | 108 | py::object decimal_exp = Decimal.attr("exp"); 109 | 110 | // Compute the e^n for n=0..4 111 | for (int n = 0; n < 5; n++) { 112 | py::print(decimal_exp(Decimal(n)); 113 | } 114 | 115 | Keyword arguments 116 | ================= 117 | 118 | Keyword arguments are also supported. In Python, there is the usual call syntax: 119 | 120 | .. code-block:: python 121 | 122 | def f(number, say, to): 123 | ... # function code 124 | 125 | f(1234, say="hello", to=some_instance) # keyword call in Python 126 | 127 | In C++, the same call can be made using: 128 | 129 | .. code-block:: cpp 130 | 131 | using namespace pybind11::literals; // to bring in the `_a` literal 132 | f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++ 133 | 134 | Unpacking arguments 135 | =================== 136 | 137 | Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with 138 | other arguments: 139 | 140 | .. code-block:: cpp 141 | 142 | // * unpacking 143 | py::tuple args = py::make_tuple(1234, "hello", some_instance); 144 | f(*args); 145 | 146 | // ** unpacking 147 | py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance); 148 | f(**kwargs); 149 | 150 | // mixed keywords, * and ** unpacking 151 | py::tuple args = py::make_tuple(1234); 152 | py::dict kwargs = py::dict("to"_a=some_instance); 153 | f(*args, "say"_a="hello", **kwargs); 154 | 155 | Generalized unpacking according to PEP448_ is also supported: 156 | 157 | .. code-block:: cpp 158 | 159 | py::dict kwargs1 = py::dict("number"_a=1234); 160 | py::dict kwargs2 = py::dict("to"_a=some_instance); 161 | f(**kwargs1, "say"_a="hello", **kwargs2); 162 | 163 | .. seealso:: 164 | 165 | The file :file:`tests/test_pytypes.cpp` contains a complete 166 | example that demonstrates passing native Python types in more detail. The 167 | file :file:`tests/test_callbacks.cpp` presents a few examples of calling 168 | Python functions from C++, including keywords arguments and unpacking. 169 | 170 | .. _PEP448: https://www.python.org/dev/peps/pep-0448/ 171 | -------------------------------------------------------------------------------- /superpixel/pybind11/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Setup script for PyPI; use CMakeFile.txt to build extension modules 5 | 6 | from setuptools import setup 7 | from distutils.command.install_headers import install_headers 8 | from distutils.command.build_py import build_py 9 | from pybind11 import __version__ 10 | import os 11 | 12 | package_data = [ 13 | 'include/pybind11/detail/class.h', 14 | 'include/pybind11/detail/common.h', 15 | 'include/pybind11/detail/descr.h', 16 | 'include/pybind11/detail/init.h', 17 | 'include/pybind11/detail/internals.h', 18 | 'include/pybind11/detail/typeid.h', 19 | 'include/pybind11/attr.h', 20 | 'include/pybind11/buffer_info.h', 21 | 'include/pybind11/cast.h', 22 | 'include/pybind11/chrono.h', 23 | 'include/pybind11/common.h', 24 | 'include/pybind11/complex.h', 25 | 'include/pybind11/eigen.h', 26 | 'include/pybind11/embed.h', 27 | 'include/pybind11/eval.h', 28 | 'include/pybind11/functional.h', 29 | 'include/pybind11/iostream.h', 30 | 'include/pybind11/numpy.h', 31 | 'include/pybind11/operators.h', 32 | 'include/pybind11/options.h', 33 | 'include/pybind11/pybind11.h', 34 | 'include/pybind11/pytypes.h', 35 | 'include/pybind11/stl.h', 36 | 'include/pybind11/stl_bind.h', 37 | ] 38 | 39 | # Prevent installation of pybind11 headers by setting 40 | # PYBIND11_USE_CMAKE. 41 | if os.environ.get('PYBIND11_USE_CMAKE'): 42 | headers = [] 43 | else: 44 | headers = package_data 45 | 46 | 47 | class InstallHeaders(install_headers): 48 | """Use custom header installer because the default one flattens subdirectories""" 49 | def run(self): 50 | if not self.distribution.headers: 51 | return 52 | 53 | for header in self.distribution.headers: 54 | subdir = os.path.dirname(os.path.relpath(header, 'include/pybind11')) 55 | install_dir = os.path.join(self.install_dir, subdir) 56 | self.mkpath(install_dir) 57 | 58 | (out, _) = self.copy_file(header, install_dir) 59 | self.outfiles.append(out) 60 | 61 | 62 | # Install the headers inside the package as well 63 | class BuildPy(build_py): 64 | def build_package_data(self): 65 | build_py.build_package_data(self) 66 | for header in package_data: 67 | target = os.path.join(self.build_lib, 'pybind11', header) 68 | self.mkpath(os.path.dirname(target)) 69 | self.copy_file(header, target, preserve_mode=False) 70 | 71 | def get_outputs(self, include_bytecode=1): 72 | outputs = build_py.get_outputs(self, include_bytecode=include_bytecode) 73 | for header in package_data: 74 | target = os.path.join(self.build_lib, 'pybind11', header) 75 | outputs.append(target) 76 | return outputs 77 | 78 | 79 | setup( 80 | name='pybind11', 81 | version=__version__, 82 | description='Seamless operability between C++11 and Python', 83 | author='Wenzel Jakob', 84 | author_email='wenzel.jakob@epfl.ch', 85 | url='https://github.com/pybind/pybind11', 86 | download_url='https://github.com/pybind/pybind11/tarball/v' + __version__, 87 | packages=['pybind11'], 88 | license='BSD', 89 | headers=headers, 90 | zip_safe=False, 91 | cmdclass=dict(install_headers=InstallHeaders, build_py=BuildPy), 92 | classifiers=[ 93 | 'Development Status :: 5 - Production/Stable', 94 | 'Intended Audience :: Developers', 95 | 'Topic :: Software Development :: Libraries :: Python Modules', 96 | 'Topic :: Utilities', 97 | 'Programming Language :: C++', 98 | 'Programming Language :: Python :: 2.7', 99 | 'Programming Language :: Python :: 3', 100 | 'Programming Language :: Python :: 3.2', 101 | 'Programming Language :: Python :: 3.3', 102 | 'Programming Language :: Python :: 3.4', 103 | 'Programming Language :: Python :: 3.5', 104 | 'Programming Language :: Python :: 3.6', 105 | 'License :: OSI Approved :: BSD License' 106 | ], 107 | keywords='C++11, Python bindings', 108 | long_description="""pybind11 is a lightweight header-only library that 109 | exposes C++ types in Python and vice versa, mainly to create Python bindings of 110 | existing C++ code. Its goals and syntax are similar to the excellent 111 | Boost.Python by David Abrahams: to minimize boilerplate code in traditional 112 | extension modules by inferring type information using compile-time 113 | introspection. 114 | 115 | The main issue with Boost.Python-and the reason for creating such a similar 116 | project-is Boost. Boost is an enormously large and complex suite of utility 117 | libraries that works with almost every C++ compiler in existence. This 118 | compatibility has its cost: arcane template tricks and workarounds are 119 | necessary to support the oldest and buggiest of compiler specimens. Now that 120 | C++11-compatible compilers are widely available, this heavy machinery has 121 | become an excessively large and unnecessary dependency. 122 | 123 | Think of this library as a tiny self-contained version of Boost.Python with 124 | everything stripped away that isn't relevant for binding generation. Without 125 | comments, the core header files only require ~4K lines of code and depend on 126 | Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This 127 | compact implementation was possible thanks to some of the new C++11 language 128 | features (specifically: tuples, lambda functions and variadic templates). Since 129 | its creation, this library has grown beyond Boost.Python in many ways, leading 130 | to dramatically simpler binding code in many common situations.""") 131 | -------------------------------------------------------------------------------- /superpixel/pybind11/docs/advanced/pycpp/utilities.rst: -------------------------------------------------------------------------------- 1 | Utilities 2 | ######### 3 | 4 | Using Python's print function in C++ 5 | ==================================== 6 | 7 | The usual way to write output in C++ is using ``std::cout`` while in Python one 8 | would use ``print``. Since these methods use different buffers, mixing them can 9 | lead to output order issues. To resolve this, pybind11 modules can use the 10 | :func:`py::print` function which writes to Python's ``sys.stdout`` for consistency. 11 | 12 | Python's ``print`` function is replicated in the C++ API including optional 13 | keyword arguments ``sep``, ``end``, ``file``, ``flush``. Everything works as 14 | expected in Python: 15 | 16 | .. code-block:: cpp 17 | 18 | py::print(1, 2.0, "three"); // 1 2.0 three 19 | py::print(1, 2.0, "three", "sep"_a="-"); // 1-2.0-three 20 | 21 | auto args = py::make_tuple("unpacked", true); 22 | py::print("->", *args, "end"_a="<-"); // -> unpacked True <- 23 | 24 | .. _ostream_redirect: 25 | 26 | Capturing standard output from ostream 27 | ====================================== 28 | 29 | Often, a library will use the streams ``std::cout`` and ``std::cerr`` to print, 30 | but this does not play well with Python's standard ``sys.stdout`` and ``sys.stderr`` 31 | redirection. Replacing a library's printing with `py::print ` may not 32 | be feasible. This can be fixed using a guard around the library function that 33 | redirects output to the corresponding Python streams: 34 | 35 | .. code-block:: cpp 36 | 37 | #include 38 | 39 | ... 40 | 41 | // Add a scoped redirect for your noisy code 42 | m.def("noisy_func", []() { 43 | py::scoped_ostream_redirect stream( 44 | std::cout, // std::ostream& 45 | py::module::import("sys").attr("stdout") // Python output 46 | ); 47 | call_noisy_func(); 48 | }); 49 | 50 | This method respects flushes on the output streams and will flush if needed 51 | when the scoped guard is destroyed. This allows the output to be redirected in 52 | real time, such as to a Jupyter notebook. The two arguments, the C++ stream and 53 | the Python output, are optional, and default to standard output if not given. An 54 | extra type, `py::scoped_estream_redirect `, is identical 55 | except for defaulting to ``std::cerr`` and ``sys.stderr``; this can be useful with 56 | `py::call_guard`, which allows multiple items, but uses the default constructor: 57 | 58 | .. code-block:: py 59 | 60 | // Alternative: Call single function using call guard 61 | m.def("noisy_func", &call_noisy_function, 62 | py::call_guard()); 64 | 65 | The redirection can also be done in Python with the addition of a context 66 | manager, using the `py::add_ostream_redirect() ` function: 67 | 68 | .. code-block:: cpp 69 | 70 | py::add_ostream_redirect(m, "ostream_redirect"); 71 | 72 | The name in Python defaults to ``ostream_redirect`` if no name is passed. This 73 | creates the following context manager in Python: 74 | 75 | .. code-block:: python 76 | 77 | with ostream_redirect(stdout=True, stderr=True): 78 | noisy_function() 79 | 80 | It defaults to redirecting both streams, though you can use the keyword 81 | arguments to disable one of the streams if needed. 82 | 83 | .. note:: 84 | 85 | The above methods will not redirect C-level output to file descriptors, such 86 | as ``fprintf``. For those cases, you'll need to redirect the file 87 | descriptors either directly in C or with Python's ``os.dup2`` function 88 | in an operating-system dependent way. 89 | 90 | .. _eval: 91 | 92 | Evaluating Python expressions from strings and files 93 | ==================================================== 94 | 95 | pybind11 provides the `eval`, `exec` and `eval_file` functions to evaluate 96 | Python expressions and statements. The following example illustrates how they 97 | can be used. 98 | 99 | .. code-block:: cpp 100 | 101 | // At beginning of file 102 | #include 103 | 104 | ... 105 | 106 | // Evaluate in scope of main module 107 | py::object scope = py::module::import("__main__").attr("__dict__"); 108 | 109 | // Evaluate an isolated expression 110 | int result = py::eval("my_variable + 10", scope).cast(); 111 | 112 | // Evaluate a sequence of statements 113 | py::exec( 114 | "print('Hello')\n" 115 | "print('world!');", 116 | scope); 117 | 118 | // Evaluate the statements in an separate Python file on disk 119 | py::eval_file("script.py", scope); 120 | 121 | C++11 raw string literals are also supported and quite handy for this purpose. 122 | The only requirement is that the first statement must be on a new line following 123 | the raw string delimiter ``R"(``, ensuring all lines have common leading indent: 124 | 125 | .. code-block:: cpp 126 | 127 | py::exec(R"( 128 | x = get_answer() 129 | if x == 42: 130 | print('Hello World!') 131 | else: 132 | print('Bye!') 133 | )", scope 134 | ); 135 | 136 | .. note:: 137 | 138 | `eval` and `eval_file` accept a template parameter that describes how the 139 | string/file should be interpreted. Possible choices include ``eval_expr`` 140 | (isolated expression), ``eval_single_statement`` (a single statement, return 141 | value is always ``none``), and ``eval_statements`` (sequence of statements, 142 | return value is always ``none``). `eval` defaults to ``eval_expr``, 143 | `eval_file` defaults to ``eval_statements`` and `exec` is just a shortcut 144 | for ``eval``. 145 | -------------------------------------------------------------------------------- /superpixel/pybind11/tests/pybind11_cross_module_tests.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules 3 | 4 | Copyright (c) 2017 Jason Rhinelander 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include "local_bindings.h" 12 | #include 13 | #include 14 | 15 | PYBIND11_MODULE(pybind11_cross_module_tests, m) { 16 | m.doc() = "pybind11 cross-module test module"; 17 | 18 | // test_local_bindings.py tests: 19 | // 20 | // Definitions here are tested by importing both this module and the 21 | // relevant pybind11_tests submodule from a test_whatever.py 22 | 23 | // test_load_external 24 | bind_local(m, "ExternalType1", py::module_local()); 25 | bind_local(m, "ExternalType2", py::module_local()); 26 | 27 | // test_exceptions.py 28 | m.def("raise_runtime_error", []() { PyErr_SetString(PyExc_RuntimeError, "My runtime error"); throw py::error_already_set(); }); 29 | m.def("raise_value_error", []() { PyErr_SetString(PyExc_ValueError, "My value error"); throw py::error_already_set(); }); 30 | m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); }); 31 | m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); }); 32 | m.def("throw_stop_iteration", []() { throw py::stop_iteration(); }); 33 | 34 | // test_local_bindings.py 35 | // Local to both: 36 | bind_local(m, "LocalType", py::module_local()) 37 | .def("get2", [](LocalType &t) { return t.i + 2; }) 38 | ; 39 | 40 | // Can only be called with our python type: 41 | m.def("local_value", [](LocalType &l) { return l.i; }); 42 | 43 | // test_nonlocal_failure 44 | // This registration will fail (global registration when LocalFail is already registered 45 | // globally in the main test module): 46 | m.def("register_nonlocal", [m]() { 47 | bind_local(m, "NonLocalType"); 48 | }); 49 | 50 | // test_stl_bind_local 51 | // stl_bind.h binders defaults to py::module_local if the types are local or converting: 52 | py::bind_vector(m, "LocalVec"); 53 | py::bind_map(m, "LocalMap"); 54 | 55 | // test_stl_bind_global 56 | // and global if the type (or one of the types, for the map) is global (so these will fail, 57 | // assuming pybind11_tests is already loaded): 58 | m.def("register_nonlocal_vec", [m]() { 59 | py::bind_vector(m, "NonLocalVec"); 60 | }); 61 | m.def("register_nonlocal_map", [m]() { 62 | py::bind_map(m, "NonLocalMap"); 63 | }); 64 | // The default can, however, be overridden to global using `py::module_local()` or 65 | // `py::module_local(false)`. 66 | // Explicitly made local: 67 | py::bind_vector(m, "NonLocalVec2", py::module_local()); 68 | // Explicitly made global (and so will fail to bind): 69 | m.def("register_nonlocal_map2", [m]() { 70 | py::bind_map(m, "NonLocalMap2", py::module_local(false)); 71 | }); 72 | 73 | // test_mixed_local_global 74 | // We try this both with the global type registered first and vice versa (the order shouldn't 75 | // matter). 76 | m.def("register_mixed_global_local", [m]() { 77 | bind_local(m, "MixedGlobalLocal", py::module_local()); 78 | }); 79 | m.def("register_mixed_local_global", [m]() { 80 | bind_local(m, "MixedLocalGlobal", py::module_local(false)); 81 | }); 82 | m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); 83 | m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); 84 | 85 | // test_internal_locals_differ 86 | m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::registered_local_types_cpp(); }); 87 | 88 | // test_stl_caster_vs_stl_bind 89 | py::bind_vector>(m, "VectorInt"); 90 | 91 | m.def("load_vector_via_binding", [](std::vector &v) { 92 | return std::accumulate(v.begin(), v.end(), 0); 93 | }); 94 | 95 | // test_cross_module_calls 96 | m.def("return_self", [](LocalVec *v) { return v; }); 97 | m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); 98 | 99 | class Dog : public pets::Pet { public: Dog(std::string name) : Pet(name) {}; }; 100 | py::class_(m, "Pet", py::module_local()) 101 | .def("name", &pets::Pet::name); 102 | // Binding for local extending class: 103 | py::class_(m, "Dog") 104 | .def(py::init()); 105 | m.def("pet_name", [](pets::Pet &p) { return p.name(); }); 106 | 107 | py::class_(m, "MixGL", py::module_local()).def(py::init()); 108 | m.def("get_gl_value", [](MixGL &o) { return o.i + 100; }); 109 | 110 | py::class_(m, "MixGL2", py::module_local()).def(py::init()); 111 | 112 | // test_vector_bool 113 | // We can't test both stl.h and stl_bind.h conversions of `std::vector` within 114 | // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool` 115 | // is defined here and tested in `test_stl_binders.py`. 116 | py::bind_vector>(m, "VectorBool"); 117 | 118 | // test_missing_header_message 119 | // The main module already includes stl.h, but we need to test the error message 120 | // which appears when this header is missing. 121 | m.def("missing_header_arg", [](std::vector) { }); 122 | m.def("missing_header_return", []() { return std::vector(); }); 123 | } 124 | -------------------------------------------------------------------------------- /holoprot/utils/tensor.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import numpy as np 5 | from typing import List, Tuple, Any, Optional, Union 6 | 7 | 8 | def zip_tensors(tup_list): 9 | arr0, arr1, arr2 = zip(*tup_list) 10 | if type(arr2[0]) is int: 11 | arr0 = torch.stack(arr0, dim=0) 12 | arr1 = torch.tensor(arr1, dtype=torch.long) 13 | arr2 = torch.tensor(arr2, dtype=torch.long) 14 | else: 15 | arr0 = torch.cat(arr0, dim=0) 16 | arr1 = [x for a in arr1 for x in a] 17 | arr1 = torch.tensor(arr1, dtype=torch.long) 18 | arr2 = torch.cat(arr2, dim=0) 19 | return arr0, arr1, arr2 20 | 21 | 22 | def create_pad_tensor(alist): 23 | max_len = max([len(a) for a in alist]) + 1 24 | for a in alist: 25 | pad_len = max_len - len(a) 26 | a.extend([0] * pad_len) 27 | return torch.tensor(alist, dtype=torch.long) 28 | 29 | 30 | def index_scatter(sub_data, all_data, index): 31 | d0, d1 = all_data.size() 32 | buf = torch.zeros_like(all_data).scatter_(0, 33 | index.repeat(d1, 1).t(), sub_data) 34 | mask = torch.ones(d0, device=all_data.device).scatter_(0, index, 0) 35 | return all_data * mask.unsqueeze(-1) + buf 36 | 37 | 38 | def create_scope_tensor(scope: List[Tuple[int, int]], 39 | return_rev: bool = True, 40 | device: str = 'cpu') -> Tuple[torch.Tensor]: 41 | """ 42 | :return: A tensor that ind selects into flat to produce batch. A tensor that does the reverse. 43 | """ 44 | max_num_bonds = max([num for ind, num in scope]) 45 | sel, rev = [], [] 46 | for i, entry in enumerate(scope): 47 | start, num = entry 48 | sel.append([start + ind for ind in range(num)]) 49 | sel[-1].extend([0] * (max_num_bonds - num)) 50 | if return_rev: 51 | rev.extend([i * max_num_bonds + ind for ind in range(num)]) 52 | if return_rev: 53 | return torch.from_numpy( 54 | np.array(sel)).long().to(device), torch.from_numpy( 55 | np.array(rev)).long().to(device) 56 | else: 57 | return torch.from_numpy(np.array(sel)).long().to(device) 58 | 59 | 60 | def flat_to_batch(source: torch.Tensor, scope: torch.Tensor) -> torch.Tensor: 61 | """ 62 | :param source: A tensor of shape (num_bonds, hidden_size) containing message features. 63 | :param scope: A tensor of shape (batch_size, max_num_bonds) expressing bond indices for each mol/row. 64 | :return: A tensor of shape (batch, max_num_bonds, hidden_size) containing the message features. 65 | """ 66 | final_size = (scope.shape[0], -1, 67 | source.shape[1]) # batch x max_num_bonds x hidden_size 68 | ret = source.index_select(dim=0, index=scope.view(-1)) 69 | return ret.view(final_size) 70 | 71 | 72 | def batch_to_flat(source: torch.Tensor, scope: torch.Tensor) -> torch.Tensor: 73 | """ 74 | :param source: A tensor of shape (batch, max_num_bonds, hidden_size). 75 | :param scope: A tensor of shape (batch_size, max_num_bonds) expressing bond indices for each mol/row. 76 | :return: A tensor of shape (num_bonds, hidden_size) with mols concatenated. 77 | """ 78 | hidden_size = source.shape[-1] 79 | ret = source.reshape(-1, hidden_size) # (batch*max_num_bonds) x hidden_size 80 | ret = ret.index_select(dim=0, index=scope) 81 | 82 | return ret 83 | 84 | 85 | def stack_pad_tensor(tensor_list): 86 | max_len = max([t.size(0) for t in tensor_list]) 87 | for i, tensor in enumerate(tensor_list): 88 | pad_len = max_len - tensor.size(0) 89 | tensor_list[i] = F.pad(tensor, (0, 0, 0, pad_len)) 90 | return torch.stack(tensor_list, dim=0) 91 | 92 | 93 | def get_pair(tensor): 94 | """Gets paired combination. 95 | 96 | Given a tensor of shape (x0, x1, x2), this gives you a tensor of shape 97 | (x0, x1, x1, x2) where the pairs of elements in the x1 dim. 98 | """ 99 | return tensor.unsqueeze(1) + tensor.unsqueeze(-2) 100 | 101 | 102 | def index_select_ND(input, dim, index): 103 | """Wrapper around torch.index_select for non 1D index tensors.""" 104 | input_shape = input.shape 105 | target_shape = index.shape + input_shape[dim + 1:] 106 | out_tensor = input.index_select(dim, index.view(-1)) 107 | return out_tensor.view(target_shape) 108 | 109 | def build_mlp(in_dim: int, 110 | h_dim: Union[int, List], 111 | out_dim: int = None, 112 | dropout_p: float = 0.2, 113 | activation: str = 'relu') -> nn.Sequential: 114 | """Builds an MLP. 115 | Parameters 116 | ---------- 117 | in_dim: int, 118 | Input dimension of the MLP 119 | h_dim: int, 120 | Hidden layer dimension of the MLP 121 | out_dim: int, default None 122 | Output size of the MLP. If None, a Linear layer is returned, with ReLU 123 | dropout_p: float, default 0.2, 124 | Dropout probability 125 | """ 126 | if isinstance(h_dim, int): 127 | h_dim = [h_dim] 128 | 129 | sizes = [in_dim] + h_dim 130 | mlp_size_tuple = list(zip(*(sizes[:-1], sizes[1:]))) 131 | 132 | if isinstance(dropout_p, float): 133 | dropout_p = [dropout_p] * len(mlp_size_tuple) 134 | 135 | layers = [] 136 | 137 | for idx, (prev_size, next_size) in enumerate(mlp_size_tuple): 138 | layers.append(nn.Linear(prev_size, next_size)) 139 | if activation == 'relu': 140 | layers.append(nn.LeakyReLU()) 141 | elif activation == 'lrelu': 142 | layers.append(nn.ReLU()) 143 | layers.append(nn.Dropout(dropout_p[idx])) 144 | 145 | if out_dim is not None: 146 | layers.append(nn.Linear(sizes[-1], out_dim)) 147 | 148 | return nn.Sequential(*layers) 149 | --------------------------------------------------------------------------------