opengm-2.3.6+20160905/000077500000000000000000000000001276346362400137265ustar00rootroot00000000000000opengm-2.3.6+20160905/.gitignore000066400000000000000000000001401276346362400157110ustar00rootroot00000000000000*/src/interfaces/python/docsrc/source/conf.py /build /.settings /.cproject /.project *~ *.swp opengm-2.3.6+20160905/.travis.yml000066400000000000000000000102661276346362400160440ustar00rootroot00000000000000language: cpp #sudo: false cache: directories: - $HOME/.cache/pip addons: apt: sources: - ubuntu-toolchain-r-test - boost-latest - deadsnakes packages: - g++-4.8 - g++-4.8-multilib - g++-multilib - libhdf5-serial-dev #- python3.5 #- python3.5-dev #- python3.5-venv #- python3.5-dev:i386 - libboost-thread1.55-dev - libboost-system1.55-dev - libboost-date-time1.55-dev - libboost-chrono1.55-dev - libboost-python1.55-dev - python-numpy - python-pip - python-nose before_install: - if [ `uname` = "Darwin" ]; then brew update >/dev/null; brew install homebrew/science/hdf5; fi matrix: include: - os: linux compiler: gcc-4.8 script: - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE #- make externalLibs -j4 - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE - make -j4 - make test ARGS="-V" - make test-python-wrapper - sudo make install # - os: osx compiler: clang script: - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=FALSE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE #- make externalLibs -j4 - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=FALSE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE - make -j4 - make test ARGS="-V" #- make test-python-wrapper - sudo make install ################################# ## OLD TRAVIS ################################# # compiler: # - gcc # - clang # before_install : # - sudo add-apt-repository https://launchpad.net/~gnode/+archive/pandora # - sudo apt-get update -qq # - sudo apt-get install -qq libhdf5-dev # - sudo apt-get install python-numpy # - sudo apt-get install python-pip # - sudo add-apt-repository ppa:ukplc-team/testing -y # - sudo apt-get update -qq # - sudo apt-get install -qq python-nose libboost1.49-dev libboost-python1.49-dev # #- wget http://sourceforge.net/projects/boost/files/boost/1.54.0/boost_1_54_0.tar.bz2 # #- tar --bzip2 -xf boost_1_54_0.tar.bz2 # #- cd boost_1_54_0 # #- ./bootstrap.sh --help # #- sudo ./bootstrap.sh --with-libraries=python # #- sudo ./b2 install # #- cd .. # # Change this to your needs.. # script: # #- cmake . -DWITH_BOOST=FALSE -DWITH_HDF5=FALSE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=FALSE -DBUILD_COMMANDLINE=FALSE # #- make -j6 # #- make test ARGS="-V" # - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE # #- make externalLibs -j4 # - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE # - make -j4 # - make test ARGS="-V" # - make test-python-wrapper # - sudo make install # #- python src/interfaces/python/examples/markov_chain.py opengm-2.3.6+20160905/CMakeLists.txt000066400000000000000000000645451276346362400165040ustar00rootroot00000000000000#-------------------------------------------------------------- # default build-type (release) # (the next lines must be called bevore project(opengm2)) #-------------------------------------------------------------- IF(DEFINED CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.") ELSE() SET(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel.") ENDIF() #-------------------------------------------------------------- # OpenGM #-------------------------------------------------------------- cmake_minimum_required(VERSION 2.6) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) project(opengm2) set (OPENGM_VERSION_MAJOR 2) set (OPENGM_VERSION_MINOR 3) set (OPENGM_VERSION_PATCH 1) #-------------------------------------------------------------- # global headers #-------------------------------------------------------------- file(GLOB_RECURSE headers include/*.hxx) include_directories(include) #-------------------------------------------------------------- # debug info #-------------------------------------------------------------- #add_definitions(-DTRWS_DEBUG_OUTPUT) #-------------------------------------------------------------- # warning level #-------------------------------------------------------------- SET(WARNINGLEVEL "0" CACHE STRING "selected level for compiler warning from 0 (sloppy) to 4 (sadistic)") if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) # no warnings if(WARNINGLEVEL STREQUAL "0" ) message(STATUS "--------------------------------------------------------------------------") message(STATUS "WARNING: Compiler warnings are very sloppy -> increase CMake-WARNINGLEVEL") message(STATUS "--------------------------------------------------------------------------") endif() # with warning if(WARNINGLEVEL STREQUAL "1" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++98") endif() # PEDANTIC -> a lot of warnings if(WARNINGLEVEL STREQUAL "2" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++98 -pedantic -Wno-long-long ") endif() # VERY PEDANTIC -> very lot of warnings if(WARNINGLEVEL STREQUAL "3" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++98 -pedantic -Wno-long-long -Wextra") endif() # SADISTIC -> all warnings become errors if(WARNINGLEVEL STREQUAL "4" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++98 -pedantic -Wno-long-long -Wextra -Werror") endif() elseif(MSVC) add_definitions(-D_SCL_SECURE_NO_WARNINGS) endif() #-------------------------------------------------------------- # options #-------------------------------------------------------------- OPTION(BUILD_EXAMPLES "Build Examples" ON) OPTION(BUILD_TUTORIALS "Build Tutorials" ON) OPTION(BUILD_COMMANDLINE "Build Commandline" OFF) OPTION(WITH_AD3 "Include AD3" OFF) OPTION(WITH_CPLEX "Include CPLEX" OFF) OPTION(WITH_GUROBI "Include GUROBI" OFF) OPTION(WITH_BOOST "Include BOOST" OFF) OPTION(WITH_HDF5 "Include HDF5" OFF) OPTION(WITH_TRWS "Include wrapper for TRWS code" OFF) OPTION(WITH_GCO "Include wrapper for GCO code" OFF) OPTION(WITH_MRF "Include wrapper for MRF code" OFF) OPTION(WITH_QPBO "Include wrapper for QPBO code" OFF) OPTION(WITH_FASTPD "Include wrapper for FastPD code" OFF) OPTION(WITH_MAXFLOW "Include wrapper for MAXFLOW code" OFF) OPTION(WITH_MAXFLOW_IBFS "Include wrapper for MAXFLOW-IBFScode" OFF) OPTION(WITH_LIBDAI "Include wrapper for LIBDAI code" OFF) OPTION(WITH_DAOOPT "Include wrapper for DAOOPT code" OFF) OPTION(WITH_MPLP "Include wrapper for MPLP code" OFF) OPTION(WITH_SRMP "Include wrapper for SRMP code" OFF) OPTION(WITH_PLANARITY "Include wrapper for PLANARITY code" OFF) OPTION(WITH_BLOSSOM5 "Include wrapper for BLOSSOM5 code" OFF) OPTION(WITH_OPENMP "Include OpenMP" OFF) OPTION(WITH_VIGRA "Include VIGRA" OFF) OPTION(WITH_CONICBUNDLE "Include ConicBundleLibrary" OFF) OPTION(WITH_MATLAB "Activate MatLab-Code" OFF) OPTION(BUILD_CONVERTER "Build several converters" OFF) OPTION(BUILD_PYTHON_WRAPPER "Build python wrapper" OFF) OPTION(BUILD_MATLAB_WRAPPER "Build matlab wrapper" OFF) ###Grante needs C++11. Since we have not tested OpenGM under this standard yet, using Grante is realy experimental!!! ###OPTION(WITH_GRANTE "Include wrapper for grante" OFF) OPTION(WITH_MEMINFO "Use memory logging in visitor" OFF) INCLUDE(TestBigEndian) TEST_BIG_ENDIAN(BIGENDIAN) IF(${BIGENDIAN}) ADD_DEFINITIONS(-DBIGENDIAN) ENDIF(${BIGENDIAN}) #-------------------------------------------------------------- # MEMINFO #-------------------------------------------------------------- if(WITH_MEMINFO) add_definition(-DSYS_MEMORYINFO_ON) endif() #-------------------------------------------------------------- # Cplex #-------------------------------------------------------------- if(WITH_CPLEX) message(STATUS "build with CPLEX interface") find_package(CPLEX REQUIRED) add_definitions(-DWITH_CPLEX) include_directories(${CPLEX_INCLUDE_DIRS}) # add_definitions(-DILOUSESTL) redundant according to http://www-01.ibm.com/support/docview.wss?uid=swg21399983 add_definitions(-DIL_STD) else() message(STATUS "build without CPLEX interface") endif() #-------------------------------------------------------------- # AD3 #-------------------------------------------------------------- if(WITH_AD3) #message(STATUS "build with AD3 interface") #find_package(AD3 REQUIRED) #add_definitions(-DWITH_AD3) #include_directories(${AD3_INCLUDE_DIR}) message(STATUS "build with external inference algorithm AD3") SET(AD3_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/AD3-patched" CACHE STRING "AD3 patched source code directory") add_definitions(-DWITH_AD3) include_directories(${AD3_PATCHEDSRCDIR}) else() message(STATUS "build without AD3 interface") endif() #-------------------------------------------------------------- # Gurobi #-------------------------------------------------------------- if(WITH_GUROBI) message(STATUS "build with GUROBI interface") find_package(GUROBI REQUIRED) add_definitions(-DWITH_GUROBI) include_directories(${GUROBI_INCLUDE_DIRS}) else() message(STATUS "build without GUROBI interface") endif() #-------------------------------------------------------------- # Boost #-------------------------------------------------------------- if(WITH_BOOST) message(STATUS "build with Boost") find_package(Boost 1.47 REQUIRED) add_definitions(-DWITH_BOOST) add_definitions(-DWITH_BOOST_GRAPH) include_directories(${Boost_INCLUDE_DIR}) else() message(STATUS "build without Boost") endif() #-------------------------------------------------------------- # HDF5 #-------------------------------------------------------------- if(WITH_HDF5) message(STATUS "build with HDF5 support") if(WIN32) # FindHDF5 is broken on Windows # it wrongly discovers the dlls instead of the lib files # see: www.cmake.org/Bug/bug_relationship_graph.php?bug_id=14111 # therefore we set the variable manually find_library( HDF5_IMPORT_LIB NAMES hdf5 hdf5dll ) find_library( HDF5_HL_IMPORT_LIB NAMES hdf5_hl hdf5_hldll ) find_path(HDF5_INCLUDE_DIR hdf5.h) set( HDF5_LIBRARIES ${HDF5_IMPORT_LIB} ${HDF5_HL_IMPORT_LIB} ) message(STATUS "HDF5: autodiscovery is broken on WIN32; using global search paths") message(STATUS "HDF5: found ${HDF5_LIBRARIES}") else() find_package(HDF5 REQUIRED) endif() include_directories(${HDF5_INCLUDE_DIR}) add_definitions(${HDF5_CPPFLAGS}) add_definitions(-DWITH_HDF5) else() message(STATUS "build without HDF5") endif() #-------------------------------------------------------------- # MATLAB #-------------------------------------------------------------- if(WITH_MATLAB) message(STATUS "build with MatLab support") find_package(MATLAB REQUIRED) message(STATUS "Matlab include dir: ${MATLAB_INCLUDE_DIR}") message(STATUS "Matlab libmex: ${MATLAB_MEX_LIBRARY}") message(STATUS "Matlab libeng: ${MATLAB_ENG_LIBRARY}") message(STATUS "Matlab libmx: ${MATLAB_MX_LIBRARY}") #include_directories(${MATLAB_INCLUDE_DIR}) #add_definitions(-DWITH_MATLAB) endif(WITH_MATLAB) #-------------------------------------------------------------- # TRWS #-------------------------------------------------------------- if(WITH_TRWS) message(STATUS "build with external inference algorithm TRWS") SET(TRWS_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/TRWS-v1.3.src-patched" CACHE STRING "TRWS patched source code directory") add_definitions(-DWITH_TRWS) include_directories(${TRWS_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm TRWS") endif(WITH_TRWS) #-------------------------------------------------------------- # GCO #-------------------------------------------------------------- if(WITH_GCO) message(STATUS "build with external inference algorithm GCO") SET(GCO_LABEL_VALUE "int" CACHE STRING "selected label type for GCO library") add_definitions(-DGCOLABELVALUE=${GCO_LABEL_VALUE}) SET(GCO_ENERGY_VALUE "double" CACHE STRING "selected energy type for GCO library") add_definitions(-DGCOENERGYVALUE=${GCO_ENERGY_VALUE}) SET(GCO_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/GCO-v3.0.src-patched" CACHE STRING "GCO patched source code directory") add_definitions(-DWITH_GCO) include_directories(${GCO_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm GCO") endif(WITH_GCO) #-------------------------------------------------------------- # MRF #-------------------------------------------------------------- if(WITH_MRF) message(STATUS "build with external inference algorithm MRF") SET(MRF_LABEL_VALUE "int" CACHE STRING "selected label type for MRF library") add_definitions(-DMRFLABELVALUE=${MRF_LABEL_VALUE}) SET(MRF_ENERGY_VALUE "double" CACHE STRING "selected energy type for MRF library") add_definitions(-DMRFENERGYVALUE=${MRF_ENERGY_VALUE}) SET(MRF_COST_VALUE "double" CACHE STRING "selected cost type for MRF library") add_definitions(-DMRFCOSTVALUE=${MRF_COST_VALUE}) SET(MRF_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/MRF-v2.1.src-patched" CACHE STRING "MRF patched source code directory") add_definitions(-DWITH_MRF) include_directories(${MRF_PATCHEDSRCDIR}) set(bitness 32) if(CMAKE_SIZEOF_VOID_P EQUAL 8) MESSAGE (STATUS "Detected a 64 Bit Machine") set(bitness 64) add_definitions(-DUSE_64_BIT_PTR_CAST) else() MESSAGE (STATUS "Detected a 32 Bit Machine") endif() #TODO add 64 bit check here! #if(64Bit???) #add_definitions(-DUSE_64_BIT_PTR_CAST) #endif(64Bit???) else() message(STATUS "build without external inference algorithm MRF") endif(WITH_MRF) #-------------------------------------------------------------- # QPBO #-------------------------------------------------------------- if(WITH_QPBO) message(STATUS "build with external inference algorithm QPBO") SET(QPBO_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/QPBO-v1.3.src-patched" CACHE STRING "QPBO patched source code directory") add_definitions(-DWITH_QPBO) include_directories(${QPBO_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm QPBO") endif(WITH_QPBO) #-------------------------------------------------------------- # FastPD #-------------------------------------------------------------- if(WITH_FASTPD) message(STATUS "build with external inference algorithm FastPD") SET(FASTPD_URL "" CACHE STRING "URL for downloading FastPD (Registration required at http://www.csd.uoc.gr/~komod/FastPD/)") SET(FASTPD_ENERGY_VALUE "double" CACHE STRING "selected energy type for FASTPD library") add_definitions(-DFASTPDENERGYVALUE=${FASTPD_ENERGY_VALUE}) SET(FASTPD_LABEL_VALUE "size_t" CACHE STRING "selected label type for FASTPD library") add_definitions(-DFASTPDLABELVALUE=${FASTPD_LABEL_VALUE}) SET(FASTPD_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/FastPD.src-patched" CACHE STRING "FastPD patched source code directory") add_definitions(-DWITH_FASTPD) include_directories(${FASTPD_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm FastPD") endif(WITH_FASTPD) #-------------------------------------------------------------- # MaxFlow-IBFS #-------------------------------------------------------------- if(WITH_MAXFLOW_IBFS) message(STATUS "build with external inference algorithm MaxFlow-IBFS") SET(MAXFLOW_IBFS_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/ibfs.src-patched/" CACHE STRING "MAXFLOW-IBFS source code directory") add_definitions(-DWITH_MAXFLOW_IBFS) include_directories(${MAXFLOW_IBFS_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm MaxFlow-IBFS") endif(WITH_MAXFLOW_IBFS) #-------------------------------------------------------------- # MaxFlow #-------------------------------------------------------------- if(WITH_MAXFLOW) message(STATUS "build with external inference algorithm MaxFlow") SET(MAXFLOW_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/MaxFlow-v3.02.src-patched/" CACHE STRING "MAXFLOW patched source code directory") add_definitions(-DWITH_MAXFLOW) include_directories(${MAXFLOW_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm MaxFlow") endif(WITH_MAXFLOW) #-------------------------------------------------------------- # VIGRA #-------------------------------------------------------------- if(WITH_VIGRA) find_package(VIGRA) IF(VIGRA_FOUND) message(STATUS "build with VIGRA") include_directories(${VIGRA_INCLUDE_DIR}) add_definitions(-DWITH_VIGRA) else() message(STATUS "VIGRA not found") add_definitions(-DNOVIGRA) endif() else() message(STATUS "build without VIGRA") add_definitions(-DNOVIGRA) endif(WITH_VIGRA) #------------------------------------------------------------- # ConicBundle Library #------------------------------------------------------------- if(WITH_CONICBUNDLE) IF(NOT EXISTS "${PROJECT_SOURCE_DIR}/src/external/ConicBundle-v0.3.11.src-patched") MESSAGE ("ConicBundle not installed, run make externalLibs first and configure again") SET(WITH_CONICBUNDLE OFF) ELSE(NOT EXISTS "${PROJECT_SOURCE_DIR}/src/external/ConicBundle-v0.3.11.src-patched") message(STATUS "build with ConicBundle-Library") find_package(CONICBUNDLE REQUIRED) include_directories(${CONICBUNDLE_INCLUDE_DIR}) add_definitions(-DWITH_CONICBUNDLE) add_definitions(-DWITH_BUNDLE) ENDIF(NOT EXISTS "${PROJECT_SOURCE_DIR}/src/external/ConicBundle-v0.3.11.src-patched") else() message(STATUS "build without inference algorithm DDBundle") endif(WITH_CONICBUNDLE) #------------------------------------------------------------- # grante Library #------------------------------------------------------------- if(WITH_GRANTE) if(WITH_BOOST) message(STATUS "build with external inference algorithm grante") SET(GRANTE_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/grante-v1.0.src-patched/" CACHE STRING "Grante source code directory") add_definitions(-DWITH_GRANTE) include_directories(${GRANTE_PATCHEDSRCDIR}) set(Boost_USE_STATIC_LIBS ON) find_package(Boost 1.47 COMPONENTS serialization REQUIRED) else(WITH_BOOST) message(SEND_ERROR "Grante requires Boost! Enable WITH_BOOST in CMake.") endif(WITH_BOOST) else() message(STATUS "build without external inference library grante") endif(WITH_GRANTE) #------------------------------------------------------------- # OpenMP #------------------------------------------------------------- if(WITH_OPENMP) FIND_PACKAGE(OpenMP REQUIRED) message(STATUS "build with OpenMP") #SET(OPENMP_INCLUDE_DIR "" CACHE STRING "OpenMP include dir") #include_directories(${OPENMP_INCLUDE_DIR}) add_definitions(-DWITH_OPENMP) else() message(STATUS "build without openMP -> multithreaded options disabled") endif(WITH_OPENMP) #-------------------------------------------------------------- # LIB DAI #-------------------------------------------------------------- if(WITH_LIBDAI) find_package(LIBDAI REQUIRED) find_package(GMP REQUIRED) find_package(GMPXX REQUIRED) include_directories(${LIBDAI_INCLUDE_DIR}) include_directories(${GMP_INCLUDE_DIR}) include_directories(${GMPXX_INCLUDE_DIR}) add_definitions(-DWITH_LIBDAI) # Add defines for libdai/include/dai/util.h if(WIN32) add_definitions(-DWINDOWS) else(CYGWIN) add_definitions(-DCYGWIN) else(APPLE) add_definitions(-DMACOSX) endif() else() message(STATUS "build without external inference algorithms from LibDai") endif(WITH_LIBDAI) #-------------------------------------------------------------- # DAOOPT #-------------------------------------------------------------- if(WITH_DAOOPT) if(WITH_BOOST) message(STATUS "build with external inference algorithm DAOOPT") SET(DAOOPT_SRCDIR "${PROJECT_SOURCE_DIR}/src/external/DAOOPT.src/" CACHE STRING "DAOOPT source code directory") add_definitions(-DWITH_DAOOPT) add_definitions(-DWITH_OPENGM) include_directories(${DAOOPT_SRCDIR}/include ${DAOOPT_SRCDIR}/lib ) set(Boost_USE_MULTITHREADED OFF) # To select the two master modes option(DAOOPT_WORKER "Force worker binary" ON) option(DAOOPT_MASTER_STATIC "Force static master binary" OFF) option(DAOOPT_MASTER_DYNAMIC "Force dynamic master binary" OFF) # To enable static linking of the final daoopt binary option(DAOOPT_LINK_STATIC "Link binary statically" OFF) # Add defines for DAOOPT if(WIN32) add_definitions(-DWINDOWS) else() add_definitions(-DLINUX) endif() if(DAOOPT_LINK_STATIC) set(CMAKE_EXE_LINKER_FLAGS "-static") endif() # Optional forced version: static over dynamic master, worker over both if(DAOOPT_WORKER) add_definitions(-DNOTHREADS) else() if(DAOOPT_MASTER_STATIC) add_definitions(-DPARALLEL_STATIC) endif() if(DAOOPT_MASTER_DYNAMIC AND NOT DAOOPT_MASTER_STATIC) add_definitions(-DPARALLEL_DYNAMIC) find_package(Threads) # includes pthread find_package( Boost REQUIRED COMPONENTS system ) endif() endif() find_package( Boost REQUIRED COMPONENTS program_options thread ) include_directories( ${Boost_INCLUDE_DIRS} ) else(WITH_BOOST) message(SEND_ERROR "DAOOPT requires Boost! Enable WITH_BOOST in CMake.") endif(WITH_BOOST) else() message(STATUS "build without external inference algorithm DAOOPT") endif(WITH_DAOOPT) #-------------------------------------------------------------- # MPLP #-------------------------------------------------------------- if(WITH_MPLP) message(STATUS "build with external inference algorithm MPLP") SET(MPLP_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/mplp_ver2.src-patched/" CACHE STRING "MPLP patched source code directory") add_definitions(-DWITH_MPLP) include_directories(${MPLP_PATCHEDSRCDIR}) else() message(STATUS "build without external inference algorithm MPLP") endif(WITH_MPLP) #-------------------------------------------------------------- # SRMP #-------------------------------------------------------------- if(WITH_SRMP) message(STATUS "build with external inference algorithm SRMP") add_definitions(-DWITH_SRMP) SET(SRMP_BASEDIR "${PROJECT_SOURCE_DIR}/src/external/SRMP/" CACHE STRING "SRMP base directory") include_directories(${SRMP_BASEDIR}/include/) else(WITH_SRMP) message(STATUS "build without external inference algorithm MPLP") endif(WITH_SRMP) #-------------------------------------------------------------- # PLANARITY #-------------------------------------------------------------- if(WITH_PLANARITY) message(STATUS "build with external inference algorithm PLANARITY") add_definitions(-DWITH_PLANARITY) SET(PLANARITY_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/planarity.src-patched/" CACHE STRING "PLANARITY base directory") include_directories("${PLANARITY_PATCHEDSRCDIR}../") else(WITH_PLANARITY) message(STATUS "build without external inference algorithm PLANARYTY") endif(WITH_PLANARITY) #-------------------------------------------------------------- # BLOSSOM5 #-------------------------------------------------------------- if(WITH_BLOSSOM5) message(STATUS "build with external inference algorithm BLOSSOM5") add_definitions(-DWITH_BLOSSOM5) add_definitions(-DPERFECT_MATCHING_DOUBLE) SET(BLOSSOM5_PATCHEDSRCDIR "${PROJECT_SOURCE_DIR}/src/external/blossom5.src-patched/" CACHE STRING "BLOSSOM5 base directory") include_directories("${BLOSSOM5_PATCHEDSRCDIR}../") else(WITH_BLOSSOM5) message(STATUS "build without external inference algorithm BLOSSOM5") endif(WITH_BLOSSOM5) #-------------------------------------------------------------- # thread lib #-------------------------------------------------------------- find_package(Threads) #-------------------------------------------------------------- # rt lib #-------------------------------------------------------------- if(UNIX AND NOT APPLE) find_library(RT rt) set(LINK_RT true) message(STATUS "Linking to RT is enabled") else() set(LINK_RT false) message(STATUS "Linking to RT is diabled") endif() #-------------------------------------------------------------- # source directory #-------------------------------------------------------------- add_subdirectory(src) #-------------------------------------------------------------- # testing with CTest #-------------------------------------------------------------- INCLUDE(CTest) ENABLE_TESTING() if(BUILD_TESTING) add_subdirectory(src/unittest) endif() #-------------------------------------------------------------- # WordLength #-------------------------------------------------------------- if(CMAKE_SIZEOF_VOID_P EQUAL 8) MESSAGE (STATUS "Detected a 64 Bit Machine") elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) MESSAGE (STATUS "Detected a 32 Bit Machine") endif() set(OPENGM_WORD_LENGTH ${CMAKE_SIZEOF_VOID_P}) #-------------------------------------------------------------- # TypeChecking #-------------------------------------------------------------- INCLUDE (${CMAKE_ROOT}/Modules/CheckTypeSize.cmake) set(listTypes "char" "signed char" "unsigned char" "wchar_t" "short" "unsigned short" "int" "unsigned int" "long" "unsigned long" "long long" "unsigned long long" "float" "double" "long double" ) set(listTypeNames CHAR SIGNED_CHAR UNSIGNED_CHAR WCHAR_T SHORT UNSIGNED_SHORT INT UNSIGNED_INT LONG UNSIGNED_LONG LONG_LONG UNSIGNED_LONG_LONG FLOAT DOUBLE LONG_DOUBLE ) MACRO (OPENGM_CHECK_TYPE_SIZE type var) SET (aType ${type}) SET (sizeVar OPENGM_SIZE_OF_${var}) CHECK_TYPE_SIZE (${aType} ${sizeVar}) IF(NOT ${sizeVar} ) SET (${sizeVar} 0 CACHE INTERNAL "SizeOf for ${sizeVar}") MESSAGE (STATUS "Type ${aType} was NOT Found") SET(OPENGM_NO_${var} ON ) MESSAGE (STATUS "Set ${noTypeVar} ") ELSE(NOT ${sizeVar}) #MESSAGE (STATUS "Size of ${aType} is ${${sizeVar}}") ENDIF(NOT ${sizeVar}) ENDMACRO (OPENGM_CHECK_TYPE_SIZE) list(LENGTH listTypes sizelistTypes) math(EXPR sizeOfList "${sizelistTypes} - 1") foreach(val RANGE ${sizeOfList}) list(GET listTypes ${val} valTypes) list(GET listTypeNames ${val} valTypeNames) #message(STATUS "Check Type : ${valTypes}") OPENGM_CHECK_TYPE_SIZE( ${valTypes} ${valTypeNames} ) endforeach() #-------------------------------------------------------------- # doxygen documentation #-------------------------------------------------------------- option(BUILD_DOCS "Build API documentation." OFF) if(BUILD_DOCS) find_package(Doxygen REQUIRED) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY ) add_custom_target(doc ALL ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM ) install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/doc/html" DESTINATION share/doc/opengm PATTERN ".git" EXCLUDE PATTERN ".cmake" EXCLUDE ) endif() #-------------------------------------------------------------- # install #-------------------------------------------------------------- install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/opengm" DESTINATION include FILES_MATCHING PATTERN "*.hxx" PATTERN "*.hpp" PATTERN "*.h" ) #-------------------------------------------------------------- # test and install opengm python #-------------------------------------------------------------- if(BUILD_PYTHON_WRAPPER) #find python FIND_PACKAGE(PythonInterp REQUIRED) #find nose execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import nose" RESULT_VARIABLE PYTHON_NOSETESTS_NOT_FOUND) # find numpy find_package(NUMPY) #add python unit test IF(NOT PYTHON_NOSETESTS_NOT_FOUND) MESSAGE(STATUS "Searching for Python nosetests: ok") add_custom_target( test-python-wrapper nosetests #add_custom_target( test-python-wrapper ALL nosetests --all-modules --traverse-namespace --cover-tests --with-doctest -v WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/src/interfaces/python" --where "${CMAKE_CURRENT_BINARY_DIR}/src/interfaces/python" ) add_dependencies(test-python-wrapper _opengmcore ) add_dependencies(test-python-wrapper _inference ) add_dependencies(test-python-wrapper _hdf5 ) ELSE() MESSAGE(STATUS "Could NOT find Python nosetests ('import nose' failed)") ENDIF() install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/src/interfaces/python/opengm" DESTINATION "lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages" FILES_MATCHING PATTERN "*.py" PATTERN "*.so" PATTERN "CMakeFiles" EXCLUDE ) endif() #-------------------------------------------------------------- # package with cpack # - this is just a starting point # #-------------------------------------------------------------- #SET(CPACK_GENERATOR "DEB") #SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Thorsten Beier") #required #set(CPACK_PACKAGE_VERSION_MAJOR "${OPENGM_VERSION_MAJOR}") #set(CPACK_PACKAGE_VERSION_MINOR "${OPENGM_VERSION_MINOR}") #set(CPACK_PACKAGE_VERSION_PATCH "${OPENGM_VERSION_PATCH}") #INCLUDE(CPack) opengm-2.3.6+20160905/ChangeLog.txt000066400000000000000000000432621276346362400163250ustar00rootroot00000000000000**************************************************************************************************** ** OpenGM develop ** **************************************************************************************************** * **** **************************************************************************************************** ** OpenGM GithubVersion ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * * ******* **************************************************************************************************** ** OpenGM 2.3.6 (30.10.2015) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * * *********** * bugfixes: *********** * several small python bugfixes * bugfix several typos * add missing includes * replace assert by OPENGM_TEST in unit-tests * *************** * New Features: *************** * Add Cut, Glue and Cut (CGC) inference for multicut-problems * Add Multicut Fusion (intersection based inference) inference for multicut-problems * Muticut supports generalized Potts functions up to order 11 * Add CanonicalView Function * Extend MatLab interface * TRWS can now return min marginals * improved install scripts (Thanks to Ghislain Antony Vaillant) * Multicut can start with a tighter polytope **************************************************************************************************** ** OpenGM 2.3.5 (02.07.2015) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * news: ******** * new branch at github that supports learning (experimental) * *********** * bugfixes: *********** * undef eps-def in MPLP * bugfix of minor typos * fix compiler issues on OSX * fix cmake issues * make compatiblewith Vigra 1.10 * *************** * New Features: *************** * add wrapper for SRMP * support for blackbox-test of higher-order models * adjusting parameters for smoothing based algorithms * improved detection of gurobi * interfaces for bloosomV and planarity -> planar max-cut solver available * implement interface for LPCPLEX to set a starting-point (this can help a lot) * add implementation for more advanced queues * Multicut: * - speed up multicut by using advanced queues (ChangeablePriorityQueue) * - add option for multicut with chordal-search or post-chordal testing * - add option to buffer the best state for the multicut algorithm * add more inference method in the reduced inference caller * add support for constrained graphical models: * - add generic (I)LP-interface for CPLEX and Gurobi * - add (I)LP solver for graphical models (based on CPLEX and GUROBI) that can handel * --- constrained-based functions ( constraints and constraints with additional auxillary variables) * --- support incrematal construction of the polytope * - add interface for constrain-functions * - add linear constraint function * - add label order function * - add number of active labels function * add so;vers to Matlab-Interface ***** **************************************************************************************************** ** OpenGM 2.3.4 (19.11.2014) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * bugfixes: ************ * adopt patches for GCO and MPLP to latest versions * fix several warnings * *************** * New features: *************** * add Wrapper for Gurobi * extended interface for LPCPlex * add support for FoE-functions * ***** **************************************************************************************************** ** OpenGM 2.3.3 (01.08.2014) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * bugfixes: ************ * Ad3 (wrong bound) -> use now our own fork, need to be deleted and downloaded new * InfAndFlip (tiny numerical problems) * DAOOPT (worker flag is set to ON automatically ) * LibDAI (wrapper was brocken - fixed ) * model-order : 32-bit bug * python : minor small fixes * *************** * New features: *************** * Graphical Model: * - Implement the functor concept which avoids lookups from the factor to the function * This allows to call a functor on a factor, which will work on the function behind directly. * * Inference: * - Proposal Based Fusion (new) * - Self Fusion (new) * - LSA-TR (new) * - Make Sequential BP and Sequential TRBP available trough the caller * - Asymetric Multyway Cuts (new - supported by multicut) * - ADSAL (smoothing strategy significantly refactored) * - Astar (improfe default ordering) * - DD-based (decomposition into k-fans) * - Message Passing: implement functor operations -> sigificant speedup * * Timming Visitor: * - stores accumulated time instead of time for a single step * - supports memmory logging * * Python: * - convenient function to create potts model for 3d grid graph with a flexible regularizer * - added workflow parm to multicut-python * * Matlab: * - efficient interface to load and store Potts models * * C++-Tutorials: * - learning modelparameters with EM * - inference on the or-and-semiring * - inference on the min-sum-semiring * - inference on the max-sum-semiring * - building models * - load and store models * - reimplementations of the Middleburry MRF benchmark * - supervised image segmentation ***** **************************************************************************************************** ** OpenGM 2.3.2 (05.5.2014) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * some bugfixes ***** * minor MAC bugfixes * increase soft-inf for MQPBO ( was too small) * Bugfix in commandlineinterface concerning storing empty vectors * Bugfixes for ADSAL, TRWSi, Nesterov * Bugfix incorrect assert-usage in MArray -> Signifficant speedup * Bugfix manual decomposition in DD-based methods * add exception if dynamic programming is used for higher-order models * some bugfixes in doxygen * fix code for some warnings * new features ***** * MatLab: Interface for a more efficient adding of pairwise factors * MatLab: enable some inference algorithms for the matlab interface * additional features for ADSAL, TRWSi, Nesterov * added code to get fractional ad3 solutions * Speedup for model evaluation * Refactoring generation of primal solution for DD-Based algorithms ->Speedup * make parameter for stoppint TRWS on change of dual available via parameter object * make manual decomposition available for DD-based methods * Implement bound and reparametrisation interface for FastPD **************************************************************************************************** ** OpenGM 2.3.1 (04.3.2014) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * some bugfixes ***** * bugfixes ***** * fix incorrect linking in CMake for MAC * add missing cmath-include in visitor * fix bug in dynamic programming (had worked only up to 255 states correctly before (this bug had caused sideeffects in DualDecomosition and Astar, this is fixed too) * new features ***** * add nesterovs algorithm * add smoothing strategy in seperate file * add interface to dual variables for some methods **************************************************************************************************** ** OpenGM 2.3.0 (24.2.2014) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * simpler visitor framework (not fully compatible with the old one * update of instalation scripts for external code * several bugfixes ***** * bugfixes ***** * bugfix in pythpn glue code for generalized inference interface generation * bugfix in python wrapped graphical model manipulator (lock/unlocks's where missing) * simplified the adding of mebmber function of python wrapped inference algorithms * minor bugfixes for several solvers * bugfixes for TWSi,transportation-solver, CombiLP * GCO: Patches updated for latest version * IBFS: Patch and wrapper updated for latest version (still bugy - bug reported to the IBFS authors) * MULTICUT: Better timeout handling * DAOOPT: Visitor injection * new features ***** * Visitor: New and simpler Visitor implementation * Visitor: addlog() and log() for additional protocolation * FastPD: Lower bound * DualDecomposition: Add hypergraph-subproblems into cmd * Converter: Partition models -> weighted UDAG * Python: fusion Moves **************************************************************************************************** ** OpenGM 2.2.1 (05.12.2013) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * bugfixes ***** * several bugfixes for MacOS (thanks to Toru Tamaki) * clean up of old/unused code * Fix critical bug in python-interface with Potts functions * TRWSi can hande isolated nodes * Add stopping condition for for TRWSi * Some fixes in the LibDAI-wrapper (Thanks to Toru Tamaki) * Improve CMake Find-Script for CPleX (Thanks to Ulrich Koethe) * start with the new visitor interface **************************************************************************************************** ** OpenGM 2.2.0 (10.10.2013) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * some refactoring ***** * remove editable support for graphical model ( was to slow any way -> use graphicalmodelmanipolator * change internal storage of factor-variables -> use reserve options to speedup code and avoid szstem calls * add LPGurobi (still alpha version with linking problems, we will fix this soon) * add support for naming cplex constraints (thanks to martinsch) * bugfix partition-move: typo in macro * add unsigned char support to marray_hdf5 * bugfixes in cmake for better MAC-support (thanks to vene) * add autodetect for numpy (thanks to vene) * add wrapper for MPLP * add wrapper for daoopt/braobb * refactoring reduced inference - supports now higher order too * add modelmanipulator for fixing variables in models **************************************************************************************************** ** OpenGM 2.1.2 (18.07.2013) ** ** Developers in charge: ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * Bugfixes ***** * fix memory leak in QPBO interface * bugfix for modelgenerator/unittest - testing with varying number of labels * bugfixes TRWSi * bugfixes ADSAL * TRWS interface now supports varying number of labels * add unittest for gco interface * add modelmanipulator to add evidence to models * use modelmanipulator instead of editable-models in AStar **************************************************************************************************** ** OpenGM 2.1.1 (17.06.2013) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * Bugfixes ***** * update matlab interface * bugfixes python interface * bugfix libdai interface/cales * bugfix mqpbo visitor **************************************************************************************************** ** OpenGM 2.1 (31.05.2013) ** ** Developers in charge: ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * Since the release of 2.0.2 some time has gone we have fixed several bugs and add new functionality. * OpenGM has been used for a computer vision benchmark, which has profit from the high flexibility of * OpenGM. ***** * bug-fixes in DualDecomposition * bug-fixes in Alpha-beta-swap (stopping condition) * bug-fixes for several functions ( e.g. sparsefunction) * bug-fixes for Gibbs * bug-fixes for code using external libraries * several small bugfixes * CMake cleanup * add support for maximizing models with LPCPLEX * add compiler-warning-level-option to cmake * add method to get the function corresponding to a factor * add method to get internalIDs to add additional constraints to LPCPLEX * generalize the caller interface -> all callers need to be a bit modified * add python interface (beta-state) * add new matlab interface (beta-state) * add some modelconverters e.g. opengm2uai * change default mode into RELEASE * unittest now always use asserts even in release mode * New inference Methods - MQPBO - Reduced Inference - Alpha-Expansion-Fusion (using the reduction code of Alexander Fix) - InfAndFlip (Meta-solver) - native opengm TRWS solver (implemented by Bogdan Savchynskyy) - native opengm ADSAL solver (implemented by Bogdan Savchynskyy) - primal-LP-bound - code to get feasible primal values for local polytope relaxations (implemented by Bogdan Savchynskyy) * new wrappers for external libs - FastPD - GCO-Lib **************************************************************************************************** ** OpenGM 2.0.2 beta (01.06.2012) ** ** Developers in charge: ** * Bjoern Andres ( bjoern[AT]andres[DOT]sc ) ** * Thorsten Beier ( thorsten.beier[AT]iwr[DOT]uni-heidelberg[DOT]de ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * We realize, that having just tables available to store/represent functions, which was sufficient for * our problems at this time, is not sufficient for many large scale problems. The fact that i) many * factors map the same function to different variables and ii) functions can often be represented much * more memory efficient. This ends up in the extended factor graph framework which includes functions * as another set of nodes in the graph and allows factors to share functions. Furthermore, opengm-model * can now deal with different types of functions. * As a consequence OpenGM2 is not compatible with OpenGM1 ***** * Change to from BSD to MIT licence * put project on github * reorganize project structure * Extend factor graph models by a set of function(-nodes) * add several type of functions * introduce more template parameters to the model - ValueType type used for objective function - IndexType type used to index variables and factors - LabelType type used for state-/label-space * add different space types * re-implement the model-decomposition * model-generator and blackbox-test-framework for inference-unit-tests * add inference algorithms - dualdecomposition with subgradient and bundle methods - alpha-expansion - alpha-beta-swap - dynamic programming - ILP and LP-relaxation solvers (using CPLEX) - LOC - QPBO - 2SAT-solver - gibbs-sampler - swendsenwang algorithm * add wrappers to external inference libraries - extern/MRF-LIB - extern/QPBO - extern/TRWS - extern/LibDAI - provide wrappers for fast external maxflow code (IBFS, Kolmogorov's MaxFlow) * redesign LBP and TRBP * redesign the visitor concept for code injection * implement our own command-line tool **************************************************************************************************** ** OpenGM 1.0 (21.09.2010) ** ** Developers in charge: ** * Bjoern Andres ( bjoern[AT]andres[DOT]sc ) ** * Joerg Hendrik Kappes ( kappes[AT]math[DOT]uni-heidelberg[DOT]de ) **************************************************************************************************** * Initial release as a merge of two independent projects by Bjoern Andres and Joerg Hendrik Kappes. ***** * discrete factor graph models over various semi-rings which can be exchanged by templates * factors only support explicit functions (tables) but can depend from more than 2 variables * inference algorithms - AStar - LBP - TRBP - GraphCut (using boost/max-flow) - ICM - LazzyFlipper * command-line interface with tclap * file i/o which allows to save models into HDF5 files * primitive matlab interface * cmake build scripts opengm-2.3.6+20160905/Doxyfile.in000066400000000000000000002204251276346362400160460ustar00rootroot00000000000000# Doxyfile 1.7.4 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = OpenGM # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = 2.3.x # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "Discrete Graphical Model Library" # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@/doc # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = YES # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 3 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = YES # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = YES # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = NO # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= NO # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = NO # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = YES # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = NO # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = doxyerror #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @CMAKE_CURRENT_SOURCE_DIR@/include/ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.cpp \ *.h \ *.hxx \ *.cxx \ *.m \ *.py # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. #EXCLUDE = @CMAKE_CURRENT_SOURCE_DIR@/include/opengm/inference/external \ EXCLUDE = @CMAKE_CURRENT_SOURCE_DIR@/include/opengm/inference/experimental # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = */unittests/* \ *test_* # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/src/examples \ @CMAKE_CURRENT_SOURCE_DIR@/src/interfaces/matlab/opengm/matlab-examples/ \ @CMAKE_CURRENT_SOURCE_DIR@/src/interfaces/matlab/opengm/m_files/examples/ \ @CMAKE_CURRENT_SOURCE_DIR@/include/opengm/inference/ \ @CMAKE_CURRENT_SOURCE_DIR@/src/interfaces/python/examples/ # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 3 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is adviced to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the stylesheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = NO # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = YES # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = YES # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the # mathjax.org site, so you can quickly see the result without installing # MathJax, but it is strongly recommended to install a local copy of MathJax # before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = amsmath euscript # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = YES #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. This is useful # if you want to understand what is going on. On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/include/opengm # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = DATABASE # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = NO # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = YES # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 0 # By default doxygen will write a font called Helvetica to the output # directory and reference it in all dot files that doxygen generates. # When you want a differently looking font you can specify the font name # using DOT_FONTNAME. You need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 9 # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = YES # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = YES # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = YES # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 250 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = NO opengm-2.3.6+20160905/Licence-OpenGM.txt000066400000000000000000000021061276346362400171530ustar00rootroot00000000000000Copyright (C) 2013 Bjoern Andres, Thorsten Beier and Joerg H.~Kappes. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. opengm-2.3.6+20160905/README.md000066400000000000000000000174421276346362400152150ustar00rootroot00000000000000OpenGM 2 ======== [![Build Status](https://travis-ci.org/opengm/opengm.png?branch=master)](https://travis-ci.org/opengm/opengm) ----------------------------------------------------------------------------------------------- **Forum / Newsgroup** -> https://groups.google.com/forum/#!forum/opengm **Manual for OpenGM 2.0.2** -> http://hciweb2.iwr.uni-heidelberg.de/opengm/download/opengm-2.0.2-beta-manual.pdf **Code-Documentation for OpenGM 2.1.1** -> http://hciweb2.iwr.uni-heidelberg.de/opengm/doxygen/opengm-2.1.1/index.html OpenGM is a C++ template library for discrete factor graph models and distributive operations on these models. It includes state-of-the-art optimization and inference algorithms beyond message passing. OpenGM handles large models efficiently, since (i) functions that occur repeatedly need to be stored only once and (ii) when functions require different parametric or non-parametric encodings, multiple encodings can be used alongside each other, in the same model, using included and custom C++ code. No restrictions are imposed on the factor graph or the operations of the model. OpenGM is modular and extendible. Elementary data types can be chosen to maximize efficiency. The graphical model data structure, inference algorithms and different encodings of functions interoperate through well-defined interfaces. The binary OpenGM file format is based on the HDF5 standard and incorporates user extensions automatically. Features Factor Graph Models (Kschischang et al. 2001) Graphs of any order and structure, from second order grid graphs to irregular higher-order models Arbitrary (commutative and associative) operations, including sum, product, conjunction and disjunction Flexible number of labels (different variables can have differently many labels) Function sharing across factors Function type abstraction. Different (built-in and custom) encodings can be used alongside each other Functions Explicit function (multi-dimensional table) Sparse function (sparse multi-dimensional table) Potts functions (different types, including higher-order) Truncated absolute difference Truncated squared difference Views that treat one graphical model as a function within another graphical model Algorithms Loopy Belief Propagation (Pearl 1988, Yedidia et al. 2000) parallel and sequential min-sum and max-product message passing (also for higher-order models) message damping (Wainwright 2008) Tree-reweighted Belief Propagation (TRBP) (Wainwright et al. 2005) parallel and sequential min-sum and max-product message passing (also for higher-order models) message damping (Wainwright 2008) A-star branch-and-bound search (Bergtholdt et al. 2009) Dual Decomposition With sub-gradient methods (Kappes et al. 2010) With bundle methods (Kappes et al. 2012) Automated decomposition of arbitrary factor graphs Arbitrary sub-solvers via templates Graph Cut (Boykov et al. 2001). Push-Relabel (Goldberg and Tarjan 1986) Edmonds-Karp (Edmonds and Karp 1972) Kolmogorov (Boykov and Kolmogorov 2004) QPBO MQPBO Linear Programming Relaxations over the Local Polytope TRWS ADSAL CombiLP Integer Linear Programming Multicut (Kappes et al. 2011) Fusion Moves for Correlation clustering (Beier et al. 2015) Cut & Glue and Cut (Beier et al. 2014) Reduced-Inference (Kappes et al. 2013) Alpha-Expansion Alpha-Beta-Swap Alpha-Fusion Inf and Flip Iterated Conditional Modes (ICM) (Besag 1986) Lazy Flipper (Andres et al. 2010) Kerninghan Lin MCMC Metropolis-Hastings algorithms (Metropolis et al. 1953) Gibbs sampling (Geman and Geman 1984) Swendsen-Wang sampling (Swendsen and Wang 1987) Wrappers around other graphical model libraries MRF-LIB LIB-DAI TRW-S QPBO GCO FastPD AD3 DAOOPT MPLP, MPLP-C Binary HDF5 file format Command Line Optimizer with built-in protocol mode for runtime and convergence analyses Python Module with OpenGM C++ API exported to Python with boost::python Allmost the complete C++ API is exported to Python Allmost all C++ inference algorithms wrapped to Python Vectorized API to add multiple functions and factors at once Add functions via numpy ndarrays Add functions via all default opengm function types Extendibility through interfaces for custom pure python function types custom pure python visitor for inference visualization of current inference state with matplotlib Visualize Factor Graph (needs networkx and graphviz) High performance Graphical models with more than 10,000,000 factors Specialized functions for optimized cache usage Extendibility through interfaces for custom algorithms custom functions custom label spaces How to cite OpenGM? @Article{opengm-library, author = {Andres, B. and Beier, T. and Kappes, J.H.}, title = {{OpenGM}: {A} {C++} Library for Discrete Graphical Models}, journal = {CoRR}, volume = {abs/1206.0111}, year = {2012}, url = {http://arxiv.org/abs/1206.0111} } @Article{opengm-benchmark, Title = {A Comparative Study of Modern Inference Techniques for Structured Discrete Energy Minimization Problems}, Author = {Kappes, J\"orgH. and Andres, Bjoern and Hamprecht, FredA. and Schn\"orr, Christoph and Nowozin, Sebastian and Batra, Dhruv and Kim, Sungwoong and Kausler, BernhardX. and Kr\"oger, Thorben and Lellmann, Jan and Komodakis, Nikos and Savchynskyy, Bogdan and Rother, Carsten}, Journal = {International Journal of Computer Vision}, Year = {2015}, Number = {2}, Pages = {155-184}, Volume = {115}, Doi = {10.1007/s11263-015-0809-x}, ISSN = {0920-5691}, Language = {English}, Publisher = {Springer US} } opengm/opengm - master [![Build Status](https://travis-ci.org/opengm/opengm.png?branch=master)](https://travis-ci.org/opengm/opengm) DerThorsten/opengm - master (opengm-python dev.) [![Build Status](https://travis-ci.org/DerThorsten/opengm.png?branch=master)](https://travis-ci.org/DerThorsten/opengm) Copyright (C) 2012 Bjoern Andres, Thorsten Beier and Joerg H.~Kappes. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. opengm-2.3.6+20160905/cmake/000077500000000000000000000000001276346362400150065ustar00rootroot00000000000000opengm-2.3.6+20160905/cmake/modules/000077500000000000000000000000001276346362400164565ustar00rootroot00000000000000opengm-2.3.6+20160905/cmake/modules/FindAD3.cmake000066400000000000000000000010311276346362400206230ustar00rootroot00000000000000 FIND_PATH(AD3_INCLUDE_DIR ad3/FactorGraph.h) FIND_LIBRARY(AD3_LIBRARY NAMES libad3 ad3 ) # handle the QUIETLY and REQUIRED arguments and set AD3_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(AD3 DEFAULT_MSG AD3_INCLUDE_DIR AD3_LIBRARY ) IF(AD3_FOUND) SET(AD3_LIBRARIES ${AD3_LIBRARY} ) ELSE() SET(AD3_INCLUDE_DIR AD3_INCLUDE_DIR-NOTFOUND) SET(AD3_LIBRARY AD3_LIBRARY-NOTFOUND) ENDIF() opengm-2.3.6+20160905/cmake/modules/FindCONICBUNDLE.cmake000066400000000000000000000013711276346362400220100ustar00rootroot00000000000000FIND_PATH(CONICBUNDLE_INCLUDE_DIR CBSolver.hxx HINTS "src/external/ConicBundle-v0.3.11.src-patched/include/" ) if(WIN32) FIND_LIBRARY(CONICBUNDLE_LIBRARY cb.lib #TODO check lib name for windows HINTS "src/external/ConicBundle-v0.3.11.src-patched/lib/" ) else() FIND_LIBRARY(CONICBUNDLE_LIBRARY libcb.a HINTS "src/external/ConicBundle-v0.3.11.src-patched/lib/" ) endif() INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CONICBUNDLE DEFAULT_MSG CONICBUNDLE_LIBRARY CONICBUNDLE_INCLUDE_DIR ) IF(CONICBUNDLE_FOUND) ELSE() SET(CONICBUNDLE_INCLUDE_DIR CONICBUNDLE_INCLUDE_DIR-NOTFOUND) SET(CONICBUNDLE_LIBRARY CONICBUNDLE_LIBRARY-NOTFOUND) ENDIF(CONICBUNDLE_FOUND) opengm-2.3.6+20160905/cmake/modules/FindCPLEX.cmake000066400000000000000000000130721276346362400211370ustar00rootroot00000000000000# This module finds cplex. # # User can give CPLEX_ROOT_DIR as a hint stored in the cmake cache. # # It sets the following variables: # CPLEX_FOUND - Set to false, or undefined, if cplex isn't found. # CPLEX_INCLUDE_DIRS - include directory # CPLEX_LIBRARIES - library files if(WIN32) execute_process(COMMAND cmd /C set CPLEX_STUDIO_DIR OUTPUT_VARIABLE CPLEX_STUDIO_DIR_VAR ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) if(NOT CPLEX_STUDIO_DIR_VAR) MESSAGE(FATAL_ERROR "Unable to find CPLEX: environment variable CPLEX_STUDIO_DIR not set.") endif() STRING(REGEX REPLACE "^CPLEX_STUDIO_DIR" "" CPLEX_STUDIO_DIR_VAR ${CPLEX_STUDIO_DIR_VAR}) STRING(REGEX MATCH "^[0-9]+" CPLEX_WIN_VERSION ${CPLEX_STUDIO_DIR_VAR}) STRING(REGEX REPLACE "^[0-9]+=" "" CPLEX_STUDIO_DIR_VAR ${CPLEX_STUDIO_DIR_VAR}) file(TO_CMAKE_PATH "${CPLEX_STUDIO_DIR_VAR}" CPLEX_ROOT_DIR_GUESS) set(CPLEX_WIN_VERSION ${CPLEX_WIN_VERSION} CACHE STRING "CPLEX version to be used.") set(CPLEX_ROOT_DIR "${CPLEX_ROOT_DIR_GUESS}" CACHE PATH "CPLEX root directory.") MESSAGE(STATUS "Found CLPEX version ${CPLEX_WIN_VERSION} at '${CPLEX_ROOT_DIR}'") STRING(REGEX REPLACE "/VC/bin/.*" "" VISUAL_STUDIO_PATH ${CMAKE_C_COMPILER}) STRING(REGEX MATCH "Studio [0-9]+" CPLEX_WIN_VS_VERSION ${VISUAL_STUDIO_PATH}) STRING(REGEX REPLACE "Studio " "" CPLEX_WIN_VS_VERSION ${CPLEX_WIN_VS_VERSION}) if(${CPLEX_WIN_VS_VERSION} STREQUAL "9") set(CPLEX_WIN_VS_VERSION 2008) elseif(${CPLEX_WIN_VS_VERSION} STREQUAL "10") set(CPLEX_WIN_VS_VERSION 2010) elseif(${CPLEX_WIN_VS_VERSION} STREQUAL "11") set(CPLEX_WIN_VS_VERSION 2012) else() MESSAGE(FATAL_ERROR "CPLEX: unknown Visual Studio version at '${VISUAL_STUDIO_PATH}'.") endif() set(CPLEX_WIN_VS_VERSION ${CPLEX_WIN_VS_VERSION} CACHE STRING "Visual Studio Version") if("${CMAKE_C_COMPILER}" MATCHES "amd64") set(CPLEX_WIN_BITNESS x64) else() set(CPLEX_WIN_BITNESS x86) endif() set(CPLEX_WIN_BITNESS ${CPLEX_WIN_BITNESS} CACHE STRING "On Windows: x86 or x64 (32bit resp. 64bit)") MESSAGE(STATUS "CPLEX: using Visual Studio ${CPLEX_WIN_VS_VERSION} ${CPLEX_WIN_BITNESS} at '${VISUAL_STUDIO_PATH}'") if(NOT CPLEX_WIN_LINKAGE) set(CPLEX_WIN_LINKAGE mda CACHE STRING "CPLEX linkage variant on Windows. One of these: mda (dll, release), mdd (dll, debug), mta (static, release), mtd (static, debug)") endif(NOT CPLEX_WIN_LINKAGE) # now, generate platform string set(CPLEX_WIN_PLATFORM "${CPLEX_WIN_BITNESS}_windows_vs${CPLEX_WIN_VS_VERSION}/stat_${CPLEX_WIN_LINKAGE}") else() set(CPLEX_ROOT_DIR "" CACHE PATH "CPLEX root directory.") set(CPLEX_WIN_PLATFORM "") endif() FIND_PATH(CPLEX_INCLUDE_DIR ilcplex/cplex.h HINTS ${CPLEX_ROOT_DIR}/cplex/include ${CPLEX_ROOT_DIR}/include PATHS ENV C_INCLUDE_PATH ENV C_PLUS_INCLUDE_PATH ENV INCLUDE_PATH ) FIND_PATH(CPLEX_CONCERT_INCLUDE_DIR ilconcert/iloenv.h HINTS ${CPLEX_ROOT_DIR}/concert/include ${CPLEX_ROOT_DIR}/include PATHS ENV C_INCLUDE_PATH ENV C_PLUS_INCLUDE_PATH ENV INCLUDE_PATH ) FIND_LIBRARY(CPLEX_LIBRARY NAMES cplex${CPLEX_WIN_VERSION} cplex HINTS ${CPLEX_ROOT_DIR}/cplex/lib/${CPLEX_WIN_PLATFORM} #windows ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_debian4.0_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_sles10_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_osx/static_pic #osx PATHS ENV LIBRARY_PATH #unix ENV LD_LIBRARY_PATH #unix ) message(STATUS "CPLEX Library: ${CPLEX_LIBRARY}") FIND_LIBRARY(CPLEX_ILOCPLEX_LIBRARY ilocplex HINTS ${CPLEX_ROOT_DIR}/cplex/lib/${CPLEX_WIN_PLATFORM} #windows ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_debian4.0_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_sles10_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/cplex/lib/x86-64_osx/static_pic #osx PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH ) message(STATUS "ILOCPLEX Library: ${CPLEX_ILOCPLEX_LIBRARY}") FIND_LIBRARY(CPLEX_CONCERT_LIBRARY concert HINTS ${CPLEX_ROOT_DIR}/concert/lib/${CPLEX_WIN_PLATFORM} #windows ${CPLEX_ROOT_DIR}/concert/lib/x86-64_debian4.0_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/concert/lib/x86-64_sles10_4.1/static_pic #unix ${CPLEX_ROOT_DIR}/concert/lib/x86-64_osx/static_pic #osx PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH ) message(STATUS "CONCERT Library: ${CPLEX_CONCERT_LIBRARY}") if(WIN32) FIND_PATH(CPLEX_BIN_DIR cplex${CPLEX_WIN_VERSION}.dll HINTS ${CPLEX_ROOT_DIR}/cplex/bin/${CPLEX_WIN_PLATFORM} #windows ) else() FIND_PATH(CPLEX_BIN_DIR cplex HINTS ${CPLEX_ROOT_DIR}/cplex/bin/x86-64_sles10_4.1 #unix ${CPLEX_ROOT_DIR}/cplex/bin/x86-64_debian4.0_4.1 #unix ${CPLEX_ROOT_DIR}/cplex/bin/x86-64_osx #osx ENV LIBRARY_PATH ENV LD_LIBRARY_PATH ) endif() message(STATUS "CPLEX Bin Dir: ${CPLEX_BIN_DIR}") INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CPLEX DEFAULT_MSG CPLEX_LIBRARY CPLEX_INCLUDE_DIR CPLEX_ILOCPLEX_LIBRARY CPLEX_CONCERT_LIBRARY CPLEX_CONCERT_INCLUDE_DIR) IF(CPLEX_FOUND) SET(CPLEX_INCLUDE_DIRS ${CPLEX_INCLUDE_DIR} ${CPLEX_CONCERT_INCLUDE_DIR}) SET(CPLEX_LIBRARIES ${CPLEX_CONCERT_LIBRARY} ${CPLEX_ILOCPLEX_LIBRARY} ${CPLEX_LIBRARY} ) IF(CMAKE_SYSTEM_NAME STREQUAL "Linux") SET(CPLEX_LIBRARIES "${CPLEX_LIBRARIES};m;pthread") ENDIF(CMAKE_SYSTEM_NAME STREQUAL "Linux") ENDIF(CPLEX_FOUND) MARK_AS_ADVANCED(CPLEX_LIBRARY CPLEX_INCLUDE_DIR CPLEX_ILOCPLEX_LIBRARY CPLEX_CONCERT_INCLUDE_DIR CPLEX_CONCERT_LIBRARY) opengm-2.3.6+20160905/cmake/modules/FindFASTINF.cmake000066400000000000000000000011671276346362400213600ustar00rootroot00000000000000 FIND_PATH(FASTINF_INCLUDE_DIR lbDefinitions.h) FIND_LIBRARY(FASTINF_LOOPY_INF_LIBRARY NAMES libLoopyInf ) # handle the QUIETLY and REQUIRED arguments and set FASTINF_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(FASTINF DEFAULT_MSG FASTINF_INCLUDE_DIR FASTINF_LOOPY_INF_LIBRARY ) IF(FASTINF_FOUND) SET(FASTINF_LIBRARIES ${FASTINF_LOOPY_INF_LIBRARY} ) ELSE() SET(FASTINF_INCLUDE_DIR FASTINF_INCLUDE_DIR-NOTFOUND) SET(FASTINF_LOOPY_INF_LIBRARY FASTINF_LOOPY_INF_LIBRARY-NOTFOUND) ENDIF() opengm-2.3.6+20160905/cmake/modules/FindGMP.cmake000066400000000000000000000007231276346362400207060ustar00rootroot00000000000000FIND_PATH(GMP_INCLUDE_DIR gmp.h $ENV{HOME}/.local/include) FIND_LIBRARY(GMP_LIBRARY NAMES gmp PATH $ENV{HOME}/.local/include) IF (GMP_INCLUDE_DIR AND GMP_LIBRARY) SET(GMP_FOUND TRUE) ENDIF (GMP_INCLUDE_DIR AND GMP_LIBRARY) IF (GMP_FOUND) IF (NOT GMP_FIND_QUIETLY) MESSAGE(STATUS "Found GMP: ${GMP_LIBRARY}") ENDIF (NOT GMP_FIND_QUIETLY) ELSE (GMP_FOUND) IF (GMP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find GMP") ENDIF (GMP_FIND_REQUIRED) ENDIF (GMP_FOUND) opengm-2.3.6+20160905/cmake/modules/FindGMPXX.cmake000066400000000000000000000010151276346362400211610ustar00rootroot00000000000000FIND_PATH(GMPXX_INCLUDE_DIR gmpxx.h $ENV{HOME}/.local/include) FIND_LIBRARY(GMPXX_LIBRARY NAMES gmpxx PATH $ENV{HOME}/.local/include) IF (GMPXX_INCLUDE_DIR AND GMPXX_LIBRARY) SET(GMPXX_FOUND TRUE) ENDIF (GMPXX_INCLUDE_DIR AND GMPXX_LIBRARY) IF (GMPXX_FOUND) IF (NOT GMPXX_FIND_QUIETLY) MESSAGE(STATUS "Found GMPXX: ${GMPXX_LIBRARY}") ENDIF(NOT GMPXX_FIND_QUIETLY) ELSE (GMPXX_FOUND) IF (GMPXX_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find GMPXX") ENDIF (GMPXX_FIND_REQUIRED) ENDIF (GMPXX_FOUND) opengm-2.3.6+20160905/cmake/modules/FindGSL.cmake000066400000000000000000000101631276346362400207070ustar00rootroot00000000000000# Try to find gnu scientific library GSL # See # http://www.gnu.org/software/gsl/ and # http://gnuwin32.sourceforge.net/packages/gsl.htm # # Based on a script of Felix Woelk and Jan Woetzel # (www.mip.informatik.uni-kiel.de) # # It defines the following variables: # GSL_FOUND - system has GSL lib # GSL_INCLUDE_DIRS - where to find headers # GSL_LIBRARIES - full path to the libraries # GSL_LIBRARY_DIRS, the directory where the PLplot library is found. # CMAKE_GSL_CXX_FLAGS = Unix compiler flags for GSL, essentially "`gsl-config --cxxflags`" # GSL_LINK_DIRECTORIES = link directories, useful for rpath on Unix # GSL_EXE_LINKER_FLAGS = rpath on Unix set( GSL_FOUND OFF ) set( GSL_CBLAS_FOUND OFF ) # Windows, but not for Cygwin and MSys where gsl-config is available if( WIN32 AND NOT CYGWIN AND NOT MSYS ) # look for headers find_path( GSL_INCLUDE_DIR NAMES gsl/gsl_cdf.h gsl/gsl_randist.h ) if( GSL_INCLUDE_DIR ) # look for gsl library find_library( GSL_LIBRARY NAMES gsl ) if( GSL_LIBRARY ) set( GSL_INCLUDE_DIRS ${GSL_INCLUDE_DIR} ) get_filename_component( GSL_LIBRARY_DIRS ${GSL_LIBRARY} PATH ) set( GSL_FOUND ON ) endif( GSL_LIBRARY ) # look for gsl cblas library find_library( GSL_CBLAS_LIBRARY NAMES gslcblas ) if( GSL_CBLAS_LIBRARY ) set( GSL_CBLAS_FOUND ON ) endif( GSL_CBLAS_LIBRARY ) set( GSL_LIBRARIES ${GSL_LIBRARY} ${GSL_CBLAS_LIBRARY} ) endif( GSL_INCLUDE_DIR ) mark_as_advanced( GSL_INCLUDE_DIR GSL_LIBRARY GSL_CBLAS_LIBRARY ) else( WIN32 AND NOT CYGWIN AND NOT MSYS ) if( UNIX OR MSYS ) find_program( GSL_CONFIG_EXECUTABLE gsl-config /usr/bin/ /usr/local/bin ) if( GSL_CONFIG_EXECUTABLE ) set( GSL_FOUND ON ) # run the gsl-config program to get cxxflags execute_process( COMMAND sh "${GSL_CONFIG_EXECUTABLE}" --cflags OUTPUT_VARIABLE GSL_CFLAGS RESULT_VARIABLE RET ERROR_QUIET ) if( RET EQUAL 0 ) string( STRIP "${GSL_CFLAGS}" GSL_CFLAGS ) separate_arguments( GSL_CFLAGS ) # parse definitions from cflags; drop -D* from CFLAGS string( REGEX MATCHALL "-D[^;]+" GSL_DEFINITIONS "${GSL_CFLAGS}" ) string( REGEX REPLACE "-D[^;]+;" "" GSL_CFLAGS "${GSL_CFLAGS}" ) # parse include dirs from cflags; drop -I prefix string( REGEX MATCHALL "-I[^;]+" GSL_INCLUDE_DIRS "${GSL_CFLAGS}" ) string( REPLACE "-I" "" GSL_INCLUDE_DIRS "${GSL_INCLUDE_DIRS}") string( REGEX REPLACE "-I[^;]+;" "" GSL_CFLAGS "${GSL_CFLAGS}") message("GSL_DEFINITIONS=${GSL_DEFINITIONS}") message("GSL_INCLUDE_DIRS=${GSL_INCLUDE_DIRS}") message("GSL_CFLAGS=${GSL_CFLAGS}") else( RET EQUAL 0 ) set( GSL_FOUND FALSE ) endif( RET EQUAL 0 ) # run the gsl-config program to get the libs execute_process( COMMAND sh "${GSL_CONFIG_EXECUTABLE}" --libs OUTPUT_VARIABLE GSL_LIBRARIES RESULT_VARIABLE RET ERROR_QUIET ) if( RET EQUAL 0 ) string(STRIP "${GSL_LIBRARIES}" GSL_LIBRARIES ) separate_arguments( GSL_LIBRARIES ) # extract linkdirs (-L) for rpath (i.e., LINK_DIRECTORIES) string( REGEX MATCHALL "-L[^;]+" GSL_LIBRARY_DIRS "${GSL_LIBRARIES}" ) string( REPLACE "-L" "" GSL_LIBRARY_DIRS "${GSL_LIBRARY_DIRS}" ) else( RET EQUAL 0 ) set( GSL_FOUND FALSE ) endif( RET EQUAL 0 ) MARK_AS_ADVANCED( GSL_CFLAGS ) message( STATUS "Using GSL from ${GSL_PREFIX}" ) else( GSL_CONFIG_EXECUTABLE ) message( STATUS "FindGSL: gsl-config not found.") endif( GSL_CONFIG_EXECUTABLE ) endif( UNIX OR MSYS ) endif( WIN32 AND NOT CYGWIN AND NOT MSYS ) if( GSL_FOUND ) if( NOT GSL_FIND_QUIETLY ) message( STATUS "FindGSL: Found both GSL headers and library" ) endif( NOT GSL_FIND_QUIETLY ) else( GSL_FOUND ) if( GSL_FIND_REQUIRED ) message( FATAL_ERROR "FindGSL: Could not find GSL headers or library" ) endif( GSL_FIND_REQUIRED ) endif( GSL_FOUND )opengm-2.3.6+20160905/cmake/modules/FindGUROBI.cmake000066400000000000000000000050561276346362400212560ustar00rootroot00000000000000#### Taken from http://www.openflipper.org/svnrepo/CoMISo/trunk/CoMISo/cmake/FindGUROBI.cmake # - Try to find GUROBI # Once done this will define # GUROBI_FOUND - System has Gurobi # GUROBI_INCLUDE_DIRS - The Gurobi include directories # GUROBI_LIBRARIES - The libraries needed to use Gurobi if (GUROBI_INCLUDE_DIR) # in cache already set(GUROBI_FOUND TRUE) set(GUROBI_INCLUDE_DIRS "${GUROBI_INCLUDE_DIR}" ) set(GUROBI_LIBRARIES "${GUROBI_CXX_LIBRARY};${GUROBI_LIBRARY}" ) else (GUROBI_INCLUDE_DIR) find_path(GUROBI_INCLUDE_DIR NAMES gurobi_c++.h PATHS "$ENV{GUROBI_HOME}/include" "/Library/gurobi502/mac64/include" "C:\\libs\\gurobi502\\include" ) find_library( GUROBI_LIBRARY NAMES gurobi gurobi45 gurobi46 gurobi50 gurobi51 gurobi52 gurobi55 gurobi60 PATHS "$ENV{GUROBI_HOME}/lib" "/Library/gurobi502/mac64/lib" "C:\\libs\\gurobi502\\lib" ) if (MSVC) STRING(REGEX REPLACE "/VC/bin/.*" "" VISUAL_STUDIO_PATH ${CMAKE_C_COMPILER}) STRING(REGEX MATCH "Studio [0-9]+" VISUAL_STUDIO_VERSION ${VISUAL_STUDIO_PATH}) STRING(REGEX REPLACE "Studio " "" VISUAL_STUDIO_VERSION ${VISUAL_STUDIO_VERSION}) if (VISUAL_STUDIO_VERSION STREQUAL "10") set (VISUAL_STUDIO_YEAR "2010") elseif (VISUAL_STUDIO_VERSION STREQUAL "11") set (VISUAL_STUDIO_YEAR "2012") elseif (VISUAL_STUDIO_VERSION STREQUAL "12") set (VISUAL_STUDIO_YEAR "2013") else () message(FATAL_ERROR "Unsupported compiler version: ${VISUAL_STUDIO_VERSION}") endif () set (GUROBI_LIB_NAME gurobi_c++md${VISUAL_STUDIO_YEAR}) else () set (GUROBI_LIB_NAME gurobi_c++) endif () find_library( GUROBI_CXX_LIBRARY NAMES ${GUROBI_LIB_NAME} PATHS "$ENV{GUROBI_HOME}/lib" "/Library/gurobi502/mac64/lib" "C:\\libs\\gurobi502\\lib" ) set(GUROBI_INCLUDE_DIRS "${GUROBI_INCLUDE_DIR}" ) set(GUROBI_LIBRARIES "${GUROBI_CXX_LIBRARY};${GUROBI_LIBRARY}" ) # use c++ headers as default # set(GUROBI_COMPILER_FLAGS "-DIL_STD" CACHE STRING "Gurobi Compiler Flags") include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set LIBCPLEX_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args(GUROBI DEFAULT_MSG GUROBI_LIBRARY GUROBI_CXX_LIBRARY GUROBI_INCLUDE_DIR) mark_as_advanced(GUROBI_INCLUDE_DIR GUROBI_LIBRARY GUROBI_CXX_LIBRARY) endif(GUROBI_INCLUDE_DIR) opengm-2.3.6+20160905/cmake/modules/FindHDF5.cmake000066400000000000000000000102031276346362400207430ustar00rootroot00000000000000# - Find HDF5, a library for reading and writing self describing array data. # FIND_PATH(HDF5_INCLUDE_DIR hdf5.h PATH_SUFFIXES hdf5/serial) if(HDF5_INCLUDE_DIR) SET(HDF5_TRY_COMPILE_INCLUDE_DIR "-DINCLUDE_DIRECTORIES:STRING=${HDF5_INCLUDE_DIR}") set(HDF5_SUFFICIENT_VERSION FALSE) TRY_COMPILE(HDF5_SUFFICIENT_VERSION ${CMAKE_BINARY_DIR} ${PROJECT_SOURCE_DIR}/cmake/modules/checkHDF5version.c CMAKE_FLAGS "${HDF5_TRY_COMPILE_INCLUDE_DIR}") if(NOT HDF5_SUFFICIENT_VERSION) MESSAGE(STATUS " HDF5: unable to compile a simple test program.\n (include path: '${HDF5_INCLUDE_DIR}')" ) else() SET(HDF5_VERSION_MAJOR 1) SET(HDF5_VERSION_MINOR 8) set(HDF5_SUFFICIENT_VERSION FALSE) TRY_COMPILE(HDF5_SUFFICIENT_VERSION ${CMAKE_BINARY_DIR} ${PROJECT_SOURCE_DIR}/cmake/modules/checkHDF5version.c COMPILE_DEFINITIONS "-DCHECK_VERSION=1 -DMIN_MAJOR=${HDF5_VERSION_MAJOR} -DMIN_MINOR=${HDF5_VERSION_MINOR}" CMAKE_FLAGS "${HDF5_TRY_COMPILE_INCLUDE_DIR}") if(NOT HDF5_SUFFICIENT_VERSION) MESSAGE(STATUS " HDF5: need at least version ${HDF5_VERSION_MAJOR}.${HDF5_VERSION_MINOR}" ) else() MESSAGE(STATUS " Checking HDF5 version (at least ${HDF5_VERSION_MAJOR}.${HDF5_VERSION_MINOR}): ok") endif() endif() # Only configure HDF5 if a suitable version of the library was found if(HDF5_SUFFICIENT_VERSION) FIND_LIBRARY(HDF5_CORE_LIBRARY NAMES hdf5dll hdf5 PATH_SUFFIXES hdf5/serial ) FIND_LIBRARY(HDF5_HL_LIBRARY NAMES hdf5_hldll hdf5_hl PATH_SUFFIXES hdf5/serial ) # FIXME: as of version 1.8.9 and 1.8.10-patch1 (but NOT 1.8.10), these flags are # already set correctly => remove or set conditionally according to version IF(WIN32 AND HDF5_CORE_LIBRARY MATCHES "dll.lib$") SET(HDF5_CFLAGS "-D_HDF5USEDLL_") SET(HDF5_CPPFLAGS "-D_HDF5USEDLL_ -DHDF5CPP_USEDLL") ELSE() SET(HDF5_CFLAGS) SET(HDF5_CPPFLAGS) ENDIF() set(HDF5_USES_ZLIB FALSE) TRY_COMPILE(HDF5_USES_ZLIB ${CMAKE_BINARY_DIR} ${PROJECT_SOURCE_DIR}/cmake/modules/checkHDF5usesCompression.c COMPILE_DEFINITIONS "-DH5_SOMETHING=H5_HAVE_FILTER_DEFLATE" CMAKE_FLAGS "${HDF5_TRY_COMPILE_INCLUDE_DIR}") if(HDF5_USES_ZLIB) FIND_LIBRARY(HDF5_Z_LIBRARY NAMES zlib1 zlib z ) set(HDF5_ZLIB_OK ${HDF5_Z_LIBRARY}) else() set(HDF5_ZLIB_OK TRUE) set(HDF5_Z_LIBRARY "") endif() set(HDF5_USES_SZLIB FALSE) TRY_COMPILE(HDF5_USES_SZLIB ${CMAKE_BINARY_DIR} ${PROJECT_SOURCE_DIR}/cmake/modules/checkHDF5usesCompression.c COMPILE_DEFINITIONS "-DH5_SOMETHING=H5_HAVE_FILTER_SZIP" CMAKE_FLAGS "${HDF5_TRY_COMPILE_INCLUDE_DIR}") if(HDF5_USES_SZLIB) FIND_LIBRARY(HDF5_SZ_LIBRARY NAMES szlibdll sz szip) set(HDF5_SZLIB_OK ${HDF5_SZ_LIBRARY}) else() set(HDF5_SZLIB_OK TRUE) set(HDF5_SZ_LIBRARY "") endif() endif() endif() # handle the QUIETLY and REQUIRED arguments and set HDF5_FOUND to TRUE if # all listed variables are TRUE INCLUDE(FindPackageHandleStandardArgs) if(NOT HDF5_INCLUDE_DIR) FIND_PACKAGE_HANDLE_STANDARD_ARGS(HDF5 DEFAULT_MSG HDF5_INCLUDE_DIR) elseif(NOT HDF5_SUFFICIENT_VERSION) # undo unsuccessful configuration set(HDF5_INCLUDE_DIR "") FIND_PACKAGE_HANDLE_STANDARD_ARGS(HDF5 DEFAULT_MSG HDF5_SUFFICIENT_VERSION) else() FIND_PACKAGE_HANDLE_STANDARD_ARGS(HDF5 DEFAULT_MSG HDF5_CORE_LIBRARY HDF5_HL_LIBRARY HDF5_ZLIB_OK HDF5_SZLIB_OK HDF5_INCLUDE_DIR) endif() IF(HDF5_FOUND) SET(HDF5_LIBRARIES ${HDF5_CORE_LIBRARY} ${HDF5_HL_LIBRARY} ${HDF5_Z_LIBRARY} ${HDF5_SZ_LIBRARY}) ELSE() SET(HDF5_CORE_LIBRARY HDF5_CORE_LIBRARY-NOTFOUND) SET(HDF5_HL_LIBRARY HDF5_HL_LIBRARY-NOTFOUND) SET(HDF5_Z_LIBRARY HDF5_Z_LIBRARY-NOTFOUND) SET(HDF5_SZ_LIBRARY HDF5_SZ_LIBRARY-NOTFOUND) ENDIF(HDF5_FOUND) opengm-2.3.6+20160905/cmake/modules/FindLIBDAI.cmake000066400000000000000000000007541276346362400212130ustar00rootroot00000000000000FIND_PATH(LIBDAI_INCLUDE_DIR dai/alldai.h HINTS "~/usr/local/include/dai" "~/usr/include/dai" ) FIND_LIBRARY(LIBDAI_LIBRARY libdai HINTS "~/usr/local/lib/dai" "~/usr/lib/dai" ) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBDAI DEFAULT_MSG LIBDAI_LIBRARY LIBDAI_INCLUDE_DIR ) IF(LIBDAI_FOUND) ELSE() SET(LIBDAI_INCLUDE_DIR LIBDAI_INCLUDE_DIR-NOTFOUND) SET(LIBDAI_LIBRARY LIBDAI_LIBRARY-NOTFOUND) ENDIF(LIBDAI_FOUND) opengm-2.3.6+20160905/cmake/modules/FindMATLAB.cmake000066400000000000000000000033741276346362400212300ustar00rootroot00000000000000# - this module looks for Matlab # Defines: # MATLAB_ROOT_DIR: path to Matlab's root directory # MATLAB_INCLUDE_DIR: include path for mex.h, engine.h # MATLAB_LIBRARY_DIR : map path for mexFunction.map, .... # MATLAB_LIBRARIES: required libraries: libmex, etc # MATLAB_MEX_LIBRARY: path to libmex.lib # MATLAB_MX_LIBRARY: path to libmx.lib # MATLAB_ENG_LIBRARY: path to libeng.lib # ## config set(MATLAB_ROOT_DIR "" CACHE PATH "CPLEX root directory") set(MATLAB_FOUND 0) if(WIN32) #TODO endif(WIN32) if(UNIX) ## LINUX 64 BIT SET(MATLAB_MEXEXT "mexa64" CACHE STRING "Matlab MEX file extension") FIND_PATH(MATLAB_INCLUDE_DIR mex.h HINTS ${MATLAB_ROOT_DIR}/extern/include/ PATHS ENV C_INCLUDE_PATH ENV C_PLUS_INCLUDE_PATH ENV INCLUDE_PATH ) FIND_PATH( MATLAB_LIBRARY_DIR mexFunction.map HINTS ${MATLAB_ROOT_DIR}/extern/lib/glnxa64/ ) FIND_LIBRARY(MATLAB_MEX_LIBRARY libmex.so HINTS ${MATLAB_ROOT_DIR}/bin/glnxa64/ PATHS ENV LIBRARY_PATH #unix ENV LD_LIBRARY_PATH #unix ) FIND_LIBRARY(MATLAB_MX_LIBRARY libmx.so HINTS ${MATLAB_ROOT_DIR}/bin/glnxa64/ PATHS ENV LIBRARY_PATH #unix ENV LD_LIBRARY_PATH #unix ) FIND_LIBRARY(MATLAB_ENG_LIBRARY libeng.so HINTS ${MATLAB_ROOT_DIR}/bin/glnxa64/ PATHS ENV LIBRARY_PATH #unix ENV LD_LIBRARY_PATH #unix ) endif(UNIX) SET(MATLAB_LIBRARIES ${MATLAB_MEX_LIBRARY} ${MATLAB_MX_LIBRARY} ${MATLAB_ENG_LIBRARY} ) IF(MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES) SET(MATLAB_FOUND 1) ENDIF(MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES) MARK_AS_ADVANCED( MATLAB_LIBRARIES MATLAB_MEX_LIBRARY MATLAB_MX_LIBRARY MATLAB_ENG_LIBRARY MATLAB_INCLUDE_DIR MATLAB_LIBRARY_DIR MATLAB_MEXEXT MATLAB_FOUND ) opengm-2.3.6+20160905/cmake/modules/FindNUMPY.cmake000066400000000000000000000021501276346362400211670ustar00rootroot00000000000000# Find the Python NumPy package # PYTHON_NUMPY_INCLUDE_DIR # NUMPY_FOUND # will be set by this script if(NUMPY_FIND_QUIETLY) find_package(PythonInterp) else() find_package(PythonInterp QUIET) set(_numpy_out 1) endif() if (PYTHON_EXECUTABLE) # write a python script that finds the numpy path file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/FindNumpyPath.py "try: import numpy; print numpy.get_include()\nexcept:pass\n") # execute the find script exec_program("${PYTHON_EXECUTABLE}" ${CMAKE_CURRENT_BINARY_DIR} ARGS "FindNumpyPath.py" OUTPUT_VARIABLE NUMPY_PATH) elseif(_numpy_out) message(STATUS "Python executable not found.") endif(PYTHON_EXECUTABLE) find_path(PYTHON_NUMPY_INCLUDE_DIR numpy/arrayobject.h "${NUMPY_PATH}" "${PYTHON_INCLUDE_PATH}" /usr/include/python2.7/ /usr/include/python2.6/ /usr/include/python2.5/ /usr/include/python2.4/) if(PYTHON_NUMPY_INCLUDE_DIR) set(PYTHON_NUMPY_FOUND 1 CACHE INTERNAL "Python numpy found") endif(PYTHON_NUMPY_INCLUDE_DIR) #include(FindPackageHandleStandardArgs) find_package_handle_standard_args( NUMPY DEFAULT_MSG PYTHON_NUMPY_INCLUDE_DIR)opengm-2.3.6+20160905/cmake/modules/FindSPHINX.cmake000066400000000000000000000005701276346362400212740ustar00rootroot00000000000000find_program(SPHINX_EXECUTABLE NAMES sphinx-build HINTS $ENV{SPHINX_DIR} PATH_SUFFIXES bin\r\n DOC "Sphinx documentation generator" ) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Sphinx DEFAULT_MSG\r\n SPHINX_EXECUTABLE ) IF (SPHINX_EXECUTABLE ) SET(SPHINX_FOUND TRUE) ENDIF (SPHINX_EXECUTABLE) mark_as_advanced( SPHINX_EXECUTABLE )opengm-2.3.6+20160905/cmake/modules/FindVIGRA.cmake000066400000000000000000000010051276346362400211250ustar00rootroot00000000000000FIND_PATH(VIGRA_INCLUDE_DIR vigra/basicimage.hxx HINTS "~/usr/local/include/vigra" "~/usr/include/vigra" ) FIND_LIBRARY(VIGRA_IMPEX_LIBRARY vigraimpex HINTS "~/usr/local/include/vigra" "~/usr/include/vigra" ) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(VIGRA DEFAULT_MSG VIGRA_IMPEX_LIBRARY VIGRA_INCLUDE_DIR) IF(VIGRA_FOUND) ELSE() SET(VIGRA_INCLUDE_DIR VIGRA_INCLUDE_DIR-NOTFOUND) SET(VIGRA_IMPEX_LIBRARY VIGRA_IMPEX_LIBRARY-NOTFOUND) ENDIF(VIGRA_FOUND)opengm-2.3.6+20160905/cmake/modules/UseLATEX.cmake000066400000000000000000001317411276346362400210210ustar00rootroot00000000000000# File: UseLATEX.cmake # CMAKE commands to actually use the LaTeX compiler # Version: 1.8.1 # Author: Kenneth Moreland (kmorel at sandia dot gov) # # Copyright 2004 Sandia Corporation. # Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive # license for use of this work by or on behalf of the # U.S. Government. Redistribution and use in source and binary forms, with # or without modification, are permitted provided that this Notice and any # statement of authorship are reproduced on all copies. # # The following MACROS are defined: # # ADD_LATEX_DOCUMENT( # [BIBFILES ] # [INPUTS ] # [IMAGE_DIRS] # [IMAGES] # [CONFIGURE] # [DEPENDS] # [USE_INDEX] [USE_GLOSSARY] [USE_NOMENCL] # [DEFAULT_PDF] [DEFAULT_SAFEPDF] # [MANGLE_TARGET_NAMES]) # Adds targets that compile . The latex output is placed # in LATEX_OUTPUT_PATH or CMAKE_CURRENT_BINARY_DIR if the former is # not set. The latex program is picky about where files are located, # so all input files are copied from the source directory to the # output directory. This includes the target tex file, any tex file # listed with the INPUTS option, the bibliography files listed with # the BIBFILES option, and any .cls, .bst, and .clo files found in # the current source directory. Images found in the IMAGE_DIRS # directories or listed by IMAGES are also copied to the output # directory and coverted to an appropriate format if necessary. Any # tex files also listed with the CONFIGURE option are also processed # with the CMake CONFIGURE_FILE command (with the @ONLY flag. Any # file listed in CONFIGURE but not the target tex file or listed with # INPUTS has no effect. DEPENDS can be used to specify generated files # that are needed to compile the latex target. # # The following targets are made: # dvi: Makes .dvi # pdf: Makes .pdf using pdflatex. # safepdf: Makes .pdf using ps2pdf. If using the default # program arguments, this will ensure all fonts are # embedded and no lossy compression has been performed # on images. # ps: Makes .ps # html: Makes .html # auxclean: Deletes .aux and other auxiliary files. # This is sometimes necessary if a LaTeX error occurs # and writes a bad aux file. Unlike the regular clean # target, it does not delete other input files, such as # converted images, to save time on the rebuild. # # The dvi target is added to the ALL. That is, it will be the target # built by default. If the DEFAULT_PDF argument is given, then the # pdf target will be the default instead of dvi. # # If the argument MANGLE_TARGET_NAMES is given, then each of the # target names above will be mangled with the name. This # is to make the targets unique if ADD_LATEX_DOCUMENT is called for # multiple documents. If the argument USE_INDEX is given, then # commands to build an index are made. If the argument USE_GLOSSARY # is given, then commands to build a glossary are made. # # History: # # 1.8.1 Fix problem where ps2pdf was not getting the appropriate arguments. # # 1.8.0 Add support for synctex. # # 1.7.7 Support calling xindy when making glossaries. # # Improved make clean support. # # 1.7.6 Add support for the nomencl package (thanks to Myles English). # # 1.7.5 Fix issue with bibfiles being copied two different ways, which causes # Problems with dependencies (thanks to Edwin van Leeuwen). # # 1.7.4 Added the DEFAULT_SAFEPDF option (thanks to Raymond Wan). # # Added warnings when image directories are not found (and were # probably not given relative to the source directory). # # 1.7.3 Fix some issues with interactions between makeglossaries and bibtex # (thanks to Mark de Wever). # # 1.7.2 Use ps2pdf to convert eps to pdf to get around the problem with # ImageMagick dropping the bounding box (thanks to Lukasz Lis). # # 1.7.1 Fixed some dependency issues. # # 1.7.0 Added DEPENDS options (thanks to Theodore Papadopoulo). # # 1.6.1 Ported the makeglossaries command to CMake and embedded the port # into UseLATEX.cmake. # # 1.6.0 Allow the use of the makeglossaries command. Thanks to Oystein # S. Haaland for the patch. # # 1.5.0 Allow any type of file in the INPUTS lists, not just tex file # (suggested by Eric Noulard). As a consequence, the ability to # specify tex files without the .tex extension is removed. The removed # function is of dubious value anyway. # # When copying input files, skip over any file that exists in the # binary directory but does not exist in the source directory with the # assumption that these files were added by some other mechanism. I # find this useful when creating large documents with multiple # chapters that I want to build separately (for speed) as I work on # them. I use the same boilerplate as the starting point for all # and just copy it with different configurations. This was what the # separate ADD_LATEX_DOCUMENT method was supposed to originally be for. # Since its external use is pretty much deprecated, I removed that # documentation. # # 1.4.1 Copy .sty files along with the other class and package files. # # 1.4.0 Added a MANGLE_TARGET_NAMES option that will mangle the target names. # # Fixed problem with copying bib files that became apparent with # CMake 2.4. # # 1.3.0 Added a LATEX_OUTPUT_PATH variable that allows you or the user to # specify where the built latex documents to go. This is especially # handy if you want to do in-source builds. # # Removed the ADD_LATEX_IMAGES macro and absorbed the functionality # into ADD_LATEX_DOCUMENT. The old interface was always kind of # clunky anyway since you had to specify the image directory in both # places. It also made supporting LATEX_OUTPUT_PATH problematic. # # Added support for jpeg files. # # 1.2.0 Changed the configuration options yet again. Removed the NO_CONFIGURE # Replaced it with a CONFIGURE option that lists input files for which # configure should be run. # # The pdf target no longer depends on the dvi target. This allows you # to build latex documents that require pdflatex. Also added an option # to make the pdf target the default one. # # 1.1.1 Added the NO_CONFIGURE option. The @ character can be used when # specifying table column separators. If two or more are used, then # will incorrectly substitute them. # # 1.1.0 Added ability include multiple bib files. Added ability to do copy # sub-tex files for multipart tex files. # # 1.0.0 If both ps and pdf type images exist, just copy the one that # matches the current render mode. Replaced a bunch of STRING # commands with GET_FILENAME_COMPONENT commands that were made to do # the desired function. # # 0.4.0 First version posted to CMake Wiki. # ############################################################################# # Find the location of myself while originally executing. If you do this # inside of a macro, it will recode where the macro was invoked. ############################################################################# SET(LATEX_USE_LATEX_LOCATION ${CMAKE_CURRENT_LIST_FILE} CACHE INTERNAL "Location of UseLATEX.cmake file." FORCE ) ############################################################################# # Generic helper macros ############################################################################# # Helpful list macros. MACRO(LATEX_CAR var) SET(${var} ${ARGV1}) ENDMACRO(LATEX_CAR) MACRO(LATEX_CDR var junk) SET(${var} ${ARGN}) ENDMACRO(LATEX_CDR) MACRO(LATEX_LIST_CONTAINS var value) SET(${var}) FOREACH (value2 ${ARGN}) IF (${value} STREQUAL ${value2}) SET(${var} TRUE) ENDIF (${value} STREQUAL ${value2}) ENDFOREACH (value2) ENDMACRO(LATEX_LIST_CONTAINS) # Parse macro arguments. MACRO(LATEX_PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option}) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) LATEX_LIST_CONTAINS(is_arg_name ${arg} ${arg_names}) IF (is_arg_name) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name) LATEX_LIST_CONTAINS(is_option ${arg} ${option_names}) IF (is_option) SET(${prefix}_${arg} TRUE) ELSE (is_option) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option) ENDIF (is_arg_name) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(LATEX_PARSE_ARGUMENTS) # Match the contents of a file to a regular expression. MACRO(LATEX_FILE_MATCH variable filename regexp default) # The FILE STRINGS command would be a bit better, but it's not supported on # older versions of CMake. FILE(READ ${filename} file_contents) STRING(REGEX MATCHALL "${regexp}" ${variable} ${file_contents} ) IF (NOT ${variable}) SET(${variable} "${default}") ENDIF (NOT ${variable}) ENDMACRO(LATEX_FILE_MATCH) ############################################################################# # Macros that perform processing during a LaTeX build. ############################################################################# MACRO(LATEX_MAKEGLOSSARIES) # This is really a bare bones port of the makeglossaries perl script into # CMake scripting. MESSAGE("**************************** In makeglossaries") IF (NOT LATEX_TARGET) MESSAGE(SEND_ERROR "Need to define LATEX_TARGET") ENDIF (NOT LATEX_TARGET) SET(aux_file ${LATEX_TARGET}.aux) IF (NOT EXISTS ${aux_file}) MESSAGE(SEND_ERROR "${aux_file} does not exist. Run latex on your target file.") ENDIF (NOT EXISTS ${aux_file}) LATEX_FILE_MATCH(newglossary_lines ${aux_file} "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}" "@newglossary{main}{glg}{gls}{glo}" ) LATEX_FILE_MATCH(istfile_line ${aux_file} "@istfilename[ \t]*{([^}]*)}" "@istfilename{${LATEX_TARGET}.ist}" ) STRING(REGEX REPLACE "@istfilename[ \t]*{([^}]*)}" "\\1" istfile ${istfile_line} ) STRING(REGEX MATCH ".*\\.xdy" use_xindy "${istfile}") IF (use_xindy) MESSAGE("*************** Using xindy") IF (NOT XINDY_COMPILER) MESSAGE(SEND_ERROR "Need to define XINDY_COMPILER") ENDIF (NOT XINDY_COMPILER) ELSE (use_xindy) MESSAGE("*************** Using makeindex") IF (NOT MAKEINDEX_COMPILER) MESSAGE(SEND_ERROR "Need to define MAKEINDEX_COMPILER") ENDIF (NOT MAKEINDEX_COMPILER) ENDIF (use_xindy) FOREACH(newglossary ${newglossary_lines}) STRING(REGEX REPLACE "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}" "\\1" glossary_name ${newglossary} ) STRING(REGEX REPLACE "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}" "${LATEX_TARGET}.\\2" glossary_log ${newglossary} ) STRING(REGEX REPLACE "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}" "${LATEX_TARGET}.\\3" glossary_out ${newglossary} ) STRING(REGEX REPLACE "@newglossary[ \t]*{([^}]*)}{([^}]*)}{([^}]*)}{([^}]*)}" "${LATEX_TARGET}.\\4" glossary_in ${newglossary} ) IF (use_xindy) LATEX_FILE_MATCH(xdylanguage_line ${aux_file} "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}" "@xdylanguage{${glossary_name}}{english}" ) STRING(REGEX REPLACE "@xdylanguage[ \t]*{${glossary_name}}{([^}]*)}" "\\1" language ${xdylanguage_line} ) # What crazy person makes a LaTeX index generater that uses different # identifiers for language than babel (or at least does not support # the old ones)? IF (${language} STREQUAL "frenchb") SET(language "french") ELSEIF (${language} MATCHES "^n?germanb?$") SET(language "german") ELSEIF (${language} STREQUAL "magyar") SET(language "hungarian") ELSEIF (${language} STREQUAL "lsorbian") SET(language "lower-sorbian") ELSEIF (${language} STREQUAL "norsk") SET(language "norwegian") ELSEIF (${language} STREQUAL "portuges") SET(language "portuguese") ELSEIF (${language} STREQUAL "russianb") SET(language "russian") ELSEIF (${language} STREQUAL "slovene") SET(language "slovenian") ELSEIF (${language} STREQUAL "ukraineb") SET(language "ukrainian") ELSEIF (${language} STREQUAL "usorbian") SET(language "upper-sorbian") ENDIF (${language} STREQUAL "frenchb") IF (language) SET(language_flags "-L ${language}") ELSE (language) SET(language_flags "") ENDIF (language) LATEX_FILE_MATCH(codepage_line ${aux_file} "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}" "@gls@codepage{${glossary_name}}{utf}" ) STRING(REGEX REPLACE "@gls@codepage[ \t]*{${glossary_name}}{([^}]*)}" "\\1" codepage ${codepage_line} ) IF (codepage) SET(codepage_flags "-C ${codepage}") ELSE (codepage) # Ideally, we would check that the language is compatible with the # default codepage, but I'm hoping that distributions will be smart # enough to specify their own codepage. I know, it's asking a lot. SET(codepage_flags "") ENDIF (codepage) MESSAGE("${XINDY_COMPILER} ${MAKEGLOSSARIES_COMPILER_FLAGS} ${language_flags} ${codepage_flags} -I xindy -M ${glossary_name} -t ${glossary_log} -o ${glossary_out} ${glossary_in}" ) EXEC_PROGRAM(${XINDY_COMPILER} ARGS ${MAKEGLOSSARIES_COMPILER_FLAGS} ${language_flags} ${codepage_flags} -I xindy -M ${glossary_name} -t ${glossary_log} -o ${glossary_out} ${glossary_in} OUTPUT_VARIABLE xindy_output ) MESSAGE("${xindy_output}") # So, it is possible (perhaps common?) for aux files to specify a # language and codepage that are incompatible with each other. Check # for that condition, and if it happens run again with the default # codepage. IF ("${xindy_output}" MATCHES "^Cannot locate xindy module for language (.+) in codepage (.+)\\.$") MESSAGE("*************** Retrying xindy with default codepage.") EXEC_PROGRAM(${XINDY_COMPILER} ARGS ${MAKEGLOSSARIES_COMPILER_FLAGS} ${language_flags} -I xindy -M ${glossary_name} -t ${glossary_log} -o ${glossary_out} ${glossary_in} ) ENDIF ("${xindy_output}" MATCHES "^Cannot locate xindy module for language (.+) in codepage (.+)\\.$") #ENDIF ("${xindy_output}" MATCHES "Cannot locate xindy module for language (.+) in codepage (.+)\\.") ELSE (use_xindy) MESSAGE("${MAKEINDEX_COMPILER} ${MAKEGLOSSARIES_COMPILER_FLAGS} -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in}") EXEC_PROGRAM(${MAKEINDEX_COMPILER} ARGS ${MAKEGLOSSARIES_COMPILER_FLAGS} -s ${istfile} -t ${glossary_log} -o ${glossary_out} ${glossary_in} ) ENDIF (use_xindy) ENDFOREACH(newglossary) ENDMACRO(LATEX_MAKEGLOSSARIES) MACRO(LATEX_MAKENOMENCLATURE) MESSAGE("**************************** In makenomenclature") IF (NOT LATEX_TARGET) MESSAGE(SEND_ERROR "Need to define LATEX_TARGET") ENDIF (NOT LATEX_TARGET) IF (NOT MAKEINDEX_COMPILER) MESSAGE(SEND_ERROR "Need to define MAKEINDEX_COMPILER") ENDIF (NOT MAKEINDEX_COMPILER) SET(nomencl_out ${LATEX_TARGET}.nls) SET(nomencl_in ${LATEX_TARGET}.nlo) EXEC_PROGRAM(${MAKEINDEX_COMPILER} ARGS ${MAKENOMENCLATURE_COMPILER_FLAGS} ${nomencl_in} -s "nomencl.ist" -o ${nomencl_out} ) ENDMACRO(LATEX_MAKENOMENCLATURE) MACRO(LATEX_CORRECT_SYNCTEX) MESSAGE("**************************** In correct SyncTeX") IF (NOT LATEX_TARGET) MESSAGE(SEND_ERROR "Need to define LATEX_TARGET") ENDIF (NOT LATEX_TARGET) IF (NOT GZIP) MESSAGE(SEND_ERROR "Need to define GZIP") ENDIF (NOT GZIP) IF (NOT LATEX_SOURCE_DIRECTORY) MESSAGE(SEND_ERROR "Need to define LATEX_SOURCE_DIRECTORY") ENDIF (NOT LATEX_SOURCE_DIRECTORY) IF (NOT LATEX_BINARY_DIRECTORY) MESSAGE(SEND_ERROR "Need to define LATEX_BINARY_DIRECTORY") ENDIF (NOT LATEX_BINARY_DIRECTORY) SET(synctex_file ${LATEX_BINARY_DIRECTORY}/${LATEX_TARGET}.synctex) SET(synctex_file_gz ${synctex_file}.gz) IF (EXISTS ${synctex_file_gz}) MESSAGE("Making backup of synctex file.") CONFIGURE_FILE(${synctex_file_gz} ${synctex_file}.bak.gz COPYONLY) MESSAGE("Uncompressing synctex file.") EXEC_PROGRAM(${GZIP} ARGS --decompress ${synctex_file_gz} ) MESSAGE("Reading synctex file.") FILE(READ ${synctex_file} synctex_data) MESSAGE("Replacing relative with absolute paths.") STRING(REGEX REPLACE "(Input:[0-9]+:)([^/\n][^\n]*)" "\\1${LATEX_SOURCE_DIRECTORY}/\\2" synctex_data "${synctex_data}" ) MESSAGE("Writing synctex file.") FILE(WRITE ${synctex_file} "${synctex_data}") MESSAGE("Compressing synctex file.") EXEC_PROGRAM(${GZIP} ARGS ${synctex_file} ) ELSE (EXISTS ${synctex_file_gz}) MESSAGE(SEND_ERROR "File ${synctex_file_gz} not found. Perhaps synctex is not supported by your LaTeX compiler.") ENDIF (EXISTS ${synctex_file_gz}) ENDMACRO(LATEX_CORRECT_SYNCTEX) ############################################################################# # Helper macros for establishing LaTeX build. ############################################################################# MACRO(LATEX_NEEDIT VAR NAME) IF (NOT ${VAR}) MESSAGE(SEND_ERROR "I need the ${NAME} command.") ENDIF(NOT ${VAR}) ENDMACRO(LATEX_NEEDIT) MACRO(LATEX_WANTIT VAR NAME) IF (NOT ${VAR}) MESSAGE(STATUS "I could not find the ${NAME} command.") ENDIF(NOT ${VAR}) ENDMACRO(LATEX_WANTIT) MACRO(LATEX_SETUP_VARIABLES) SET(LATEX_OUTPUT_PATH "${LATEX_OUTPUT_PATH}" CACHE PATH "If non empty, specifies the location to place LaTeX output." ) FIND_PACKAGE(LATEX) FIND_PROGRAM(XINDY_COMPILER NAME xindy PATHS ${MIKTEX_BINARY_PATH} /usr/bin ) FIND_PACKAGE(UnixCommands) MARK_AS_ADVANCED(CLEAR LATEX_COMPILER PDFLATEX_COMPILER BIBTEX_COMPILER MAKEINDEX_COMPILER XINDY_COMPILER DVIPS_CONVERTER PS2PDF_CONVERTER LATEX2HTML_CONVERTER ) LATEX_NEEDIT(LATEX_COMPILER latex) LATEX_WANTIT(PDFLATEX_COMPILER pdflatex) LATEX_NEEDIT(BIBTEX_COMPILER bibtex) LATEX_NEEDIT(MAKEINDEX_COMPILER makeindex) LATEX_WANTIT(DVIPS_CONVERTER dvips) LATEX_WANTIT(PS2PDF_CONVERTER ps2pdf) LATEX_WANTIT(LATEX2HTML_CONVERTER latex2html) SET(LATEX_COMPILER_FLAGS "-interaction=nonstopmode" CACHE STRING "Flags passed to latex.") SET(PDFLATEX_COMPILER_FLAGS ${LATEX_COMPILER_FLAGS} CACHE STRING "Flags passed to pdflatex.") SET(LATEX_SYNCTEX_FLAGS "-synctex=1" CACHE STRING "latex/pdflatex flags used to create synctex file.") SET(BIBTEX_COMPILER_FLAGS "" CACHE STRING "Flags passed to bibtex.") SET(MAKEINDEX_COMPILER_FLAGS "" CACHE STRING "Flags passed to makeindex.") SET(MAKEGLOSSARIES_COMPILER_FLAGS "" CACHE STRING "Flags passed to makeglossaries.") SET(MAKENOMENCLATURE_COMPILER_FLAGS "" CACHE STRING "Flags passed to makenomenclature.") SET(DVIPS_CONVERTER_FLAGS "-Ppdf -G0 -t letter" CACHE STRING "Flags passed to dvips.") SET(PS2PDF_CONVERTER_FLAGS "-dMaxSubsetPct=100 -dCompatibilityLevel=1.3 -dSubsetFonts=true -dEmbedAllFonts=true -dAutoFilterColorImages=false -dAutoFilterGrayImages=false -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -dMonoImageFilter=/FlateEncode" CACHE STRING "Flags passed to ps2pdf.") SET(LATEX2HTML_CONVERTER_FLAGS "" CACHE STRING "Flags passed to latex2html.") MARK_AS_ADVANCED( LATEX_COMPILER_FLAGS PDFLATEX_COMPILER_FLAGS LATEX_SYNCTEX_FLAGS BIBTEX_COMPILER_FLAGS MAKEINDEX_COMPILER_FLAGS MAKEGLOSSARIES_COMPILER_FLAGS MAKENOMENCLATURE_COMPILER_FLAGS DVIPS_CONVERTER_FLAGS PS2PDF_CONVERTER_FLAGS LATEX2HTML_CONVERTER_FLAGS ) SEPARATE_ARGUMENTS(LATEX_COMPILER_FLAGS) SEPARATE_ARGUMENTS(PDFLATEX_COMPILER_FLAGS) SEPARATE_ARGUMENTS(LATEX_SYNCTEX_FLAGS) SEPARATE_ARGUMENTS(BIBTEX_COMPILER_FLAGS) SEPARATE_ARGUMENTS(MAKEINDEX_COMPILER_FLAGS) SEPARATE_ARGUMENTS(MAKEGLOSSARIES_COMPILER_FLAGS) SEPARATE_ARGUMENTS(MAKENOMENCLATURE_COMPILER_FLAGS) SEPARATE_ARGUMENTS(DVIPS_CONVERTER_FLAGS) SEPARATE_ARGUMENTS(PS2PDF_CONVERTER_FLAGS) SEPARATE_ARGUMENTS(LATEX2HTML_CONVERTER_FLAGS) FIND_PROGRAM(IMAGEMAGICK_CONVERT convert DOC "The convert program that comes with ImageMagick (available at http://www.imagemagick.org)." ) IF (NOT IMAGEMAGICK_CONVERT) MESSAGE(SEND_ERROR "Could not find convert program. Please download ImageMagick from http://www.imagemagick.org and install.") ENDIF (NOT IMAGEMAGICK_CONVERT) OPTION(LATEX_USE_SYNCTEX "If on, have LaTeX generate a synctex file, which WYSIWYG editors can use to correlate output files like dvi and pdf with the lines of LaTeX source that generates them. In addition to adding the LATEX_SYNCTEX_FLAGS to the command line, this option also adds build commands that \"corrects\" the resulting synctex file to point to the original LaTeX files rather than those generated by UseLATEX.cmake." OFF ) OPTION(LATEX_SMALL_IMAGES "If on, the raster images will be converted to 1/6 the original size. This is because papers usually require 600 dpi images whereas most monitors only require at most 96 dpi. Thus, smaller images make smaller files for web distributation and can make it faster to read dvi files." OFF) IF (LATEX_SMALL_IMAGES) SET(LATEX_RASTER_SCALE 16) SET(LATEX_OPPOSITE_RASTER_SCALE 100) ELSE (LATEX_SMALL_IMAGES) SET(LATEX_RASTER_SCALE 100) SET(LATEX_OPPOSITE_RASTER_SCALE 16) ENDIF (LATEX_SMALL_IMAGES) # Just holds extensions for known image types. They should all be lower case. SET(LATEX_DVI_VECTOR_IMAGE_EXTENSIONS .eps) SET(LATEX_DVI_RASTER_IMAGE_EXTENSIONS) SET(LATEX_DVI_IMAGE_EXTENSIONS ${LATEX_DVI_VECTOR_IMAGE_EXTENSIONS} ${LATEX_DVI_RASTER_IMAGE_EXTENSIONS}) SET(LATEX_PDF_VECTOR_IMAGE_EXTENSIONS .pdf) SET(LATEX_PDF_RASTER_IMAGE_EXTENSIONS .png .jpeg .jpg) SET(LATEX_PDF_IMAGE_EXTENSIONS ${LATEX_PDF_VECTOR_IMAGE_EXTENSIONS} ${LATEX_PDF_RASTER_IMAGE_EXTENSIONS}) SET(LATEX_IMAGE_EXTENSIONS ${LATEX_DVI_IMAGE_EXTENSIONS} ${LATEX_PDF_IMAGE_EXTENSIONS}) ENDMACRO(LATEX_SETUP_VARIABLES) MACRO(LATEX_GET_OUTPUT_PATH var) SET(${var}) IF (LATEX_OUTPUT_PATH) IF ("${LATEX_OUTPUT_PATH}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") MESSAGE(SEND_ERROR "You cannot set LATEX_OUTPUT_PATH to the same directory that contains LaTeX input files.") ELSE ("${LATEX_OUTPUT_PATH}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") SET(${var} "${LATEX_OUTPUT_PATH}") ENDIF ("${LATEX_OUTPUT_PATH}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") ELSE (LATEX_OUTPUT_PATH) IF ("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") MESSAGE(SEND_ERROR "LaTeX files must be built out of source or you must set LATEX_OUTPUT_PATH.") ELSE ("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") SET(${var} "${CMAKE_CURRENT_BINARY_DIR}") ENDIF ("${CMAKE_CURRENT_BINARY_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}") ENDIF (LATEX_OUTPUT_PATH) ENDMACRO(LATEX_GET_OUTPUT_PATH) MACRO(LATEX_ADD_CONVERT_COMMAND output_path input_path output_extension input_extension flags) SET (converter ${IMAGEMAGICK_CONVERT}) SET (convert_flags "") # ImageMagick has broken eps to pdf conversion # use ps2pdf instead IF (${input_extension} STREQUAL ".eps" AND ${output_extension} STREQUAL ".pdf") IF (PS2PDF_CONVERTER) SET (converter ${PS2PDF_CONVERTER}) SET (convert_flags -dEPSCrop ${PS2PDF_CONVERTER_FLAGS}) ELSE (PS2PDF_CONVERTER) MESSAGE(SEND_ERROR "Using postscript files with pdflatex requires ps2pdf for conversion.") ENDIF (PS2PDF_CONVERTER) ELSE (${input_extension} STREQUAL ".eps" AND ${output_extension} STREQUAL ".pdf") SET (convert_flags ${flags}) ENDIF (${input_extension} STREQUAL ".eps" AND ${output_extension} STREQUAL ".pdf") ADD_CUSTOM_COMMAND(OUTPUT ${output_path} COMMAND ${converter} ARGS ${convert_flags} ${input_path} ${output_path} DEPENDS ${input_path} ) ENDMACRO(LATEX_ADD_CONVERT_COMMAND) # Makes custom commands to convert a file to a particular type. MACRO(LATEX_CONVERT_IMAGE output_files input_file output_extension convert_flags output_extensions other_files) SET(input_dir ${CMAKE_CURRENT_SOURCE_DIR}) LATEX_GET_OUTPUT_PATH(output_dir) GET_FILENAME_COMPONENT(extension "${input_file}" EXT) STRING(REGEX REPLACE "\\.[^.]*\$" ${output_extension} output_file "${input_file}") LATEX_LIST_CONTAINS(is_type ${extension} ${output_extensions}) IF (is_type) IF (convert_flags) LATEX_ADD_CONVERT_COMMAND(${output_dir}/${output_file} ${input_dir}/${input_file} ${output_extension} ${extension} "${convert_flags}") SET(${output_files} ${${output_files}} ${output_dir}/${output_file}) ELSE (convert_flags) # As a shortcut, we can just copy the file. ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${input_file} COMMAND ${CMAKE_COMMAND} ARGS -E copy ${input_dir}/${input_file} ${output_dir}/${input_file} DEPENDS ${input_dir}/${input_file} ) SET(${output_files} ${${output_files}} ${output_dir}/${input_file}) ENDIF (convert_flags) ELSE (is_type) SET(do_convert TRUE) # Check to see if there is another input file of the appropriate type. FOREACH(valid_extension ${output_extensions}) STRING(REGEX REPLACE "\\.[^.]*\$" ${output_extension} try_file "${input_file}") LATEX_LIST_CONTAINS(has_native_file "${try_file}" ${other_files}) IF (has_native_file) SET(do_convert FALSE) ENDIF (has_native_file) ENDFOREACH(valid_extension) # If we still need to convert, do it. IF (do_convert) LATEX_ADD_CONVERT_COMMAND(${output_dir}/${output_file} ${input_dir}/${input_file} ${output_extension} ${extension} "${convert_flags}") SET(${output_files} ${${output_files}} ${output_dir}/${output_file}) ENDIF (do_convert) ENDIF (is_type) ENDMACRO(LATEX_CONVERT_IMAGE) # Adds custom commands to process the given files for dvi and pdf builds. # Adds the output files to the given variables (does not replace). MACRO(LATEX_PROCESS_IMAGES dvi_outputs pdf_outputs) LATEX_GET_OUTPUT_PATH(output_dir) FOREACH(file ${ARGN}) IF (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${file}") GET_FILENAME_COMPONENT(extension "${file}" EXT) SET(convert_flags) # Check to see if we need to downsample the image. LATEX_LIST_CONTAINS(is_raster extension ${LATEX_DVI_RASTER_IMAGE_EXTENSIONS} ${LATEX_PDF_RASTER_IMAGE_EXTENSIONS}) IF (LATEX_SMALL_IMAGES) IF (is_raster) SET(convert_flags -resize ${LATEX_RASTER_SCALE}%) ENDIF (is_raster) ENDIF (LATEX_SMALL_IMAGES) # Make sure the output directory exists. GET_FILENAME_COMPONENT(path "${output_dir}/${file}" PATH) MAKE_DIRECTORY("${path}") # Do conversions for dvi. LATEX_CONVERT_IMAGE(${dvi_outputs} "${file}" .eps "${convert_flags}" "${LATEX_DVI_IMAGE_EXTENSIONS}" "${ARGN}") # Do conversions for pdf. IF (is_raster) LATEX_CONVERT_IMAGE(${pdf_outputs} "${file}" .png "${convert_flags}" "${LATEX_PDF_IMAGE_EXTENSIONS}" "${ARGN}") ELSE (is_raster) LATEX_CONVERT_IMAGE(${pdf_outputs} "${file}" .pdf "${convert_flags}" "${LATEX_PDF_IMAGE_EXTENSIONS}" "${ARGN}") ENDIF (is_raster) ELSE (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${file}") MESSAGE(WARNING "Could not find file ${CMAKE_CURRENT_SOURCE_DIR}/${file}. Are you sure you gave relative paths to IMAGES?") ENDIF (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${file}") ENDFOREACH(file) ENDMACRO(LATEX_PROCESS_IMAGES) MACRO(ADD_LATEX_IMAGES) MESSAGE("The ADD_LATEX_IMAGES macro is deprecated. Image directories are specified with LATEX_ADD_DOCUMENT.") ENDMACRO(ADD_LATEX_IMAGES) MACRO(LATEX_COPY_GLOBBED_FILES pattern dest) FILE(GLOB file_list ${pattern}) FOREACH(in_file ${file_list}) GET_FILENAME_COMPONENT(out_file ${in_file} NAME) CONFIGURE_FILE(${in_file} ${dest}/${out_file} COPYONLY) ENDFOREACH(in_file) ENDMACRO(LATEX_COPY_GLOBBED_FILES) MACRO(LATEX_COPY_INPUT_FILE file) LATEX_GET_OUTPUT_PATH(output_dir) IF (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}) GET_FILENAME_COMPONENT(path ${file} PATH) FILE(MAKE_DIRECTORY ${output_dir}/${path}) LATEX_LIST_CONTAINS(use_config ${file} ${LATEX_CONFIGURE}) IF (use_config) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file} ${output_dir}/${file} @ONLY ) ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${file} COMMAND ${CMAKE_COMMAND} ARGS ${CMAKE_BINARY_DIR} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${file} ) ELSE (use_config) ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${file} COMMAND ${CMAKE_COMMAND} ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${file} ${output_dir}/${file} DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${file} ) ENDIF (use_config) ELSE (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}) IF (EXISTS ${output_dir}/${file}) # Special case: output exists but input does not. Assume that it was # created elsewhere and skip the input file copy. ELSE (EXISTS ${output_dir}/${file}) MESSAGE("Could not find input file ${CMAKE_CURRENT_SOURCE_DIR}/${file}") ENDIF (EXISTS ${output_dir}/${file}) ENDIF (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${file}) ENDMACRO(LATEX_COPY_INPUT_FILE) ############################################################################# # Commands provided by the UseLATEX.cmake "package" ############################################################################# MACRO(LATEX_USAGE command message) MESSAGE(SEND_ERROR "${message}\nUsage: ${command}(\n [BIBFILES ...]\n [INPUTS ...]\n [IMAGE_DIRS ...]\n [IMAGES \n [CONFIGURE ...]\n [DEPENDS ...]\n [USE_INDEX] [USE_GLOSSARY] [USE_NOMENCL]\n [DEFAULT_PDF] [DEFAULT_SAFEPDF]\n [MANGLE_TARGET_NAMES])" ) ENDMACRO(LATEX_USAGE command message) # Parses arguments to ADD_LATEX_DOCUMENT and ADD_LATEX_TARGETS and sets the # variables LATEX_TARGET, LATEX_IMAGE_DIR, LATEX_BIBFILES, LATEX_DEPENDS, and # LATEX_INPUTS. MACRO(PARSE_ADD_LATEX_ARGUMENTS command) LATEX_PARSE_ARGUMENTS( LATEX "BIBFILES;INPUTS;IMAGE_DIRS;IMAGES;CONFIGURE;DEPENDS" "USE_INDEX;USE_GLOSSARY;USE_GLOSSARIES;USE_NOMENCL;DEFAULT_PDF;DEFAULT_SAFEPDF;MANGLE_TARGET_NAMES" ${ARGN} ) # The first argument is the target latex file. IF (LATEX_DEFAULT_ARGS) LATEX_CAR(LATEX_MAIN_INPUT ${LATEX_DEFAULT_ARGS}) LATEX_CDR(LATEX_DEFAULT_ARGS ${LATEX_DEFAULT_ARGS}) GET_FILENAME_COMPONENT(LATEX_TARGET ${LATEX_MAIN_INPUT} NAME_WE) ELSE (LATEX_DEFAULT_ARGS) LATEX_USAGE(${command} "No tex file target given to ${command}.") ENDIF (LATEX_DEFAULT_ARGS) IF (LATEX_DEFAULT_ARGS) LATEX_USAGE(${command} "Invalid or depricated arguments: ${LATEX_DEFAULT_ARGS}") ENDIF (LATEX_DEFAULT_ARGS) # Backward compatibility between 1.6.0 and 1.6.1. IF (LATEX_USE_GLOSSARIES) SET(LATEX_USE_GLOSSARY TRUE) ENDIF (LATEX_USE_GLOSSARIES) ENDMACRO(PARSE_ADD_LATEX_ARGUMENTS) MACRO(ADD_LATEX_TARGETS) LATEX_GET_OUTPUT_PATH(output_dir) PARSE_ADD_LATEX_ARGUMENTS(ADD_LATEX_TARGETS ${ARGV}) IF (LATEX_USE_SYNCTEX) SET(synctex_flags ${LATEX_SYNCTEX_FLAGS}) ELSE (LATEX_USE_SYNCTEX) SET(synctex_flags) ENDIF (LATEX_USE_SYNCTEX) # The commands to run LaTeX. They are repeated multiple times. SET(latex_build_command ${LATEX_COMPILER} ${LATEX_COMPILER_FLAGS} ${synctex_flags} ${LATEX_MAIN_INPUT} ) SET(pdflatex_build_command ${PDFLATEX_COMPILER} ${PDFLATEX_COMPILER_FLAGS} ${synctex_flags} ${LATEX_MAIN_INPUT} ) # Set up target names. IF (LATEX_MANGLE_TARGET_NAMES) SET(dvi_target ${LATEX_TARGET}_dvi) SET(pdf_target ${LATEX_TARGET}_pdf) SET(ps_target ${LATEX_TARGET}_ps) SET(safepdf_target ${LATEX_TARGET}_safepdf) SET(html_target ${LATEX_TARGET}_html) SET(auxclean_target ${LATEX_TARGET}_auxclean) ELSE (LATEX_MANGLE_TARGET_NAMES) SET(dvi_target dvi) SET(pdf_target pdf) SET(ps_target ps) SET(safepdf_target safepdf) SET(html_target html) SET(auxclean_target auxclean) ENDIF (LATEX_MANGLE_TARGET_NAMES) # Probably not all of these will be generated, but they could be. # Note that the aux file is added later. SET(auxiliary_clean_files ${output_dir}/${LATEX_TARGET}.bbl ${output_dir}/${LATEX_TARGET}.blg ${output_dir}/${LATEX_TARGET}-blx.bib ${output_dir}/${LATEX_TARGET}.glg ${output_dir}/${LATEX_TARGET}.glo ${output_dir}/${LATEX_TARGET}.gls ${output_dir}/${LATEX_TARGET}.idx ${output_dir}/${LATEX_TARGET}.ilg ${output_dir}/${LATEX_TARGET}.ind ${output_dir}/${LATEX_TARGET}.ist ${output_dir}/${LATEX_TARGET}.log ${output_dir}/${LATEX_TARGET}.out ${output_dir}/${LATEX_TARGET}.toc ${output_dir}/${LATEX_TARGET}.lof ${output_dir}/${LATEX_TARGET}.xdy ${output_dir}/${LATEX_TARGET}.synctex.gz ${output_dir}/${LATEX_TARGET}.synctex.bak.gz ${output_dir}/${LATEX_TARGET}.dvi ${output_dir}/${LATEX_TARGET}.ps ${output_dir}/${LATEX_TARGET}.pdf ) # For each directory in LATEX_IMAGE_DIRS, glob all the image files and # place them in LATEX_IMAGES. FOREACH(dir ${LATEX_IMAGE_DIRS}) FOREACH(extension ${LATEX_IMAGE_EXTENSIONS}) IF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${dir}) MESSAGE(WARNING "Image directory ${CMAKE_CURRENT_SOURCE_DIR}/${dir} does not exist. Are you sure you gave relative directories to IMAGE_DIRS?") ENDIF (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${dir}) FILE(GLOB files ${CMAKE_CURRENT_SOURCE_DIR}/${dir}/*${extension}) FOREACH(file ${files}) GET_FILENAME_COMPONENT(filename ${file} NAME) SET(LATEX_IMAGES ${LATEX_IMAGES} ${dir}/${filename}) ENDFOREACH(file) ENDFOREACH(extension) ENDFOREACH(dir) SET(dvi_images) SET(pdf_images) LATEX_PROCESS_IMAGES(dvi_images pdf_images ${LATEX_IMAGES}) SET(make_dvi_command ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command}) SET(make_pdf_command ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command} ) SET(make_dvi_depends ${LATEX_DEPENDS} ${dvi_images}) SET(make_pdf_depends ${LATEX_DEPENDS} ${pdf_images}) FOREACH(input ${LATEX_MAIN_INPUT} ${LATEX_INPUTS}) SET(make_dvi_depends ${make_dvi_depends} ${output_dir}/${input}) SET(make_pdf_depends ${make_pdf_depends} ${output_dir}/${input}) IF (${input} MATCHES "\\.tex$") STRING(REGEX REPLACE "\\.tex$" "" input_we ${input}) SET(auxiliary_clean_files ${auxiliary_clean_files} ${output_dir}/${input_we}.aux ${output_dir}/${input}.aux ) ENDIF (${input} MATCHES "\\.tex$") ENDFOREACH(input) IF (LATEX_USE_GLOSSARY) FOREACH(dummy 0 1) # Repeat these commands twice. SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=makeglossaries -D LATEX_TARGET=${LATEX_TARGET} -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER} -D XINDY_COMPILER=${XINDY_COMPILER} -D MAKEGLOSSARIES_COMPILER_FLAGS=${MAKEGLOSSARIES_COMPILER_FLAGS} -P ${LATEX_USE_LATEX_LOCATION} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command} ) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=makeglossaries -D LATEX_TARGET=${LATEX_TARGET} -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER} -D XINDY_COMPILER=${XINDY_COMPILER} -D MAKEGLOSSARIES_COMPILER_FLAGS=${MAKEGLOSSARIES_COMPILER_FLAGS} -P ${LATEX_USE_LATEX_LOCATION} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command} ) ENDFOREACH(dummy) ENDIF (LATEX_USE_GLOSSARY) IF (LATEX_USE_NOMENCL) FOREACH(dummy 0 1) # Repeat these commands twice. SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=makenomenclature -D LATEX_TARGET=${LATEX_TARGET} -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER} -D MAKENOMENCLATURE_COMPILER_FLAGS=${MAKENOMENCLATURE_COMPILER_FLAGS} -P ${LATEX_USE_LATEX_LOCATION} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command} ) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=makenomenclature -D LATEX_TARGET=${LATEX_TARGET} -D MAKEINDEX_COMPILER=${MAKEINDEX_COMPILER} -D MAKENOMENCLATURE_COMPILER_FLAGS=${MAKENOMENCLATURE_COMPILER_FLAGS} -P ${LATEX_USE_LATEX_LOCATION} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command} ) ENDFOREACH(dummy) ENDIF (LATEX_USE_NOMENCL) IF (LATEX_BIBFILES) SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${BIBTEX_COMPILER} ${BIBTEX_COMPILER_FLAGS} ${LATEX_TARGET}) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${BIBTEX_COMPILER} ${BIBTEX_COMPILER_FLAGS} ${LATEX_TARGET}) FOREACH (bibfile ${LATEX_BIBFILES}) SET(make_dvi_depends ${make_dvi_depends} ${output_dir}/${bibfile}) SET(make_pdf_depends ${make_pdf_depends} ${output_dir}/${bibfile}) ENDFOREACH (bibfile ${LATEX_BIBFILES}) ENDIF (LATEX_BIBFILES) IF (LATEX_USE_INDEX) SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${MAKEINDEX_COMPILER} ${MAKEINDEX_COMPILER_FLAGS} ${LATEX_TARGET}.idx) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${MAKEINDEX_COMPILER} ${MAKEINDEX_COMPILER_FLAGS} ${LATEX_TARGET}.idx) ENDIF (LATEX_USE_INDEX) SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${latex_build_command}) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command} COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${pdflatex_build_command}) IF (LATEX_USE_SYNCTEX) IF (NOT GZIP) MESSAGE(SEND_ERROR "UseLATEX.cmake: USE_SYNTEX option requires gzip program. Set GZIP variable.") ENDIF (NOT GZIP) SET(make_dvi_command ${make_dvi_command} COMMAND ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=correct_synctex -D LATEX_TARGET=${LATEX_TARGET} -D GZIP=${GZIP} -D "LATEX_SOURCE_DIRECTORY=${CMAKE_CURRENT_SOURCE_DIR}" -D "LATEX_BINARY_DIRECTORY=${output_dir}" -P ${LATEX_USE_LATEX_LOCATION} ) SET(make_pdf_command ${make_pdf_command} COMMAND ${CMAKE_COMMAND} -D LATEX_BUILD_COMMAND=correct_synctex -D LATEX_TARGET=${LATEX_TARGET} -D GZIP=${GZIP} -D "LATEX_SOURCE_DIRECTORY=${CMAKE_CURRENT_SOURCE_DIR}" -D "LATEX_BINARY_DIRECTORY=${output_dir}" -P ${LATEX_USE_LATEX_LOCATION} ) ENDIF (LATEX_USE_SYNCTEX) # Add commands and targets for building dvi outputs. ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${LATEX_TARGET}.dvi COMMAND ${make_dvi_command} DEPENDS ${make_dvi_depends} ) IF (LATEX_DEFAULT_PDF OR LATEX_DEFAULT_SAFEPDF) ADD_CUSTOM_TARGET(${dvi_target} DEPENDS ${output_dir}/${LATEX_TARGET}.dvi) ELSE (LATEX_DEFAULT_PDF OR LATEX_DEFAULT_SAFEPDF) ADD_CUSTOM_TARGET(${dvi_target} ALL DEPENDS ${output_dir}/${LATEX_TARGET}.dvi) ENDIF (LATEX_DEFAULT_PDF OR LATEX_DEFAULT_SAFEPDF) # Add commands and targets for building pdf outputs (with pdflatex). IF (PDFLATEX_COMPILER) ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${LATEX_TARGET}.pdf COMMAND ${make_pdf_command} DEPENDS ${make_pdf_depends} ) IF (LATEX_DEFAULT_PDF) ADD_CUSTOM_TARGET(${pdf_target} ALL DEPENDS ${output_dir}/${LATEX_TARGET}.pdf) ELSE (LATEX_DEFAULT_PDF) ADD_CUSTOM_TARGET(${pdf_target} DEPENDS ${output_dir}/${LATEX_TARGET}.pdf) ENDIF (LATEX_DEFAULT_PDF) ENDIF (PDFLATEX_COMPILER) IF (DVIPS_CONVERTER) ADD_CUSTOM_COMMAND(OUTPUT ${output_dir}/${LATEX_TARGET}.ps COMMAND ${CMAKE_COMMAND} -E chdir ${output_dir} ${DVIPS_CONVERTER} ${DVIPS_CONVERTER_FLAGS} -o ${LATEX_TARGET}.ps ${LATEX_TARGET}.dvi DEPENDS ${output_dir}/${LATEX_TARGET}.dvi) ADD_CUSTOM_TARGET(${ps_target} DEPENDS ${output_dir}/${LATEX_TARGET}.ps) IF (PS2PDF_CONVERTER) # Since both the pdf and safepdf targets have the same output, we # cannot properly do the dependencies for both. When selecting safepdf, # simply force a recompile every time. IF (LATEX_DEFAULT_SAFEPDF) ADD_CUSTOM_TARGET(${safepdf_target} ALL ${CMAKE_COMMAND} -E chdir ${output_dir} ${PS2PDF_CONVERTER} ${PS2PDF_CONVERTER_FLAGS} ${LATEX_TARGET}.ps ${LATEX_TARGET}.pdf ) ELSE (LATEX_DEFAULT_SAFEPDF) ADD_CUSTOM_TARGET(${safepdf_target} ${CMAKE_COMMAND} -E chdir ${output_dir} ${PS2PDF_CONVERTER} ${PS2PDF_CONVERTER_FLAGS} ${LATEX_TARGET}.ps ${LATEX_TARGET}.pdf ) ENDIF (LATEX_DEFAULT_SAFEPDF) ADD_DEPENDENCIES(${safepdf_target} ${ps_target}) ENDIF (PS2PDF_CONVERTER) ENDIF (DVIPS_CONVERTER) IF (LATEX2HTML_CONVERTER) ADD_CUSTOM_TARGET(${html_target} ${CMAKE_COMMAND} -E chdir ${output_dir} ${LATEX2HTML_CONVERTER} ${LATEX2HTML_CONVERTER_FLAGS} ${LATEX_MAIN_INPUT} ) ADD_DEPENDENCIES(${html_target} ${LATEX_MAIN_INPUT} ${LATEX_INPUTS}) ENDIF (LATEX2HTML_CONVERTER) SET_DIRECTORY_PROPERTIES(. ADDITIONAL_MAKE_CLEAN_FILES "${auxiliary_clean_files}" ) ADD_CUSTOM_TARGET(${auxclean_target} COMMENT "Cleaning auxiliary LaTeX files." COMMAND ${CMAKE_COMMAND} -E remove ${auxiliary_clean_files} ) ENDMACRO(ADD_LATEX_TARGETS) MACRO(ADD_LATEX_DOCUMENT) LATEX_GET_OUTPUT_PATH(output_dir) IF (output_dir) PARSE_ADD_LATEX_ARGUMENTS(ADD_LATEX_DOCUMENT ${ARGV}) LATEX_COPY_INPUT_FILE(${LATEX_MAIN_INPUT}) FOREACH (bib_file ${LATEX_BIBFILES}) LATEX_COPY_INPUT_FILE(${bib_file}) ENDFOREACH (bib_file) FOREACH (input ${LATEX_INPUTS}) LATEX_COPY_INPUT_FILE(${input}) ENDFOREACH(input) LATEX_COPY_GLOBBED_FILES(${CMAKE_CURRENT_SOURCE_DIR}/*.cls ${output_dir}) LATEX_COPY_GLOBBED_FILES(${CMAKE_CURRENT_SOURCE_DIR}/*.bst ${output_dir}) LATEX_COPY_GLOBBED_FILES(${CMAKE_CURRENT_SOURCE_DIR}/*.clo ${output_dir}) LATEX_COPY_GLOBBED_FILES(${CMAKE_CURRENT_SOURCE_DIR}/*.sty ${output_dir}) LATEX_COPY_GLOBBED_FILES(${CMAKE_CURRENT_SOURCE_DIR}/*.ist ${output_dir}) ADD_LATEX_TARGETS(${ARGV}) ENDIF (output_dir) ENDMACRO(ADD_LATEX_DOCUMENT) ############################################################################# # Actually do stuff ############################################################################# IF (LATEX_BUILD_COMMAND) SET(command_handled) IF ("${LATEX_BUILD_COMMAND}" STREQUAL makeglossaries) LATEX_MAKEGLOSSARIES() SET(command_handled TRUE) ENDIF ("${LATEX_BUILD_COMMAND}" STREQUAL makeglossaries) IF ("${LATEX_BUILD_COMMAND}" STREQUAL makenomenclature) LATEX_MAKENOMENCLATURE() SET(command_handled TRUE) ENDIF ("${LATEX_BUILD_COMMAND}" STREQUAL makenomenclature) IF ("${LATEX_BUILD_COMMAND}" STREQUAL correct_synctex) LATEX_CORRECT_SYNCTEX() SET(command_handled TRUE) ENDIF ("${LATEX_BUILD_COMMAND}" STREQUAL correct_synctex) IF (NOT command_handled) MESSAGE(SEND_ERROR "Unknown command: ${LATEX_BUILD_COMMAND}") ENDIF (NOT command_handled) ELSE (LATEX_BUILD_COMMAND) # Must be part of the actual configure (included from CMakeLists.txt). LATEX_SETUP_VARIABLES() ENDIF (LATEX_BUILD_COMMAND) opengm-2.3.6+20160905/cmake/modules/__FindNUMPY2000066400000000000000000000101511276346362400204700ustar00rootroot00000000000000# - Find the NumPy libraries # This module finds if NumPy is installed, and sets the following variables # indicating where it is. # # TODO: Update to provide the libraries and paths for linking npymath lib. # # NUMPY_FOUND - was NumPy found # NUMPY_VERSION - the version of NumPy found as a string # NUMPY_VERSION_MAJOR - the major version number of NumPy # NUMPY_VERSION_MINOR - the minor version number of NumPy # NUMPY_VERSION_PATCH - the patch version number of NumPy # NUMPY_VERSION_DECIMAL - e.g. version 1.6.1 is 10601 # PYTHON_NUMPY_INCLUDE_DIR - path to the NumPy include files #============================================================================ # Copyright 2012 Continuum Analytics, Inc. # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # #============================================================================ # Finding NumPy involves calling the Python interpreter if(BUILD_PYTHON_WRAPPER) find_package(PythonInterp REQUIRED) else() find_package(PythonInterp) endif() if(NOT PYTHONINTERP_FOUND) set(NUMPY_FOUND FALSE) return() endif() execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-c" "import numpy as n; print(n.__version__); print(n.get_include());" RESULT_VARIABLE _NUMPY_SEARCH_SUCCESS OUTPUT_VARIABLE _NUMPY_VALUES_OUTPUT ERROR_VARIABLE _NUMPY_ERROR_VALUE OUTPUT_STRIP_TRAILING_WHITESPACE) if(NOT _NUMPY_SEARCH_SUCCESS MATCHES 0) if(NumPy_FIND_REQUIRED) message(FATAL_ERROR "NumPy import failure:\n${_NUMPY_ERROR_VALUE}") endif() set(NUMPY_FOUND FALSE) return() endif() # Convert the process output into a list string(REGEX REPLACE ";" "\\\\;" _NUMPY_VALUES ${_NUMPY_VALUES_OUTPUT}) string(REGEX REPLACE "\n" ";" _NUMPY_VALUES ${_NUMPY_VALUES}) list(GET _NUMPY_VALUES 0 NUMPY_VERSION) list(GET _NUMPY_VALUES 1 PYTHON_NUMPY_INCLUDE_DIR) string(REGEX MATCH "^[0-9]+\\.[0-9]+\\.[0-9]+" _VER_CHECK "${NUMPY_VERSION}") if("${_VER_CHECK}" STREQUAL "") # The output from Python was unexpected. Raise an error always # here, because we found NumPy, but it appears to be corrupted somehow. message(FATAL_ERROR "Requested version and include path from NumPy, got instead:\n${_NUMPY_VALUES_OUTPUT}\n") return() endif() # Make sure all directory separators are '/' string(REGEX REPLACE "\\\\" "/" PYTHON_NUMPY_INCLUDE_DIR ${PYTHON_NUMPY_INCLUDE_DIR}) # Get the major and minor version numbers string(REGEX REPLACE "\\." ";" _NUMPY_VERSION_LIST ${NUMPY_VERSION}) list(GET _NUMPY_VERSION_LIST 0 NUMPY_VERSION_MAJOR) list(GET _NUMPY_VERSION_LIST 1 NUMPY_VERSION_MINOR) list(GET _NUMPY_VERSION_LIST 2 NUMPY_VERSION_PATCH) string(REGEX MATCH "[0-9]*" NUMPY_VERSION_PATCH ${NUMPY_VERSION_PATCH}) math(EXPR NUMPY_VERSION_DECIMAL "(${NUMPY_VERSION_MAJOR} * 10000) + (${NUMPY_VERSION_MINOR} * 100) + ${NUMPY_VERSION_PATCH}") find_package_message(NUMPY "Found NumPy: version \"${NUMPY_VERSION}\" ${PYTHON_NUMPY_INCLUDE_DIR}" "${PYTHON_NUMPY_INCLUDE_DIR}${NUMPY_VERSION}") FIND_PACKAGE_HANDLE_STANDARD_ARGS( NUMPY DEFAULT_MSG PYTHON_NUMPY_INCLUDE_DIR ) set(NUMPY_FOUND TRUE) opengm-2.3.6+20160905/cmake/modules/checkHDF5usesCompression.c000066400000000000000000000001671276346362400234340ustar00rootroot00000000000000#include #if !defined(H5_SOMETHING) || !H5_SOMETHING #error "flag is not defined" #endif int main() {} opengm-2.3.6+20160905/cmake/modules/checkHDF5version.c000066400000000000000000000003321276346362400217120ustar00rootroot00000000000000#include #if defined(CHECK_VERSION) # if (H5_VERS_MAJOR < MIN_MAJOR) || \ ((H5_VERS_MAJOR == MIN_MAJOR) && (H5_VERS_MINOR < MIN_MINOR)) # error "insufficient HDF5 version" # endif #endif int main() {} opengm-2.3.6+20160905/include/000077500000000000000000000000001276346362400153515ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/000077500000000000000000000000001276346362400166365ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/config.hxx000066400000000000000000000336211276346362400206410ustar00rootroot00000000000000#ifndef CONFIG_HXX #define CONFIG_HXX #ifdef OPENGM_CONFIGFILE // include own include file with // g++ ... -DOPENGM_CONFIGFILE=path/config.hxx .... #include OPENGM_CONFIGFILE #else // OPENGM_CONFIGFILE /// \file config.cxx configuration file for OpenGM /// /// this header should be generated by cmake (from config.hxx.cmake) /// \warning if cmake is not used to configure opengm config.hxx can be wrong. /// Since this header is used to get the size of fundamental types from cmake one /// may has to corret the OPENGM_SIZE_OF_UNSIGNED_* definitions by hand or call cmake /// to configure this header. // has no typedef ? (TODO make this a option in cmake list or // find out in cmake if this define should be active or not #ifdef OPENGM_NO_TYPENAME # define typename #endif #include "opengm/utilities/metaprogramming.hxx" #define OPENGM_WORD_LENGTH sizeof(void *) #define OPENGM_SIZE_OF_BOOL 1 #define OPENGM_SIZE_OF_CHAR sizeof(char) #define OPENGM_SIZE_OF_SIGNED_CHAR sizeof(unsigned char) #define OPENGM_SIZE_OF_UNSIGNED_CHAR sizeof(unsigned char) #define OPENGM_SIZE_OF_WCHAR_T sizeof(wchar_t) #define OPENGM_SIZE_OF_SHORT sizeof(short) #define OPENGM_SIZE_OF_UNSIGNED_SHORT sizeof(unsigned short) #define OPENGM_SIZE_OF_INT sizeof(int) #define OPENGM_SIZE_OF_UNSIGNED_INT sizeof(unsigned int) #define OPENGM_SIZE_OF_LONG sizeof(long) #define OPENGM_SIZE_OF_UNSIGNED_LONG sizeof(unsigned long) #define OPENGM_SIZE_OF_LONG_LONG sizeof(long long) #define OPENGM_SIZE_OF_UNSIGNED_LONG_LONG sizeof(unsigned long long) #define OPENGM_SIZE_OF_FLOAT sizeof(float) #define OPENGM_SIZE_OF_DOUBLE sizeof(double) #define OPENGM_SIZE_OF_LONG_DOUBLE sizeof(long double) namespace opengm{ /// major version number of opengm const unsigned int VERSION_MAJOR = 2; /// minor version number of opengm const unsigned int VERSION_MINOR = 0; /// patch version number of opengm const unsigned int VERSION_PATCH = 2; /// usual factor order /// /// this size indicates how many values (usualy the variables indices /// of a factor ) can be stored on the stack. This value is only used /// in opengm::FastSequence (as second template parameter ) const size_t USUAL_MAX_FACTOR_ORDER=5; /// \var NO_DEBUG true if NDEBUG is true #ifdef NDEBUG const bool NO_DEBUG = true; #else const bool NO_DEBUG = false; #endif /// \cond HIDDEN_SYMBOLS namespace detail_types{ // structs to identify if am system // does not have a certain type struct NoCharOnSystem; struct NoUnsignedCharOnSystem; struct NoSignedCharOnSystem; struct NoWCharTOnSystem; struct NoShortOnSystem; struct NoUnsignedShortOnSystem; struct NoIntOnSystem; struct NoUnsignedIntOnSystem; struct NoLongOnSystem; struct NoUnsignedLongOnSystem; struct NoUnsignedLongLongOnSystem; struct NoLongLongOnSystem; struct NoFloatOnSystem; struct NoDoubleOnSystem; struct NoLongDoubleOnSystem; struct NoUIntTypeOnSystem; struct NoIntTypeOnSystem; struct NoFloatTypeOnSystem; struct NoUInt8OnSystem; struct NoUInt16OnSystem; struct NoUInt32OnSystem; struct NoUInt64OnSystem; struct NoInt8OnSystem; struct NoInt16OnSystem; struct NoInt32OnSystem; struct NoInt64OnSystem; struct NoFloat32OnSystem; struct NoFloat64OnSystem; struct NoFloat128OnSystem; // typedefs to types to identify if am system // does not have a certain type #ifdef OPENGM_NO_CHAR typedef opengm::meta::InvalideType Char; #else typedef char Char; #endif #ifdef OPENGM_NO_UNSIGNED_CHAR typedef opengm::meta::InvalideType UnsignedChar; #else typedef unsigned char UnsignedChar; #endif #ifdef OPENGM_NO_SIGNED_CHAR typedef opengm::meta::InvalideType SignedChar; #else typedef signed char SignedChar; #endif #ifdef OPENGM_NO_WCHAR_T typedef opengm::meta::InvalideType WCharT; #else typedef wchar_t WCharT; #endif #ifdef OPENGM_NO_SHORT typedef NoShortOnSystem Short; #else typedef short Short; #endif #ifdef OPENGM_NO_UNSIGNED_SHORT typedef opengm::meta::InvalideType UnsignedShort; #else typedef unsigned short UnsignedShort; #endif #ifdef OPENGM_NO_INT typedef opengm::meta::InvalideType Int; #else typedef int Int; #endif #ifdef OPENGM_NO_UNSIGNED_INT typedef opengm::meta::InvalideType UnsignedInt; #else typedef unsigned int UnsignedInt; #endif #ifdef OPENGM_NO_LONG typedef opengm::meta::InvalideType Long; #else typedef long Long; #endif #ifdef OPENGM_NO_UNSIGNED_LONG typedef opengm::meta::InvalideType UnsignedLong; #else typedef unsigned long UnsignedLong; #endif #ifdef OPENGM_NO_LONG_LONG typedef opengm::meta::InvalideType LongLong; #else typedef long long LongLong; #endif #ifdef OPENGM_NO_UNSIGNED_LONG typedef opengm::meta::InvalideType UnsignedLongLong; #else typedef unsigned long long UnsignedLongLong; #endif #ifdef OPENGM_NO_Float typedef opengm::meta::InvalideType Float; #else typedef float Float; #endif #ifdef OPENGM_NO_DOUBLE typedef opengm::meta::InvalideType Double; #else typedef double Double; #endif #ifdef OPENGM_NO_LONG_DOUBLE typedef opengm::meta::InvalideType LongDouble; #else typedef long double LongDouble; #endif typedef bool Bool ; // typelists of the basic c++ types // Floats: typedef opengm::meta::TypeListGenerator< Float,Double , LongDouble >::type StdFloatingPointTypesTypeList; // UInt: typedef opengm::meta::TypeListGenerator< UnsignedChar,UnsignedShort, UnsignedInt, UnsignedLong, UnsignedLongLong >::type StdUnsignedIntegerTypesTypeList; // Int: typedef opengm::meta::TypeListGenerator< Char, SignedChar, Short, Int, Long,LongLong >::type StdSignedIntegerTypesTypeList; // typelists of the sizes of the basic c++ types // Float sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT,meta::SizeT, opengm::meta::SizeT >::type StdFloatingPointSizesTypeList; // UInt sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT >::type StdUnsignedIntegerSizesTypeList; // Int sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT,opengm::meta::SizeT, opengm::meta::SizeT,opengm::meta::SizeT >::type StdSignedIntegerSizesTypeList; // platform independent // UInt : typedef opengm::meta::FindSizedType >::type UInt8Type ; typedef opengm::meta::FindSizedType >::type UInt16Type ; typedef opengm::meta::FindSizedType >::type UInt32Type ; typedef opengm::meta::FindSizedType >::type UInt64Type ; //Int : typedef opengm::meta::FindSizedType >::type Int8Type ; typedef opengm::meta::FindSizedType >::type Int16Type ; typedef opengm::meta::FindSizedType >::type Int32Type ; typedef opengm::meta::FindSizedType >::type Int64Type ; // Float : typedef opengm::meta::FindSizedType >::type Float32Type ; typedef opengm::meta::FindSizedType >::type Float64Type ; typedef opengm::meta::FindSizedType >::type Float128Type ; // opengm::meta-"switch-cases" typelists to find out the // biggest and smallest uint, int and float type typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt64Type >::value >::value ,UInt64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt32Type >::value >::value ,UInt32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt16Type >::value >::value ,UInt16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt8Type >::value >::value ,UInt8Type> >::type UIntSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int64Type >::value >::value ,Int64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int32Type >::value >::value ,Int32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int16Type >::value >::value ,Int16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int8Type >::value >::value ,Int8Type> >::type IntSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float128Type >::value >::value ,Float128Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float64Type >::value >::value ,Float64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float32Type >::value >::value ,Float32Type> >::type FloatSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt8Type >::value >::value ,UInt8Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt16Type >::value >::value ,UInt16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt32Type >::value >::value ,UInt32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt64Type >::value >::value ,UInt64Type> >::type UIntSwitchCasesSmallest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int8Type >::value >::value ,Int8Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int16Type >::value >::value ,Int16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int32Type >::value >::value ,Int32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int64Type >::value >::value ,Int64Type> >::type IntSwitchCasesSmallest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float32Type >::value >::value,Float32Type >, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float64Type >::value >::value ,Float64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float128Type >::value >::value ,Float128Type> >::type FloatSwitchCasesSmallest; // biggest type typedef opengm::meta::Switch< UIntSwitchCasesBiggest , NoUIntTypeOnSystem >::type BiggestUIntType; typedef opengm::meta::Switch< IntSwitchCasesBiggest , NoIntTypeOnSystem >::type BiggestIntType; typedef opengm::meta::Switch< FloatSwitchCasesBiggest , NoFloatTypeOnSystem >::type BiggestFloatType; // smallest types typedef opengm::meta::Switch< UIntSwitchCasesSmallest , NoUIntTypeOnSystem >::type SmallestUIntType; typedef opengm::meta::Switch< IntSwitchCasesSmallest , NoIntTypeOnSystem >::type SmallestIntType; typedef opengm::meta::Switch< FloatSwitchCasesSmallest , NoFloatTypeOnSystem >::type SmallestFloatType; } // end namespace detail_types /// \endcond /// SizeT //typedef size_t ::size_t; // UInt Types /// uint8 typedef detail_types::UInt8Type UInt8Type; /// uint16 typedef detail_types::UInt16Type UInt16Type; /// uint32 typedef detail_types::UInt32Type UInt32Type; /// uint64 typedef detail_types::UInt64Type UInt64Type; // Int Types: typedef detail_types::Int8Type Int8Type; /// int8 typedef detail_types::Int16Type Int16Type; /// int16 typedef detail_types::Int32Type Int32Type; /// int32 typedef detail_types::Int64Type Int64Type; // Float Types: /// float32 typedef detail_types::Float32Type Float32Type; /// float64 typedef detail_types::Float64Type Float64Type; /// biggest / longest uint typedef detail_types::BiggestUIntType BiggestUIntType; /// biggest / longest int typedef detail_types::BiggestIntType BiggestIntType; typedef detail_types::BiggestFloatType BiggestFloatType; // smallest Types: /// smallest / shortest int typedef detail_types::SmallestUIntType SmallestUIntType; typedef detail_types::SmallestIntType SmallestIntType; typedef detail_types::SmallestFloatType SmallestFloatType; // default Types: /// default uint (biggest / longest uint) typedef BiggestUIntType UIntType; /// default uint (biggest / longest int) typedef BiggestIntType IntType; /// default uint (biggest / longest float) typedef SmallestFloatType FloatType; } // end namespace opengm #endif // OPENGM_CONFIGFILE #endif // CONFIG_HXX opengm-2.3.6+20160905/include/opengm/config.hxx.cmake000066400000000000000000000414511276346362400217200ustar00rootroot00000000000000#ifndef CONFIG_HXX #define CONFIG_HXX /// \file config.cxx configuration file for OpenGM /// /// this header should be generated by cmake (from config.hxx.cmake) /// \warning if cmake is not used to configure opengm config.hxx can be wrong. /// Since this header is used to get the size of fundamental types from cmake one /// may has to corret the OPENGM_SIZE_OF_UNSIGNED_* definitions by hand or call cmake /// to configure this header. // \def OPENGM_ASSERT /// opengm assertion /// if NDEBUG is not set OPENGM_ASSERT will check the /// assertion, if NDEBUG is not set OPENGM_ASSERT will do nothing #ifdef NDEBUG # define OPENGM_ASSERT(expression) #else # define OPENGM_ASSERT(expression) if(!(expression)) { \ std::stringstream s; \ s << "OpenGM assertion " << #expression \ << " failed in file " << __FILE__ \ << ", line " << __LINE__ << std::endl; \ throw std::runtime_error(s.str()); \ } #endif // meta-assert /// opengm compile time assertion #define OPENGM_META_ASSERT(assertion, msg){ \ meta::Assert< meta::Compare< meta::Bool<(assertion)> , meta::Bool >::value > \ OPENGM_COMPILE_TIME_ASSERTION_FAILED_____REASON_____##msg; \ (void) OPENGM_COMPILE_TIME_ASSERTION_FAILED_____REASON_____##msg; \ } // has no typedef ? (TODO make this a option in cmake list or // find out in cmake if this define should be active or not #ifdef OPENGM_NO_TYPENAME # define typename #endif #include "opengm/utilities/metaprogramming.hxx" #ifndef OPENGM_USED_CMAKE // assume all types have been detected #else // has cmake detected a type? #cmakedefine OPENGM_NO_CHAR #cmakedefine OPENGM_NO_SIGNED_CHAR #cmakedefine OPENGM_NO_UNSIGNED_CHAR #cmakedefine OPENGM_NO_WCHAR_T #cmakedefine OPENGM_NO_SHORT #cmakedefine OPENGM_NO_UNSIGNED_SHORT #cmakedefine OPENGM_NO_INT #cmakedefine OPENGM_NO_UNSIGNED_INT #cmakedefine OPENGM_NO_LONG #cmakedefine OPENGM_NO_UNSIGNED_LONG #cmakedefine OPENGM_NO_LONG_LONG #cmakedefine OPENGM_NO_UNSIGNED_LONG_LONG #cmakedefine OPENGM_NO_FLOAT #cmakedefine OPENGM_NO_DOUBLE #cmakedefine OPENGM_NO_LONG_DOUBLE #endif // #ifndef OPENGM_USED_CMAKE #define OPENGM_WORD_LENGTH sizeof(void *) #define OPENGM_SIZE_OF_BOOL 1 #define OPENGM_SIZE_OF_CHAR sizeof(char) #define OPENGM_SIZE_OF_SIGNED_CHAR sizeof(unsigned char) #define OPENGM_SIZE_OF_UNSIGNED_CHAR sizeof(unsigned char) #define OPENGM_SIZE_OF_WCHAR_T sizeof(wchar_t) #define OPENGM_SIZE_OF_SHORT sizeof(short) #define OPENGM_SIZE_OF_UNSIGNED_SHORT sizeof(unsigned short) #define OPENGM_SIZE_OF_INT sizeof(int) #define OPENGM_SIZE_OF_UNSIGNED_INT sizeof(unsigned int) #define OPENGM_SIZE_OF_LONG sizeof(long) #define OPENGM_SIZE_OF_UNSIGNED_LONG sizeof(unsigned long) #define OPENGM_SIZE_OF_LONG_LONG sizeof(long long) #define OPENGM_SIZE_OF_UNSIGNED_LONG_LONG sizeof(unsigned long long) #define OPENGM_SIZE_OF_FLOAT sizeof(float) #define OPENGM_SIZE_OF_DOUBLE sizeof(double) #define OPENGM_SIZE_OF_LONG_DOUBLE sizeof(long double) #else // size of types detected by cmake #define OPENGM_WORD_LENGTH @OPENGM_WORD_LENGTH@ #define OPENGM_SIZE_OF_BOOL 1 #define OPENGM_SIZE_OF_CHAR @OPENGM_SIZE_OF_CHAR@ #define OPENGM_SIZE_OF_SIGNED_CHAR @OPENGM_SIZE_OF_SIGNED_CHAR@ #define OPENGM_SIZE_OF_UNSIGNED_CHAR @OPENGM_SIZE_OF_UNSIGNED_CHAR@ #define OPENGM_SIZE_OF_WCHAR_T @OPENGM_SIZE_OF_WCHAR_T@ #define OPENGM_SIZE_OF_SHORT @OPENGM_SIZE_OF_SHORT@ #define OPENGM_SIZE_OF_UNSIGNED_SHORT @OPENGM_SIZE_OF_UNSIGNED_SHORT@ #define OPENGM_SIZE_OF_INT @OPENGM_SIZE_OF_INT@ #define OPENGM_SIZE_OF_UNSIGNED_INT @OPENGM_SIZE_OF_UNSIGNED_INT@ #define OPENGM_SIZE_OF_LONG @OPENGM_SIZE_OF_LONG@ #define OPENGM_SIZE_OF_UNSIGNED_LONG @OPENGM_SIZE_OF_UNSIGNED_LONG@ #define OPENGM_SIZE_OF_LONG_LONG @OPENGM_SIZE_OF_LONG_LONG@ #define OPENGM_SIZE_OF_UNSIGNED_LONG_LONG @OPENGM_SIZE_OF_UNSIGNED_LONG_LONG@ #define OPENGM_SIZE_OF_FLOAT @OPENGM_SIZE_OF_FLOAT@ #define OPENGM_SIZE_OF_DOUBLE @OPENGM_SIZE_OF_DOUBLE@ #define OPENGM_SIZE_OF_LONG_DOUBLE @OPENGM_SIZE_OF_LONG_DOUBLE@ #endif namespace opengm{ #ifndef OPENGM_USED_CMAKE /// major version number of opengm const unsigned int VERSION_MAJOR = 2; /// minor version number of opengm const unsigned int VERSION_MINOR = 0; /// patch version number of opengm const unsigned int VERSION_PATCH = 2; #else /// major version number of opengm const unsigned int VERSION_MAJOR = @OPENGM_VERSION_MAJOR@; /// minor version number of opengm const unsigned int VERSION_MINOR = @OPENGM_VERSION_MINOR@; /// patch version number of opengm const unsigned int VERSION_PATCH = @OPENGM_VERSION_PATCH@; #endif /// usual factor order /// /// this size indicates how many values (usualy the variables indices /// of a factor ) can be stored on the stack. This value is only used /// in opengm::FastSequence (as second template parameter ) const size_t USUAL_MAX_FACTOR_ORDER=5; /// \var NO_DEBUG true if NDEBUG is true #ifdef NDEBUG const bool NO_DEBUG = true; #else const bool NO_DEBUG = false; #endif /// \cond HIDDEN_SYMBOLS namespace detail_types{ // structs to identify if am system // does not have a certain type struct NoCharOnSystem; struct NoUnsignedCharOnSystem; struct NoSignedCharOnSystem; struct NoWCharTOnSystem; struct NoShortOnSystem; struct NoUnsignedShortOnSystem; struct NoIntOnSystem; struct NoUnsignedIntOnSystem; struct NoLongOnSystem; struct NoUnsignedLongOnSystem; struct NoUnsignedLongLongOnSystem; struct NoLongLongOnSystem; struct NoFloatOnSystem; struct NoDoubleOnSystem; struct NoLongDoubleOnSystem; struct NoUIntTypeOnSystem; struct NoIntTypeOnSystem; struct NoFloatTypeOnSystem; struct NoUInt8OnSystem; struct NoUInt16OnSystem; struct NoUInt32OnSystem; struct NoUInt64OnSystem; struct NoInt8OnSystem; struct NoInt16OnSystem; struct NoInt32OnSystem; struct NoInt64OnSystem; struct NoFloat32OnSystem; struct NoFloat64OnSystem; struct NoFloat128OnSystem; // typedefs to types to identify if am system // does not have a certain type #ifdef OPENGM_NO_CHAR typedef opengm::meta::InvalideType Char; #else typedef char Char; #endif #ifdef OPENGM_NO_UNSIGNED_CHAR typedef opengm::meta::InvalideType UnsignedChar; #else typedef unsigned char UnsignedChar; #endif #ifdef OPENGM_NO_SIGNED_CHAR typedef opengm::meta::InvalideType SignedChar; #else typedef signed char SignedChar; #endif #ifdef OPENGM_NO_WCHAR_T typedef opengm::meta::InvalideType WCharT; #else typedef wchar_t WCharT; #endif #ifdef OPENGM_NO_SHORT typedef NoShortOnSystem Short; #else typedef short Short; #endif #ifdef OPENGM_NO_UNSIGNED_SHORT typedef opengm::meta::InvalideType UnsignedShort; #else typedef unsigned short UnsignedShort; #endif #ifdef OPENGM_NO_INT typedef opengm::meta::InvalideType Int; #else typedef int Int; #endif #ifdef OPENGM_NO_UNSIGNED_INT typedef opengm::meta::InvalideType UnsignedInt; #else typedef unsigned int UnsignedInt; #endif #ifdef OPENGM_NO_LONG typedef opengm::meta::InvalideType Long; #else typedef long Long; #endif #ifdef OPENGM_NO_UNSIGNED_LONG typedef opengm::meta::InvalideType UnsignedLong; #else typedef unsigned long UnsignedLong; #endif #ifdef OPENGM_NO_LONG_LONG typedef opengm::meta::InvalideType LongLong; #else typedef long long LongLong; #endif #ifdef OPENGM_NO_UNSIGNED_LONG typedef opengm::meta::InvalideType UnsignedLongLong; #else typedef unsigned long long UnsignedLongLong; #endif #ifdef OPENGM_NO_Float typedef opengm::meta::InvalideType Float; #else typedef float Float; #endif #ifdef OPENGM_NO_DOUBLE typedef opengm::meta::InvalideType Double; #else typedef double Double; #endif #ifdef OPENGM_NO_LONG_DOUBLE typedef opengm::meta::InvalideType LongDouble; #else typedef long double LongDouble; #endif typedef bool Bool ; // typelists of the basic c++ types // Floats: typedef opengm::meta::TypeListGenerator< Float,Double , LongDouble >::type StdFloatingPointTypesTypeList; // UInt: typedef opengm::meta::TypeListGenerator< UnsignedChar,UnsignedShort, UnsignedInt, UnsignedLong, UnsignedLongLong >::type StdUnsignedIntegerTypesTypeList; // Int: typedef opengm::meta::TypeListGenerator< Char, SignedChar, Short, Int, Long,LongLong >::type StdSignedIntegerTypesTypeList; // typelists of the sizes of the basic c++ types // Float sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT,meta::SizeT, opengm::meta::SizeT >::type StdFloatingPointSizesTypeList; // UInt sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT >::type StdUnsignedIntegerSizesTypeList; // Int sizes: typedef opengm::meta::TypeListGenerator< opengm::meta::SizeT, opengm::meta::SizeT, opengm::meta::SizeT,opengm::meta::SizeT, opengm::meta::SizeT,opengm::meta::SizeT >::type StdSignedIntegerSizesTypeList; // platform independent // UInt : typedef opengm::meta::FindSizedType >::type UInt8Type ; typedef opengm::meta::FindSizedType >::type UInt16Type ; typedef opengm::meta::FindSizedType >::type UInt32Type ; typedef opengm::meta::FindSizedType >::type UInt64Type ; //Int : typedef opengm::meta::FindSizedType >::type Int8Type ; typedef opengm::meta::FindSizedType >::type Int16Type ; typedef opengm::meta::FindSizedType >::type Int32Type ; typedef opengm::meta::FindSizedType >::type Int64Type ; // Float : typedef opengm::meta::FindSizedType >::type Float32Type ; typedef opengm::meta::FindSizedType >::type Float64Type ; typedef opengm::meta::FindSizedType >::type Float128Type ; // opengm::meta-"switch-cases" typelists to find out the // biggest and smallest uint, int and float type typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt64Type >::value >::value ,UInt64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt32Type >::value >::value ,UInt32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt16Type >::value >::value ,UInt16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt8Type >::value >::value ,UInt8Type> >::type UIntSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int64Type >::value >::value ,Int64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int32Type >::value >::value ,Int32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int16Type >::value >::value ,Int16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int8Type >::value >::value ,Int8Type> >::type IntSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float128Type >::value >::value ,Float128Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float64Type >::value >::value ,Float64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float32Type >::value >::value ,Float32Type> >::type FloatSwitchCasesBiggest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt8Type >::value >::value ,UInt8Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt16Type >::value >::value ,UInt16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt32Type >::value >::value ,UInt32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< UInt64Type >::value >::value ,UInt64Type> >::type UIntSwitchCasesSmallest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int8Type >::value >::value ,Int8Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int16Type >::value >::value ,Int16Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int32Type >::value >::value ,Int32Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Int64Type >::value >::value ,Int64Type> >::type IntSwitchCasesSmallest; typedef opengm::meta::TypeListGenerator< opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float32Type >::value >::value,Float32Type >, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float64Type >::value >::value ,Float64Type>, opengm::meta::SwitchCase< opengm::meta::Not< opengm::meta::IsInvalidType< Float128Type >::value >::value ,Float128Type> >::type FloatSwitchCasesSmallest; // biggest type typedef opengm::meta::Switch< UIntSwitchCasesBiggest , NoUIntTypeOnSystem >::type BiggestUIntType; typedef opengm::meta::Switch< IntSwitchCasesBiggest , NoIntTypeOnSystem >::type BiggestIntType; typedef opengm::meta::Switch< FloatSwitchCasesBiggest , NoFloatTypeOnSystem >::type BiggestFloatType; // smallest types typedef opengm::meta::Switch< UIntSwitchCasesSmallest , NoUIntTypeOnSystem >::type SmallestUIntType; typedef opengm::meta::Switch< IntSwitchCasesSmallest , NoIntTypeOnSystem >::type SmallestIntType; typedef opengm::meta::Switch< FloatSwitchCasesSmallest , NoFloatTypeOnSystem >::type SmallestFloatType; } // end namespace detail_types /// \endcond // UInt Types: /// uint8 typedef detail_types::UInt8Type UInt8Type; /// uint16 typedef detail_types::UInt16Type UInt16Type; /// uint32 typedef detail_types::UInt32Type UInt32Type; /// uint64 typedef detail_types::UInt64Type UInt64Type; // Int Types: typedef detail_types::Int8Type Int8Type; /// int8 typedef detail_types::Int16Type Int16Type; /// int16 typedef detail_types::Int32Type Int32Type; /// int32 typedef detail_types::Int64Type Int64Type; // Float Types: /// float32 typedef detail_types::Float32Type Float32Type; /// float64 typedef detail_types::Float64Type Float64Type; /// biggest / longest uint typedef detail_types::BiggestUIntType BiggestUIntType; /// biggest / longest int typedef detail_types::BiggestIntType BiggestIntType; typedef detail_types::BiggestFloatType BiggestFloatType; // smallest Types: /// smallest / shortest int typedef detail_types::SmallestUIntType SmallestUIntType; typedef detail_types::SmallestIntType SmallestIntType; typedef detail_types::SmallestFloatType SmallestFloatType; // default Types: /// default uint (biggest / longest uint) typedef BiggestUIntType UIntType; /// default uint (biggest / longest int) typedef BiggestIntType IntType; /// default uint (biggest / longest float) typedef SmallestFloatType FloatType; } // end namespace opengm #endif /* CONFIG_HXX */ opengm-2.3.6+20160905/include/opengm/datastructures/000077500000000000000000000000001276346362400217135ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/datastructures/buffer_randomaccessset.hxx000066400000000000000000000007031276346362400271530ustar00rootroot00000000000000#pragma once #ifndef OPENGM_BUFFER_RANDOM_ACCESS_SET_HXX #define OPENGM_BUFFER_RANDOM_ACCESS_SET_HXX #include #include #include #include namespace opengm { template class BufferRandomAccessSet{ public: void insert(const T & ); private: BufferVector vector_; }; } // namespace opengm #endif // #ifndef OPENGM_BUFFER_RANDOM_ACCESS_SET_HXXopengm-2.3.6+20160905/include/opengm/datastructures/buffer_vector.hxx000066400000000000000000000175611276346362400253110ustar00rootroot00000000000000#pragma once #ifndef OPENGM_BUFFER_VECTOR_HXX #define OPENGM_BUFFER_VECTOR_HXX #include #include #include "opengm/opengm.hxx" /// \cond HIDDEN_SYMBOLS namespace opengm{ /// buffer vector to avoid allocatios /// /// a resize and clear does decrease the capacity of the vector. /// Only the destructor deallocates memory /// \ingroup datastructures template class BufferVector{ public: typedef T ValueType; typedef T value_type; typedef T const * ConstIteratorType; typedef T const * const_iterator; typedef T * IteratorType; typedef T * iterator; BufferVector( ); BufferVector(const size_t ); BufferVector(const size_t ,const T & ); BufferVector(const BufferVector &); ~BufferVector( ); BufferVector & operator= (const BufferVector &); size_t size() const ; T const * begin() const; T const * end() const; T * const begin(); T * const end(); T const * data() const; T * data(); T const & operator[](const size_t)const; T & operator[](const size_t); void push_back(const T &); void resize(const size_t ); void reserve(const size_t ); void clear(); bool empty()const; const T & front()const; const T & back()const; T & front(); T & back(); template void assign(ITERATOR ,ITERATOR); private: size_t size_; size_t capacity_; T * data_; }; /// empty constructor template inline BufferVector::BufferVector( ) : size_(0), capacity_(0), data_(NULL) { } /// constructor /// \param size of vector template inline BufferVector::BufferVector ( const size_t size ) : size_(size), capacity_(size) { if(size_!=0) { data_ = new T[size]; } } /// constructor /// \param size /// \param value template inline BufferVector::BufferVector ( const size_t size, const T & value ) : size_(size), capacity_(size) { data_ = new T[size]; std::fill(data_,data_+size_,value); } /// copy constructor /// \param other other vector template inline BufferVector::BufferVector ( const BufferVector & other ) : size_(other.size_), capacity_(other.size_) { if(size_!=0) { data_ = new T[size_]; std::copy(other.data_,other.data_+size_,data_); } } /// get pointer to the data template inline T const * BufferVector::data() const{ return data_; } /// get pointer to the data template inline T * BufferVector::data() { return data_; } /// destructor template inline BufferVector::~BufferVector( ) { if(capacity_!=0) { OPENGM_ASSERT(data_!=NULL); delete[] data_; } } /// assignment operator template inline BufferVector & BufferVector::operator= ( const BufferVector & other ) { if(&other!=this) { size_=other.size_; if(size_>capacity_) { delete [] data_; data_ = new T[size_]; capacity_=size_; } std::copy(other.data_,other.data_+size_,data_); } return *this; } /// size of the vector template inline size_t BufferVector::size() const { OPENGM_ASSERT(data_!=NULL ||size_== 0 ); return size_; } /// begin iterator template inline T const * BufferVector::begin() const{ OPENGM_ASSERT(data_!=NULL); return data_; } /// end iterator template inline T const * BufferVector::end() const{ OPENGM_ASSERT(data_!=NULL); return data_ + size_; } /// begin iterator template inline T * const BufferVector::begin() { OPENGM_ASSERT(data_!=NULL); return data_; } /// end iterator template inline T * const BufferVector::end() { OPENGM_ASSERT(data_!=NULL); return data_ + size_; } /// bracket operator to access values /// \param index index template inline T const & BufferVector::operator[] ( const size_t index )const{ OPENGM_ASSERT(data_!=NULL); OPENGM_ASSERT(index inline T & BufferVector::operator[] ( const size_t index ) { OPENGM_ASSERT(index inline void BufferVector::push_back ( const T & value ) { OPENGM_ASSERT(size_<=capacity_); if(capacity_==size_) { if(size_!=0) { T * tmp=new T[capacity_*2]; std::copy(data_,data_+size_,tmp); delete[] data_; capacity_*=2; data_=tmp; } else{ T * tmp=new T[2]; capacity_=2; data_=tmp; } } data_[size_]=value; ++size_; OPENGM_ASSERT(size_<=capacity_); } /// resize /// \param size new size of the array template inline void BufferVector::resize ( const size_t size ) { OPENGM_ASSERT(size_<=capacity_); if(size>capacity_) { if(size_!=0) { T * tmp=new T[size]; std::copy(data_,data_+size_,tmp); delete[] data_; capacity_=size; data_=tmp; } else{ data_=new T[size]; capacity_=size; } } size_=size; OPENGM_ASSERT(size_<=capacity_); } /// reserve memory /// \param size to reserve template inline void BufferVector::reserve ( const size_t size ) { OPENGM_ASSERT(size_<=capacity_); if(size>capacity_) { if(size_!=0) { T * tmp=new T[size]; std::copy(data_,data_+size_,tmp); delete[] data_; data_=tmp; } else{ data_=new T[size]; } size_=size; capacity_=size; } //size_=size; OPENGM_ASSERT(size_<=capacity_); } /// clear sets the size to zero but does/// bracket operator to access values /// \param index index no deallocations /// \warning no deallocations are done template inline void BufferVector::clear() { OPENGM_ASSERT(size_<=capacity_); size_=0; } /// is vector is empty template inline bool BufferVector::empty()const{ return size_==0 ? true:false; } /// assign data /// \param begin begin of values /// \param end end of values template template inline void BufferVector::assign(ITERATOR begin,ITERATOR end) { this->resize(std::distance(begin,end)); std::copy(begin, end, data_); } /// reference to last element template inline const T & BufferVector::back()const{ return data_[size_-1]; } /// reference to last element template inline T & BufferVector::back() { return data_[size_-1]; } /// reference to the first element template inline const T & BufferVector::front()const{ return data_[0]; } /// reference to the first element template inline T & BufferVector::front() { return data_[0]; } } /// \endcond #endif //OPENGM_BUFFER_VECTOR_HXX opengm-2.3.6+20160905/include/opengm/datastructures/fast_sequence.hxx000066400000000000000000000221031276346362400252670ustar00rootroot00000000000000#pragma once #ifndef OPENGM_FAST_SEQUENCE_HXX #define OPENGM_FAST_SEQUENCE_HXX #include #include #include "opengm/opengm.hxx" namespace opengm { /// \brief Vector that stores values on the stack if size is smaller than MAX_STACK /// \tparam T value type /// \tparam MAX_STACK maximum number of elements kept on the stack /// /// The member functions resize and clear reduce the size but not the /// capacity of the vector. /// /// \ingroup datastructures template class FastSequence{ public: typedef T ValueType; typedef T value_type; typedef T const * ConstIteratorType; typedef T const * const_iterator; typedef T* IteratorType; typedef T* iterator; FastSequence( ); FastSequence(const size_t ); FastSequence(const size_t , const T & ); FastSequence(const FastSequence &); ~FastSequence( ); FastSequence& operator=(const FastSequence &); template void assign(ITERATOR , ITERATOR); size_t size() const ; T const * begin() const; T const * end() const; T* const begin(); T* const end(); T const & operator[](const size_t) const; T& operator[](const size_t); void push_back(const T &); void resize(const size_t ); void reserve(const size_t ); void clear(); bool empty() const; const T& front() const; const T& back() const; T& front(); T& back(); private: size_t size_; size_t capacity_; T stackSequence_[MAX_STACK]; T* pointerToSequence_; }; /// constructor template FastSequence::FastSequence( ) : size_(0), capacity_(MAX_STACK), pointerToSequence_(stackSequence_) { } /// constructor /// \param size length of the sequence template FastSequence::FastSequence ( const size_t size ) : size_(size), capacity_(size>MAX_STACK?size:MAX_STACK) { OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); if(size_>MAX_STACK) { pointerToSequence_ = new T[size]; } else{ pointerToSequence_=stackSequence_; } } /// constructor /// \param size lenght of the sequence /// \param value initial value template FastSequence::FastSequence ( const size_t size, const T & value ) : size_(size), capacity_(size>MAX_STACK?size:MAX_STACK) { OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); if(size_>MAX_STACK) { pointerToSequence_ = new T[size_]; } else{ pointerToSequence_=stackSequence_; } std::fill(pointerToSequence_, pointerToSequence_+size_, value); } /// copy constructor /// \param other container to copy template FastSequence::FastSequence ( const FastSequence & other ) : size_(other.size_), capacity_(other.capacity_) { OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); if(size_>MAX_STACK) { pointerToSequence_ = new T[size_]; } else{ pointerToSequence_=stackSequence_; } std::copy(other.pointerToSequence_, other.pointerToSequence_+size_, pointerToSequence_); } /// destructor template FastSequence::~FastSequence( ) { if(capacity_>MAX_STACK) { OPENGM_ASSERT(pointerToSequence_!=NULL); delete[] pointerToSequence_; } } /// assignment operator /// \param other container to copy template FastSequence & FastSequence::operator= ( const FastSequence & other ) { if(&other != this) { // size_=other.size_; // capacity_=other.capacity_; // OPENGM_ASSERT(size_<=capacity_); // OPENGM_ASSERT(capacity_>=MAX_STACK); if(other.size_>MAX_STACK) { // delete old sequence if(size_>MAX_STACK) { delete [] pointerToSequence_; pointerToSequence_ = new T[other.size_]; } // nothing to delete else{ pointerToSequence_ = new T[other.size_]; } size_=other.size_; capacity_=size_; } else{ pointerToSequence_=stackSequence_; size_=other.size_; } std::copy(other.pointerToSequence_, other.pointerToSequence_+size_, pointerToSequence_); } return *this; } /// size template inline size_t FastSequence::size() const { OPENGM_ASSERT(pointerToSequence_!=NULL ||size_== 0 ); return size_; } /// begin iterator template inline T const * FastSequence::begin() const{ OPENGM_ASSERT(pointerToSequence_!=NULL); return pointerToSequence_; } /// end iterator template inline T const * FastSequence::end() const{ OPENGM_ASSERT(pointerToSequence_!=NULL); return pointerToSequence_ + size_; } /// begin iterator template inline T * const FastSequence::begin() { OPENGM_ASSERT(pointerToSequence_!=NULL); return pointerToSequence_; } /// end iterator template inline T * const FastSequence::end() { OPENGM_ASSERT(pointerToSequence_!=NULL); return pointerToSequence_ + size_; } /// access entries template inline T const & FastSequence::operator[] ( const size_t index ) const { OPENGM_ASSERT(pointerToSequence_!=NULL); OPENGM_ASSERT(index inline T & FastSequence::operator[] ( const size_t index ) { OPENGM_ASSERT(index inline void FastSequence::push_back ( const T & value ) { OPENGM_ASSERT(capacity_ >= MAX_STACK); OPENGM_ASSERT(size_ <= capacity_); if(capacity_ == size_) { T * tmp=new T[capacity_ * 2]; std::copy(pointerToSequence_, pointerToSequence_ + size_, tmp); if(capacity_ > MAX_STACK) { delete[] pointerToSequence_; } capacity_ *= 2; pointerToSequence_ = tmp; } pointerToSequence_[size_]=value; ++size_; OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); } /// resize the sequence /// \param size new size of the container template inline void FastSequence::resize ( const size_t size ) { OPENGM_ASSERT(capacity_>=MAX_STACK); OPENGM_ASSERT(size_<=capacity_); if(size>capacity_) { T * tmp=new T[size]; std::copy(pointerToSequence_, pointerToSequence_+size_, tmp); if(capacity_>MAX_STACK) { delete[] pointerToSequence_; } capacity_=size; pointerToSequence_=tmp; } size_=size; OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); } /// reserve memory /// \param size new size of the container template inline void FastSequence::reserve ( const size_t size ) { OPENGM_ASSERT(capacity_>=MAX_STACK); OPENGM_ASSERT(size_<=capacity_); if(size>capacity_) { T * tmp=new T[size]; std::copy(pointerToSequence_, pointerToSequence_+size_, tmp); if(capacity_>MAX_STACK) { delete[] pointerToSequence_; } capacity_=size; pointerToSequence_=tmp; } // size_ = size; OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); } /// clear the sequence template inline void FastSequence::clear() { OPENGM_ASSERT(capacity_>=MAX_STACK); OPENGM_ASSERT(size_<=capacity_); if(capacity_>MAX_STACK) { delete[] pointerToSequence_; } pointerToSequence_=stackSequence_; capacity_=MAX_STACK; size_=0; OPENGM_ASSERT(size_<=capacity_); OPENGM_ASSERT(capacity_>=MAX_STACK); } /// query if the sequence is empty template inline bool FastSequence::empty() const { return (size_ == 0); } /// assign values /// \param begin begin iterator /// \param end end iterator template template inline void FastSequence::assign(ITERATOR begin, ITERATOR end) { this->resize(std::distance(begin, end)); std::copy(begin, end, pointerToSequence_); } /// reference to the last entry template inline const T & FastSequence::back()const{ return pointerToSequence_[size_-1]; } /// reference to the last entry template inline T & FastSequence::back() { return pointerToSequence_[size_-1]; } /// reference to the first entry template inline const T & FastSequence::front()const{ return pointerToSequence_[0]; } /// reference to the first entry template inline T & FastSequence::front() { return pointerToSequence_[0]; } } // namespace opengm #endif // OPENGM_FAST_SEQUENCE_HXX opengm-2.3.6+20160905/include/opengm/datastructures/indicator_variable.hxx000066400000000000000000000754241276346362400263010ustar00rootroot00000000000000#ifndef OPENGM_INDICATOR_VARIABLE_HXX_ #define OPENGM_INDICATOR_VARIABLE_HXX_ #include // for std::pair #include #include namespace opengm { /********************* * class definition * *********************/ template class IndicatorVariable { public: // typedefs typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; enum LogicalOperatorType {And, Or, Not}; typedef std::pair VariableLabelPair; typedef std::vector VariableLabelPairContainerType; typedef typename VariableLabelPairContainerType::const_iterator IteratorType; // constructors IndicatorVariable(); IndicatorVariable(const IndexType variable, const LabelType label, const LogicalOperatorType logicalOperatorType = And); IndicatorVariable(const VariableLabelPair& variableLabelPair, const LogicalOperatorType logicalOperatorType = And); IndicatorVariable(const VariableLabelPairContainerType& variableLabelPairs, const LogicalOperatorType logicalOperatorType = And); template IndicatorVariable(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd, const LogicalOperatorType logicalOperatorType = And); // modify void reserve(const size_t numPairs); void add(const IndexType variable, const LabelType label); void add(const VariableLabelPair& variableLabelPair); void add(const VariableLabelPairContainerType& variableLabelPairs); template void add(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd); void setLogicalOperatorType(const LogicalOperatorType logicalOperatorType); // evaluate template bool operator()(const ITERATOR_TYPE statesBegin) const; // const access IteratorType begin() const; IteratorType end() const; LogicalOperatorType getLogicalOperatorType() const; protected: // storage VariableLabelPairContainerType variableLabelPairs_; LogicalOperatorType logicalOperatorType_; // friends template friend bool operator==(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template friend bool operator!=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template friend bool operator<(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template friend bool operator>(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template friend bool operator<=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template friend bool operator>=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); }; // operators for IndicatorVariable template bool operator==(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template bool operator!=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template bool operator<(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template bool operator>(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template bool operator<=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); template bool operator>=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); /*********************** * class documentation * ***********************/ /*! \file indicator_variable.hxx * \brief Provides implementation for class IndicatorVariable. */ /*! \class IndicatorVariable * \brief Combine a group of variables to a new variable. * * An indicator variable defines a new boolean variable from a set of variable * label pairs. Depending on the selected logical operator type an indicator * variable will be interpreted as 1 if all (logical and), at least one * (logical or) or none (logical not) of the variables take the labels stated * by the variable label pairs. * * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. * * \note The set of variable label pairs will be stored in an ordered sequence. * This means a variable label pair will come in the sequence before all * other variable label pairs whose variable index is greater. And if two * variable label pairs have the same variable index the one with the * smaller label will come first. */ /*! \typedef IndicatorVariable::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * IndicatorVariable. */ /*! \typedef IndicatorVariable::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * IndicatorVariable. */ /*! \enum IndicatorVariable::LogicalOperatorType * \brief This enum defines the logical operator types which are supported by * the indicator variables. */ /*! \var IndicatorVariable::LogicalOperatorType IndicatorVariable::And * \brief The indicator variable will be interpreted as 1 if all variables * associated by the indicator variable take the labels stated by * the variable label pairs of the indicator variable. Otherwise it will * be interpreted as 0. */ /*! \var IndicatorVariable::LogicalOperatorType IndicatorVariable::Or * \brief The indicator variable will be interpreted as 1 if at least one of * the variables associated by the indicator variable takes the label * stated by the variable label pairs of the indicator variable. * Otherwise it will be interpreted as 0. */ /*! \var IndicatorVariable::LogicalOperatorType IndicatorVariable::Not * \brief The indicator variable will be interpreted as 1 if none of the * variables associated by the indicator variable takes the label * stated by the variable label pairs of the indicator variable. * Otherwise it will be interpreted as 0. */ /*! \typedef IndicatorVariable::VariableLabelPair * \brief A pair representing a single state of a variable. */ /*! \typedef IndicatorVariable::VariableLabelPairContainerType * \brief A vector containing VariableLabelPair elements. */ /*! \typedef IndicatorVariable::IteratorType * \brief A const iterator to iterate over the VariableLabelPair elements. */ /*! \fn IndicatorVariable::IndicatorVariable() * \brief IndicatorVariable constructor. * * This constructor will create an empty IndicatorVariable. */ /*! \fn IndicatorVariable::IndicatorVariable(const IndexType variable, const LabelType label, const LogicalOperatorType logicalOperatorType) * \brief IndicatorVariable constructor. * * This constructor will create an IndicatorVariable containing just one * variable label pair. * * \param[in] variable Index of the variable. * \param[in] label Label of the variable. * \param[in] logicalOperatorType The logical operator type by which the * indicator variable is evaluated. */ /*! \fn IndicatorVariable::IndicatorVariable(const VariableLabelPair& variableLabelPair, const LogicalOperatorType logicalOperatorType) * \brief IndicatorVariable constructor. * * This constructor will create an IndicatorVariable containing just one * variable label pair. * * \param[in] variableLabelPair A pair containing index and label of a * variable. * \param[in] logicalOperatorType The logical operator type by which the * indicator variable is evaluated. */ /*! \fn IndicatorVariable::IndicatorVariable(const IndicatorVariableLabelPairContainerTypeorVariable, const LogicalOperatorType logicalOperatorType) * \brief IndicatorVariable constructor. * * This constructor will create an IndicatorVariable by copying the indicator * variable vector. * * \param[in] indicatorVariable A vector of VariableLabelPair elements which * define a IndicatorVariable. * \param[in] logicalOperatorType The logical operator type by which the * indicator variable is evaluated. */ /*! \fn IndicatorVariable::IndicatorVariable(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd, const LogicalOperatorType logicalOperatorType) * \brief IndicatorVariable constructor. * * This constructor will create an IndicatorVariable by copying variable label * pairs. * * \tparam ITERATOR_TYPE Iterator type. * * \param[in] variableLabelPairsBegin Iterator pointing to the begin of a * sequence of variable label pairs. * \param[in] variableLabelPairsEnd Iterator pointing to the end of a sequence * of variable label pairs. * \param[in] logicalOperatorType The logical operator type by which the * indicator variable is evaluated. */ /*! \fn void IndicatorVariable::reserve(const size_t numPairs) * \brief Preallocate memory. * * The reserve function fill preallocate enough memory to store at least the * stated number of variable label pairs. * * \param[in] numPairs The number of variable label pairs for which memory will * be allocated. */ /*! \fn void IndicatorVariable::add(const IndexType variable, const LabelType label) * \brief Add a variable label pair to the indicator variable. * * \param[in] variable Index of the variable. * \param[in] label Label of the variable. */ /*! \fn void IndicatorVariable::add(const VariableLabelPair& variableLabelPair) * \brief Add a variable label pair to the indicator variable. * * \param[in] variableLabelPair A pair containing index and label of a * variable. * */ /*! \fn void IndicatorVariable::add(const VariableLabelPairContainerType& indicatorVariable) * \brief Add a sequence of variable label pairs to the indicator variable. * * \param[in] indicatorVariable A vector of VariableLabelPair elements which * define an IndicatorVariable. */ /*! \fn void IndicatorVariable::add(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd) * \brief Add a sequence of variable label pairs to the indicator variable. * * \tparam ITERATOR_TYPE Iterator type. * * \param[in] variableLabelPairsBegin Iterator pointing to the begin of a * sequence of variable label pairs. * \param[in] variableLabelPairsEnd Iterator pointing to the end of a sequence * of variable label pairs. */ /*! \fn void IndicatorVariable::setLogicalOperatorType(const LogicalOperatorType logicalOperatorType) * \brief Set the logical operator type of the indicator variable. * * \param[in] logicalOperatorType The new logical operator type. */ /*! \fn bool IndicatorVariable::operator()(const ITERATOR_TYPE statesBegin) const * \brief Evaluation operator to check if the indicator variable is active for * the given labeling. * * \tparam ITERATOR_TYPE Iterator type. * * \param[in] statesBegin Iterator pointing to the begin of the labeling. * * \return True if the indicator variable is active for the given labeling, * false otherwise. * * \warning No boundary check is performed. */ /*! \fn IndicatorVariable::IteratorType IndicatorVariable::begin() const * \brief Get the iterator over the sequence of variable label pairs from the * indicator variable. * * \return Returns a const iterator to the begin of the sequence of variable * label pairs from the indicator variable. */ /*! \fn IndicatorVariable::IteratorType IndicatorVariable::end() const * \brief Get the end iterator of the sequence of variable label pairs from the * indicator variable. * * \return Returns a const iterator to the end of the sequence of variable * label pairs from the indicator variable. */ /*! \fn IndicatorVariable::LogicalOperatorType IndicatorVariable::getLogicalOperatorType() * \brief Get the logical operator type of the indicator variable. * * \return The current logical operator type of the indicator variable. */ /*! \var IndicatorVariable::variableLabelPairs_ * \brief Storage for the variable label pairs. */ /*! \var IndicatorVariable::logicalOperatorType_ * \brief Storage for the logical operator type of the indicator variable. */ /*! \fn bool IndicatorVariable::operator==(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Equality operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if two IndicatorVariables are equal. False otherwise. */ /*! \fn bool IndicatorVariable::operator!=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Inequality operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if two IndicatorVariables are different. False * otherwise. */ /*! \fn bool IndicatorVariable::operator<(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Less operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if an IndicatorVariables is smaller than an other one. * False otherwise. * * \note Indicator variables will be ordered first by the logical operator type * (And < Or < Not), then by the number of variable label pairs. If both * the logical operator type and the number of variable label pairs are * equal the first variable label pairs which are different in the first * and the second indicator variable will be used for comparison. */ /*! \fn bool IndicatorVariable::operator>(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Greater operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if an IndicatorVariables is greater than an other one. * False otherwise. * * \note Indicator variables will be ordered first by the logical operator type * (And < Or < Not), then by the number of variable label pairs. If both * the logical operator type and the number of variable label pairs are * equal the first variable label pairs which are different in the first * and the second indicator variable will be used for comparison. */ /*! \fn bool IndicatorVariable::operator<=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Less equal operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if an IndicatorVariables is smaller than or equal to an * other one. False otherwise. * * \note Indicator variables will be ordered first by the logical operator type * (And < Or < Not), then by the number of variable label pairs. If both * the logical operator type and the number of variable label pairs are * equal the first variable label pairs which are different in the first * and the second indicator variable will be used for comparison. */ /*! \fn bool IndicatorVariable::operator>=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2); * \brief Greater equal operator for IndicatorVariable. * * \tparam INDEX1_TYPE Index type of the first indicator variable. * \tparam LABEL1_TYPE Label type of the first indicator variable. * \tparam INDEX2_TYPE Index type of the second indicator variable. * \tparam LABEL2_TYPE Label type of the second indicator variable. * * \param[in] indicatorVar1 First indicator variable. * \param[in] indicatorVar2 Second indicator variable. * * \return Returns true if an IndicatorVariables is greater than or equal to an * other one. False otherwise. * * \note Indicator variables will be ordered first by the logical operator type * (And < Or < Not), then by the number of variable label pairs. If both * the logical operator type and the number of variable label pairs are * equal the first variable label pairs which are different in the first * and the second indicator variable will be used for comparison. */ /****************** * implementation * ******************/ // constructors template inline IndicatorVariable::IndicatorVariable() : variableLabelPairs_(), logicalOperatorType_(And) { } template inline IndicatorVariable::IndicatorVariable(const IndexType variable, const LabelType label, const LogicalOperatorType logicalOperatorType) : variableLabelPairs_(1, VariableLabelPair(variable, label)), logicalOperatorType_(logicalOperatorType) { } template inline IndicatorVariable::IndicatorVariable(const VariableLabelPair& variableLabelPair, const LogicalOperatorType logicalOperatorType) : variableLabelPairs_(1, variableLabelPair), logicalOperatorType_(logicalOperatorType) { } template inline IndicatorVariable::IndicatorVariable(const VariableLabelPairContainerType& variableLabelPairs, const LogicalOperatorType logicalOperatorType) : variableLabelPairs_(variableLabelPairs), logicalOperatorType_(logicalOperatorType) { std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } template template inline IndicatorVariable::IndicatorVariable(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd, const LogicalOperatorType logicalOperatorType) : variableLabelPairs_(variableLabelPairsBegin, variableLabelPairsEnd), logicalOperatorType_(logicalOperatorType) { std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } // modify template inline void IndicatorVariable::reserve(const size_t numPairs) { variableLabelPairs_.reserve(numPairs); } template inline void IndicatorVariable::add(const IndexType variable, const LabelType label) { variableLabelPairs_.push_back(VariableLabelPair(variable, label)); std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } template inline void IndicatorVariable::add(const VariableLabelPair& variableLabelPair) { variableLabelPairs_.push_back(variableLabelPair); std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } template inline void IndicatorVariable::add(const VariableLabelPairContainerType& variableLabelPairs) { variableLabelPairs_.insert(variableLabelPairs_.end(), variableLabelPairs.begin(), variableLabelPairs.end()); std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } template template inline void IndicatorVariable::add(const ITERATOR_TYPE variableLabelPairsBegin, const ITERATOR_TYPE variableLabelPairsEnd) { variableLabelPairs_.insert(variableLabelPairs_.end(), variableLabelPairsBegin, variableLabelPairsEnd); std::sort(variableLabelPairs_.begin(), variableLabelPairs_.end()); } template inline void IndicatorVariable::setLogicalOperatorType(const LogicalOperatorType logicalOperatorType) { logicalOperatorType_ = logicalOperatorType; } // evaluate template template inline bool IndicatorVariable::operator()(const ITERATOR_TYPE statesBegin) const { bool result = true; if(logicalOperatorType_ == And) { for(IteratorType indicatorVariableIter = begin(); indicatorVariableIter != end(); ++indicatorVariableIter) { if(indicatorVariableIter->second != statesBegin[indicatorVariableIter->first]) { result = false; break; } } } else if(logicalOperatorType_ == Or) { result = false; for(IteratorType indicatorVariableIter = begin(); indicatorVariableIter != end(); ++indicatorVariableIter) { if(indicatorVariableIter->second == statesBegin[indicatorVariableIter->first]) { result = true; break; } } } else { // logicalOperatorType_ == Not for(IteratorType indicatorVariableIter = begin(); indicatorVariableIter != end(); ++indicatorVariableIter) { if(indicatorVariableIter->second == statesBegin[indicatorVariableIter->first]) { result = false; break; } } } return result; } // const access template inline typename IndicatorVariable::IteratorType IndicatorVariable::begin() const { return variableLabelPairs_.begin(); } template inline typename IndicatorVariable::IteratorType IndicatorVariable::end() const { return variableLabelPairs_.end(); } template inline typename IndicatorVariable::LogicalOperatorType IndicatorVariable::getLogicalOperatorType() const { return logicalOperatorType_; } template bool operator==(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { return (indicatorVar1.logicalOperatorType_ == indicatorVar2.logicalOperatorType_) && (indicatorVar1.variableLabelPairs_ == indicatorVar2.variableLabelPairs_); } template bool operator!=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { return (indicatorVar1.logicalOperatorType_ != indicatorVar2.logicalOperatorType_) || (indicatorVar1.variableLabelPairs_ != indicatorVar2.variableLabelPairs_); } template bool operator<(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { if(indicatorVar1.logicalOperatorType_ < indicatorVar2.logicalOperatorType_) { return true; } else if(indicatorVar1.logicalOperatorType_ > indicatorVar2.logicalOperatorType_) { return false; } else { if(indicatorVar1.variableLabelPairs_.size() > indicatorVar2.variableLabelPairs_.size()) { return false; } if(indicatorVar1.variableLabelPairs_.size() == indicatorVar2.variableLabelPairs_.size()) { if(indicatorVar1.variableLabelPairs_.size() == 0) { return false; } for(size_t i = 0; i < indicatorVar1.variableLabelPairs_.size(); ++i) { if(indicatorVar1.variableLabelPairs_[i].first > indicatorVar2.variableLabelPairs_[i].first) { return false; } else if(indicatorVar1.variableLabelPairs_[i].first == indicatorVar2.variableLabelPairs_[i].first) { if(indicatorVar1.variableLabelPairs_[i].second >= indicatorVar2.variableLabelPairs_[i].second) { return false; } } } } return true; } } template bool operator>(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { if(indicatorVar1.logicalOperatorType_ < indicatorVar2.logicalOperatorType_) { return false; } else if(indicatorVar1.logicalOperatorType_ > indicatorVar2.logicalOperatorType_) { return true; } else { if(indicatorVar1.variableLabelPairs_.size() < indicatorVar2.variableLabelPairs_.size()) { return false; } if(indicatorVar1.variableLabelPairs_.size() == indicatorVar2.variableLabelPairs_.size()) { if(indicatorVar1.variableLabelPairs_.size() == 0) { return false; } for(size_t i = 0; i < indicatorVar1.variableLabelPairs_.size(); ++i) { if(indicatorVar1.variableLabelPairs_[i].first < indicatorVar2.variableLabelPairs_[i].first) { return false; } else if(indicatorVar1.variableLabelPairs_[i].first == indicatorVar2.variableLabelPairs_[i].first) { if(indicatorVar1.variableLabelPairs_[i].second <= indicatorVar2.variableLabelPairs_[i].second) { return false; } } } } return true; } } template bool operator<=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { if(indicatorVar1.logicalOperatorType_ < indicatorVar2.logicalOperatorType_) { return true; } else if(indicatorVar1.logicalOperatorType_ > indicatorVar2.logicalOperatorType_) { return false; } else { if(indicatorVar1.variableLabelPairs_.size() > indicatorVar2.variableLabelPairs_.size()) { return false; } if(indicatorVar1.variableLabelPairs_.size() == indicatorVar2.variableLabelPairs_.size()) { for(size_t i = 0; i < indicatorVar1.variableLabelPairs_.size(); ++i) { if(indicatorVar1.variableLabelPairs_[i].first > indicatorVar2.variableLabelPairs_[i].first) { return false; } else if(indicatorVar1.variableLabelPairs_[i].first == indicatorVar2.variableLabelPairs_[i].first) { if(indicatorVar1.variableLabelPairs_[i].second > indicatorVar2.variableLabelPairs_[i].second) { return false; } } } } return true; } } template bool operator>=(const IndicatorVariable& indicatorVar1, const IndicatorVariable& indicatorVar2) { if(indicatorVar1.logicalOperatorType_ < indicatorVar2.logicalOperatorType_) { return false; } else if(indicatorVar1.logicalOperatorType_ > indicatorVar2.logicalOperatorType_) { return true; } else { if(indicatorVar1.variableLabelPairs_.size() < indicatorVar2.variableLabelPairs_.size()) { return false; } if(indicatorVar1.variableLabelPairs_.size() == indicatorVar2.variableLabelPairs_.size()) { for(size_t i = 0; i < indicatorVar1.variableLabelPairs_.size(); ++i) { if(indicatorVar1.variableLabelPairs_[i].first < indicatorVar2.variableLabelPairs_[i].first) { return false; } else if(indicatorVar1.variableLabelPairs_[i].first == indicatorVar2.variableLabelPairs_[i].first) { if(indicatorVar1.variableLabelPairs_[i].second < indicatorVar2.variableLabelPairs_[i].second) { return false; } } } } return true; } } } // namespace opengm #endif /* OPENGM_INDICATOR_VARIABLE_HXX_ */ opengm-2.3.6+20160905/include/opengm/datastructures/linear_constraint.hxx000066400000000000000000000574671276346362400262050ustar00rootroot00000000000000#ifndef OPENGM_LINEAR_CONSTRAINT_HXX_ #define OPENGM_LINEAR_CONSTRAINT_HXX_ #include #include #include namespace opengm { /********************* * class definition * *********************/ class LinearConstraintTraits { public: // typedefs struct LinearConstraintOperator {enum ValueType {LessEqual, Equal, GreaterEqual};}; }; template class LinearConstraint { public: // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef IndicatorVariable IndicatorVariableType; typedef std::vector IndicatorVariablesContainerType; typedef std::vector CoefficientsContainerType; typedef ValueType BoundType; typedef LinearConstraintTraits::LinearConstraintOperator LinearConstraintOperatorType; typedef LinearConstraintOperatorType::ValueType LinearConstraintOperatorValueType; typedef typename IndicatorVariableType::IteratorType VariableLabelPairsIteratorType; typedef typename IndicatorVariablesContainerType::const_iterator IndicatorVariablesIteratorType; typedef typename CoefficientsContainerType::const_iterator CoefficientsIteratorType; // constructors LinearConstraint(); LinearConstraint(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients, const BoundType bound = 0.0, const LinearConstraintOperatorValueType constraintOperator = LinearConstraintOperatorType::LessEqual); template LinearConstraint(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const BoundType bound = 0.0, const LinearConstraintOperatorValueType constraintOperator = LinearConstraintOperatorType::LessEqual); LinearConstraint(const LinearConstraint& linearConstraint); // modify void reserve(const size_t numIndicatorVariables); void add(const IndicatorVariableType& indicatorVariable, const ValueType coefficient); void add(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients); template void add(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin); void setBound(const BoundType bound); void setConstraintOperator(const LinearConstraintOperatorValueType constraintOperator); // evaluate template ValueType operator()(const ITERATOR_TYPE statesBegin) const; // const access IndicatorVariablesIteratorType indicatorVariablesBegin() const; IndicatorVariablesIteratorType indicatorVariablesEnd() const; CoefficientsIteratorType coefficientsBegin() const; CoefficientsIteratorType coefficientsEnd() const; BoundType getBound() const; LinearConstraintOperatorValueType getConstraintOperator() const; protected: // storage IndicatorVariablesContainerType indicatorVariables_; CoefficientsContainerType coefficients_; BoundType bound_; LinearConstraintOperatorValueType constraintOperator_; }; /*********************** * class documentation * ***********************/ /*! \file linear_constraint.hxx * \brief Provides implementation for class LinearConstraint. */ /*! \class LinearConstraintTraits * \brief Traits class for LinearConstraint to provide template independent * enum for ConstraintOperatorType. * * This is a traits class for the class LinearConstraint to provide an enum for * ConstraintOperatorType. This has to be done outside the LinearConstraint * class. Otherwise there would be several different types defining the * same enum. One for each instantiation of LinearConstraint, as * LinearConstraint is a template class. */ /*! \struct LinearConstraintTraits::LinearConstraintOperator * \brief This struct is used to create an own scope for the * LinearConstraintTraits::LinearConstraintOperator::ValueType enum as * this is not done in C++ by default. */ /*! \enum LinearConstraintTraits::LinearConstraintOperator::ValueType * \brief This enum defines the operator type for the linear constraint. */ /*! \var LinearConstraintTraits::LinearConstraintOperator::ValueType LinearConstraintTraits::LinearConstraintOperator::LessEqual * \brief Defines the linear constraint operator type to be \f$\leq\f$. Hence * the left hand side of the constraint will be compared against the * bound using the operator <=. */ /*! \var LinearConstraintTraits::LinearConstraintOperator::ValueType LinearConstraintTraits::LinearConstraintOperator::Equal * \brief Defines the linear constraint operator type to be \f$=\f$. Hence the * left hand side of the constraint will be compared against the bound * using the operator ==. */ /*! \var LinearConstraintTraits::LinearConstraintOperator::ValueType LinearConstraintTraits::LinearConstraintOperator::GreaterEqual * \brief Defines the linear constraint operator type to be \f$\geq\f$. Hence * the left hand side of the constraint will be compared against the * bound using the operator >=. */ /*! \class LinearConstraint * \brief Define a linear constraint for a set of indicatorVariables. * * This class defines a linear constraint for a set of indicator variables. * Each variable has to be an indicator variable of the class * IndicatorVariable. Each constraint consists of four parts: * * 1. A set of indicator variables. * 2. A set of coefficients. One coefficient for each indicator variable. * 3. A bound. * 4. An operator type which defines how the left hand side of the * constraint is compared against the bound. * * The constraint will be evaluated by the following formula: * \f[ * \sum_i c_i \cdot v_i \quad \bigcirc \quad b. * \f] * Here \f$v_i\f$ represents the \f$i\f$-th indicator variable, \f$c_i\f$ * represents the coefficient belonging to the \f$i\f$-th indictor variable, * \f$b\f$ represents the bound and \f$\bigcirc\f$ is the selected operator * type (\f$\leq\f$, \f$=\f$ or \f$\geq\f$). * * \tparam VALUE_TYPE Value type. * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. */ /*! \typedef LinearConstraint::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LinearConstraint. */ /*! \typedef LinearConstraint::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LinearConstraint. */ /*! \typedef LinearConstraint::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LinearConstraint. */ /*! \typedef LinearConstraint::IndicatorVariableType * \brief Typedef of the IndicatorVariable class with appropriate template * parameter. */ /*! \typedef LinearConstraint::IndicatorVariablesContainerType * \brief Defines the storage type for the set of indicator variables. */ /*! \typedef LinearConstraint::CoefficientsContainerType * \brief Defines the storage type for the set of coefficients for the * indicator variables. */ /*! \typedef LinearConstraint::BoundType * \brief Defines the data type for the bound. */ /*! \typedef LinearConstraint::LinearConstraintOperatorType * \brief Defines the linear constraint operator. */ /*! \typedef LinearConstraint::LinearConstraintOperatorValueType * \brief Defines the linear constraint operator type. */ /*! \typedef LinearConstraint::VariableLabelPairsIteratorType * \brief Defines the const iterator type to iterate over the variable label * pairs of an indicator variable. */ /*! \typedef LinearConstraint::IndicatorVariablesIteratorType * \brief Defines the const iterator type to iterate over the set of indicator * variables. */ /*! \typedef LinearConstraint::CoefficientsIteratorType * \brief Defines the const iterator type to iterate over the set of * coefficients for the indicator variables. */ /*! \fn LinearConstraint::LinearConstraint() * \brief LinearConstraint constructor. * * This constructor will create an empty LinearConstraint. */ /*! \fn LinearConstraint::LinearConstraint(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients, const BoundType bound = 0.0, const LinearConstraintOperatorValueType constraintOperator = LinearConstraintOperatorType::LessEqual) * \brief LinearConstraint constructor. * * This constructor will create a LinearConstraint by copying the set of * indicator variables and coefficients. * * \param[in] indicatorVariables The set of indicator variables. * \param[in] coefficients The set of coefficients for the indicator variables. * \param[in] bound The right hand side of the constraint. * \param[in] constraintOperator The comparison operator by which the * constraint will be evaluated. */ /*! \fn LinearConstraint::LinearConstraint(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const BoundType bound = 0.0, const LinearConstraintOperatorValueType constraintOperator = LinearConstraintOperatorType::LessEqual) * \brief LinearConstraint constructor. * * This constructor will create a LinearConstraint by copying the set of * indicator variables and coefficients. * * \tparam INDICATOR_VARIABLES_ITERATOR_TYPE Iterator type to iterate over the * set of indicator variables. * \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type to iterate over the set of * coefficients for the indicator variables. * * \param[in] indicatorVariablesBegin Iterator pointing to the begin of the set * of indicator variables. * \param[in] indicatorVariablesEnd Iterator pointing to the end of the set of * indicator variables. * \param[in] coefficientsBegin Iterator pointing to the begin of the set of * coefficients for the indicator variables. * \param[in] bound The right hand side of the constraint. * \param[in] constraintOperator The comparison operator by which the * constraint will be evaluated. */ /*! \fn LinearConstraint::LinearConstraint(const LinearConstraint& linearConstraint) * \brief LinearConstraint constructor. * * This constructor will create a LinearConstraint by copying an existing * linear constraint. * * \param[in] linearConstraint Existing linear constraint which will be copied. */ /*! \fn void LinearConstraint::reserve(const size_t numIndicatorVariables) * \brief Preallocate memory * * The reserve function fill preallocate enough memory to store at least the * stated number of indicator variables and the corresponding coefficients. * * \param[in] numIndicatorVariables The number of indicator variables for which * memory will be allocated. */ /*! \fn void LinearConstraint::add(const IndicatorVariableType& indicatorVariable, const ValueType coefficient) * \brief Add a single indicator variable and the corresponding coefficient to * the linear constraint. * * \param[in] indicatorVariable Indicator variable which will be added to the * linear constraint. * \param[in] coefficient Coefficient of the indicator variable. */ /*! \fn void LinearConstraint::add(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients) * \brief Add a set of indicator variables and the corresponding coefficients * to the linear constraint. * * \param[in] indicatorVariables Set of indicator variables which will be added * to the linear constraint. * \param[in] coefficients Set of coefficients for the indicator variables. */ /*! \fn void LinearConstraint::add(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin) * \brief Add a set of indicator variables and the corresponding coefficients * to the linear constraint. * * \tparam INDICATOR_VARIABLES_ITERATOR_TYPE Iterator type to iterate over the * set of indicator variables. * \tparam COEFFICIENTS_ITERATOR_TYPE Iterator type to iterate over the set of * coefficients for the indicator variables. * * \param[in] indicatorVariablesBegin Iterator pointing to the begin of the set * of indicator variables which will be * added to the linear constraint. * \param[in] indicatorVariablesEnd Iterator pointing to the end of the set of * indicator variables which will be added to * the linear constraint. * \param[in] coefficientsBegin Iterator pointing to the begin of the set of * coefficients for the indicator variables. */ /*! \fn void LinearConstraint::setBound(const BoundType bound) * \brief Set the bound of the linear constraint. * * \param[in] bound The new bound for the linear constraint. */ /*! \fn void LinearConstraint::setConstraintOperator(const LinearConstraintOperatorValueType constraintOperator) * \brief Set the constraint operator for the linear constraint. * * \param[in] constraintOperator The new constraint operator for the linear * constraint. */ /*! \fn LinearConstraint::ValueType LinearConstraint::operator()(const ITERATOR_TYPE statesBegin) const * \brief Evaluation operator to check if the linear constraint is violated by * the given labeling. * * \tparam ITERATOR_TYPE Iterator type. * * \param[in] statesBegin Iterator pointing to the begin of the labeling. * * \return The absolute value by which the constraint is violated (0.0 if the * linear constraint is not violated). * * \warning No boundary check is performed. */ /*! \fn LinearConstraint::IndicatorVariablesIteratorType LinearConstraint::indicatorVariablesBegin() const * \brief Get the begin iterator to the set of indicator variables. * * \return The const iterator pointing to the begin of the set of indicator * variables. */ /*! \fn LinearConstraint::IndicatorVariablesIteratorType LinearConstraint::indicatorVariablesEnd() const * \brief Get the end iterator to the set of indicator variables. * * \return The const iterator pointing to the end of the set of indicator * variables. */ /*! \fn LinearConstraint::CoefficientsIteratorType LinearConstraint::coefficientsBegin() const * \brief Get the begin iterator to the set of coefficients for the indicator * variables. * * \return The const iterator pointing to the begin of the set of coefficients * for the indicator variables. */ /*! \fn LinearConstraint::CoefficientsIteratorType LinearConstraint::coefficientsEnd() const * \brief Get the end iterator to the set of coefficients for the indicator * variables. * * \return The const iterator pointing to the end of the set of coefficients * for the indicator variables. */ /*! \fn LinearConstraint::BoundType LinearConstraint::getBound() const * \brief Get the bound of the linear constraint. * * \return The bound of the linear constraint. */ /*! \fn LinearConstraint::ConstraintOperatorType LinearConstraint::getConstraintOperator() const * \brief Get the constraint operator of the linear constraint. * * \return The constraint operator of the linear constraint. */ /*! \var LinearConstraint::indicatorVariables_ * \brief Storage for the set of indicator variables. */ /*! \var LinearConstraint::coefficients_ * \brief Storage for the set of coefficients for the indicator variables. */ /*! \var LinearConstraint::bound_ * \brief Storage for the bound of the linear constraint. */ /*! \var LinearConstraint::constraintOperator_ * \brief Storage for the constraint operator of the linear constraint. */ /****************** * implementation * ******************/ template inline LinearConstraint::LinearConstraint() : indicatorVariables_(), coefficients_(), bound_(0.0), constraintOperator_(LinearConstraintOperatorType::LessEqual) { } template inline LinearConstraint::LinearConstraint(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients, const BoundType bound, const LinearConstraintOperatorValueType constraintOperator) : indicatorVariables_(indicatorVariables), coefficients_(coefficients), bound_(bound), constraintOperator_(constraintOperator) { } template template inline LinearConstraint::LinearConstraint(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin, const BoundType bound, const LinearConstraintOperatorValueType constraintOperator) : indicatorVariables_(indicatorVariablesBegin, indicatorVariablesEnd), coefficients_(coefficientsBegin, coefficientsBegin + std::distance(indicatorVariablesBegin, indicatorVariablesEnd)), bound_(bound), constraintOperator_(constraintOperator) { } template inline LinearConstraint::LinearConstraint(const LinearConstraint& linearConstraint) : indicatorVariables_(linearConstraint.indicatorVariables_), coefficients_(linearConstraint.coefficients_), bound_(linearConstraint.bound_), constraintOperator_(linearConstraint.constraintOperator_) { } template inline void LinearConstraint::reserve(const size_t numIndicatorVariables) { indicatorVariables_.reserve(numIndicatorVariables); coefficients_.reserve(numIndicatorVariables); } template inline void LinearConstraint::add(const IndicatorVariableType& indicatorVariable, const ValueType coefficient) { indicatorVariables_.push_back(indicatorVariable); coefficients_.push_back(coefficient); } template inline void LinearConstraint::add(const IndicatorVariablesContainerType& indicatorVariables, const CoefficientsContainerType& coefficients) { indicatorVariables_.insert(indicatorVariables_.end(), indicatorVariables.begin(), indicatorVariables.end()); coefficients_.insert(coefficients_.end(), coefficients.begin(), coefficients.end()); } template template inline void LinearConstraint::add(const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesBegin, const INDICATOR_VARIABLES_ITERATOR_TYPE indicatorVariablesEnd, const COEFFICIENTS_ITERATOR_TYPE coefficientsBegin) { indicatorVariables_.insert(indicatorVariables_.end(), indicatorVariablesBegin, indicatorVariablesEnd); coefficients_.insert(coefficients_.end(), coefficientsBegin, coefficientsBegin + std::distance(indicatorVariablesBegin, indicatorVariablesEnd)); } template inline void LinearConstraint::setBound(const BoundType bound) { bound_ = bound; } template inline void LinearConstraint::setConstraintOperator(const LinearConstraintOperatorValueType constraintOperator) { constraintOperator_ = constraintOperator; } template template inline typename LinearConstraint::ValueType LinearConstraint::operator()(const ITERATOR_TYPE statesBegin) const { ValueType leftHandSide = 0.0; for(IndexType i = 0; i < indicatorVariables_.size(); ++i) { if(indicatorVariables_[i](statesBegin)) { leftHandSide += coefficients_[i]; } } // compare left hand side against bound const ValueType weight = leftHandSide - bound_; switch(constraintOperator_) { case LinearConstraintOperatorType::LessEqual : { if(weight > 0.0) { return weight; } else { return 0.0; } break; } case LinearConstraintOperatorType::Equal : { if(weight > 0.0) { return weight; } else if(weight < 0.0) { return -weight; } else { return 0.0; } break; } /*case LinearConstraintOperatorType::GreaterEqual : { if(weight < 0.0) { return -weight; } else { return 0.0; } break; } */ default : { // default corresponds to GreaterEqual case if(weight < 0.0) { return -weight; } else { return 0.0; } } } } template inline typename LinearConstraint::IndicatorVariablesIteratorType LinearConstraint::indicatorVariablesBegin() const { return indicatorVariables_.begin(); } template inline typename LinearConstraint::IndicatorVariablesIteratorType LinearConstraint::indicatorVariablesEnd() const { return indicatorVariables_.end(); } template inline typename LinearConstraint::CoefficientsIteratorType LinearConstraint::coefficientsBegin() const { return coefficients_.begin(); } template inline typename LinearConstraint::CoefficientsIteratorType LinearConstraint::coefficientsEnd() const { return coefficients_.end(); } template inline typename LinearConstraint::BoundType LinearConstraint::getBound() const { return bound_; } template inline typename LinearConstraint::LinearConstraintOperatorValueType LinearConstraint::getConstraintOperator() const { return constraintOperator_; } } // namespace opengm #endif /* OPENGM_LINEAR_CONSTRAINT_HXX_ */ opengm-2.3.6+20160905/include/opengm/datastructures/marray/000077500000000000000000000000001276346362400232065ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/datastructures/marray/marray.hxx000066400000000000000000006302321276346362400252400ustar00rootroot00000000000000#pragma once #ifndef MARRAY_HXX #define MARRAY_HXX #include #include #include // runtime_error #include #include #include #include // memcpy #include // reverse_iterator, distance #include #include #include // cout #include // allocator #include // accumulate /// Runtime-flexible multi-dimensional views and arrays namespace marray { enum StringStyle {TableStyle, MatrixStyle}; ///< Flag to be used with the member function asString() of View. enum CoordinateOrder {FirstMajorOrder, LastMajorOrder}; ///< Flag setting the order of coordinate tuples. struct InitializationSkipping { }; ///< Flag to indicate initialization skipping. static const bool Const = true; ///< Flag to be used with the template parameter isConst of View and Iterator. static const bool Mutable = false; ///< Flag to be used with the template parameter isConst of View and Iterator. static const CoordinateOrder defaultOrder = LastMajorOrder; ///< Default order of coordinate tuples. static const InitializationSkipping SkipInitialization = InitializationSkipping(); ///< Flag to indicate initialization skipping. template class ViewExpression; // \cond suppress doxygen template class UnaryViewExpression; template class BinaryViewExpression; template class BinaryViewExpressionScalarFirst; template class BinaryViewExpressionScalarSecond; // \endcond suppress doxygen template > class View; #ifdef HAVE_CPP0X_TEMPLATE_ALIASES template using ConstView = View; #endif template > class Iterator; template > class Vector; template > class Matrix; template > class Marray; // assertion testing #ifdef NDEBUG const bool MARRAY_NO_DEBUG = true; ///< General assertion testing disabled. const bool MARRAY_NO_ARG_TEST = true; ///< Argument testing disabled. #else const bool MARRAY_NO_DEBUG = false; ///< General assertion testing enabled. const bool MARRAY_NO_ARG_TEST = false; ///< Argument testing enabled. #endif // \cond suppress doxygen namespace marray_detail { // meta-programming template struct IfBool; template struct IfBool { typedef TRUECASE type; }; template struct IfBool { typedef FALSECASE type; }; template struct IsEqual { static const bool type = false; }; template struct IsEqual { static const bool type = true; }; template struct TypeTraits { static const unsigned char position = 255; }; template<> struct TypeTraits { static const unsigned char position = 0; }; template<> struct TypeTraits { static const unsigned char position = 1; }; template<> struct TypeTraits { static const unsigned char position = 2; }; template<> struct TypeTraits { static const unsigned char position = 3; }; template<> struct TypeTraits { static const unsigned char position = 4; }; template<> struct TypeTraits { static const unsigned char position = 5; }; template<> struct TypeTraits { static const unsigned char position = 6; }; template<> struct TypeTraits { static const unsigned char position = 7; }; template<> struct TypeTraits { static const unsigned char position = 8; }; template<> struct TypeTraits { static const unsigned char position = 9; }; template<> struct TypeTraits { static const unsigned char position = 10; }; template struct PromoteType { typedef typename IfBool::position >= TypeTraits::position, A, B>::type type; }; // assertion testing template inline void Assert(A assertion) { #ifdef NDEBUG #else if(!assertion) throw std::runtime_error("Assertion failed."); #endif } // geometry of views template > class Geometry; template inline void stridesFromShape(ShapeIterator, ShapeIterator, StridesIterator, const CoordinateOrder& = defaultOrder); // operations on entries of views template inline void operate(View&, Functor); template inline void operate(View&, const T&, Functor); template inline void operate(View&, const View&, Functor); template inline void operate(View& v, const ViewExpression& expression, Functor f); // helper classes template struct OperateHelperUnary; template struct OperateHelperBinaryScalar; template struct OperateHelperBinary; template struct AssignmentOperatorHelper; template struct AccessOperatorHelper; // unary in-place functors template struct Negative { void operator()(T& x) { x = -x; } }; template struct PrefixIncrement { void operator()(T& x) { ++x; } }; template struct PostfixIncrement { void operator()(T& x) { x++; } }; template struct PrefixDecrement { void operator()(T& x) { --x; } }; template struct PostfixDecrement { void operator()(T& x) { x--; } }; // binary in-place functors template struct Assign { void operator()(T1& x, const T2& y) { x = y; } }; template struct PlusEqual { void operator()(T1& x, const T2& y) { x += y; } }; template struct MinusEqual { void operator()(T1& x, const T2& y) { x -= y; } }; template struct TimesEqual { void operator()(T1& x, const T2& y) { x *= y; } }; template struct DividedByEqual { void operator()(T1& x, const T2& y) { x /= y; } }; // unary functors template struct Negate { T operator()(const T& x) const { return -x; } }; // binary functors template struct Plus { U operator()(const T1& x, const T2& y) const { return x + y; } }; template struct Minus { U operator()(const T1& x, const T2& y) const { return x - y; } }; template struct Times { U operator()(const T1& x, const T2& y) const { return x * y; } }; template struct DividedBy { U operator()(const T1& x, const T2& y) const { return x / y; } }; } // \endcond suppress doxygen /// Array-Interface to an interval of memory. /// /// A view makes a subset of memory look as if it was stored in an /// Marray. With the help of a view, data in a subset of memory can /// be accessed and manipulated conveniently. In contrast to arrays /// which allocate and de-allocate their own memory, views only /// reference memory that has been allocated by other means. /// Perhaps the simplest and most important use of views is to /// read and manipulate sub-arrays. /// /// Notes on arithmetic operators of View: /// - Only the pre-fix operators ++ and -- and not the corresponding post-fix /// operators are implemented for View because the return value of the /// post-fix operators would have to be the View as it is prior to the /// operator call. However, the data under the view cannot be preserved when /// incrementing or decrementing. Some compilers might accept the post-fix /// operators, use the pre-fix implementation implicitly and issue a warning. /// template class View : public ViewExpression, T> { public: typedef T value_type; typedef T ValueType; typedef typename marray_detail::IfBool::type pointer; typedef const T* const_pointer; typedef typename marray_detail::IfBool::type reference; typedef const T& const_reference; typedef Iterator iterator; typedef Iterator const_iterator; typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef ViewExpression, T> base; typedef typename A::template rebind::other allocator_type; // construction View(const allocator_type& = allocator_type()); View(pointer, const allocator_type& = allocator_type()); View(const View&); template View(ShapeIterator, ShapeIterator, pointer, const CoordinateOrder& = defaultOrder, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); template View(ShapeIterator, ShapeIterator, StrideIterator, pointer, const CoordinateOrder&, const allocator_type& = allocator_type()); #ifdef HAVE_CPP0X_INITIALIZER_LISTS View(std::initializer_list, pointer, const CoordinateOrder& = defaultOrder, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); View(std::initializer_list, std::initializer_list, pointer, const CoordinateOrder&, const allocator_type& = allocator_type()); #endif // assignment View& operator=(const T&); View& operator=(const View&); // over-write default View& operator=(const View&); // over-write default template View& operator=(const View&); template View& operator=(const ViewExpression&); void assign(const allocator_type& = allocator_type()); template void assign(ShapeIterator, ShapeIterator, pointer, const CoordinateOrder& = defaultOrder, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); template void assign(ShapeIterator, ShapeIterator, StrideIterator, pointer, const CoordinateOrder&, const allocator_type& = allocator_type()); #ifdef HAVE_CPP0X_INITIALIZER_LISTS void assign(std::initializer_list, pointer, const CoordinateOrder& = defaultOrder, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); void assign(std::initializer_list, std::initializer_list, pointer, const CoordinateOrder&, const allocator_type& = allocator_type()); #endif // query const size_t dimension() const; const size_t size() const; const size_t shape(const size_t) const; const size_t* shapeBegin() const; const size_t* shapeEnd() const; const size_t strides(const size_t) const; const size_t* stridesBegin() const; const size_t* stridesEnd() const; const CoordinateOrder& coordinateOrder() const; const bool isSimple() const; template bool overlaps(const View&) const; // element access template reference operator()(U); template reference operator()(U) const; #ifndef HAVE_CPP0X_VARIADIC_TEMPLATES reference operator()(const size_t, const size_t); reference operator()(const size_t, const size_t) const; reference operator()(const size_t, const size_t, const size_t); reference operator()(const size_t, const size_t, const size_t) const; reference operator()(const size_t, const size_t, const size_t, const size_t); reference operator()(const size_t, const size_t, const size_t, const size_t) const; reference operator()(const size_t, const size_t, const size_t, const size_t, const size_t); reference operator()(const size_t, const size_t, const size_t, const size_t, const size_t) const; reference operator()(const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t); reference operator()(const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t, const size_t) const; #else reference operator()(const size_t); reference operator()(const size_t) const; template reference operator()(const size_t, const Args...); template reference operator()(const size_t, const Args...) const; private: size_t elementAccessHelper(const size_t, const size_t); size_t elementAccessHelper(const size_t, const size_t) const; template size_t elementAccessHelper(const size_t, const size_t, const Args...); template size_t elementAccessHelper(const size_t, const size_t, const Args...) const; public: #endif // sub-views template void view(BaseIterator, ShapeIterator, View&) const; template void view(BaseIterator, ShapeIterator, const CoordinateOrder&, View&) const; template View view(BaseIterator, ShapeIterator) const; template View view(BaseIterator, ShapeIterator, const CoordinateOrder&) const; template void constView(BaseIterator, ShapeIterator, View&) const; template void constView(BaseIterator, ShapeIterator, const CoordinateOrder&, View&) const; template View constView(BaseIterator, ShapeIterator) const; template View constView(BaseIterator, ShapeIterator, const CoordinateOrder&) const; #ifdef HAVE_CPP0X_INITIALIZER_LISTS void view(std::initializer_list, std::initializer_list, View&) const; void view(std::initializer_list, std::initializer_list, const CoordinateOrder&, View&) const; void constView(std::initializer_list, std::initializer_list, View&) const; void constView(std::initializer_list, std::initializer_list, const CoordinateOrder&, View&) const; #endif // iterator access iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; // coordinate transformation template void reshape(ShapeIterator, ShapeIterator); template void permute(CoordinateIterator); void transpose(const size_t, const size_t); void transpose(); void shift(const int); void squeeze(); template View reshapedView(ShapeIterator, ShapeIterator) const; template View permutedView(CoordinateIterator) const; View transposedView(const size_t, const size_t) const; View transposedView() const; View shiftedView(const int) const; View boundView(const size_t, const size_t = 0) const; View squeezedView() const; #ifdef HAVE_CPP0X_INITIALIZER_LISTS void reshape(std::initializer_list); void permute(std::initializer_list); View reshapedView(std::initializer_list) const; View permutedView(std::initializer_list) const; #endif // conversion between coordinates, index and offset template void coordinatesToIndex(CoordinateIterator, size_t&) const; template void coordinatesToOffset(CoordinateIterator, size_t&) const; template void indexToCoordinates(size_t, CoordinateIterator) const; void indexToOffset(size_t, size_t&) const; #ifdef HAVE_CPP0X_INITIALIZER_LISTS void coordinatesToIndex(std::initializer_list, size_t&) const; void coordinatesToOffset(std::initializer_list, size_t&) const; #endif // output as string std::string asString(const StringStyle& = MatrixStyle) const; private: typedef typename marray_detail::Geometry geometry_type; View(pointer, const geometry_type&); void updateSimplicity(); void testInvariant() const; // unsafe direct memory access const T& operator[](const size_t) const; T& operator[](const size_t); // data and memory address pointer data_; geometry_type geometry_; template friend class View; template friend class Marray; template friend class Vector; template friend class Matrix; // \cond suppress doxygen template friend struct marray_detail::AssignmentOperatorHelper; friend struct marray_detail::AccessOperatorHelper; friend struct marray_detail::AccessOperatorHelper; template friend class ViewExpression; template friend class UnaryViewExpression; template friend class BinaryViewExpression; template friend class BinaryViewExpressionScalarFirst; template friend class BinaryViewExpressionScalarSecond; template friend void marray_detail::operate(View& v, const ViewExpression& expression, Functor f); // \endcond end suppress doxygen }; /// STL-compliant random access iterator for View and Marray. /// /// In addition to the STL iterator interface, the member functions /// hasMore(), index(), and coordinate() are defined. /// template class Iterator { public: // STL random access iterator typedefs typedef typename std::random_access_iterator_tag iterator_category; typedef T value_type; typedef std::ptrdiff_t difference_type; typedef typename marray_detail::IfBool::type pointer; typedef typename marray_detail::IfBool::type reference; // non-standard typedefs typedef typename marray_detail::IfBool*, View*>::type view_pointer; typedef typename marray_detail::IfBool&, View&>::type view_reference; // construction Iterator(); Iterator(const View&, const size_t = 0); Iterator(View&, const size_t = 0); Iterator(const View&, const size_t = 0); Iterator(const Iterator&); // conversion from mutable to const // STL random access iterator operations reference operator*() const; pointer operator->() const; reference operator[](const size_t) const; Iterator& operator+=(const difference_type&); Iterator& operator-=(const difference_type&); Iterator& operator++(); // prefix Iterator& operator--(); // prefix Iterator operator++(int); // postfix Iterator operator--(int); // postfix Iterator operator+(const difference_type&) const; Iterator operator-(const difference_type&) const; template difference_type operator-(const Iterator&) const; template bool operator==(const Iterator&) const; template bool operator!=(const Iterator&) const; template bool operator<(const Iterator&) const; template bool operator>(const Iterator&) const; template bool operator<=(const Iterator&) const; template bool operator>=(const Iterator&) const; // operations beyond the STL standard bool hasMore() const; size_t index() const; template void coordinate(CoordinateIterator) const; private: void testInvariant() const; // attributes view_pointer view_; pointer pointer_; size_t index_; std::vector coordinates_; friend class Marray; friend class Iterator; // for comparison operators }; /// Runtime-flexible multi-dimensional array. template class Marray : public View { public: typedef View base; typedef typename base::value_type value_type; typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::iterator iterator; typedef typename base::reverse_iterator reverse_iterator; typedef typename base::const_iterator const_iterator; typedef typename base::const_reverse_iterator const_reverse_iterator; typedef typename A::template rebind::other allocator_type; // constructors and destructor Marray(const allocator_type& = allocator_type()); Marray(const T&, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); template Marray(ShapeIterator, ShapeIterator, const T& = T(), const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); template Marray(const InitializationSkipping&, ShapeIterator, ShapeIterator, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); #ifdef HAVE_CPP0X_INITIALIZER_LISTS Marray(std::initializer_list, const T& = T(), const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); #endif Marray(const Marray&); template Marray(const ViewExpression&, const allocator_type& = allocator_type()); template Marray(const View&); ~Marray(); // assignment Marray& operator=(const T&); Marray& operator=(const Marray&); // over-write default template Marray& operator=(const View&); template Marray& operator=(const ViewExpression&); void assign(const allocator_type& = allocator_type()); // resize template void resize(ShapeIterator, ShapeIterator, const T& = T()); template void resize(const InitializationSkipping&, ShapeIterator, ShapeIterator); #ifdef HAVE_CPP0X_INITIALIZER_LISTS void resize(std::initializer_list, const T& = T()); void resize(const InitializationSkipping&, std::initializer_list); #endif private: typedef typename base::geometry_type geometry_type; // hiding inherited functions template void permute(CoordinateIterator) {} void transpose(const size_t, const size_t) {} void transpose() {} void shift(const int) {} void squeeze() {} void testInvariant() const; template void resizeHelper(ShapeIterator, ShapeIterator, const T& = T()); allocator_type dataAllocator_; friend class Vector; friend class Matrix; }; /// One-dimensional Marray. template class Vector : public Marray { public: typedef Marray base; typedef typename base::value_type value_type; typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::iterator iterator; typedef typename base::reverse_iterator reverse_iterator; typedef typename base::const_iterator const_iterator; typedef typename base::const_reverse_iterator const_reverse_iterator; typedef typename base::allocator_type allocator_type; // constructors and destructor Vector(const allocator_type& = allocator_type()); template Vector(const View&); Vector(const size_t, const T& = T(), const allocator_type& = allocator_type()); Vector(const InitializationSkipping&, const size_t, const allocator_type& = allocator_type()); template Vector(const ViewExpression&, const allocator_type& = allocator_type()); #ifdef HAVE_CPP0X_INITIALIZER_LISTS Vector(std::initializer_list list, const allocator_type& = allocator_type()); #endif // assignment operator Vector& operator=(const T&); Vector& operator=(const Vector&); // over-write default template Vector& operator=(const View&); template Vector& operator=(const ViewExpression&); // element access T& operator[](const size_t); const T& operator[](const size_t) const; // reshape, resize void reshape(const size_t); void resize(const size_t, const T& = T()); void resize(const InitializationSkipping&, const size_t); private: void testInvariant() const; }; /// Two-dimensional Marray. template class Matrix : public Marray { public: typedef Marray base; typedef typename base::value_type value_type; typedef typename base::pointer pointer; typedef typename base::const_pointer const_pointer; typedef typename base::reference reference; typedef typename base::const_reference const_reference; typedef typename base::iterator iterator; typedef typename base::reverse_iterator reverse_iterator; typedef typename base::const_iterator const_iterator; typedef typename base::const_reverse_iterator const_reverse_iterator; typedef typename base::allocator_type allocator_type; // constructors and destructor Matrix(const allocator_type& = allocator_type()); template Matrix(const View&); Matrix(const size_t, const size_t, const T& = T(), const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); Matrix(const InitializationSkipping&, const size_t, const size_t, const CoordinateOrder& = defaultOrder, const allocator_type& = allocator_type()); template Matrix(const ViewExpression&, const allocator_type& = allocator_type()); // assignment operator Matrix& operator=(const T&); Matrix& operator=(const Matrix&); // over-write default // overwrite standard operator= template Matrix& operator=(const View&); template Matrix& operator=(const ViewExpression&); // resize and reshape void reshape(const size_t, const size_t); void resize(const size_t, const size_t, const T& = T()); void resize(const InitializationSkipping&, const size_t, const size_t); private: void testInvariant() const; }; // implementation of View #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Compute the index that corresponds to a sequence of coordinates. /// /// \param coordinate Coordinate given as initializer list. /// \param out Index (output) /// \sa coordinatesToOffset(), indexToCoordinates(), and indexToOffset() /// template inline void View::coordinatesToIndex ( std::initializer_list coordinate, size_t& out ) const { coordinatesToIndex(coordinate.begin(), out); } #endif /// Compute the index that corresponds to a sequence of coordinates. /// /// \param it An iterator to the beginning of the coordinate sequence. /// \param out Index (output) /// \sa coordinatesToOffset(), indexToCoordinates(), and indexToOffset() /// template template inline void View::coordinatesToIndex ( CoordinateIterator it, size_t& out ) const { testInvariant(); out = 0; for(size_t j=0; jdimension(); ++j, ++it) { marray_detail::Assert(MARRAY_NO_ARG_TEST || static_cast(*it) < shape(j)); out += static_cast(*it) * geometry_.shapeStrides(j); } } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Compute the offset that corresponds to a sequence of coordinates. /// /// \param it An iterator to the beginning of the coordinate sequence. /// \param out Index (output) /// \sa coordinatesToIndex(), indexToCoordinates(), and indexToOffset() /// template inline void View::coordinatesToOffset ( std::initializer_list coordinate, size_t& out ) const { coordinatesToOffset(coordinate.begin(), out); } #endif /// Compute the offset that corresponds to a sequence of coordinates. /// /// \param it An iterator to the beginning of the coordinate sequence. /// \param out Index (output) /// \sa coordinatesToIndex(), indexToCoordinates(), and indexToOffset() /// template template inline void View::coordinatesToOffset ( CoordinateIterator it, size_t& out ) const { testInvariant(); out = 0; for(size_t j=0; jdimension(); ++j, ++it) { marray_detail::Assert(MARRAY_NO_ARG_TEST || static_cast(*it) < shape(j)); out += static_cast(*it) * strides(j); } } /// Compute the coordinate sequence that corresponds to an index. /// /// \param index Index /// \param outit An iterator into a container into which the coordinate /// sequence is to be written (output). /// \sa coordinatesToIndex(), coordinatesToOffset(), and indexToOffset() /// template template inline void View::indexToCoordinates ( size_t index, // copy to work on CoordinateIterator outit ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || this->dimension() > 0); marray_detail::Assert(MARRAY_NO_ARG_TEST || index < this->size()); if(coordinateOrder() == FirstMajorOrder) { for(size_t j=0; jdimension(); ++j, ++outit) { *outit = size_t(index / geometry_.shapeStrides(j)); index = index % geometry_.shapeStrides(j); } } else { // last major order size_t j = this->dimension()-1; outit += j; for(;;) { *outit = size_t(index / geometry_.shapeStrides(j)); index = index % geometry_.shapeStrides(j); if(j == 0) { break; } else { --outit; --j; } } } } /// Compute the offset that corresponds to an index. /// /// \param index Index. /// \param out Offset (output). /// \sa coordinatesToIndex(), coordinatesToOffset(), and indexToCoordinates() /// template inline void View::indexToOffset ( size_t index, size_t& out ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_ARG_TEST || index < this->size()); if(isSimple()) { out = index; } else { out = 0; if(coordinateOrder() == FirstMajorOrder) { for(size_t j=0; jdimension(); ++j) { out += geometry_.strides(j) * (index / geometry_.shapeStrides(j)); index = index % geometry_.shapeStrides(j); } } else { // last major order if(this->dimension() == 0) { marray_detail::Assert(MARRAY_NO_ARG_TEST || index == 0); return; } else { size_t j = this->dimension()-1; for(;;) { out += geometry_.strides(j) * (index / geometry_.shapeStrides(j)); index = index % geometry_.shapeStrides(j); if(j == 0) { break; } else { --j; } } } } } } /// Empty constructor. /// /// The empty constructor sets the data pointer to 0. /// It does not allocate memory for a scalar. /// /// \param allocator Allocator. /// template inline View::View ( const allocator_type& allocator ) : data_(0), geometry_(geometry_type(allocator)) { testInvariant(); } // private constructor template inline View::View ( pointer data, const geometry_type& geometry ) : data_(data), geometry_(geometry) { testInvariant(); } /// Construct View from a scalar. /// /// \param data Pointer to data. /// \param allocator Allocator. /// template inline View::View ( pointer data, const allocator_type& allocator ) : data_(data), geometry_(geometry_type(0, defaultOrder, 1, true, allocator)) { testInvariant(); } /// Construct View from a View on mutable data. /// /// \param in View on mutable data. /// template inline View::View ( const View& in ) : data_(in.data_), geometry_(in.geometry_) { testInvariant(); } /// Construct unstrided View /// /// \param begin Iterator to the beginning of a sequence that /// defines the shape. /// \param end Iterator to the end of this sequence. /// \param data Pointer to data. /// \param externalCoordinateOrder Flag specifying the order /// of coordinates based on which the strides are computed. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template template inline View::View ( ShapeIterator begin, ShapeIterator end, pointer data, const CoordinateOrder& externalCoordinateOrder, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) : data_(data), geometry_(begin, end, externalCoordinateOrder, internalCoordinateOrder, allocator) { testInvariant(); } /// Construct strided View /// /// \param begin Iterator to the beginning of a sequence that /// defines the shape. /// \param end Iterator to the end of this sequence. /// \param it Iterator to the beginning of a sequence that /// defines the strides. /// \param data Pointer to data. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template template inline View::View ( ShapeIterator begin, ShapeIterator end, StrideIterator it, pointer data, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) : data_(data), geometry_(begin, end, it, internalCoordinateOrder, allocator) { testInvariant(); } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Construct unstrided View /// /// \param shape Shape initializer list. /// \param data Pointer to data. /// \param externalCoordinateOrder Flag specifying the order /// of coordinates based on which the strides are computed. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template inline View::View ( std::initializer_list shape, pointer data, const CoordinateOrder& externalCoordinateOrder, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) : data_(data), geometry_(shape.begin(), shape.end(), externalCoordinateOrder, internalCoordinateOrder, allocator) { testInvariant(); } /// Construct strided View /// /// \param shape Shape initializer list. /// \param strides Strides initializer list. /// \param data Pointer to data. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// template inline View::View ( std::initializer_list shape, std::initializer_list strides, pointer data, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) : data_(data), geometry_(shape.begin(), shape.end(), strides.begin(), internalCoordinateOrder, allocator) { testInvariant(); } #endif /// Clear View. /// /// Leaves the View in the same state as if the empty constructor /// had been called. /// /// \sa View() /// template inline void View::assign ( const allocator_type& allocator ) { geometry_ = geometry_type(allocator); data_ = 0; testInvariant(); } /// Initialize unstrided View /// /// \param begin Iterator to the beginning of a sequence that /// defines the shape. /// \param end Iterator to the end of this sequence. /// \param data Pointer to data. /// \param externalCoordinateOrder Flag specifying the order /// of coordinates based on which the strides are computed. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template template inline void View::assign ( ShapeIterator begin, ShapeIterator end, pointer data, const CoordinateOrder& externalCoordinateOrder, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) { // the invariant is not tested as a pre-condition of this // function to allow for unsafe manipulations prior to its // call geometry_ = typename marray_detail::Geometry(begin, end, externalCoordinateOrder, internalCoordinateOrder, allocator); data_ = data; testInvariant(); } /// Initialize strided View /// /// \param begin Iterator to the beginning of a sequence that /// defines the shape. /// \param end Iterator to the end of this sequence. /// \param it Iterator to the beginning of a sequence that /// defines the strides. /// \param data Pointer to data. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template template inline void View::assign ( ShapeIterator begin, ShapeIterator end, StrideIterator it, pointer data, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) { // the invariant is not tested as a pre-condition of this // function to allow for unsafe manipulations prior to its // call geometry_ = typename marray_detail::Geometry(begin, end, it, internalCoordinateOrder, allocator); data_ = data; testInvariant(); } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Initialize unstrided View /// /// \param shape Shape initializer list. /// \param data Pointer to data. /// \param externalCoordinateOrder Flag specifying the order /// of coordinates based on which the strides are computed. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template inline void View::assign ( std::initializer_list shape, pointer data, const CoordinateOrder& externalCoordinateOrder, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) { assign(shape.begin(), shape.end(), data, externalCoordinateOrder, internalCoordinateOrder, allocator); } /// Initialize strided View /// /// \param shape Shape initializer list. /// \param strides Strides initialier list. /// defines the strides. /// \param data Pointer to data. /// \param internalCoordinateOrder Flag specifying the order /// of coordinates used for scalar indexing and iterators. /// \param allocator Allocator. /// template inline void View::assign ( std::initializer_list shape, std::initializer_list strides, pointer data, const CoordinateOrder& internalCoordinateOrder, const allocator_type& allocator ) { assign(shape.begin(), shape.end(), strides.begin(), data, internalCoordinateOrder, allocator); } #endif /// Reference data. /// /// \param u If u is an integer type, scalar indexing is performed. /// Otherwise, it is assumed that u is an iterator to the beginning /// of a coordinate sequence. /// \return Reference to the entry at u. /// template template inline typename View::reference View::operator() ( U u ) { return marray_detail::AccessOperatorHelper::is_integer>::execute(*this, u); } /// Reference data. /// /// \param u If u is an integer type, scalar indexing is performed. /// Otherwise, it is assumed that u is an iterator to the beginning /// of a coordinate sequence. /// \return Reference to the entry at u. /// template template inline typename View::reference View::operator() ( U u ) const { return marray_detail::AccessOperatorHelper::is_integer>::execute(*this, u); } #ifndef HAVE_CPP0X_VARIADIC_TEMPLATES /// Reference data in a 2-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 2-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 2)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1))); return data_[c0*strides(0) + c1*strides(1)]; } /// Reference data in a 2-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 2-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1 ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 2)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1))); return data_[c0*strides(0) + c1*strides(1)]; } /// Reference data in a 3-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 3-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 3)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2)]; } /// Reference data in a 3-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 3-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2 ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 3)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2)]; } /// Reference data in a 4-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 4-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 4)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3)]; } /// Reference data in a 4-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 4-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3 ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 4)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3)]; } /// Reference data in a 5-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 5-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// \param c4 5th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3, const size_t c4 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 5)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3) && c4 < shape(4))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3) + c4*strides(4)]; } /// Reference data in a 5-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 5-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// \param c4 5th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3, const size_t c4 ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 5)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3) && c4 < shape(4))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3) + c4*strides(4)]; } /// Reference data in a 10-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 5-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// \param c4 5th coordinate. /// \param c5 6th coordinate. /// \param c6 7th coordinate. /// \param c7 8th coordinate. /// \param c8 9th coordinate. /// \param c9 10th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3, const size_t c4, const size_t c5, const size_t c6, const size_t c7, const size_t c8, const size_t c9 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 10)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3) && c4 < shape(4) && c5 < shape(5) && c6 < shape(6) && c7 < shape(7) && c8 < shape(8) && c9 < shape(9))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3) + c4*strides(4) + c5*strides(5) + c6*strides(6) + c7*strides(7) + c8*strides(8) + c9*strides(9)]; } /// Reference data in a 10-dimensional View by coordinates. /// /// This function issues a runtime error if the View is not /// 5-dimensional. /// /// \param c0 1st coordinate. /// \param c1 2nd coordinate. /// \param c2 3rd coordinate. /// \param c3 4th coordinate. /// \param c4 5th coordinate. /// \param c5 6th coordinate. /// \param c6 7th coordinate. /// \param c7 8th coordinate. /// \param c8 9th coordinate. /// \param c9 10th coordinate. /// template inline typename View::reference View::operator() ( const size_t c0, const size_t c1, const size_t c2, const size_t c3, const size_t c4, const size_t c5, const size_t c6, const size_t c7, const size_t c8, const size_t c9 ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || (data_ != 0 && dimension() == 10)); marray_detail::Assert(MARRAY_NO_ARG_TEST || (c0 < shape(0) && c1 < shape(1) && c2 < shape(2) && c3 < shape(3) && c4 < shape(4) && c5 < shape(5) && c6 < shape(6) && c7 < shape(7) && c8 < shape(8) && c9 < shape(9))); return data_[c0*strides(0) + c1*strides(1) + c2*strides(2) + c3*strides(3) + c4*strides(4) + c5*strides(5) + c6*strides(6) + c7*strides(7) + c8*strides(8) + c9*strides(9)]; } #else template inline size_t View::elementAccessHelper ( const size_t Dim, const size_t value ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || (value < shape(Dim-1) ) ); return strides(Dim-1) * value; } template inline size_t View::elementAccessHelper ( const size_t Dim, const size_t value ) const { marray_detail::Assert(MARRAY_NO_ARG_TEST || (value < shape(Dim-1) ) ); return strides(Dim-1) * value; } template template inline size_t View::elementAccessHelper ( const size_t Dim, const size_t value, const Args... args ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || (value < shape(Dim-1-sizeof...(args)) ) ); return value * strides(Dim-1-sizeof...(args)) + elementAccessHelper(Dim, args...); } template template inline size_t View::elementAccessHelper ( const size_t Dim, const size_t value, const Args... args ) const { marray_detail::Assert(MARRAY_NO_ARG_TEST || (value < shape(Dim-1-sizeof...(args)) ) ); return value * strides(Dim-1-sizeof...(args)) + elementAccessHelper(Dim, args...); } template inline typename View::reference View::operator() ( const size_t value ) { testInvariant(); if(dimension() == 0) { marray_detail::Assert(MARRAY_NO_ARG_TEST || value == 0); return data_[0]; } else { size_t offset; indexToOffset(value, offset); return data_[offset]; } } template inline typename View::reference View::operator() ( const size_t value ) const { testInvariant(); if(dimension() == 0) { marray_detail::Assert(MARRAY_NO_ARG_TEST || value == 0); return data_[0]; } else { size_t offset; indexToOffset(value, offset); return data_[offset]; } } template template inline typename View::reference View::operator() ( const size_t value, const Args... args ) { testInvariant(); marray_detail::Assert( MARRAY_NO_DEBUG || ( data_ != 0 && sizeof...(args)+1 == dimension() ) ); return data_[strides(0)*value + elementAccessHelper(sizeof...(args)+1, args...) ]; } template template inline typename View::reference View::operator() ( const size_t value, const Args... args ) const { testInvariant(); marray_detail::Assert( MARRAY_NO_DEBUG || ( data_ != 0 && sizeof...(args)+1 == dimension() ) ); return data_[ strides(0) * static_cast(value) + static_cast(elementAccessHelper(sizeof...(args)+1, args...)) ]; } #endif // #ifndef HAVE_CPP0X_VARIADIC_TEMPLATES /// Get the number of data items. /// /// \return Size. /// template inline const size_t View::size() const { return geometry_.size(); } /// Get the dimension. /// /// Not well-defined if the data pointer is 0. /// /// \return Dimension. /// template inline const size_t View::dimension() const { marray_detail::Assert(MARRAY_NO_DEBUG || this->data_ != 0); return geometry_.dimension(); } /// Get the shape in one dimension. /// /// \param dimension Dimension /// \return Shape in that dimension. /// template inline const size_t View::shape ( const size_t dimension ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); marray_detail::Assert(MARRAY_NO_ARG_TEST || dimension < this->dimension()); return geometry_.shape(dimension); } /// Get a constant iterator to the beginning of the shape vector. /// /// \return iterator. /// \sa shapeEnd() /// template inline const size_t* View::shapeBegin() const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); return geometry_.shapeBegin(); } /// Get a constant iterator to the end of the shape vector. /// /// \return iterator. /// \sa shapeBegin() /// template inline const size_t* View::shapeEnd() const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); return geometry_.shapeEnd(); } /// Get the strides in one dimension. /// /// \param dimension Dimension /// \return Stride in that dimension. /// template inline const size_t View::strides ( const size_t dimension ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); marray_detail::Assert(MARRAY_NO_ARG_TEST || dimension < this->dimension()); return geometry_.strides(dimension); } /// Get a constant iterator to the beginning of the strides vector. /// /// \return iterator. /// \sa stridesEnd() /// template inline const size_t* View::stridesBegin() const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); return geometry_.stridesBegin(); } /// Get a constant iterator to the end of the strides vector. /// /// \return iterator. /// \sa stridesBegin() /// template inline const size_t* View::stridesEnd() const { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); return geometry_.stridesEnd(); } /// Get the coordinate order used for scalar indexing and iterators. /// /// \return CoordinateOrder. enum: FirstMajorOrder, LastMajorOrder /// template inline const CoordinateOrder& View::coordinateOrder() const { testInvariant(); return geometry_.coordinateOrder(); } /// Determine whether the shape strides equal the strides of the View. /// /// \return bool. /// template inline const bool View::isSimple() const { testInvariant(); return geometry_.isSimple(); } /// Assignment. /// /// operator= (the assignment operator) has a non-trivial behavior. /// In most cases, it will work as most programmers will expect. /// Here's a complete description of the semantics of to.operator=(from) /// or equivalently, to = from. /// /// Consider the following cases: /// (1) 'to' is mutable (isConst == false) /// (a) 'from' is mutable (isConst == false) /// (i) 'to' is initialized (data_ != 0) /// (ii) 'to' is un-initialized (data_ == 0) /// (b) 'from' is constant (isConst == true) /// (2) 'to' is constant (isConst == true) /// /// (i) The operator attempts to copy the data under view 'b' to /// the memory under view 'a'. This works if both views have the /// same size, regardless of their dimension and shape. Equality /// of sizes is checked by an assertion. /// /// (ii) Unless &a == &b (self-assignment), the operator copies /// the (data) pointer of view 'b' to view 'a', without copying /// the data itself. In addition, all the properties of view 'b' /// are copied to view 'a'. /// /// (b) The operator attempts to copy the data under view 'b' to /// the memory under view 'a'. This works if both views have the /// same size, regardless of their dimension and shape. Equality /// of sizes is checked by an assertion. If 'a' is un-initialized /// the assertion fails (because the size of a will be zero). /// Unlike in (ii), the pointer is not copied in this case. /// Thus, a conversion from mutable to const is prevented. /// /// (2) Unless &a == &b (self-assignment), the operator copies /// the (data) pointer of view 'b' to view 'a', without copying /// the data itself. In addition, all the properties of view 'b' /// are copied to view 'a'. Note that changing the data under /// a constant view would be counter-intuitive. /// template inline View& View::operator= ( const View& in ) { testInvariant(); marray_detail::AssignmentOperatorHelper::execute(in, *this); testInvariant(); return *this; } /// Assignment. /// template inline View& View::operator= ( const View& in ) { testInvariant(); marray_detail::AssignmentOperatorHelper::execute(in, *this); testInvariant(); return *this; } /// Assignment. /// template template inline View& View::operator= ( const View& in ) { testInvariant(); marray_detail::AssignmentOperatorHelper::execute(in, *this); testInvariant(); return *this; } /// Assignment. /// /// \param value Value. /// /// All entries are set to value. /// template inline View& View::operator= ( const T& value ) { marray_detail::Assert(MARRAY_NO_DEBUG || data_ != 0); if(isSimple()) { for(size_t j=0; j, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 2) marray_detail::OperateHelperBinaryScalar<2, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 3) marray_detail::OperateHelperBinaryScalar<3, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 4) marray_detail::OperateHelperBinaryScalar<4, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 5) marray_detail::OperateHelperBinaryScalar<5, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 6) marray_detail::OperateHelperBinaryScalar<6, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 7) marray_detail::OperateHelperBinaryScalar<7, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 8) marray_detail::OperateHelperBinaryScalar<8, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 9) marray_detail::OperateHelperBinaryScalar<9, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else if(dimension() == 10) marray_detail::OperateHelperBinaryScalar<10, marray_detail::Assign, T, T, A>::operate(*this, value, marray_detail::Assign(), data_); else { for(iterator it = begin(); it.hasMore(); ++it) { *it = value; } } return *this; } template template inline View& View::operator= ( const ViewExpression& expression ) { marray_detail::operate(*this, expression, marray_detail::Assign()); return *this; } /// Get a sub-view with the same coordinate order. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param out Sub-View (output). /// template template inline void View::view ( BaseIterator bit, ShapeIterator sit, View& out ) const { view(bit, sit, coordinateOrder(), out); } /// Get a sub-view. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// \param out Sub-View (output). /// template template inline void View::view ( BaseIterator bit, ShapeIterator sit, const CoordinateOrder& internalCoordinateOrder, View& out ) const { testInvariant(); size_t offset = 0; coordinatesToOffset(bit, offset); out.assign(sit, sit+dimension(), geometry_.stridesBegin(), data_+offset, internalCoordinateOrder); } /// Get a sub-view with the same coordinate order. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \return Sub-View. /// template template inline View View::view ( BaseIterator bit, ShapeIterator sit ) const { View v; this->view(bit, sit, v); return v; } /// Get a sub-view. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// \return Sub-View. /// template template inline View View::view ( BaseIterator bit, ShapeIterator sit, const CoordinateOrder& internalCoordinateOrder ) const { View v; this->view(bit, sit, internalCoordinateOrder, v); return v; } /// Get a sub-view to constant data with the same coordinate /// order. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param out Sub-View (output). /// template template inline void View::constView ( BaseIterator bit, ShapeIterator sit, View& out ) const { constView(bit, sit, coordinateOrder(), out); } /// Get a sub-view to constant data. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// \param out Sub-View (output). /// template template inline void View::constView ( BaseIterator bit, ShapeIterator sit, const CoordinateOrder& internalCoordinateOrder, View& out ) const { testInvariant(); size_t offset = 0; coordinatesToOffset(bit, offset); out.assign(sit, sit+dimension(), geometry_.stridesBegin(), static_cast(data_) + offset, internalCoordinateOrder); } /// Get a sub-view to constant data with the same coordinate /// order. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \return Sub-View. /// template template inline View View::constView ( BaseIterator bit, ShapeIterator sit ) const { View v; this->constView(bit, sit, v); return v; } /// Get a sub-view to constant data. /// /// \param bit Iterator to the beginning of a coordinate sequence /// that determines the start position of the sub-view. /// \param sit Iterator to the beginning of a sequence /// that determines the shape of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// \return Sub-View. /// template template inline View View::constView ( BaseIterator bit, ShapeIterator sit, const CoordinateOrder& internalCoordinateOrder ) const { View v; this->constView(bit, sit, internalCoordinateOrder, v); return v; } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Get a sub-view. /// /// \param b Initializer list defining the coordinate sequence /// that determines the start position of the sub-view. /// \param s Initializer list defining the coordinate sequence /// that determines the stop position of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// template inline void View::view ( std::initializer_list b, std::initializer_list s, const CoordinateOrder& internalCoordinateOrder, View& out ) const { view(b.begin(), s.begin(), internalCoordinateOrder, out); } /// Get a sub-view with the same coordinate order. /// /// \param b Initializer list coordinate sequence /// that determines the start position of the sub-view. /// \param s Initializer list coordinate sequence /// that determines the stop position of the sub-view. /// \param out Sub-View (output). /// template inline void View::view ( std::initializer_list b, std::initializer_list s, View& out ) const { view(b.begin(), s.begin(), coordinateOrder(), out); } /// Get a sub-view to constant data. /// /// \param b Initializer list coordinate sequence /// that determines the start position of the sub-view. /// \param s Initializer list coordinate sequence /// that determines the stop position of the sub-view. /// \param internalCoordinateOrder Flag to set the coordinate order /// for scalar indexing and iterators of the sub-view. /// template inline void View::constView ( std::initializer_list b, std::initializer_list s, const CoordinateOrder& internalCoordinateOrder, View& out ) const { constView(b.begin(), s.begin(), internalCoordinateOrder, out); } /// Get a sub-view to constant data with the same coordinate /// order. /// /// \param b Initializer list coordinate sequence /// that determines the start position of the sub-view. /// \param s Initializer list coordinate sequence /// that determines the stop position of the sub-view. /// \param out Sub-View (output). /// template inline void View::constView ( std::initializer_list b, std::initializer_list s, View& out ) const { constView(b.begin(), s.begin(), coordinateOrder(), out); } #endif /// Reshape the View. /// /// Two conditions have to be fulfilled in order for reshape to work: /// - The new and the old shape must have the same size. /// - The view must be simple, cf. isSimple(). /// . /// /// \param begin Iterator to the beginning of a sequence that determines /// the new shape. /// \param end Iterator to the end of that sequence. /// /// \sa reshapedView(), isSimple() /// template template inline void View::reshape ( ShapeIterator begin, ShapeIterator end ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || isSimple()); if(!MARRAY_NO_ARG_TEST) { size_t size = std::accumulate(begin, end, 1, std::multiplies()); marray_detail::Assert(size == this->size()); } assign(begin, end, data_, coordinateOrder(), coordinateOrder()); testInvariant(); } /// Get a reshaped View. /// /// Two conditions have to be fulfilled: /// - The new and the old shape must have the same size. /// - The view must be simple, cf. isSimple(). /// . /// /// \param begin Iterator to the beginning of a sequence that determines /// the new shape. /// \param end Iterator to the end of that sequence. /// /// \sa reshape(), isSimple() /// template template inline View View::reshapedView ( ShapeIterator begin, ShapeIterator end ) const { View out = *this; out.reshape(begin, end); return out; } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Reshape the View. /// /// Two conditions have to be fulfilled in order for reshape to work: /// - The new and the old shape must have the same size. /// - The view must be simple, cf. isSimple(). /// . /// /// \param shape Initializer list defining the new shape. /// /// \sa reshapedView(), isSimple() /// template inline void View::reshape ( std::initializer_list shape ) { reshape(shape.begin(), shape.end()); } /// Get a reshaped View. /// /// Two conditions have to be fulfilled: /// - The new and the old shape must have the same size. /// - The view must be simple, cf. isSimple(). /// . /// /// \param shape Initializer list defining the new shape. /// /// \sa reshape(), isSimple() /// template inline View View::reshapedView ( std::initializer_list shape ) const { return reshapedView(shape.begin(), shape.end()); } #endif /// Get a View where one coordinate is bound to a value. /// /// Binds one coordinate to a certain value. This reduces the /// dimension by 1. /// /// \param dimension Dimension of the coordinate to bind. /// \param value Value to assign to the coordinate. /// \return The bound view. /// \sa squeeze(), squeezeView() /// template View View::boundView ( const size_t dimension, const size_t value ) const { testInvariant(); marray_detail::Assert(MARRAY_NO_ARG_TEST || (dimension < this->dimension() && value < shape(dimension))); if(this->dimension() == 1) { View v(&((*this)(value))); v.geometry_.coordinateOrder() = coordinateOrder(); return v; } else { View v; v.geometry_.resize(this->dimension()-1); v.geometry_.coordinateOrder() = coordinateOrder(); v.geometry_.size() = size() / shape(dimension); for(size_t j=0, k=0; jdimension(); ++j) { if(j != dimension) { v.geometry_.shape(k) = shape(j); v.geometry_.strides(k) = strides(j); ++k; } } marray_detail::stridesFromShape(v.geometry_.shapeBegin(), v.geometry_.shapeEnd(), v.geometry_.shapeStridesBegin(), v.geometry_.coordinateOrder()); v.data_ = data_ + strides(dimension) * value; v.updateSimplicity(); v.testInvariant(); return v; } } /// Remove singleton dimensions by setting their coordinates to zero. /// /// \sa squeezedView(), boundView() /// template void View::squeeze() { testInvariant(); if(dimension() != 0) { size_t newDimension = dimension(); for(size_t j=0; j inline View View::squeezedView() const { View v = *this; v.squeeze(); return v; } #ifdef HAVE_CPP0X_INITIALIZER_LISTS /// Permute dimensions. /// /// \param begin Iterator to the beginning of a sequence which /// has to contain the integers 0, ..., dimension()-1 in any /// order. Otherwise, a runtime error is thrown. /// \sa permutedView(), transpose(), transposedView(), shift(), /// shiftedView() /// template void View::permute ( std::initializer_list permutation ) { permute(permutation.begin()); } #endif /// Permute dimensions. /// /// \param begin Iterator to the beginning of a sequence which /// has to contain the integers 0, ..., dimension()-1 in any /// order. Otherwise, a runtime error is thrown. /// \sa permutedView(), transpose(), transposedView(), shift(), /// shiftedView() /// template template void View::permute ( CoordinateIterator begin ) { testInvariant(); if(!MARRAY_NO_ARG_TEST) { marray_detail::Assert(dimension() != 0); std::set s1, s2; CoordinateIterator it = begin; for(size_t j=0; j newShape = std::vector(dimension()); std::vector newStrides = std::vector(dimension()); for(size_t j=0; j(*begin)); newStrides[j] = geometry_.strides(static_cast(*begin)); ++begin; } for(size_t j=0; j template inline View View::permutedView ( CoordinateIterator begin ) const { View out = *this; out.permute(begin); return out; } /// Exchange two dimensions. /// /// \param c1 Dimension /// \param c2 Dimension /// \sa permute(), permutedView(), shift(), shiftedView() /// template void View::transpose ( const size_t c1, const size_t c2 ) { testInvariant(); marray_detail::Assert(MARRAY_NO_ARG_TEST || (dimension() != 0 && c1 < dimension() && c2 < dimension())); size_t j1 = c1; size_t j2 = c2; size_t c; size_t d; // transpose shape c = geometry_.shape(j2); geometry_.shape(j2) = geometry_.shape(j1); geometry_.shape(j1) = c; // transpose strides d = geometry_.strides(j2); geometry_.strides(j2) = geometry_.strides(j1); geometry_.strides(j1) = d; // update shape strides marray_detail::stridesFromShape(geometry_.shapeBegin(), geometry_.shapeEnd(), geometry_.shapeStridesBegin(), geometry_.coordinateOrder()); updateSimplicity(); testInvariant(); } /// Reverse dimensions. /// /// \sa transposedView(), permute(), permutedView(), shift(), /// shiftedView() /// template void View::transpose() { testInvariant(); for(size_t j=0; j inline View View::transposedView ( const size_t c1, const size_t c2 ) const { View out = *this; out.transpose(c1, c2); return out; } /// Get a View with dimensions reversed. /// /// \return View with dimensions reversed. /// \sa transpose(), permute(), permutedView(), shift(), /// shiftedView() /// template inline View View::transposedView() const { View out = *this; out.transpose(); return out; } /// Cycle shift dimensions. /// /// \param n Number of positions to shift /// \sa shiftedView(), permute(), permutedView(), transpose(), /// transposedView() /// template inline void View::shift ( const int n ) { testInvariant(); marray_detail::Assert(MARRAY_NO_DEBUG || dimension() != 0); if(n <= -static_cast(dimension()) || n >= static_cast(dimension())) { shift(n % static_cast(dimension())); } else { if(n > 0) { shift(n - static_cast(dimension())); } else { std::vector p(dimension()); for(size_t j=0; j((static_cast(j) - n)) % dimension(); } permute(p.begin()); } } testInvariant(); } /// Get a View which dimensions cycle shifted. /// /// \param n Number of positions to shift /// \sa shift(), permute(), permutedView(), transpose(), transposedView() /// template inline View View::shiftedView ( const int n ) const { View out = *this; out.shift(n); return out; } /// Get an iterator to the beginning. /// /// \return Iterator. /// \sa end() /// template inline typename View::iterator View::begin() { testInvariant(); return Iterator(*this, 0); } /// Get the end-iterator. /// /// \return Iterator. /// \sa begin() /// template inline typename View::iterator View::end() { testInvariant(); return Iterator(*this, geometry_.size()); } /// Get an iterator to the beginning. /// /// \return Iterator. /// \sa end() /// template inline typename View::const_iterator View::begin() const { testInvariant(); return Iterator(*this, 0); } /// Get the end-iterator. /// /// \return Iterator. /// \sa begin() /// template inline typename View::const_iterator View::end() const { testInvariant(); return Iterator(*this, geometry_.size()); } /// Get a reserve iterator to the beginning. /// /// \return Iterator. /// \sa rend() /// template inline typename View::reverse_iterator View::rbegin() { return reverse_iterator(end()); } /// Get the reverse end-iterator. /// /// \return Iterator. /// \sa rbegin() /// template inline typename View::reverse_iterator View::rend() { return reverse_iterator(begin()); } /// Get a reserve iterator to the beginning. /// /// \return Iterator. /// \sa rend() /// template inline typename View::const_reverse_iterator View::rbegin() const { return const_reverse_iterator(end()); } /// Get the reverse end-iterator. /// /// \return Iterator. /// \sa rbegin() /// template inline typename View::const_reverse_iterator View::rend() const { return const_reverse_iterator(begin()); } /// Update Simplicity. /// /// This function sets the redundant boolean attribute isSimple_. /// isSimple_ is set to true if the shape strides equal the /// strides. /// template inline void View::updateSimplicity() { // no invariant test here because this function // is called during unsafe updates of a view geometry_.updateSimplicity(); } /// Unsafe direct memory access. /// /// This function provides direct access to the data items under the view /// in the order in which these items reside in memory. /// /// \param offset offset to be added to the data pointer. /// \return constant reference to the data item. /// template inline const T& View::operator[] ( const size_t offset ) const { return data_[offset]; } /// Unsafe direct memory access. /// /// This function provides direct access to the data items under the view /// in the order in which these items reside in memory. /// /// \param offset offset to be added to the data pointer. /// \return reference to the data item. /// template inline T& View::operator[] ( const size_t offset ) { return data_[offset]; } /// Test invariant. /// /// This function tests the invariant of View and thus the consistency /// of redundant information. /// template inline void View::testInvariant() const { if(!MARRAY_NO_DEBUG) { if(geometry_.dimension() == 0) { marray_detail::Assert(geometry_.isSimple() == true); if(data_ != 0) { // scalar marray_detail::Assert(geometry_.size() == 1); } } else { marray_detail::Assert(data_ != 0); // test size_ to be consistent with shape_ size_t testSize = 1; for(size_t j=0; j template inline bool View::overlaps ( const View& v ) const { testInvariant(); if(!MARRAY_NO_ARG_TEST) { v.testInvariant(); } if(data_ == 0 || v.data_ == 0) { return false; } else { const void* dataPointer_ = data_; const void* vDataPointer_ = v.data_; const void* maxPointer = & (*this)(this->size()-1); const void* maxPointerV = & v(v.size()-1); if( (dataPointer_ <= vDataPointer_ && vDataPointer_ <= maxPointer) || (vDataPointer_ <= dataPointer_ && dataPointer_ <= maxPointerV) ) { return true; } } return false; } /// Output as string. /// template std::string View::asString ( const StringStyle& style ) const { testInvariant(); std::ostringstream out(std::ostringstream::out); if(style == MatrixStyle) { if(dimension() == 0) { // scalar out << "A = " << (*this)(0) << std::endl; } else if(dimension() == 1) { // vector out << "A = ("; for(size_t j=0; jsize(); ++j) { out << (*this)(j) << ", "; } out << "\b\b)" << std::endl; } else if(dimension() == 2) { // matrix if(coordinateOrder() == FirstMajorOrder) { out << "A(r,c) =" << std::endl; for(size_t y=0; yshape(0); ++y) { for(size_t x=0; xshape(1); ++x) { out << (*this)(y, x) << ' '; } out << std::endl; } } else { out << "A(c,r) =" << std::endl; for(size_t y=0; yshape(1); ++y) { for(size_t x=0; xshape(0); ++x) { out << (*this)(x, y) << ' '; } out << std::endl; } } } else { // higher dimensional std::vector c1(dimension()); std::vector c2(dimension()); unsigned short q = 2; if(coordinateOrder() == FirstMajorOrder) { q = dimension()-3; } for(const_iterator it = this->begin(); it.hasMore(); ++it) { it.coordinate(c2.begin()); if(it.index() == 0 || c2[q] != c1[q]) { if(it.index() != 0) { out << std::endl << std::endl; } if(coordinateOrder() == FirstMajorOrder) { out << "A("; for(size_t j=0; j class HandleCheck; template<> class HandleCheck { public: HandleCheck() { counter_ = H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL); } void check() { marray_detail::Assert( counter_ == H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL)); } private: ssize_t counter_; }; template<> class HandleCheck { public: void check() {} }; // \endcond // namespace variables const char reverseShapeAttributeName[14] = "reverse-shape"; // prototypes enum FileAccessMode {READ_ONLY, READ_WRITE}; enum HDF5Version {DEFAULT_HDF5_VERSION, LATEST_HDF5_VERSION}; inline hid_t createFile(const std::string&, HDF5Version = DEFAULT_HDF5_VERSION); inline hid_t openFile(const std::string&, FileAccessMode = READ_ONLY, HDF5Version = DEFAULT_HDF5_VERSION); inline void closeFile(const hid_t&); inline hid_t createGroup(const hid_t&, const std::string&); inline hid_t openGroup(const hid_t&, const std::string&); inline void closeGroup(const hid_t&); template void save(const hid_t&, const std::string&, const Marray&); template void save(const hid_t&, const std::string&, const View&); template void save(const hid_t&, const std::string&, const std::vector&); template void saveHyperslab(const hid_t&, const std::string&, BaseIterator, BaseIterator, ShapeIterator, const Marray&); template void create(const hid_t&, const std::string&, ShapeIterator, ShapeIterator, CoordinateOrder); template void load(const hid_t&, const std::string&, Marray&); template void loadShape(const hid_t&, const std::string&, Vector&); template void loadVec(const hid_t&, const std::string&, std::vector&); template void loadHyperslab(const hid_t&, const std::string&, BaseIterator, BaseIterator, ShapeIterator, Marray&); // type conversion from C++ to HDF5 #ifdef BIGENDIAN // \cond suppress doxygen template inline hid_t uintTypeHelper() { switch(sizeof(T)) { case 1: return H5T_STD_U8BE; case 2: return H5T_STD_U16BE; case 4: return H5T_STD_U32BE; case 8: return H5T_STD_U64BE; default: throw std::runtime_error("No matching HDF5 type."); } } template inline hid_t intTypeHelper() { switch(sizeof(T)) { case 1: return H5T_STD_I8BE; case 2: return H5T_STD_I16BE; case 4: return H5T_STD_I32BE; case 8: return H5T_STD_I64BE; default: throw std::runtime_error("No matching HDF5 type."); } } template inline hid_t floatingTypeHelper() { switch(sizeof(T)) { case 4: return H5T_IEEE_F32BE; case 8: return H5T_IEEE_F64BE; default: throw std::runtime_error("No matching HDF5 type."); } } #else // \cond suppress doxygen template inline hid_t uintTypeHelper() { switch(sizeof(T)) { case 1: return H5T_STD_U8LE; case 2: return H5T_STD_U16LE; case 4: return H5T_STD_U32LE; case 8: return H5T_STD_U64LE; default: throw std::runtime_error("No matching HDF5 type."); } } template inline hid_t intTypeHelper() { switch(sizeof(T)) { case 1: return H5T_STD_I8LE; case 2: return H5T_STD_I16LE; case 4: return H5T_STD_I32LE; case 8: return H5T_STD_I64LE; default: throw std::runtime_error("No matching HDF5 type."); } } template inline hid_t floatingTypeHelper() { switch(sizeof(T)) { case 4: return H5T_IEEE_F32LE; case 8: return H5T_IEEE_F64LE; default: throw std::runtime_error("No matching HDF5 type."); } } #endif template inline hid_t hdf5Type(); template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return uintTypeHelper(); } template<> inline hid_t hdf5Type() { return intTypeHelper(); } template<> inline hid_t hdf5Type() { return intTypeHelper(); } template<> inline hid_t hdf5Type() { return intTypeHelper(); } template<> inline hid_t hdf5Type() { return intTypeHelper(); } template<> inline hid_t hdf5Type() { return intTypeHelper(); } template<> inline hid_t hdf5Type() { return floatingTypeHelper(); } template<> inline hid_t hdf5Type() { return floatingTypeHelper(); } // \endcond // implementation /// Create and close an HDF5 dataset to store Marray data. /// /// \param groupHandle Handle of the parent HDF5 file or group. /// \param datasetName Name of the HDF5 dataset. /// \param begin Iterator to the beginning of a sequence that determines the shape of the dataset. /// \param end Iterator to the end of a sequence that determines the shape of the dataset. /// \param coordinateOrder Coordinate order of the Marray. /// /// \sa save(), saveHyperslab() /// template void create( const hid_t& groupHandle, const std::string& datasetName, ShapeIterator begin, ShapeIterator end, CoordinateOrder coordinateOrder ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; // build dataspace hid_t datatype = H5Tcopy(hdf5Type()); size_t dimension = std::distance(begin, end); Vector shape((size_t)(dimension)); if(coordinateOrder == FirstMajorOrder) { // copy shape as is for(size_t j=0; j void save( const hid_t& groupHandle, const std::string& datasetName, const Marray& in ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; // build dataspace hid_t datatype = H5Tcopy(hdf5Type()); Vector shape(in.dimension()); if(in.coordinateOrder() == FirstMajorOrder) { // copy shape as is for(size_t j=0; j inline void save( const hid_t& groupHandle, const std::string& datasetName, const View& in ) { Marray m = in; save(groupHandle, datasetName, m); } /// Save an std::vector as an HDF5 dataset. /// /// \param groupHandle Handle of the parent HDF5 file or group. /// \param datasetName Name of the HDF5 dataset. /// \param in std::vector. /// /// \sa saveHyperslab() /// template void save( const hid_t& groupHandle, const std::string& datasetName, const std::vector& in ) { marray::Vector v(in.size()); for(size_t j=0; j void load( const hid_t& groupHandle, const std::string& datasetName, Marray& out ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; hid_t dataset = H5Dopen(groupHandle, datasetName.c_str(), H5P_DEFAULT); if(dataset < 0) { throw std::runtime_error("Marray cannot open dataset."); } hid_t filespace = H5Dget_space(dataset); hid_t type = H5Dget_type(dataset); hid_t nativeType = H5Tget_native_type(type, H5T_DIR_DESCEND); if(!H5Tequal(nativeType, hdf5Type())) { H5Dclose(dataset); H5Tclose(nativeType); H5Tclose(type); H5Sclose(filespace); throw std::runtime_error("Data types not equal error."); } int dimension = H5Sget_simple_extent_ndims(filespace); Vector shape(dimension); herr_t status = H5Sget_simple_extent_dims(filespace, &shape[0], NULL); if(status < 0) { H5Dclose(dataset); H5Tclose(nativeType); H5Tclose(type); H5Sclose(filespace); throw std::runtime_error("H5Sget_simple_extent_dims error."); } hid_t memspace = H5Screate_simple(dimension, &shape[0], NULL); // resize marray marray::Vector newShape((size_t)(dimension)); for(size_t j=0; j 0) { // reverse shape out = Marray(SkipInitialization, newShape.rbegin(), newShape.rend(), LastMajorOrder); } else { // don't reverse shape out = Marray(SkipInitialization, newShape.begin(), newShape.end(), FirstMajorOrder); } // read status = H5Dread(dataset, nativeType, memspace, filespace, H5P_DEFAULT, &out(0)); H5Dclose(dataset); H5Tclose(nativeType); H5Tclose(type); H5Sclose(memspace); H5Sclose(filespace); if(status < 0) { throw std::runtime_error("Marray cannot read from dataset."); } handleCheck.check(); } /// Load the shape of an HDF5 dataset. /// /// \param groupHandle Handle of the parent HDF5 file or group. /// \param datasetName Name of the HDF5 dataset. /// \param out Shape. /// /// \sa load() /// template void loadShape( const hid_t& groupHandle, const std::string& datasetName, Vector& out ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; // load shape from HDF5 file hid_t dataset = H5Dopen(groupHandle, datasetName.c_str(), H5P_DEFAULT); if(dataset < 0) { throw std::runtime_error("Marray cannot open dataset."); } hid_t filespace = H5Dget_space(dataset); hsize_t dimension = H5Sget_simple_extent_ndims(filespace); hsize_t* shape = new hsize_t[(size_t)(dimension)]; herr_t status = H5Sget_simple_extent_dims(filespace, shape, NULL); if(status < 0) { H5Dclose(dataset); H5Sclose(filespace); delete[] shape; throw std::runtime_error("Marray cannot get extension of dataset."); } // write shape to out out = Vector((size_t)(dimension)); if(H5Aexists(dataset, reverseShapeAttributeName) > 0) { for(size_t j=0; j void loadVec( const hid_t& groupHandle, const std::string& datasetName, std::vector& out ) { marray::Marray v; load( groupHandle,datasetName,v); out.resize(v.size()); for(size_t j=0; j void loadHyperslab( const hid_t& groupHandle, const std::string& datasetName, BaseIterator baseBegin, BaseIterator baseEnd, ShapeIterator shapeBegin, Marray& out ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; // open dataset hid_t dataset = H5Dopen(groupHandle, datasetName.c_str(), H5P_DEFAULT); if(dataset < 0) { throw std::runtime_error("Marray cannot open dataset."); } // determine shape of hyperslab and array size_t size = std::distance(baseBegin, baseEnd); Vector offset(size); Vector slabShape(size); Vector marrayShape(size); CoordinateOrder coordinateOrder; if(H5Aexists(dataset, reverseShapeAttributeName) > 0) { // reverse base and shape coordinateOrder = LastMajorOrder; size_t j = size-1; size_t k = 0; for(;;) { offset[j] = hsize_t(*baseBegin); slabShape[j] = hsize_t(*shapeBegin); marrayShape[k] = slabShape[j]; if(j == 0) { break; } else { ++baseBegin; ++shapeBegin; ++k; --j; } } } else { // don't reverse base and shape coordinateOrder = FirstMajorOrder; for(size_t j=0; j())) { throw std::runtime_error("data type of stored hdf5 dataset and passed array do not match in loadHyperslab"); } hid_t dataspace = H5Dget_space(dataset); herr_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, &offset[0], NULL, &slabShape[0], NULL); if(status < 0) { H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); throw std::runtime_error("Marray cannot select hyperslab. Check offset and shape!"); } // select memspace hyperslab hid_t memspace = H5Screate_simple(int(size), &marrayShape[0], NULL); Vector offsetOut(size, 0); // no offset status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &offsetOut[0], NULL, &marrayShape[0], NULL); if(status < 0) { H5Sclose(memspace); H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); throw std::runtime_error("Marray cannot select hyperslab. Check offset and shape!"); } // read from dataspace into memspace out = Marray(SkipInitialization, &marrayShape[0], (&marrayShape[0])+size, coordinateOrder); status = H5Dread(dataset, datatype, memspace, dataspace, H5P_DEFAULT, &(out(0))); // clean up H5Sclose(memspace); H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); if(status < 0) { throw std::runtime_error("Marray cannot read from dataset."); } handleCheck.check(); } /// Save an Marray as a hyperslab into an HDF5 dataset. /// /// \param groupHandle Handle of the parent HDF5 file or group. /// \param datasetName Name of the HDF5 dataset. /// \param baseBegin Iterator to the beginning of the sequence that determines the first coordinate of the hyperslab. /// \param baseEnd Iterator to the end of the sequence that determines the first coordinate of the hyperslab. /// \param shapeBegin Iterator to the beginning of the sequence that determines the shape of the hyperslab. /// \param in Marray. /// /// \sa loadHyperslab(), create() /// template void saveHyperslab( const hid_t& groupHandle, const std::string& datasetName, BaseIterator baseBegin, BaseIterator baseEnd, ShapeIterator shapeBegin, const Marray& in ) { marray_detail::Assert(MARRAY_NO_ARG_TEST || groupHandle >= 0); HandleCheck handleCheck; // open dataset hid_t dataset = H5Dopen(groupHandle, datasetName.c_str(), H5P_DEFAULT); if(dataset < 0) { throw std::runtime_error("Marray cannot open dataset."); } // determine hyperslab shape Vector memoryShape(in.dimension()); for(size_t j=0; j offset(size); Vector slabShape(size); bool reverseShapeAttribute = (H5Aexists(dataset, reverseShapeAttributeName) > 0); if(reverseShapeAttribute && in.coordinateOrder() == LastMajorOrder) { // reverse base and shape size_t j = size-1; for(;;) { offset[j] = hsize_t(*baseBegin); slabShape[j] = hsize_t(*shapeBegin); if(j == 0) { break; } else { ++baseBegin; ++shapeBegin; --j; } } } else if(!reverseShapeAttribute && in.coordinateOrder() == FirstMajorOrder) { for(size_t j=0; j memoryOffset(int(in.dimension()), 0); // no offset status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, &memoryOffset[0], NULL, &memoryShape[0], NULL); if(status < 0) { H5Sclose(memspace); H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); throw std::runtime_error("Marray cannot select hyperslab. Check offset and shape!"); } // write from memspace to dataspace status = H5Dwrite(dataset, datatype, memspace, dataspace, H5P_DEFAULT, &(in(0))); // clean up H5Sclose(memspace); H5Tclose(datatype); H5Sclose(dataspace); H5Dclose(dataset); if(status < 0) { throw std::runtime_error("Marray cannot write to dataset."); } handleCheck.check(); } /// Create an HDF5 file. /// /// \param filename Name of the file. /// \param hdf5version HDF5 version tag. /// /// \returns HDF5 handle /// /// \sa openFile(), closeFile() /// inline hid_t createFile ( const std::string& filename, HDF5Version hdf5version ) { hid_t version = H5P_DEFAULT; if(hdf5version == LATEST_HDF5_VERSION) { version = H5Pcreate(H5P_FILE_ACCESS); H5Pset_libver_bounds(version, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST); } hid_t fileHandle = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, version); if(fileHandle < 0) { throw std::runtime_error("Could not create HDF5 file: " + filename); } return fileHandle; } /// Open an HDF5 file. /// /// \param filename Name of the file. /// \param fileAccessMode File access mode. /// \param hdf5version HDF5 version tag. /// /// \returns HDF5 handle /// /// \sa closeFile(), createFile() /// inline hid_t openFile ( const std::string& filename, FileAccessMode fileAccessMode, HDF5Version hdf5version ) { hid_t access = H5F_ACC_RDONLY; if(fileAccessMode == READ_WRITE) { access = H5F_ACC_RDWR; } hid_t version = H5P_DEFAULT; if(hdf5version == LATEST_HDF5_VERSION) { version = H5Pcreate(H5P_FILE_ACCESS); H5Pset_libver_bounds(version, H5F_LIBVER_LATEST, H5F_LIBVER_LATEST); } hid_t fileHandle = H5Fopen(filename.c_str(), access, version); if(fileHandle < 0) { throw std::runtime_error("Could not open HDF5 file: " + filename); } return fileHandle; } /// Close an HDF5 file /// /// \param handle Handle to the HDF5 file. /// /// \sa openFile(), createFile() /// inline void closeFile ( const hid_t& handle ) { H5Fclose(handle); } /// Create an HDF5 group. /// /// \param parentHandle HDF5 handle on the parent group or file. /// \param groupName Name of the group. /// \returns HDF5 handle on the created group /// /// \sa openGroup(), closeGroup() /// inline hid_t createGroup ( const hid_t& parentHandle, const std::string& groupName ) { hid_t groupHandle = H5Gcreate(parentHandle, groupName.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if(groupHandle < 0) { throw std::runtime_error("Could not create HDF5 group."); } return groupHandle; } /// Open an HDF5 group. /// /// \param parentHandle HDF5 handle on the parent group or file. /// \param groupName Name of the group. /// \returns HDF5 handle on the opened group. /// /// \sa createGroup(), closeGroup() /// inline hid_t openGroup ( const hid_t& parentHandle, const std::string& groupName ) { hid_t groupHandle = H5Gopen(parentHandle, groupName.c_str(), H5P_DEFAULT); if(groupHandle < 0) { throw std::runtime_error("Could not open HDF5 group."); } return groupHandle; } /// Close an HDF5 group. /// /// \param handle HDF5 handle on group to close. /// /// \sa openGroup(), createGroup() /// inline void closeGroup ( const hid_t& handle ) { H5Gclose(handle); } } // namespace hdf5 } // namespace marray #endif // #ifndef MARRAY_HDF5_HXX opengm-2.3.6+20160905/include/opengm/datastructures/partition.hxx000066400000000000000000000137261276346362400244660ustar00rootroot00000000000000#pragma once #ifndef OPENGM_PARTITION_HXX #define OPENGM_PARTITION_HXX #include #include namespace opengm { /// Disjoint set data structure with path compression. /// \ingroup datastructures template class Partition { public: typedef T value_type; Partition(); Partition(const value_type&); // query value_type find(const value_type&) const; // without path compression value_type find(value_type); // with path compression value_type numberOfElements() const; value_type numberOfSets() const; template void elementLabeling(Iterator) const; template void representatives(Iterator) const; void representativeLabeling(std::map&) const; // manipulation void reset(const value_type&); void merge(value_type, value_type); void insert(const value_type&); private: std::vector parents_; std::vector ranks_; value_type numberOfElements_; value_type numberOfSets_; }; /// Construct a partition. template Partition::Partition() : parents_(), ranks_(), numberOfElements_(0), numberOfSets_(0) {} /// Construct a partition. /// /// \param size Number of distinct sets. /// template inline Partition::Partition ( const value_type& size ) : parents_(static_cast(size)), ranks_(static_cast(size)), numberOfElements_(size), numberOfSets_(size) { for(T j=0; j(j)] = j; } } /// Reset a partition such that each set contains precisely one element /// /// \param size Number of distinct sets. /// template inline void Partition::reset ( const value_type& size ) { numberOfElements_ = size; numberOfSets_ = size; ranks_.resize(static_cast(size)); parents_.resize(static_cast(size)); for(T j=0; j(j)] = 0; parents_[static_cast(j)] = j; } } /// Find the representative element of the set that contains the given element. /// /// This constant function does not compress the search path. /// /// \param element Element. /// template inline typename Partition::value_type Partition::find ( const value_type& element ) const { // find the root value_type root = element; while(parents_[static_cast(root)] != root) { root = parents_[static_cast(root)]; } return root; } /// Find the representative element of the set that contains the given element. /// /// This mutable function compresses the search path. /// /// \param element Element. /// template inline typename Partition::value_type Partition::find ( value_type element // copy to work with ) { // find the root value_type root = element; while(parents_[static_cast(root)] != root) { root = parents_[static_cast(root)]; } // path compression while(element != root) { value_type tmp = parents_[static_cast(element)]; parents_[static_cast(element)] = root; element = tmp; } return root; } /// Merge two sets. /// /// \param element1 Element in the first set. /// \param element2 Element in the second set. /// template inline void Partition::merge ( value_type element1, value_type element2 ) { // merge by rank element1 = find(element1); element2 = find(element2); if(ranks_[static_cast(element1)] < ranks_[static_cast(element2)]) { parents_[static_cast(element1)] = element2; --numberOfSets_; } else if(ranks_[static_cast(element1)] > ranks_[static_cast(element2)]) { parents_[static_cast(element2)] = element1; --numberOfSets_; } else if(element1 != element2) { parents_[static_cast(element2)] = element1; ++ranks_[static_cast(element1)]; --numberOfSets_; } } /// Insert new sets. /// /// \param number Number of sets to insert. /// template inline void Partition::insert ( const value_type& number ) { ranks_.insert(ranks_.end(), static_cast(number), T(0)); parents_.insert(parents_.end(), static_cast(number), T(0)); for(value_type j=numberOfElements_; j(j)] = j; } numberOfElements_ += number; numberOfSets_ += number; } /// Output all elements which are set representatives. /// /// \param it (Output) Iterator into a container. /// template template inline void Partition::representatives ( Iterator it ) const { for(value_type j=0; j(j)] == j) { *it = j; ++it; } } } /// Output a continuous labeling of the representative elements. /// /// \param out (Output) A map that assigns each representative element to its label. /// template inline void Partition::representativeLabeling ( std::map& out ) const { out.clear(); std::vector r(static_cast(numberOfSets())); representatives(r.begin()); for(T j=0; j(j)] ] = j; } } /// Output a continuous labeling of all elements. /// /// \param out (Output) Iterator into a container in which the j-th entry is the label of the element j. /// template template inline void Partition::elementLabeling ( Iterator out ) const { std::map rl; representativeLabeling(rl); for(value_type j=0; j inline typename Partition::value_type Partition::numberOfElements() const { return numberOfElements_; } template inline typename Partition::value_type Partition::numberOfSets() const { return numberOfSets_; } } // namespace opengm #endif // #ifndef OPENGM_PARTITION_HXX opengm-2.3.6+20160905/include/opengm/datastructures/randomaccessset.hxx000066400000000000000000000406141276346362400256270ustar00rootroot00000000000000#pragma once #ifndef OPENGM_RANDOM_ACCESS_SET_HXX #define OPENGM_RANDOM_ACCESS_SET_HXX #include #include #include namespace opengm { /// set with O(n) insert and O(1) access /// /// \tparam Key key and value type of the set /// \tparam Alloc allocator of the set /// RandomAccessSet has the same interface as std::set. /// In addition, there is operator[]. /// \warning Values in set must not be changend through the mutable iterator /// because doing so would potentially change the order of the values /// \\ingroup datastructures template,class Alloc=std::allocator > class RandomAccessSet { private: /// type of the underlying vector typedef std::vector VectorType; public: // typedefs /// key type of the set typedef Key key_type; /// value type of the set typedef Key ValueType; /// value type of the set typedef Key value_type; /// comperator typedef Compare key_compare; /// value comperator typedef Compare value_compare; /// acclocator typedef Alloc allocator_type; /// const reference type typedef typename Alloc::const_reference const_reference; /// iterator type typedef typename VectorType::iterator iterator; /// const iterator type typedef typename VectorType::const_iterator const_iterator; /// size type typedef typename VectorType::size_type size_type; /// difference type typedef typename VectorType::difference_type difference_type; /// const pointer type typedef typename VectorType::const_pointer const_pointer; /// const reverse iterator typedef typename VectorType::const_reverse_iterator const_reverse_iterator; // memeber functions: // constructor RandomAccessSet(const size_t, const Compare& compare=Compare(), const Alloc& alloc=Alloc()); RandomAccessSet(const Compare& compare=Compare(), const Alloc& alloc=Alloc()); template RandomAccessSet(InputIterator, InputIterator, const Compare& compare =Compare(), const Alloc & alloc=Alloc()); RandomAccessSet(const RandomAccessSet&); // operator= RandomAccessSet& operator=(const RandomAccessSet &); // operator[] const value_type& operator[](const size_type) const; // iterators const_iterator begin() const; const_iterator end() const; const_iterator rbegin() const; const_iterator rend() const; iterator begin(); iterator end(); iterator rbegin(); iterator rend(); bool empty() const; size_type size() const; size_type max_size() const; std::pair< const_iterator,bool> insert(const value_type&); template void insert(InputIterator, InputIterator); const_iterator insert(const_iterator , const value_type&); void erase(iterator position); size_type erase(const key_type& ); void erase( const_iterator, const_iterator); void swap(RandomAccessSet&); void clear(); key_compare key_comp() const; value_compare value_comp() const; const_iterator find(const key_type&) const; iterator find(const key_type&); size_type count(const key_type&) const; const_iterator lower_bound(const key_type&) const; const_iterator upper_bound(const key_type&) const; std::pair equal_range(const key_type&) const; iterator lower_bound(const key_type&) ; iterator upper_bound(const key_type&) ; std::pair equal_range(const key_type&) ; allocator_type get_allocator() const; // std vector functions void reserve(const size_t size){ vector_.reserve(size); } size_t capacity()const{ return vector_.capacity(); } template void assignFromSet(const SET & set){ vector_.assign(set.begin(),set.end()); } private: std::vector vector_; Compare compare_; }; /// constructor /// \param reserveSize reserve /allocate space /// \param compare comperator /// \param alloc allocator template inline RandomAccessSet::RandomAccessSet ( const size_t reserveSize, const Compare& compare, const Alloc& alloc ) : vector_(alloc), compare_(compare) { vector_.reserve(reserveSize); } /// const access values /// \param index index of the value in the set /// \return value / key at the position index template inline const typename RandomAccessSet::value_type& RandomAccessSet::operator[] ( const typename RandomAccessSet::size_type index ) const { return vector_[index]; } /// constructor /// \param compare comperator /// \allloc allocator template inline RandomAccessSet::RandomAccessSet ( const Compare& compare, const Alloc& alloc ) : vector_(alloc), compare_(compare) {} /// constructor /// \tparam InputIterator (key/value) input iterator /// \param beginInput /// \param endInput template template inline RandomAccessSet::RandomAccessSet ( InputIterator beginInput, InputIterator endInput, const Compare& compare, const Alloc& alloc ) : vector_(alloc), compare_(compare) { while(beginInput!=endInput) { this->insert(*beginInput); ++beginInput; } } /// copy constructor /// \param src other random access set template inline RandomAccessSet::RandomAccessSet ( const RandomAccessSet& src ) : vector_(src.vector_), compare_(src.compare_) { } /// assignment operator /// \param src other random access set template inline RandomAccessSet& RandomAccessSet::operator= ( const RandomAccessSet & src ) { if(this!=&src) { vector_=src.vector_; compare_=src.compare_; } return *this; } /// const begin iterator /// \returns begin iterator template inline typename RandomAccessSet::const_iterator RandomAccessSet::begin() const { return vector_.begin(); } /// const end iterator /// \returns end iterator template inline typename RandomAccessSet::const_iterator RandomAccessSet::end() const { return vector_.end(); } /// reverse const begin iterator /// \returns reverse begin iterator template inline typename RandomAccessSet::const_iterator RandomAccessSet::rbegin() const { return vector_.rbegin(); } /// reverse const end iterator /// \param reverse end iterator template inline typename RandomAccessSet::const_iterator RandomAccessSet::rend() const { return vector_.rend(); } /// begin iterator /// \param begin iterator template inline typename RandomAccessSet::iterator RandomAccessSet::begin() { return vector_.begin(); } /// end iterator /// \param end iterator template inline typename RandomAccessSet::iterator RandomAccessSet::end() { return vector_.end(); } /// reverse begin iterator /// \param reverse begin iterator template inline typename RandomAccessSet::iterator RandomAccessSet::rbegin() { return vector_.rbegin(); } /// reverse end iterator /// \param reverse end iterator template inline typename RandomAccessSet::iterator RandomAccessSet::rend() { return vector_.rend(); } /// query if the set is empty /// \return true if empty template inline bool RandomAccessSet::empty() const { return vector_.empty(); } /// number of elements of the set /// \returns number of elements in the set template inline typename RandomAccessSet::size_type RandomAccessSet::size() const { return vector_.size(); } /// maximum size of the underlying container /// \return the maximum size template inline typename RandomAccessSet::size_type RandomAccessSet::max_size() const { return vector_.max_size(); } // modifiers /// insert an element into the set /// /// \param value element to insert /// \return pair in which the first entry is an iterator pointing to inserted /// value and the second entry is true iff the value had not already been in the /// set template inline std::pair::const_iterator,bool> RandomAccessSet::insert ( const typename RandomAccessSet::value_type& value ) { bool found(true); iterator i(lower_bound(static_cast(value))); if(i == end() || compare_(static_cast(value), *i)) { i = vector_.insert(i, static_cast(value)); found = false; } return std::make_pair(i, !found); } /// insert a sequence of elements /// /// \param first iterator to the first element /// \param last iterator to the last element template template inline void RandomAccessSet::insert ( InputIterator first, InputIterator last ) { while(first!=last) { this->insert(*first); ++first; } } /// insert a sequence of elements with a hint for the position /// /// \param position iterator to the position /// \param value element to insert template inline typename RandomAccessSet::const_iterator RandomAccessSet::insert ( typename RandomAccessSet::const_iterator position, const typename RandomAccessSet::value_type& value ) { if((position == begin() || this->operator()(*(position-1),value)) && (position == end() || this->operator()(value, *position))) { return vector_.insert(position, value); } return insert(value).first; } /// erase an element /// \param position iterator to the position template inline void RandomAccessSet::erase ( typename RandomAccessSet::iterator position ) { vector_.erase(position); } /// erease and element /// \param x element template inline typename RandomAccessSet::size_type RandomAccessSet::erase ( const typename RandomAccessSet::key_type& x ) { iterator i =find(x); if(i!=vector_.end()) { erase(i); return 1; } return 0; } /// erase a sequence of elements /// \param first iterator to the beginning of the sequence to erase /// \param last iterator to the end of the sequence to erase template inline void RandomAccessSet::erase ( const typename RandomAccessSet::const_iterator first, const typename RandomAccessSet::const_iterator last ) { vector_.erase(first,last); } /// swap random access sets /// \param rhs set to swap with template inline void RandomAccessSet::swap ( RandomAccessSet& rhs ) { vector_.swap(rhs.vector_); compare_=rhs.compare_; } /// clear the set /// /// erases all elements template inline void RandomAccessSet::clear() { vector_.clear(); } /// key comparator /// \return key comparator template inline typename RandomAccessSet::key_compare RandomAccessSet::key_comp() const { return compare_; } /// value comparator /// \return value comparator template inline typename RandomAccessSet::value_compare RandomAccessSet::value_comp() const { return compare_; } /// find an element /// \param value element /// \return const_iterator to the position where element was found or end /// iterator if the element was not found template inline typename RandomAccessSet::const_iterator RandomAccessSet::find ( const typename RandomAccessSet::key_type& value ) const { const_iterator i(lower_bound(value)); if (i != end() && compare_(value, *i)) { i = end(); } return i; } /// find an element /// \param value element /// \return iterator to the position where the element was found or end /// iterator if the element was not found template inline typename RandomAccessSet::iterator RandomAccessSet::find ( const typename RandomAccessSet::key_type& value ) { iterator i(lower_bound(value)); if (i != end() && compare_(value, *i)) { i = end(); } return i; } /// count elements /// \param element /// \return zero or one template inline typename RandomAccessSet::size_type RandomAccessSet::count ( const typename RandomAccessSet::key_type& value ) const { return find(value) != end(); } /// lower bound /// \param value /// \return iterator to lower bound template inline typename RandomAccessSet::const_iterator RandomAccessSet::lower_bound ( const typename RandomAccessSet::key_type& value ) const { return std::lower_bound(vector_.begin(), vector_.end(), value, compare_); } /// lower bound /// \param value /// \return iterator to lower bound template inline typename RandomAccessSet::iterator RandomAccessSet::lower_bound ( const typename RandomAccessSet::key_type& value ) { return std::lower_bound(vector_.begin(), vector_.end(), value, compare_); } /// upper bound /// \param value /// \return iterator to upper bound template inline typename RandomAccessSet::const_iterator RandomAccessSet::upper_bound ( const typename RandomAccessSet::key_type& value ) const { return std::upper_bound(vector_.begin(), vector_.end(), value, compare_); } /// upper bound /// \param value /// \return iterator to upper bound template inline typename RandomAccessSet::iterator RandomAccessSet::upper_bound ( const typename RandomAccessSet::key_type& value ) { return std::upper_bound(vector_.begin(), vector_.end(), value, compare_); } /// equal range /// \param value /// \return iterator pair to lower equal range template inline std::pair::const_iterator,typename RandomAccessSet::const_iterator> RandomAccessSet::equal_range ( const typename RandomAccessSet::key_type& value ) const { return std::equal_range(vector_.begin(), vector_.end(), value, compare_); } /// equal range /// \param value /// \return iterator pair to lower equal range template inline std::pair::iterator,typename RandomAccessSet::iterator> RandomAccessSet::equal_range ( const typename RandomAccessSet::key_type& value ) { return std::equal_range(vector_.begin(), vector_.end(), value, compare_); } /// allocators /// \return allocator template inline typename RandomAccessSet::allocator_type RandomAccessSet::get_allocator() const { return vector_.get_allocator(); } } // namespace opengm #endif // OPENGM_RANDOM_ACCESS_SET_HXX opengm-2.3.6+20160905/include/opengm/datastructures/sparsemarray/000077500000000000000000000000001276346362400244245ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/datastructures/sparsemarray/sparsemarray.hxx000077500000000000000000000140061276346362400276720ustar00rootroot00000000000000#pragma once #ifndef OPENGM_SPARSEMARRAY #define OPENGM_SPARSEMARRAY #include #include #include #include "opengm/functions/function_properties_base.hxx" namespace opengm { template > class SparseFunction : public FunctionBase, T, I, L> { public: typedef CONTAINER ContainerType; typedef typename ContainerType::key_type KeyType; typedef typename ContainerType::mapped_type MappedType; typedef std::pair KeyValPairType; typedef T ValueType; typedef I IndexType; typedef L LabelType; typedef typename ContainerType::const_iterator ConstContainerIteratorType; typedef typename ContainerType::iterator ContainerIteratorType; SparseFunction(): dimension_(0), defaultValue_(0), container_(), shape_(), strides_(){ } //constructors template SparseFunction(SHAPE_ITERATOR shapeBegin,SHAPE_ITERATOR shapeEnd ,const ValueType defaultValue): dimension_(std::distance(shapeBegin,shapeEnd)), defaultValue_(defaultValue), container_(){ shape_.resize(dimension_); strides_.resize(dimension_); // compute strides LabelType strideVal=1; for(unsigned short dim=0;dim(shape_[dim]); } return size; } const ContainerType & container()const{ return container_; } ContainerType & container(){ return container_; } const size_t dimension()const{ return dimension_; } const LabelType shape(const IndexType i)const{ return shape_[i]; } template void keyToCoordinate(const KeyType key, COORDINATE_ITERATOR coordinate )const{ typedef typename std::iterator_traits::value_type CoordType; KeyType keyRest=key; if(dimension_!=1){ for(unsigned short d=0;d( strides_[dim] ); keyRest=keyRest-c*static_cast( strides_[dim] ); coordinate[dim]=static_cast(c); } } else{ *coordinate=static_cast(key); } } template KeyType coordinateToKey(COORDINATE_ITERATOR coordinate)const{ KeyType key=static_cast(0); for(unsigned short dim=0;dim(*coordinate); ++coordinate; } return key; } template KeyType coordinateToKeyWithDim(COORDINATE_ITERATOR coordinate )const{ KeyType key=static_cast(0); for(unsigned short dim=0;dim(coordinate[dim]); } return key; } template ValueType operator()(COORDINATE_ITERATOR coordinate)const{ typedef COORDINATE_ITERATOR CoordType; KeyType key;//=coordinateToKey(coordinate); switch (dimension_) { case 1: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 2: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 3: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 4: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 5: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 6: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 7: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 8: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 9: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 10: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 11: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 12: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 13: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 14: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 15: return valueFromKey(coordinateToKeyWithDim(coordinate)); case 16: return valueFromKey(coordinateToKeyWithDim(coordinate)); default: return valueFromKey(coordinateToKey(coordinate)); } } ValueType defaultValue()const{ return defaultValue_; } ValueType valueFromKey(const KeyType key)const{ ConstContainerIteratorType iter=container_.find(key); if(iter!=container_.end()){ return iter->second; } else{ return defaultValue_; } } template void insert(COORDINATE_ITERATOR coordinate,const ValueType value){ container_.insert(KeyValPairType(coordinateToKey(coordinate),value)); } private: unsigned short dimension_; ValueType defaultValue_; ContainerType container_; std::vector shape_; std::vector strides_; }; } #endifopengm-2.3.6+20160905/include/opengm/doxygen/000077500000000000000000000000001276346362400203135ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/doxygen/mainpage.hxx000066400000000000000000000104121276346362400226230ustar00rootroot00000000000000// DOXYGEN GROUP STRUCTURE /*! * \defgroup graphical_models Graphical Models * \defgroup inference Inference Algorithms * \defgroup spaces Space Types * \defgroup operators Operators * \defgroup functions Function Types */ // DOXYGEN EXAMPLES /*! * \example quick_start.cxx * \example grid_potts.cxx * \example interpixel_boundary_segmentation.cxx * \example one_to_one_matching.cxx * \example io_graphical_model.cxx * \example gibbs.cxx * \example inference_types.cxx * \example markov-chain.cxx * \example space_types.cxx * \example swendsenwang.cxx * \example opengmBuild.cxx */ // DOXYGEN MAINPAGE /*! \mainpage OpenGM * * \section Introduction * OpenGM is a C++ template library for defining discrete graphical models and * performing inference on these models, using a wide range of state-of-the-art * algorithms. * \n * No restrictions are imposed on the factor graph to allow for higher-order * factors and arbitrary neighborhood structures. * \n * Large models with repetitive structure are handled efficiently because * (i) functions that occur repeatedly need to be stored only once, and (ii) * distinct functions can be implemented differently, using different encodings * alongside each other in the same model. * \n * Several parametric functions (e.g.~metrics), sparse and dense value tables are * provided and so is an interface for custom C++ code. * \n * Algorithms are separated by design from the representation of graphical models * and are easily exchangeable. * \n * OpenGM, its algorithms, HDF5 file format and command line tools are modular and * extendible. * * \section Handbook * A very detailed OpenGM-handbook for users and developers is available at the * OpenGM webside * or use the * direct link * to download the handbook in pdf form. * \n * The handbook covers everything from installation instructions to usage examples but also gives insides in the * mathematical foundations of graphical models. * * * \section Modules * * - \ref graphical_models * - \ref inference * - \ref spaces * - \ref operators * - \ref functions * . * . * \section examples Examples * * \subsection cppexamples C++ Examples * - \link quick_start.cxx Quick Start \endlink * - \link grid_potts.cxx N-class segmentation on a 2d grid with a Potts model \endlink * - \link interpixel_boundary_segmentation.cxx Segmentation in the dual / boundary domaine \endlink * - \link one_to_one_matching.cxx One-to-one Matching \endlink * - \link markov-chain.cxx Simple markov chain \endlink * - \link inference_types.cxx Usage of different inference algorithms \endlink * - \link space_types.cxx Usage of different space types \endlink * - \link io_graphical_model.cxx save / load a graphical model from / to hdf5 \endlink * . * * \subsection matlabexamples MatLab Examples * - \link testGridCreation.m Create a grid-structured model \endlink * - \link testAddUnaries.m Adding several unaries at ones (this is faster) \endlink * * - \link opengmBuild.cxx Example for build models from Matlab with own mex-file \endlink * - \link opengmBuildGrid.cxx Build grid models from Matlab with own mex-file \endlink * . * * \subsection pythonexamples Python Examples * - \link add_functions.py Adding functions to a model \endlink * - \link add_factors_and_functions.py Adding factors and functions to a model \endlink * - \link add_multiple_unaries.py Adding several unaries at ones (this is faster) \endlink * - \link markov_chain.py Simple markov chain \endlink * - \link inference_bp.py Inference with LBP \endlink * - \link inference_graphcut.py Inference with GraphCut \endlink * . * */ opengm-2.3.6+20160905/include/opengm/functions/000077500000000000000000000000001276346362400206465ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/functions/absolute_difference.hxx000066400000000000000000000113711276346362400253720ustar00rootroot00000000000000#pragma once #ifndef OPENGM_ABSOLUTE_DIFFERENCE_FUNCTION_HXX #define OPENGM_ABSOLUTE_DIFFERENCE_FUNCTION_HXX #include "opengm/opengm.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" namespace opengm { /// Absolute difference between two labels /// /// \ingroup functions template class AbsoluteDifferenceFunction : public FunctionBase, T, I, L> { public: typedef T ValueType; typedef I IndexType; typedef L LabelType; AbsoluteDifferenceFunction(const LabelType = 2, const LabelType = 2, const ValueType = 1); size_t shape(const IndexType) const; size_t size() const; size_t dimension() const; template ValueType operator()(ITERATOR) const; private: LabelType numberOfLabels1_; LabelType numberOfLabels2_; ValueType scale_; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration< AbsoluteDifferenceFunction >{ /// Id of the AbsoluteDifferenceFunction enum ID { Id = opengm::FUNCTION_TYPE_ID_OFFSET + 2 }; }; /// FunctionSerialization template class FunctionSerialization > { public: typedef typename AbsoluteDifferenceFunction::ValueType ValueType; static size_t indexSequenceSize(const AbsoluteDifferenceFunction&); static size_t valueSequenceSize(const AbsoluteDifferenceFunction&); template static void serialize(const AbsoluteDifferenceFunction&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template static void deserialize(INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, AbsoluteDifferenceFunction&); }; /// \endcond /// Constructor /// /// \param numberOfLabels1 number of labels of the first variable /// \param numberOfLabels2 number of labels of the second variable /// template inline AbsoluteDifferenceFunction::AbsoluteDifferenceFunction ( const LabelType numberOfLabels1, const LabelType numberOfLabels2, const ValueType scale ) : numberOfLabels1_(numberOfLabels1), numberOfLabels2_(numberOfLabels2), scale_(scale) {} template template inline typename AbsoluteDifferenceFunction::ValueType AbsoluteDifferenceFunction::operator() ( ITERATOR begin ) const { ValueType value = begin[0]; value -= begin[1]; return scale_*abs(value); } /// extension a value table encoding this function would have /// /// \param i dimension template inline size_t AbsoluteDifferenceFunction::shape ( const IndexType i ) const { OPENGM_ASSERT(i < 2); return (i==0 ? numberOfLabels1_ : numberOfLabels2_); } // order (number of variables) of the function template inline size_t AbsoluteDifferenceFunction::dimension() const { return 2; } /// number of entries a value table encoding this function would have (used for I/O) template inline size_t AbsoluteDifferenceFunction::size() const { return numberOfLabels1_ * numberOfLabels2_; } template inline size_t FunctionSerialization >::indexSequenceSize ( const AbsoluteDifferenceFunction& src ) { return 2; } template inline size_t FunctionSerialization >::valueSequenceSize ( const AbsoluteDifferenceFunction& src ) { return 1; } template template inline void FunctionSerialization >::serialize ( const AbsoluteDifferenceFunction& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { *indexOutIterator = src.shape(0); ++indexOutIterator; *indexOutIterator = src.shape(1); L l[]={0,1}; *valueOutIterator = src(l); } template template inline void FunctionSerialization< AbsoluteDifferenceFunction >::deserialize ( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, AbsoluteDifferenceFunction& dst ) { const size_t shape0=*indexInIterator; ++ indexInIterator; dst=AbsoluteDifferenceFunction(shape0, *indexInIterator,*valueInIterator); } } // namespace opengm #endif // OPENGM_ABSOLUTE_DIFFERENCE_FUNCTION_HXX opengm-2.3.6+20160905/include/opengm/functions/accumulated_view.hxx000066400000000000000000000105211276346362400247170ustar00rootroot00000000000000// // File: accumulated_view.hxx // // This file is part of OpenGM. // // Copyright (C) 2015 Stefan Haller // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #pragma once #ifndef OPENGM_FUNCTIONS_ACCUMULATED_VIEW_HXX #define OPENGM_FUNCTIONS_ACCUMULATED_VIEW_HXX #include #include namespace opengm { template class AccumulatedViewFunction : public FunctionBase< AccumulatedViewFunction, typename GM::ValueType, typename GM::IndexType, typename GM::LabelType > { public: typedef typename GM::IndexType IndexType; typedef typename GM::IndexType LabelType; typedef typename GM::ValueType ValueType; typedef typename GM::FactorType FactorType; typedef typename GM::OperatorType OperatorType; AccumulatedViewFunction(); AccumulatedViewFunction(const FactorType &); template AccumulatedViewFunction(ITERATOR begin, ITERATOR end); template ValueType operator()(ITERATOR begin) const; LabelType shape(const IndexType) const; IndexType dimension() const; IndexType size() const; private: void check() const; opengm::FastSequence factors_; }; template AccumulatedViewFunction::AccumulatedViewFunction() { } template AccumulatedViewFunction::AccumulatedViewFunction ( const FactorType &factor ) { factors_.push_back(&factor); } template template AccumulatedViewFunction::AccumulatedViewFunction ( ITERATOR begin, ITERATOR end ) { factors_.resize(end - begin); std::copy(begin, end, factors_.begin()); check(); } template template typename AccumulatedViewFunction::ValueType AccumulatedViewFunction::operator() ( Iterator begin ) const { check(); ValueType result = GM::OperatorType::template neutral(); for (size_t i = 0; i < factors_.size(); ++i) GM::OperatorType::op(factors_[i]->operator()(begin), result); return result; } template typename AccumulatedViewFunction::LabelType AccumulatedViewFunction::shape ( const IndexType index ) const { check(); return factors_[0]->numberOfLabels(index); } template typename AccumulatedViewFunction::IndexType AccumulatedViewFunction::dimension() const { check(); return factors_[0]->numberOfVariables(); } template typename AccumulatedViewFunction::IndexType AccumulatedViewFunction::size() const { check(); return factors_[0]->size(); } template void AccumulatedViewFunction::check() const { #ifndef NDEBUG OPENGM_ASSERT_OP(factors_.size(), >, 0); for (size_t i = 0; i < factors_.size(); ++i) OPENGM_ASSERT(factors_[i] != NULL); for (size_t i = 1; i < factors_.size(); ++i) { OPENGM_ASSERT_OP(factors_[0]->size(), ==, factors_[i]->size()); OPENGM_ASSERT_OP(factors_[0]->numberOfVariables(), ==, factors_[i]->numberOfVariables()); for (IndexType j = 0; j < factors_[0]->numberOfVariables(); ++j) { OPENGM_ASSERT_OP(factors_[0]->numberOfLabels(j), ==, factors_[i]->numberOfLabels(j)); OPENGM_ASSERT_OP(factors_[0]->variableIndex(j), ==, factors_[i]->variableIndex(j)); } } #endif } } // namespace opengm #endif opengm-2.3.6+20160905/include/opengm/functions/constant.hxx000066400000000000000000000127111276346362400232320ustar00rootroot00000000000000#pragma once #ifndef OPENGM_CONSTANT_FUNCTION_HXX #define OPENGM_CONSTANT_FUNCTION_HXX #include #include #include #include #include "opengm/opengm.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" namespace opengm { /// Constant function /// /// \ingroup functions template class ConstantFunction : public FunctionBase, T, I, L> { public: typedef T ValueType; typedef I IndexType; typedef L LabelType; ConstantFunction(); template ConstantFunction(ITERATOR, ITERATOR, const T); size_t shape(const IndexType) const; size_t size() const; size_t dimension() const; template ValueType operator()(ITERATOR) const; // specializations bool isPotts() const { return true; } bool isGeneralizedPotts() const { return true; } ValueType min() const { return value_; } ValueType max() const { return value_; } ValueType sum() const { return value_ * static_cast(size_); } ValueType product() const { // TODO: improve this. get rid of std::pow and write a custom pow functor class for OpenGM const double x = static_cast(value_); // possible loss of precision, e.g. if value_ is a long double const int n = static_cast(size_); return static_cast(std::pow(x, n)); // call of std::pow can otherwise be ambiguous, e.g. if x is int } MinMaxFunctor minMax() const { return MinMaxFunctor(value_, value_); } private: ValueType value_; std::vector shape_; size_t size_; template friend class FunctionSerialization; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration< ConstantFunction >{ enum ID { Id=opengm::FUNCTION_TYPE_ID_OFFSET+8 }; }; /// FunctionSerialization template class FunctionSerialization >{ public: typedef typename ConstantFunction::ValueType ValueType; static size_t indexSequenceSize(const ConstantFunction&); static size_t valueSequenceSize(const ConstantFunction&); template static void serialize(const ConstantFunction &, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR ); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, ConstantFunction &); }; /// \endcond template template inline ConstantFunction::ConstantFunction ( ITERATOR shapeBegin, ITERATOR shapeEnd, const T value ) : value_(value), shape_(shapeBegin, shapeEnd), size_(std::accumulate(shapeBegin, shapeEnd, 1, std::multiplies::value_type >())) {} template inline ConstantFunction::ConstantFunction() : value_(0), shape_(), size_(0) {} template template inline typename ConstantFunction::ValueType ConstantFunction::operator() ( ITERATOR begin ) const { return value_; } /// extension a value table encoding this function would have /// /// \param i dimension template inline size_t ConstantFunction::shape ( const IndexType i ) const { OPENGM_ASSERT(i < shape_.size()); return shape_[i]; } // order (number of variables) of the function template inline size_t ConstantFunction::dimension() const { return shape_.size(); } /// number of entries a value table encoding this function would have (used for I/O) template inline size_t ConstantFunction::size() const { return size_; } template inline size_t FunctionSerialization >::indexSequenceSize ( const ConstantFunction& src ) { return src.dimension() + 1; } template inline size_t FunctionSerialization >::valueSequenceSize ( const ConstantFunction& src ) { return 1; } template template inline void FunctionSerialization >::serialize ( const ConstantFunction& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { *valueOutIterator = src.value_; *indexOutIterator = src.dimension(); for(size_t i=0; i template inline void FunctionSerialization< ConstantFunction >::deserialize ( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, ConstantFunction& dst ) { dst.value_ = *valueInIterator; size_t dimension = *indexInIterator; dst.shape_.resize(dimension); for(size_t i=0; i()); } } // namespace opengm #endif // OPENGM_CONSTANT_FUNCTION_HXX opengm-2.3.6+20160905/include/opengm/functions/constraint_functions/000077500000000000000000000000001276346362400251225ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/functions/constraint_functions/label_order_function.hxx000066400000000000000000001131721276346362400320370ustar00rootroot00000000000000#ifndef OPENGM_LABEL_ORDER_FUNCTION_HXX_ #define OPENGM_LABEL_ORDER_FUNCTION_HXX_ #include #include #include #include #include #include #include #include namespace opengm { /********************* * class definition * *********************/ template class LabelOrderFunction : public LinearConstraintFunctionBase > { public: // public function properties static const bool useSingleConstraint_ = true; static const bool useMultipleConstraints_ = false; // typedefs typedef LabelOrderFunction LinearConstraintFunctionType; typedef LinearConstraintFunctionBase LinearConstraintFunctionBaseType; typedef LinearConstraintFunctionTraits LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef std::vector LabelOrderType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsContainerType LinearConstraintsContainerType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintFunctionTraitsType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsContainerType ViolatedLinearConstraintsWeightsContainerType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; // constructors LabelOrderFunction(); LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); template LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); ~LabelOrderFunction(); // function access template ValueType operator()(Iterator statesBegin) const; // function evaluation size_t shape(const size_t i) const; // number of labels of the indicated input variable size_t dimension() const; // number of input variables size_t size() const; // number of parameters // specializations ValueType min() const; ValueType max() const; MinMaxFunctor minMax() const; protected: // storage static const size_t dimension_ = 2; LabelType numLabelsVar1_; LabelType numLabelsVar2_; size_t size_; LabelOrderType labelOrder_; ValueType returnValid_; ValueType returnInvalid_; LinearConstraintsContainerType constraints_; mutable std::vector violatedConstraintsIds_; mutable ViolatedLinearConstraintsWeightsContainerType violatedConstraintsWeights_; IndicatorVariablesContainerType indicatorVariableList_; // implementations for LinearConstraintFunctionBase LinearConstraintsIteratorType linearConstraintsBegin_impl() const; LinearConstraintsIteratorType linearConstraintsEnd_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd_impl() const; template void challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template void challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // sanity check bool checkLabelOrder() const; // helper functions void fillIndicatorVariableList(); void createConstraints(); // friends friend class FunctionSerialization >; friend class opengm::LinearConstraintFunctionBase >; }; template struct LinearConstraintFunctionTraits > { // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef LinearConstraint LinearConstraintType; typedef std::vector LinearConstraintsContainerType; typedef typename LinearConstraintsContainerType::const_iterator LinearConstraintsIteratorType; typedef typename LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef SubsequenceIterator::const_iterator> ViolatedLinearConstraintsIteratorType; typedef std::vector ViolatedLinearConstraintsWeightsContainerType; typedef typename ViolatedLinearConstraintsWeightsContainerType::const_iterator ViolatedLinearConstraintsWeightsIteratorType; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration > { enum ID { // TODO set final Id Id = opengm::FUNCTION_TYPE_ID_OFFSET - 2 }; }; /// FunctionSerialization template class FunctionSerialization > { public: typedef typename LabelOrderFunction::ValueType ValueType; static size_t indexSequenceSize(const LabelOrderFunction&); static size_t valueSequenceSize(const LabelOrderFunction&); template static void serialize(const LabelOrderFunction&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, LabelOrderFunction&); }; /// \endcond /*********************** * class documentation * ***********************/ /*! \file label_order_function.hxx * \brief Provides implementation of a label order function. */ /*! \class LabelOrderFunction * \brief A linear constraint function class ensuring the correct label order * for two variables. * * This class implements a linear constraint function which ensures the correct * label order for two variables. Each label is associated with a weight and * the function checks the condition \f$w(l_1) \leq w(l_2)\f$ where * \f$w(l_1)\f$ is the weight of the label of the first variable and * \f$w(l_2)\f$ is the weight of the label of the second variable. * * \tparam VALUE_TYPE Value type. * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. * * \ingroup functions */ /*! \var LabelOrderFunction::useSingleConstraint_ * \brief Describe the label order constraint in one single linear constraint. * * The label order constraint is described by the following linear constraint: * \f[ * \sum_i c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise and \f$v^1_j\f$ is the indicator variable of variable 1. * * \note LabelOrderFunction::useSingleConstraint_ can be used in combination * with LabelOrderFunction::useMultipleConstraints_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \var LabelOrderFunction::useMultipleConstraints_ * \brief Describe the label order constraint in multiple linear constraints. * * The label order constraint is described by the following set of linear * constraints: * \f[ * c_i \cdot v^0_i - \sum_j c_j \cdot v^1_j \quad \leq \quad 0 \qquad \forall i \in \{0, ..., n - 1\}. * \f] * Where \f$c_i\f$ is the weight for label i, \f$v^0_i\f$ is the indicator * variable of variable 0 which is 1 if variable 0 is set to label i and 0 * otherwise, \f$v^1_j\f$ is the indicator variable of variable 1 and n is the * number of labels of variable 0. * * \note LabelOrderFunction::useMultipleConstraints_ can be used in combination * with LabelOrderFunction::useSingleConstraint_ in this case both * descriptions of the label order constraint are considered. At least * one of both variables has to be set to true. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionType * \brief Typedef of the LabelOrderFunction class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionBaseType * \brief Typedef of the LinearConstraintFunctionBase class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef LabelOrderFunction::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef LabelOrderFunction::LabelOrderType * \brief Type to store the weights of the label order. */ /*! \typedef LabelOrderFunction::LinearConstraintType * \brief Typedef of the LinearConstraint class which is used to represent * linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsContainerType * \brief Defines the linear constraints container type which is used to store * multiple linear constraints. */ /*! \typedef LabelOrderFunction::LinearConstraintsIteratorType * \brief Defines the linear constraints container iterator type which is used * to iterate over the set of linear constraints. */ /*! \typedef LabelOrderFunction::IndicatorVariablesContainerType * \brief Defines the indicator variables container type which is used to store * the indicator variables used by the linear constraint function. */ /*! \typedef LabelOrderFunction::IndicatorVariablesIteratorType * \brief Defines the indicator variables container iterator type which is used * to iterate over the indicator variables used by the linear constraint * function. */ /*! \typedef LabelOrderFunction::VariableLabelPairsIteratorType * \brief Defines the variable label pairs iterator type which is used * to iterate over the variable label pairs of an indicator variable. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsIteratorType * \brief Defines the violated linear constraints iterator type which is used * to iterate over the set of violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsContainerType * \brief Defines the violated linear constraints weights container type which * is used to store the weights of the violated linear constraints. */ /*! \typedef LabelOrderFunction::ViolatedLinearConstraintsWeightsIteratorType * \brief Defines the violated linear constraints weights iterator type which * is used to iterate over the weights of the violated linear * constraints. */ /*! \fn LabelOrderFunction::LabelOrderFunction() * \brief LabelOrderFunction constructor. * * This constructor will create an empty LabelOrderFunction. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrder Weights for the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LabelOrderFunction constructor. * * This constructor will create a LabelOrderFunction. * * \tparam ITERATOR_TYPE Iterator to iterate over the weights of the label * order. * * \param[in] numLabelsVar1 Number of labels for the first variable. * \param[in] numLabelsVar2 Number of labels for the second variable. * \param[in] labelOrderBegin Iterator pointing to the begin of the weights for * the label order. * \param[in] labelOrderBegin Iterator pointing to the end of the weights for * the label order. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LabelOrderFunction::~LabelOrderFunction() * \brief LabelOrderFunction destructor. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::operator()(Iterator statesBegin) const * \brief Function evaluation. * * \param[in] statesBegin Iterator pointing to the begin of a sequence of * labels for the variables of the function. * * \return LabelOrderFunction::returnValid_ if no constraint is violated * by the labeling. LabelOrderFunction::returnInvalid_ if at * least one constraint is violated by the labeling. */ /*! \fn size_t LabelOrderFunction::shape(const size_t i) const * \brief Number of labels of the indicated input variable. * * \param[in] i Index of the variable. * * \return Returns the number of labels of the i-th variable. */ /*! \fn size_t LabelOrderFunction::dimension() const * \brief Number of input variables. * * \return Returns the number of variables. */ /*! \fn size_t LabelOrderFunction::size() const * \brief Number of parameters. * * \return Returns the number of parameters. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::min() const * \brief Minimum value of the label order function. * * \return Returns the minimum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn LabelOrderFunction::ValueType LabelOrderFunction::max() const * \brief Maximum value of the label order function. * * \return Returns the maximum value of LabelOrderFunction::returnValid_ * and LabelOrderFunction::returnInvalid_. */ /*! \fn MinMaxFunctor LabelOrderFunction::minMax() const * \brief Get minimum and maximum at the same time. * * \return Returns a functor containing the minimum and the maximum value of * the label order function. */ /*! \var LabelOrderFunction::dimension_ * \brief The dimension of the label order function. */ /*! \var LabelOrderFunction::numLabelsVar1_ * \brief The number of labels of the first variable. */ /*! \var LabelOrderFunction::numLabelsVar2_ * \brief The number of labels of the second variable. */ /*! \var LabelOrderFunction::size_ * \brief Stores the size of the label order function. */ /*! \var LabelOrderFunction::labelOrder_ * \brief The weights defining the label order. */ /*! \var LabelOrderFunction::returnValid_ * \brief Stores the return value of LabelOrderFunction::operator() if no * constraint is violated. */ /*! \var LabelOrderFunction::returnInvalid_ * \brief Stores the return value of LabelOrderFunction::operator() if at * least one constraint is violated. */ /*! \var LabelOrderFunction::constraints_ * \brief Stores the linear constraints of the label order function. */ /*! \var LabelOrderFunction::violatedConstraintsIds_ * \brief Stores the indices of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::violatedConstraintsWeights_ * \brief Stores the weights of the violated constraints which are detected by * LabelOrderFunction::challenge and * LabelOrderFunction::challengeRelaxed. */ /*! \var LabelOrderFunction::indicatorVariableList_ * \brief A list of all indicator variables present in the label order * function. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::linearConstraintsBegin. */ /*! \fn LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsEnd. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderBegin. */ /*! \fn LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderEnd_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderEnd. */ /*! \fn void LabelOrderFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challenge. */ /*! \fn void LabelOrderFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool LabelOrderFunction::checkLabelOrder() const * \brief Check label order weights. Only used for assertion in debug mode. * * \return Returns true if the number of weights is large enough to define a * weight for each label of both variables. False otherwise. */ /*! \fn bool LabelOrderFunction::fillIndicatorVariableList() * \brief Helper function to fill LabelOrderFunction::indicatorVariableList_ * with all indicator variables used by the label order function. */ /*! \fn bool LabelOrderFunction::createConstraints() * \brief Helper function to create all linear constraints which are implied by * the label order function. */ /****************** * implementation * ******************/ template inline LabelOrderFunction::LabelOrderFunction() : numLabelsVar1_(), numLabelsVar2_(), size_(), labelOrder_(), returnValid_(), returnInvalid_(), constraints_(), violatedConstraintsIds_(), violatedConstraintsWeights_(), indicatorVariableList_() { if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } } template inline LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, const LabelOrderType& labelOrder, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrder), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template template inline LabelOrderFunction::LabelOrderFunction(const LabelType numLabelsVar1, const LabelType numLabelsVar2, ITERATOR_TYPE labelOrderBegin, const ValueType returnValid, const ValueType returnInvalid) : numLabelsVar1_(numLabelsVar1), numLabelsVar2_(numLabelsVar2), size_(numLabelsVar1_ * numLabelsVar2_), labelOrder_(labelOrderBegin, labelOrderBegin + std::max(numLabelsVar1_, numLabelsVar2_)), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsIds_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), violatedConstraintsWeights_((useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? numLabelsVar1_ : 0)), indicatorVariableList_(numLabelsVar1_ + numLabelsVar2_) { OPENGM_ASSERT(checkLabelOrder()); if(!(useSingleConstraint_ || useMultipleConstraints_)) { throw opengm::RuntimeError("Unsupported configuration for label order function. At least one of LabelOrderFunction::useSingleConstraint_ and LabelOrderFunction::useMultipleConstraints_ has to be set to true."); } // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template inline LabelOrderFunction::~LabelOrderFunction() { } template template inline typename LabelOrderFunction::ValueType LabelOrderFunction::operator()(Iterator statesBegin) const { if(labelOrder_[statesBegin[0]] <= labelOrder_[statesBegin[1]]) { return returnValid_; } else { return returnInvalid_; } } template inline size_t LabelOrderFunction::shape(const size_t i) const { OPENGM_ASSERT(i < dimension_); return (i==0 ? numLabelsVar1_ : numLabelsVar2_); } template inline size_t LabelOrderFunction::dimension() const { return dimension_; } template inline size_t LabelOrderFunction::size() const { return size_; } template inline typename LabelOrderFunction::ValueType LabelOrderFunction::min() const { return returnValid_ < returnInvalid_ ? returnValid_ : returnInvalid_; } template inline typename LabelOrderFunction::ValueType LabelOrderFunction::max() const { return returnValid_ > returnInvalid_ ? returnValid_ : returnInvalid_; } template inline MinMaxFunctor::ValueType> LabelOrderFunction::minMax() const { if(returnValid_ < returnInvalid_) { return MinMaxFunctor(returnValid_, returnInvalid_); } else { return MinMaxFunctor(returnInvalid_, returnValid_); } } template inline typename LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsBegin_impl() const { return constraints_.begin(); } template inline typename LabelOrderFunction::LinearConstraintsIteratorType LabelOrderFunction::linearConstraintsEnd_impl() const { return constraints_.end(); } template inline typename LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderBegin_impl() const { return indicatorVariableList_.begin(); } template inline typename LabelOrderFunction::IndicatorVariablesIteratorType LabelOrderFunction::indicatorVariablesOrderEnd_impl() const { return indicatorVariableList_.end(); } template template inline void LabelOrderFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { const ValueType weight = labelOrder_[labelingBegin[0]] - labelOrder_[labelingBegin[1]]; if(weight <= tolerance) { violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } else { if(useSingleConstraint_) { violatedConstraintsIds_[0] = 0; violatedConstraintsWeights_[0] = weight; } if(useMultipleConstraints_) { violatedConstraintsIds_[(useSingleConstraint_ ? 1 : 0)] = labelingBegin[0] + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[(useSingleConstraint_ ? 1 : 0)] = weight; } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), (useSingleConstraint_ ? 1 : 0) + (useMultipleConstraints_ ? 1 : 0)); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } } template template inline void LabelOrderFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { size_t numViolatedConstraints = 0; double weightVar2 = 0.0; for(IndexType i = 0; i < numLabelsVar2_; ++i) { weightVar2 -= labelOrder_[i] * labelingBegin[numLabelsVar1_ + i]; } double totalWeight = weightVar2; for(IndexType i = 0; i < numLabelsVar1_; ++i) { double currentWeight = (labelOrder_[i] * labelingBegin[i]); // - (); if(useSingleConstraint_) { totalWeight += currentWeight; } if(useMultipleConstraints_) { currentWeight += weightVar2; if(currentWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = i + (useSingleConstraint_ ? 1 : 0); violatedConstraintsWeights_[numViolatedConstraints] = currentWeight; ++numViolatedConstraints; } } } if(useSingleConstraint_) { if(totalWeight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = 0; violatedConstraintsWeights_[numViolatedConstraints] = totalWeight; ++numViolatedConstraints; } } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), numViolatedConstraints); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } template inline bool LabelOrderFunction::checkLabelOrder() const { if(labelOrder_.size() < std::max(numLabelsVar1_, numLabelsVar2_)) { return false; } else { return true; } } template inline void LabelOrderFunction::fillIndicatorVariableList() { for(size_t i = 0; i < numLabelsVar1_; ++i) { indicatorVariableList_[i] = typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)); } for(size_t i = 0; i < numLabelsVar2_; ++i) { indicatorVariableList_[numLabelsVar1_ + i] = typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)); } } template inline void LabelOrderFunction::createConstraints() { if(useSingleConstraint_) { constraints_[0].setBound(0.0); constraints_[0].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); } for(size_t i = 0; i < numLabelsVar2_; ++i) { constraints_[0].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(i)), -labelOrder_[i]); } } if(useMultipleConstraints_) { for(size_t i = 0; i < numLabelsVar1_; ++i) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(0), LabelType(i)), labelOrder_[i]); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setBound(0.0); constraints_[i + (useSingleConstraint_ ? 1 : 0)].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(size_t j = 0; j < numLabelsVar2_; ++j) { constraints_[i + (useSingleConstraint_ ? 1 : 0)].add(typename LinearConstraintType::IndicatorVariableType(IndexType(1), LabelType(j)), -labelOrder_[j]); } } } } /// \cond HIDDEN_SYMBOLS template inline size_t FunctionSerialization >::indexSequenceSize(const LabelOrderFunction& src) { const size_t shapeSize = 2; // numLabelsVar1 and numLabelsVar2 const size_t labelOrderSize = 1; const size_t totalIndexSize = shapeSize + labelOrderSize; return totalIndexSize; } template inline size_t FunctionSerialization >::valueSequenceSize(const LabelOrderFunction& src) { const size_t labelOrderSize = src.labelOrder_.size(); const size_t returnSize = 2; //returnValid and returnInvalid const size_t totalValueSize = labelOrderSize + returnSize; return totalValueSize; } template template inline void FunctionSerialization >::serialize(const LabelOrderFunction& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator) { // index output // shape *indexOutIterator = src.numLabelsVar1_; ++indexOutIterator; *indexOutIterator = src.numLabelsVar2_; ++indexOutIterator; // label order size *indexOutIterator = src.labelOrder_.size(); // value output // label order for(size_t i = 0; i < src.labelOrder_.size(); ++i) { *valueOutIterator = src.labelOrder_[i]; ++valueOutIterator; } // return values *valueOutIterator = src.returnValid_; ++valueOutIterator; *valueOutIterator = src.returnInvalid_; } template template inline void FunctionSerialization >::deserialize( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, LabelOrderFunction& dst) { // index input // shape const size_t numLabelsVar1 = *indexInIterator; ++indexInIterator; const size_t numLabelsVar2 = *indexInIterator; ++indexInIterator; // label order size const size_t labelOrderSize = *indexInIterator; // value input typename LabelOrderFunction::LabelOrderType labelOrder(valueInIterator, valueInIterator + labelOrderSize); valueInIterator += labelOrderSize; // valid value VALUE_TYPE returnValid = *valueInIterator; ++valueInIterator; // invalid value VALUE_TYPE returnInvalid = *valueInIterator; dst = LabelOrderFunction(numLabelsVar1, numLabelsVar2, labelOrder, returnValid, returnInvalid); } /// \endcond } // namespace opengm #endif /* OPENGM_LABEL_ORDER_FUNCTION_HXX_ */ opengm-2.3.6+20160905/include/opengm/functions/constraint_functions/linear_constraint_function.hxx000066400000000000000000001376201276346362400333070ustar00rootroot00000000000000#ifndef OPENGM_LINEAR_CONSTRAINT_FUNCTION_HXX_ #define OPENGM_LINEAR_CONSTRAINT_FUNCTION_HXX_ #include #include #include #include #include #include #include #include #include namespace opengm { /********************* * class definition * *********************/ template class LinearConstraintFunction : public LinearConstraintFunctionBase > { public: // typedefs typedef LinearConstraintFunction LinearConstraintFunctionType; typedef LinearConstraintFunctionBase LinearConstraintFunctionBaseType; typedef LinearConstraintFunctionTraits LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsContainerType LinearConstraintsContainerType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintFunctionTraitsType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsContainerType ViolatedLinearConstraintsWeightsContainerType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; // constructors LinearConstraintFunction(); template LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LinearConstraintsContainerType& constraints, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); template LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, CONSTRAINTS_ITERATOR_TYPE constraintsBegin, CONSTRAINTS_ITERATOR_TYPE constraintsEnd, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); ~LinearConstraintFunction(); // function access template ValueType operator()(STATES_ITERATOR_TYPE statesBegin) const; // function evaluation size_t shape(const size_t i) const; // number of labels of the indicated input variable size_t dimension() const; // number of input variables size_t size() const; // number of parameters // specializations ValueType min() const; ValueType max() const; MinMaxFunctor minMax() const; protected: // storage std::vector shape_; size_t size_; LinearConstraintsContainerType constraints_; mutable std::vector violatedConstraintsIds_; mutable ViolatedLinearConstraintsWeightsContainerType violatedConstraintsWeights_; ValueType returnValid_; ValueType returnInvalid_; IndicatorVariablesContainerType indicatorVariableList_; std::vector > indicatorVariableLookupTable_; // implementations for LinearConstraintFunctionBase LinearConstraintsIteratorType linearConstraintsBegin_impl() const; LinearConstraintsIteratorType linearConstraintsEnd_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd_impl() const; template void challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template void challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // sanity check bool checkConstraints() const; // helper functions void fillIndicatorVariableList(); void createIndicatorVariableLookupTable(); // friends friend class FunctionSerialization >; friend class opengm::LinearConstraintFunctionBase >; }; template struct LinearConstraintFunctionTraits > { // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef LinearConstraint LinearConstraintType; typedef std::vector LinearConstraintsContainerType; typedef typename LinearConstraintsContainerType::const_iterator LinearConstraintsIteratorType; typedef typename LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef SubsequenceIterator::const_iterator> ViolatedLinearConstraintsIteratorType; typedef std::vector ViolatedLinearConstraintsWeightsContainerType; typedef typename ViolatedLinearConstraintsWeightsContainerType::const_iterator ViolatedLinearConstraintsWeightsIteratorType; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration > { enum ID { // TODO set final Id Id = opengm::FUNCTION_TYPE_ID_OFFSET - 1 }; }; /// FunctionSerialization template class FunctionSerialization > { public: typedef typename LinearConstraintFunction::ValueType ValueType; static size_t indexSequenceSize(const LinearConstraintFunction&); static size_t valueSequenceSize(const LinearConstraintFunction&); template static void serialize(const LinearConstraintFunction&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, LinearConstraintFunction&); }; /// \endcond /*********************** * class documentation * ***********************/ /*! \file linear_constraint_function.hxx * \brief Provides implementation of a liner constraint function. */ /*! \class LinearConstraintFunction * \brief Default implementation of a linear constraint function class. * * This class implements a generic linear constraint function. May be slow for * function evaluations etc. but can be used to describe all kinds of linear * constraints. * * \tparam VALUE_TYPE The value type used by the linear constraint function. * \tparam INDEX_TYPE The index type used by the linear constraint function. * \tparam LABEL_TYPE The label type used by the linear constraint function. * * \ingroup functions */ /*! \typedef LinearConstraintFunction::LinearConstraintFunctionType * \brief Typedef of the LinearConstraintFunction class with appropriate * template parameter. */ /*! \typedef LinearConstraintFunction::LinearConstraintFunctionBaseType * \brief Typedef of the LinearConstraintFunctionBase class with appropriate * template parameter. */ /*! \typedef LinearConstraintFunction::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef LinearConstraintFunction::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LinearConstraintFunction. */ /*! \typedef LinearConstraintFunction::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LinearConstraintFunction. */ /*! \typedef LinearConstraintFunction::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LinearConstraintFunction. */ /*! \typedef LinearConstraintFunction::LinearConstraintType * \brief Typedef of the LinearConstraint class which is used to represent * linear constraints. */ /*! \typedef LinearConstraintFunction::LinearConstraintsContainerType * \brief Defines the linear constraints container type which is used to store * multiple linear constraints. */ /*! \typedef LinearConstraintFunction::LinearConstraintsIteratorType * \brief Defines the linear constraints container iterator type which is used * to iterate over the set of linear constraints. */ /*! \typedef LinearConstraintFunction::IndicatorVariablesContainerType * \brief Defines the indicator variables container type which is used to store * the indicator variables used by the linear constraint function. */ /*! \typedef LinearConstraintFunction::IndicatorVariablesIteratorType * \brief Defines the indicator variables container iterator type which is used * to iterate over the indicator variables used by the linear constraint * function. */ /*! \typedef LinearConstraintFunction::VariableLabelPairsIteratorType * \brief Defines the variable label pairs iterator type which is used * to iterate over the variable label pairs of an indicator variable. */ /*! \typedef LinearConstraintFunction::ViolatedLinearConstraintsIteratorType * \brief Defines the violated linear constraints iterator type which is used * to iterate over the set of violated linear constraints. */ /*! \typedef LinearConstraintFunction::ViolatedLinearConstraintsWeightsContainerType * \brief Defines the violated linear constraints weights container type which * is used to store the weights of the violated linear constraints. */ /*! \typedef LinearConstraintFunction::ViolatedLinearConstraintsWeightsIteratorType * \brief Defines the violated linear constraints weights iterator type which * is used to iterate over the weights of the violated linear * constraints. */ /*! \fn LinearConstraintFunction::LinearConstraintFunction() * \brief LinearConstraintFunction constructor. * * This constructor will create an empty LinearConstraintFunction. */ /*! \fn LinearConstraintFunction::LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LinearConstraintsContainerType& constraints, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LinearConstraintFunction constructor. * * This constructor will create a LinearConstraintFunction. * * \tparam SHAPE_ITERATOR_TYPE Iterator to iterate over the shape of the function * * \param[in] shapeBegin Iterator pointing to the begin of the sequence where * the shape of the function is stored. * \param[in] shapeEnd Iterator pointing to the end of the sequence where the * shape of the function is stored. * \param[in] constraints The container where the linear constraints for the * linear constraint function are stored. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LinearConstraintFunction::LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, CONSTRAINTS_ITERATOR_TYPE constraintsBegin, CONSTRAINTS_ITERATOR_TYPE constraintsEnd, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief LinearConstraintFunction constructor. * * This constructor will create a LinearConstraintFunction. * * \tparam SHAPE_ITERATOR_TYPE Iterator to iterate over the shape of the function. * \tparam CONSTRAINTS_ITERATOR_TYPE Iterator to iterate over the linear constraints * which shall be added to the function. * * \param[in] shapeBegin Iterator pointing to the begin of the sequence where * the shape of the function is stored. * \param[in] shapeEnd Iterator pointing to the end of the sequence where the * shape of the function is stored. * \param[in] constraintsBegin Iterator pointing to the begin of the sequence * where the linear constraints for the linear * constraint function are stored. * \param[in] constraintsEnd Iterator pointing to the end of the sequence where * the linear constraints for the linear constraint * function are stored. * \param[in] returnValid The value which will be returned by the function * evaluation if no constraint is violated. * \param[in] returnInvalid The value which will be returned by the function * evaluation if at least one constraint is violated. */ /*! \fn LinearConstraintFunction::~LinearConstraintFunction() * \brief LinearConstraintFunction destructor. */ /*! \fn LinearConstraintFunction::ValueType LinearConstraintFunction::operator()(STATES_ITERATOR_TYPE statesBegin) const * \brief Function evaluation. * * \param[in] statesBegin Iterator pointing to the begin of a sequence of * labels for the variables of the function. * * \return LinearConstraintFunction::returnValid_ if no constraint is violated * by the labeling. LinearConstraintFunction::returnInvalid_ if at * least one constraint is violated by the labeling. */ /*! \fn size_t LinearConstraintFunction::shape(const size_t i) const * \brief Number of labels of the indicated input variable. * * \param[in] i Index of the variable. * * \return Returns the number of labels of the i-th variable. */ /*! \fn size_t LinearConstraintFunction::dimension() const * \brief Number of input variables. * * \return Returns the number of variables. */ /*! \fn size_t LinearConstraintFunction::size() const * \brief Number of parameters. * * \return Returns the number of parameters. */ /*! \fn LinearConstraintFunction::ValueType LinearConstraintFunction::min() const * \brief Minimum value of the linear constraint function. * * \return Returns the minimum value of LinearConstraintFunction::returnValid_ * and LinearConstraintFunction::returnInvalid_. */ /*! \fn LinearConstraintFunction::ValueType LinearConstraintFunction::max() const * \brief Maximum value of the linear constraint function. * * \return Returns the maximum value of LinearConstraintFunction::returnValid_ * and LinearConstraintFunction::returnInvalid_. */ /*! \fn MinMaxFunctor LinearConstraintFunction::minMax() const * \brief Get minimum and maximum at the same time. * * \return Returns a functor containing the minimum and the maximum value of * the linear constraint function. */ /*! \var LinearConstraintFunction::shape_ * \brief Stores the shape of the linear constraint function. */ /*! \var LinearConstraintFunction::size_ * \brief Stores the size of the linear constraint function. */ /*! \var LinearConstraintFunction::constraints_ * \brief Stores the constraints of the linear constraint function. */ /*! \var LinearConstraintFunction::violatedConstraintsIds_ * \brief Stores the indices of the violated constraints which are detected by * LinearConstraintFunction::challenge and * LinearConstraintFunction::challengeRelaxed. */ /*! \var LinearConstraintFunction::violatedConstraintsWeights_ * \brief Stores the weights of the violated constraints which are detected by * LinearConstraintFunction::challenge and * LinearConstraintFunction::challengeRelaxed. */ /*! \var LinearConstraintFunction::returnValid_ * \brief Stores the return value of LinearConstraintFunction::operator() if no * constraint is violated. */ /*! \var LinearConstraintFunction::returnInvalid_ * \brief Stores the return value of LinearConstraintFunction::operator() if at * least one constraint is violated. */ /*! \var LinearConstraintFunction::indicatorVariableList_ * \brief A list of all indicator variables present in the linear constraint * function. */ /*! \var LinearConstraintFunction::indicatorVariableLookupTable_ * \brief Lookup table for fast access of the indicator variable IDs. */ /*! \fn LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintFunction::linearConstraintsBegin_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsBegin. */ /*! \fn LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintFunction::linearConstraintsEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsEnd. */ /*! \fn LinearConstraintFunction::IndicatorVariablesIteratorType LinearConstraintFunction::indicatorVariablesOrderBegin_impl() const * \brief Implementation of LinearConstraintFunctionBase::indicatorVariableOrderBegin. */ /*! \fn LinearConstraintFunction::IndicatorVariablesIteratorType LinearConstraintFunction::indicatorVariablesOrderEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::indicatorVariableOrderEnd. */ /*! \fn void LinearConstraintFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challenge. */ /*! \fn void LinearConstraintFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool LinearConstraintFunction::checkConstraints() const * \brief Check linear constraints. Only used for assertion in debug mode. * * \return Returns true if all linear constraints do not violate the number of * variables and states. False otherwise. */ /*! \fn bool LinearConstraintFunction::fillIndicatorVariableList() * \brief Helper function to fill * LinearConstraintFunction::indicatorVariableList_ with all indicator * variables used by the linear constraint function. */ /*! \fn bool LinearConstraintFunction::createIndicatorVariableLookupTable() * \brief Helper function to create an indicator variable lookup table. The * table is stored in * LinearConstraintFunction::indicatorVariableLookupTable_. */ /****************** * implementation * ******************/ template inline LinearConstraintFunction::LinearConstraintFunction() : shape_(), size_(), constraints_(), violatedConstraintsIds_(), violatedConstraintsWeights_(), returnValid_(), returnInvalid_(), indicatorVariableList_(), indicatorVariableLookupTable_() { } template template inline LinearConstraintFunction::LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LinearConstraintsContainerType& constraints, const ValueType returnValid, const ValueType returnInvalid) : shape_(shapeBegin, shapeEnd), size_(std::accumulate(shapeBegin, shapeEnd, 1, std::multiplies::value_type>())), constraints_(constraints), violatedConstraintsIds_(constraints_.size()), violatedConstraintsWeights_(constraints_.size()), returnValid_(returnValid), returnInvalid_(returnInvalid), indicatorVariableList_(), indicatorVariableLookupTable_() { OPENGM_ASSERT(this->checkConstraints()); // fill indicatorVariableList_ fillIndicatorVariableList(); // create indicatorVariableLookupTable_ createIndicatorVariableLookupTable(); } template template inline LinearConstraintFunction::LinearConstraintFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, CONSTRAINTS_ITERATOR_TYPE constraintsBegin, CONSTRAINTS_ITERATOR_TYPE constraintsEnd, const ValueType returnValid, const ValueType returnInvalid) : shape_(shapeBegin, shapeEnd), size_(std::accumulate(shapeBegin, shapeEnd, 1, std::multiplies::value_type>())), constraints_(constraintsBegin, constraintsEnd), violatedConstraintsIds_(constraints_.size()), violatedConstraintsWeights_(constraints_.size()), returnValid_(returnValid), returnInvalid_(returnInvalid), indicatorVariableList_(), indicatorVariableLookupTable_() { OPENGM_ASSERT(this->checkConstraints()); // fill indicatorVariableList_ fillIndicatorVariableList(); // create indicatorVariableLookupTable_ createIndicatorVariableLookupTable(); } template inline LinearConstraintFunction::~LinearConstraintFunction() { } template template inline typename LinearConstraintFunction::ValueType LinearConstraintFunction::operator()(STATES_ITERATOR_TYPE statesBegin) const { for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { // compare result against bound with floating point tolerance const ValueType weight = constraintsIter->operator()(statesBegin); if(weight > OPENGM_FLOAT_TOL) { return returnInvalid_; } } return returnValid_; } template inline size_t LinearConstraintFunction::shape(const size_t i) const { OPENGM_ASSERT(i < shape_.size()); return shape_[i]; } template inline size_t LinearConstraintFunction::dimension() const { return shape_.size(); } template inline size_t LinearConstraintFunction::size() const { return size_; } template inline typename LinearConstraintFunction::ValueType LinearConstraintFunction::min() const { return returnValid_ < returnInvalid_ ? returnValid_ : returnInvalid_; } template inline typename LinearConstraintFunction::ValueType LinearConstraintFunction::max() const { return returnValid_ > returnInvalid_ ? returnValid_ : returnInvalid_; } template inline MinMaxFunctor::ValueType> LinearConstraintFunction::minMax() const { if(returnValid_ < returnInvalid_) { return MinMaxFunctor(returnValid_, returnInvalid_); } else { return MinMaxFunctor(returnInvalid_, returnValid_); } } template inline typename LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintFunction::linearConstraintsBegin_impl() const { return constraints_.begin(); } template inline typename LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintFunction::linearConstraintsEnd_impl() const { return constraints_.end(); } template inline typename LinearConstraintFunction::IndicatorVariablesIteratorType LinearConstraintFunction::indicatorVariablesOrderBegin_impl() const { return indicatorVariableList_.begin(); } template inline typename LinearConstraintFunction::IndicatorVariablesIteratorType LinearConstraintFunction::indicatorVariablesOrderEnd_impl() const { return indicatorVariableList_.end(); } template template inline void LinearConstraintFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { size_t numViolatedConstraints = 0; for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { // compare result against bound with floating point tolerance const double weight = static_cast(constraintsIter->operator()(labelingBegin)); if(weight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = weight; ++numViolatedConstraints; } } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), numViolatedConstraints); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } template template inline void LinearConstraintFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { size_t numViolatedConstraints = 0; std::vector >::const_iterator indicatorVariableLookupTableIter = indicatorVariableLookupTable_.begin(); for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { double result = 0.0; typename LinearConstraintType::CoefficientsIteratorType coefficientsIter = constraintsIter->coefficientsBegin(); for(std::vector::const_iterator variableIDsIter = indicatorVariableLookupTableIter->begin(); variableIDsIter != indicatorVariableLookupTableIter->end(); ++variableIDsIter) { result += labelingBegin[*variableIDsIter] * (*coefficientsIter); ++coefficientsIter; } // compare result against bound with floating point tolerance const double weight = result - constraintsIter->getBound(); switch(constraintsIter->getConstraintOperator()) { case LinearConstraintType::LinearConstraintOperatorType::LessEqual : { if(weight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = weight; ++numViolatedConstraints; } break; } case LinearConstraintType::LinearConstraintOperatorType::Equal : { if(weight > tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = weight; ++numViolatedConstraints; } else if(weight < -tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = -weight; ++numViolatedConstraints; } break; } /*case LinearConstraintType::LinearConstraintOperatorType::GreaterEqual : { if(weight < -tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = -weight; ++numViolatedConstraints; } break; } */ default : { // default corresponds to GreaterEqual case if(weight < -tolerance) { violatedConstraintsIds_[numViolatedConstraints] = std::distance(constraints_.begin(), constraintsIter); violatedConstraintsWeights_[numViolatedConstraints] = -weight; ++numViolatedConstraints; } } } ++indicatorVariableLookupTableIter; } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), numViolatedConstraints); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } template inline bool LinearConstraintFunction::checkConstraints() const { for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { if(std::distance(constraintsIter->indicatorVariablesBegin(), constraintsIter->indicatorVariablesEnd()) == 0) { // no empty constraint allowed std::cout << "empty constraint" << std::endl; return false; } for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { if(std::distance(variablesIter->begin(), variablesIter->end()) == 0) { // no empty indicator variable allowed std::cout << "empty indicator variable" << std::endl; return false; } for(VariableLabelPairsIteratorType indicatorVariablesIter = variablesIter->begin(); indicatorVariablesIter != variablesIter->end(); ++indicatorVariablesIter) { if(indicatorVariablesIter->first >= shape_.size()) { return false; } else if(indicatorVariablesIter->second >= shape_[indicatorVariablesIter->first]) { return false; } } } } return true; } template inline void LinearConstraintFunction::fillIndicatorVariableList() { // fill indicatorVariableList_ for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { if(std::find(indicatorVariableList_.begin(), indicatorVariableList_.end(), *variablesIter) == indicatorVariableList_.end()) { indicatorVariableList_.push_back(*variablesIter) ; } } } // sort indicatorVariableList_ std::sort(indicatorVariableList_.begin(), indicatorVariableList_.end()); } template inline void LinearConstraintFunction::createIndicatorVariableLookupTable() { // create indicatorVariableLookupTable_ for(LinearConstraintsIteratorType constraintsIter = constraints_.begin(); constraintsIter != constraints_.end(); ++constraintsIter) { std::vector currentConstraintLookup; for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { OPENGM_ASSERT(std::find(indicatorVariableList_.begin(), indicatorVariableList_.end(), *variablesIter) != indicatorVariableList_.end()); currentConstraintLookup.push_back(std::distance(indicatorVariableList_.begin(), std::find(indicatorVariableList_.begin(), indicatorVariableList_.end(), *variablesIter))); } indicatorVariableLookupTable_.push_back(currentConstraintLookup); } } /// \cond HIDDEN_SYMBOLS template inline size_t FunctionSerialization >::indexSequenceSize(const LinearConstraintFunction& src) { const size_t dimensionSize = 1; const size_t shapeSize = src.dimension(); const size_t numConstraintsSize = 1; const size_t operatorTypeSize = src.constraints_.size(); const size_t numIndicatorVariablesPerConstraintSize = src.constraints_.size(); typedef typename LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintsIteratorType; size_t numVariablesPerIndicatorVariablePerConstraintSize = 0; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { numVariablesPerIndicatorVariablePerConstraintSize += std::distance(constraintsIter->indicatorVariablesBegin(), constraintsIter->indicatorVariablesEnd()); } numVariablesPerIndicatorVariablePerConstraintSize *= 2; typedef typename LinearConstraintFunction::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; size_t variableStatePairSize = 0; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { variableStatePairSize += std::distance(variablesIter->begin(), variablesIter->end()); } } variableStatePairSize *= 2; const size_t totalIndexSize = dimensionSize + shapeSize + operatorTypeSize + numConstraintsSize + numIndicatorVariablesPerConstraintSize + numVariablesPerIndicatorVariablePerConstraintSize + variableStatePairSize; return totalIndexSize; } template inline size_t FunctionSerialization >::valueSequenceSize(const LinearConstraintFunction& src) { const size_t boundsSize = src.constraints_.size(); const size_t validSize = 1; const size_t invalidSize = 1; typedef typename LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintsIteratorType; size_t coefficientsSize = 0; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { coefficientsSize += std::distance(constraintsIter->coefficientsBegin(), constraintsIter->coefficientsEnd()); } const size_t totalValueSize = boundsSize + validSize + invalidSize + coefficientsSize; return totalValueSize; } template template inline void FunctionSerialization >::serialize(const LinearConstraintFunction& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator) { // index output // dimension *indexOutIterator = src.dimension(); ++indexOutIterator; // shape for(size_t i = 0; i < src.dimension(); i++) { *indexOutIterator = src.shape_[i]; ++indexOutIterator; } // number of constraints *indexOutIterator = src.constraints_.size(); ++indexOutIterator; // operator type typedef typename LinearConstraintFunction::LinearConstraintsIteratorType LinearConstraintsIteratorType; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { *indexOutIterator = constraintsIter->getConstraintOperator(); ++indexOutIterator; } // number of indicator variables per constraint for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { *indexOutIterator = std::distance(constraintsIter->indicatorVariablesBegin(), constraintsIter->indicatorVariablesEnd()); ++indexOutIterator; } // number of variables per indicator variable per constraint typedef typename LinearConstraintFunction::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { *indexOutIterator = static_cast(variablesIter->getLogicalOperatorType()); ++indexOutIterator; *indexOutIterator = std::distance(variablesIter->begin(), variablesIter->end()); ++indexOutIterator; } } // variable state pairs typedef typename LinearConstraintFunction::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { for(IndicatorVariablesIteratorType variablesIter = constraintsIter->indicatorVariablesBegin(); variablesIter != constraintsIter->indicatorVariablesEnd(); ++variablesIter) { for(VariableLabelPairsIteratorType indicatorVariablesIter = variablesIter->begin(); indicatorVariablesIter != variablesIter->end(); ++indicatorVariablesIter) { *indexOutIterator = indicatorVariablesIter->first; ++indexOutIterator; *indexOutIterator = indicatorVariablesIter->second; ++indexOutIterator; } } } // value output // bound for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { *valueOutIterator = constraintsIter->getBound(); ++valueOutIterator; } // valid value *valueOutIterator = src.returnValid_; ++valueOutIterator; // invalid value *valueOutIterator = src.returnInvalid_; ++valueOutIterator; // coefficients typedef typename LinearConstraintFunction::LinearConstraintType::CoefficientsIteratorType CoefficientsIteratorType; for(LinearConstraintsIteratorType constraintsIter = src.constraints_.begin(); constraintsIter != src.constraints_.end(); ++constraintsIter) { for(CoefficientsIteratorType coefficientsIter = constraintsIter->coefficientsBegin(); coefficientsIter != constraintsIter->coefficientsEnd(); ++coefficientsIter) { *valueOutIterator = *coefficientsIter; ++valueOutIterator; } } } template template inline void FunctionSerialization >::deserialize( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, LinearConstraintFunction& dst) { // index input // dimension const size_t dimension = *indexInIterator; ++indexInIterator; // shape INDEX_INPUT_ITERATOR shapeBegin = indexInIterator; INDEX_INPUT_ITERATOR shapeEnd = indexInIterator + dimension; indexInIterator += dimension; // constraints typename LinearConstraintFunction::LinearConstraintsContainerType constraints(*indexInIterator); ++indexInIterator; // operator type typedef typename LinearConstraintFunction::LinearConstraintsContainerType::iterator LinearConstraintsIteratorType; for(LinearConstraintsIteratorType constraintsIter = constraints.begin(); constraintsIter != constraints.end(); ++constraintsIter) { constraintsIter->setConstraintOperator(static_cast::LinearConstraintType::LinearConstraintOperatorValueType>(*indexInIterator)); ++indexInIterator; } // number of indicator variables per constraint std::vector numIndicatorariablesPerConstraint; for(LinearConstraintsIteratorType constraintsIter = constraints.begin(); constraintsIter != constraints.end(); ++constraintsIter) { numIndicatorariablesPerConstraint.push_back(*indexInIterator); ++indexInIterator; } // number of variables per indicator variable per constraint std::vector > numVariablesPerIndicatorVariablePerConstraint; typedef typename LinearConstraintFunction::LinearConstraintType::IndicatorVariableType::LogicalOperatorType LogicalOperatorType; std::vector > logicalOperatorPerIndicatorVariablePerConstraint; for(size_t i = 0; i < numIndicatorariablesPerConstraint.size(); ++i) { numVariablesPerIndicatorVariablePerConstraint.push_back(std::vector()); logicalOperatorPerIndicatorVariablePerConstraint.push_back(std::vector()); for(size_t j = 0; j < numIndicatorariablesPerConstraint[i]; ++j) { logicalOperatorPerIndicatorVariablePerConstraint[i].push_back(static_cast(*indexInIterator)); ++indexInIterator; numVariablesPerIndicatorVariablePerConstraint[i].push_back(*indexInIterator); ++indexInIterator; } } // variable state pairs typedef typename LinearConstraintFunction::LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; std::vector variableStatePairs; for(size_t i = 0; i < numVariablesPerIndicatorVariablePerConstraint.size(); ++i) { variableStatePairs.push_back(IndicatorVariablesContainerType()); for(size_t j = 0; j < numVariablesPerIndicatorVariablePerConstraint[i].size(); ++j) { variableStatePairs[i].push_back(typename LinearConstraintFunction::LinearConstraintType::IndicatorVariableType()); for(size_t k = 0; k < numVariablesPerIndicatorVariablePerConstraint[i][j]; ++k) { const INDEX_TYPE variable = *indexInIterator; ++indexInIterator; const LABEL_TYPE label = *indexInIterator; ++indexInIterator; variableStatePairs[i][j].add(variable, label); } variableStatePairs[i][j].setLogicalOperatorType(logicalOperatorPerIndicatorVariablePerConstraint[i][j]); } } // value input // bound for(LinearConstraintsIteratorType constraintsIter = constraints.begin(); constraintsIter != constraints.end(); ++constraintsIter) { constraintsIter->setBound(*valueInIterator); ++valueInIterator; } // valid value const VALUE_TYPE returnValid = *valueInIterator; ++valueInIterator; // invalid value const VALUE_TYPE returnInvalid = *valueInIterator; ++valueInIterator; // coefficients typedef typename LinearConstraintFunction::LinearConstraintType::CoefficientsContainerType CoefficientsContainerType; std::vector coefficients; for(size_t i = 0; i < numIndicatorariablesPerConstraint.size(); ++i) { coefficients.push_back(CoefficientsContainerType()); for(size_t j = 0; j < numIndicatorariablesPerConstraint[i]; ++j) { coefficients[i].push_back(*valueInIterator); ++valueInIterator; } } // add variables and coefficients to constraints for(size_t i = 0; i < constraints.size(); ++i) { constraints[i].add(variableStatePairs[i].begin(), variableStatePairs[i].end(), coefficients[i].begin()); } dst = LinearConstraintFunction(shapeBegin, shapeEnd, constraints, returnValid, returnInvalid); } /// \endcond } // namespace opengm #endif /* OPENGM_LINEAR_CONSTRAINT_FUNCTION_HXX_ */ linear_constraint_function_base.hxx000066400000000000000000000376011276346362400342200ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/functions/constraint_functions#ifndef OPENGM_LINEAR_CONSTRAINT_FUNCTION_BASE_HXX_ #define OPENGM_LINEAR_CONSTRAINT_FUNCTION_BASE_HXX_ #include namespace opengm { /********************* * class definition * *********************/ struct LinearConstraintFunctionTraitsUndefined {}; template struct LinearConstraintFunctionTraits { typedef LinearConstraintFunctionTraitsUndefined ValueType; }; template class LinearConstraintFunctionBase : public FunctionBase::ValueType, typename LinearConstraintFunctionTraits::IndexType, typename LinearConstraintFunctionTraits::LabelType> { public: // typedefs typedef LINEAR_CONSTRAINT_FUNCTION_TYPE LinearConstraintFunctionType; typedef LinearConstraintFunctionTraits LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; // const access LinearConstraintsIteratorType linearConstraintsBegin() const; LinearConstraintsIteratorType linearConstraintsEnd() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd() const; template void challenge(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template void challengeRelaxed(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // specializations bool isLinearConstraint() const; }; /*********************** * class documentation * ***********************/ /*! \file linear_constraint_function_base.hxx * \brief Provides interface for liner constraint functions. */ /*! \struct LinearConstraintFunctionTraits * \brief Traits class for linear constraint functions. * * Each linear constraint function has to provide a template specialization of * this function to provide appropriate typedefs. The following types have to * be defined: * -# ValueType * -# IndexType * -# LabelType * -# LinearConstraintType * -# LinearConstraintsIteratorType * -# ViolatedLinearConstraintsIteratorType * -# ViolatedLinearConstraintsWeightsIteratorType * -# IndicatorVariablesIteratorType * * \tparam LINEAR_CONSTRAINT_FUNCTION_TYPE The linear constraint function type. * */ /*! \class LinearConstraintFunctionBase * \brief Base class for linear constraint functions. * * This class defines a base class for all linear constraint functions. It uses * the curiously recurring template pattern (CRTP) to provide static * polymorphism. It defines the interface which can be used to access the * linear constraints which are defined by a linear constraint function. * * \tparam LINEAR_CONSTRAINT_FUNCTION_TYPE The child class which inherits from * LinearConstraintFunctionBase and * thus defines a linear constraint * function. * * \note A template specialization of class LinearConstraintFunctionTraits has * to be defined for each class which inherits from * LinearConstraintFunctionBase. */ /*! \typedef LinearConstraintFunctionBase::LinearConstraintFunctionType * \brief Typedef of the LINEAR_CONSTRAINT_FUNCTION_TYPE template parameter * from the class LinearConstraintFunctionBase. */ /*! \typedef LinearConstraintFunctionBase::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef LinearConstraintFunctionBase::ValueType * \brief Typedef of the value type used by the linear constraint function. */ /*! \typedef LinearConstraintFunctionBase::IndexType * \brief Typedef of the index type used by the linear constraint function. */ /*! \typedef LinearConstraintFunctionBase::LabelType * \brief Typedef of the label type used by the linear constraint function. */ /*! \typedef LinearConstraintFunctionBase::LinearConstraintType * \brief Typedef of the linear constraint type used by the linear constraint * function. */ /*! \typedef LinearConstraintFunctionBase::LinearConstraintsIteratorType * \brief Typedef of the linear constraints iterator type used by the linear * constraint function to iterate over the set of linear constraints. */ /*! \typedef LinearConstraintFunctionBase::ViolatedLinearConstraintsIteratorType * \brief Typedef of the violated linear constraints iterator type used by the * linear constraint function to iterate over the set of violated linear * constraints. */ /*! \typedef LinearConstraintFunctionBase::ViolatedLinearConstraintsWeightsIteratorType * \brief Typedef of the violated linear constraints weights iterator type used * by the linear constraint function to iterate over the weights of the * violated linear constraints. */ /*! \typedef LinearConstraintFunctionBase::IndicatorVariablesIteratorType * \brief Typedef of the indicator variables iterator type used by the linear * constraint function to iterate over the indicator variables. */ /*! \fn LinearConstraintFunctionBase::LinearConstraintsIteratorType LinearConstraintFunctionBase::linearConstraintsBegin() const * \brief Get the begin iterator to the set of linear constraints represented * by the linear constraint function. * * \return The const iterator pointing to the begin of the set of linear * constraints. */ /*! \fn LinearConstraintFunctionBase::LinearConstraintsIteratorType LinearConstraintFunctionBase::linearConstraintsEnd() const * \brief Get the end iterator to the set of linear constraints represented by * the linear constraint function. * * \return The const iterator pointing to the end of the set of linear * constraints. */ /*! \fn LinearConstraintFunctionBase::IndicatorVariablesIteratorType LinearConstraintFunctionBase::indicatorVariablesOrderBegin() const * \brief Get the begin iterator to the set of indicator variables used by the * linear constraint function. * * \return The const iterator pointing to the begin of the set of indicator * variables. */ /*! \fn LinearConstraintFunctionBase::IndicatorVariablesIteratorType LinearConstraintFunctionBase::indicatorVariablesOrderEnd() const * \brief Get the end iterator to the set of indicator variables used by the * linear constraint function. * * \return The const iterator pointing to the end of the set of indicator * variables. */ /*! \fn void LinearConstraintFunctionBase::challenge(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Challenge the linear constraint function and get all linear * constraints which are violated by a given labeling. * * This function returns all linear constraints which are violated by a given * labeling, furthermore it returns the weights telling how much each * constraint is violated. It uses only the labeling for the first order * variables of the function to evaluate the indicator variables of the * function. Hence it is not qualified to challenge the liner function against * a relaxed labeling where each indicator variable can take values in the * range [0.0, 1.0]. Use LinearConstraintFunctionBase::challengeRelaxed for * this case. * * \tparam LABEL_ITERATOR Iterator type to iterate over the labels for the * variables. * * \param[out] violatedConstraintsBegin Iterator pointing to the begin of the * set of violated constraints. * \param[out] violatedConstraintsEnd Iterator pointing to the end of the set * of violated constraints. * \param[out] violatedConstraintsWeightsBegin Iterator pointing to the begin * of the weights for the set of * violated constraints. * \param[in] labelingBegin Iterator pointing to the begin of the labeling for * the first order variables. * \param[in] tolerance The tolerance value defines how much a constraint is * allowed to be violated without returning it as a * violated constraint. * * \warning All iterators returned by this function are only guaranteed to be * valid until the next call to the functions * LinearConstraintFunctionBase::challenge or * LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn void LinearConstraintFunctionBase::challengeRelaxed(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Challenge the linear constraint function and get all linear * constraints which are violated by a given labeling. * * This function returns all linear constraints which are violated by a given * labeling, furthermore it returns the weights telling how much each * constraint is violated. Unlike the LinearConstraintFunctionBase::challenge * function it takes the labeling for all indicator variables into account and * therefore is capable of dealing with a relaxed labeling where each indicator * variable can take values in the range [0.0, 1.0]. The order of the relaxed * labeling for the indicator variables has to follow the order which is given * by the iterators returned from indicatorVariablesOrderBegin() and * indicatorVariablesOrderEnd(). * * \tparam LABEL_ITERATOR Iterator type to iterate over the relaxed labeling * for the indicator variables. * * \param[out] violatedConstraintsBegin Iterator pointing to the begin of the * set of violated constraints. * \param[out] violatedConstraintsEnd Iterator pointing to the end of the set * of violated constraints. * \param[out] violatedConstraintsWeightsBegin Iterator pointing to the begin * of the weights for the set of * violated constraints. * \param[in] labelingBegin Iterator pointing to the begin of the relaxed * labeling for each indicator variable. * \param[in] tolerance The tolerance value defines how much a constraint is * allowed to be violated without returning it as a * violated constraint. * * \warning All iterators returned by this function are only guaranteed to be * valid until the next call to the functions * LinearConstraintFunctionBase::challenge or * LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool LinearConstraintFunctionBase::isLinearConstraint() const * \brief Function specialization for each linear constraint function. * * \return Returns always true as every function which inherits from * LinearConstraintFunctionBase is a linear constraint function. */ /****************** * implementation * ******************/ template inline typename LinearConstraintFunctionBase::LinearConstraintsIteratorType LinearConstraintFunctionBase::linearConstraintsBegin() const { return static_cast(this)->linearConstraintsBegin_impl(); } template inline typename LinearConstraintFunctionBase::LinearConstraintsIteratorType LinearConstraintFunctionBase::linearConstraintsEnd() const { return static_cast(this)->linearConstraintsEnd_impl(); } template inline typename LinearConstraintFunctionBase::IndicatorVariablesIteratorType LinearConstraintFunctionBase::indicatorVariablesOrderBegin() const { return static_cast(this)->indicatorVariablesOrderBegin_impl(); } template inline typename LinearConstraintFunctionBase::IndicatorVariablesIteratorType LinearConstraintFunctionBase::indicatorVariablesOrderEnd() const { return static_cast(this)->indicatorVariablesOrderEnd_impl(); } template template inline void LinearConstraintFunctionBase::challenge(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { return static_cast(this)->challenge_impl(violatedConstraintsBegin, violatedConstraintsEnd, violatedConstraintsWeightsBegin, labelingBegin, tolerance); } template template inline void LinearConstraintFunctionBase::challengeRelaxed(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { return static_cast(this)->challengeRelaxed_impl(violatedConstraintsBegin, violatedConstraintsEnd, violatedConstraintsWeightsBegin, labelingBegin, tolerance); } template inline bool LinearConstraintFunctionBase::isLinearConstraint() const { return true; } } // namespace opengm #endif /* OPENGM_LINEAR_CONSTRAINT_FUNCTION_BASE_HXX_ */ num_labels_limitation_function.hxx000066400000000000000000001100761276346362400340600ustar00rootroot00000000000000opengm-2.3.6+20160905/include/opengm/functions/constraint_functions#ifndef OPENGM_NUM_LABELS_LIMITATION_FUNCTION_HXX_ #define OPENGM_NUM_LABELS_LIMITATION_FUNCTION_HXX_ #include #include #include #include #include #include namespace opengm { /********************* * class definition * *********************/ template class NumLabelsLimitationFunction : public LinearConstraintFunctionBase > { public: // typedefs typedef NumLabelsLimitationFunction LinearConstraintFunctionType; typedef LinearConstraintFunctionBase LinearConstraintFunctionBaseType; typedef LinearConstraintFunctionTraits LinearConstraintFunctionTraitsType; typedef typename LinearConstraintFunctionTraitsType::ValueType ValueType; typedef typename LinearConstraintFunctionTraitsType::IndexType IndexType; typedef typename LinearConstraintFunctionTraitsType::LabelType LabelType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintType LinearConstraintType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsContainerType LinearConstraintsContainerType; typedef typename LinearConstraintFunctionTraitsType::LinearConstraintsIteratorType LinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintFunctionTraitsType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintFunctionTraitsType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsIteratorType ViolatedLinearConstraintsIteratorType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsContainerType ViolatedLinearConstraintsWeightsContainerType; typedef typename LinearConstraintFunctionTraitsType::ViolatedLinearConstraintsWeightsIteratorType ViolatedLinearConstraintsWeightsIteratorType; // constructors NumLabelsLimitationFunction(); template NumLabelsLimitationFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LabelType maxNumUsedLabels, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); NumLabelsLimitationFunction(const IndexType numVariables, const LabelType numLabels, const LabelType maxNumUsedLabels, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0); ~NumLabelsLimitationFunction(); // function access template ValueType operator()(Iterator statesBegin) const; // function evaluation size_t shape(const size_t i) const; // number of labels of the indicated input variable size_t dimension() const; // number of input variables size_t size() const; // number of parameters // specializations ValueType min() const; ValueType max() const; MinMaxFunctor minMax() const; protected: // storage std::vector shape_; size_t numVariables_; bool useSameNumLabels_; LabelType maxNumLabels_; LabelType maxNumUsedLabels_; size_t size_; ValueType returnValid_; ValueType returnInvalid_; LinearConstraintsContainerType constraints_; mutable std::vector violatedConstraintsIds_; mutable ViolatedLinearConstraintsWeightsContainerType violatedConstraintsWeights_; IndicatorVariablesContainerType indicatorVariableList_; // implementations for LinearConstraintFunctionBase LinearConstraintsIteratorType linearConstraintsBegin_impl() const; LinearConstraintsIteratorType linearConstraintsEnd_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderBegin_impl() const; IndicatorVariablesIteratorType indicatorVariablesOrderEnd_impl() const; template void challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; template void challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const; // helper functions void fillIndicatorVariableList(); void createConstraints(); // friends friend class FunctionSerialization >; friend class opengm::LinearConstraintFunctionBase >; }; template struct LinearConstraintFunctionTraits > { // typedefs typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; typedef LinearConstraint LinearConstraintType; typedef std::vector LinearConstraintsContainerType; typedef typename LinearConstraintsContainerType::const_iterator LinearConstraintsIteratorType; typedef typename LinearConstraintType::IndicatorVariablesContainerType IndicatorVariablesContainerType; typedef typename LinearConstraintType::IndicatorVariablesIteratorType IndicatorVariablesIteratorType; typedef typename LinearConstraintType::VariableLabelPairsIteratorType VariableLabelPairsIteratorType; typedef SubsequenceIterator::const_iterator> ViolatedLinearConstraintsIteratorType; typedef std::vector ViolatedLinearConstraintsWeightsContainerType; typedef typename ViolatedLinearConstraintsWeightsContainerType::const_iterator ViolatedLinearConstraintsWeightsIteratorType; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration > { enum ID { // TODO set final Id Id = opengm::FUNCTION_TYPE_ID_OFFSET - 3 }; }; /// FunctionSerialization template class FunctionSerialization > { public: typedef typename NumLabelsLimitationFunction::ValueType ValueType; static size_t indexSequenceSize(const NumLabelsLimitationFunction&); static size_t valueSequenceSize(const NumLabelsLimitationFunction&); template static void serialize(const NumLabelsLimitationFunction&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, NumLabelsLimitationFunction&); }; /// \endcond /*********************** * class documentation * ***********************/ /*! \file num_labels_limitation_function.hxx * \brief Provides implementation of a number of active labels limitation * function. */ /*! \class NumLabelsLimitationFunction * \brief A linear constraint function class for limiting the number of used * labels. * * This class implements a linear constraint function which limits the number * of used labels. The number of different labels in the assignment of the * function is counted and if this number exceeds the value of maximum allowed * different labels the function will return an invalid value. * * \tparam VALUE_TYPE Value type. * \tparam INDEX_TYPE Index type. * \tparam LABEL_TYPE Label type. * * \ingroup functions */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintFunctionType * \brief Typedef of the NumLabelsLimitationFunction class with appropriate * template parameter. */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintFunctionBaseType * \brief Typedef of the LinearConstraintFunctionBase class with appropriate * template parameter. */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintFunctionTraitsType * \brief Typedef of the LinearConstraintFunctionTraits class with appropriate * template parameter. */ /*! \typedef NumLabelsLimitationFunction::ValueType * \brief Typedef of the VALUE_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef NumLabelsLimitationFunction::IndexType * \brief Typedef of the INDEX_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef NumLabelsLimitationFunction::LabelType * \brief Typedef of the LABEL_TYPE template parameter type from the class * LabelOrderFunction. */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintType * \brief Typedef of the LinearConstraint class which is used to represent * linear constraints. */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintsContainerType * \brief Defines the linear constraints container type which is used to store * multiple linear constraints. */ /*! \typedef NumLabelsLimitationFunction::LinearConstraintsIteratorType * \brief Defines the linear constraints container iterator type which is used * to iterate over the set of linear constraints. */ /*! \typedef NumLabelsLimitationFunction::IndicatorVariablesContainerType * \brief Defines the indicator variables container type which is used to store * the indicator variables used by the linear constraint function. */ /*! \typedef NumLabelsLimitationFunction::IndicatorVariablesIteratorType * \brief Defines the indicator variables container iterator type which is used * to iterate over the indicator variables used by the linear constraint * function. */ /*! \typedef NumLabelsLimitationFunction::VariableLabelPairsIteratorType * \brief Defines the variable label pairs iterator type which is used * to iterate over the variable label pairs of an indicator variable. */ /*! \typedef NumLabelsLimitationFunction::ViolatedLinearConstraintsIteratorType * \brief Defines the violated linear constraints iterator type which is used * to iterate over the set of violated linear constraints. */ /*! \typedef NumLabelsLimitationFunction::ViolatedLinearConstraintsWeightsContainerType * \brief Defines the violated linear constraints weights container type which * is used to store the weights of the violated linear constraints. */ /*! \typedef NumLabelsLimitationFunction::ViolatedLinearConstraintsWeightsIteratorType * \brief Defines the violated linear constraints weights iterator type which * is used to iterate over the weights of the violated linear * constraints. */ /*! \fn NumLabelsLimitationFunction::NumLabelsLimitationFunction() * \brief NumLabelsLimitationFunction constructor. * * This constructor will create an empty NumLabelsLimitationFunction. */ /*! \fn NumLabelsLimitationFunction::NumLabelsLimitationFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LabelType maxNumUsedLabels, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief NumLabelsLimitationFunction constructor. * * This constructor will create a NumLabelsLimitationFunction where each * variable can have a different number of labels. * * \tparam SHAPE_ITERATOR_TYPE Iterator type to iterate over the shape of the * function. * * \param[in] shapeBegin Iterator pointing to the begin of a sequence which * defines the shape of the function. * \param[in] shapeEnd Iterator pointing to the end of a sequence which defines * the shape of the function. * \param[in] maxNumUsedLabels The maximum number of different labels which are * allowed in the assignment of the function. * \param[in] returnValid The value which will be returned by the function * evaluation if the number of different labels which * are used in the assignment of the function do not * exceed NumLabelsLimitationFunction::maxNumUsedLabels. * \param[in] returnInvalid The value which will be returned by the function * evaluation if the number of different labels which * are used in the assignment of the function exceed * NumLabelsLimitationFunction::maxNumUsedLabels. */ /*! \fn NumLabelsLimitationFunction::NumLabelsLimitationFunction(const IndexType numVariables, const LabelType numLabels, const LabelType maxNumUsedLabels, const ValueType returnValid = 0.0, const ValueType returnInvalid = 1.0) * \brief NumLabelsLimitationFunction constructor. * * This constructor will create a NumLabelsLimitationFunction where each * variable has the same number of labels. * * \param[in] numVariables The number of variables of the function * \param[in] numLabels The number of labels of each variable. * \param[in] maxNumUsedLabels The maximum number of different labels which are * allowed in the assignment of the function. * \param[in] returnValid The value which will be returned by the function * evaluation if the number of different labels which * are used in the assignment of the function do not * exceed NumLabelsLimitationFunction::maxNumUsedLabels. * \param[in] returnInvalid The value which will be returned by the function * evaluation if the number of different labels which * are used in the assignment of the function exceed * NumLabelsLimitationFunction::maxNumUsedLabels. */ /*! \fn NumLabelsLimitationFunction::~NumLabelsLimitationFunction() * \brief NumLabelsLimitationFunction destructor. */ /*! \fn NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::operator()(Iterator statesBegin) const * \brief Function evaluation. * * \param[in] statesBegin Iterator pointing to the begin of a sequence of * labels for the variables of the function. * * \return NumLabelsLimitationFunction::returnValid_ if no constraint is * violated by the labeling. * NumLabelsLimitationFunction::returnInvalid_ if at least one * constraint is violated by the labeling. */ /*! \fn size_t NumLabelsLimitationFunction::shape(const size_t i) const * \brief Number of labels of the indicated input variable. * * \param[in] i Index of the variable. * * \return Returns the number of labels of the i-th variable. */ /*! \fn size_t NumLabelsLimitationFunction::dimension() const * \brief Number of input variables. * * \return Returns the number of variables. */ /*! \fn size_t NumLabelsLimitationFunction::size() const * \brief Number of parameters. * * \return Returns the number of parameters. */ /*! \fn NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::min() const * \brief Minimum value of the function. * * \return Returns the minimum value of * NumLabelsLimitationFunction::returnValid_ and * NumLabelsLimitationFunction::returnInvalid_. */ /*! \fn NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::max() const * \brief Maximum value of the function. * * \return Returns the maximum value of * NumLabelsLimitationFunction::returnValid_ and * NumLabelsLimitationFunction::returnInvalid_. */ /*! \fn MinMaxFunctor NumLabelsLimitationFunction::minMax() const * \brief Get minimum and maximum at the same time. * * \return Returns a functor containing the minimum and the maximum value of * the function. */ /*! \var NumLabelsLimitationFunction::shape_ * \brief The shape of the function (only used if variables have different * number of labels). */ /*! \var NumLabelsLimitationFunction::numVariables_ * \brief The number of variables of the function. */ /*! \var NumLabelsLimitationFunction::useSameNumLabels_ * \brief Indicator to tell that all variables have the same number of * variables. */ /*! \var NumLabelsLimitationFunction::maxNumLabels_ * \brief The maximum number of labels of the variables. */ /*! \var NumLabelsLimitationFunction::maxNumUsedLabels_ * \brief The maximum number of different labels which are allowed in the * assignment of the function */ /*! \var NumLabelsLimitationFunction::size_ * \brief Stores the size of the function. */ /*! \var NumLabelsLimitationFunction::returnValid_ * \brief Stores the return value of NumLabelsLimitationFunction::operator() if * the number of different labels which are used in the assignment of * the function is smaller or equal to * NumLabelsLimitationFunction::maxNumUsedLabels_. */ /*! \var NumLabelsLimitationFunction::returnInvalid_ * \brief Stores the return value of NumLabelsLimitationFunction::operator() if * the number of different labels which are used in the assignment of * the function exceeds NumLabelsLimitationFunction::maxNumUsedLabels_. */ /*! \var NumLabelsLimitationFunction::constraints_ * \brief Stores the linear constraints of the function. */ /*! \var NumLabelsLimitationFunction::violatedConstraintsIds_ * \brief Stores the indices of the violated constraints which are detected by * NumLabelsLimitationFunction::challenge and * NumLabelsLimitationFunction::challengeRelaxed. */ /*! \var NumLabelsLimitationFunction::violatedConstraintsWeights_ * \brief Stores the weights of the violated constraints which are detected by * NumLabelsLimitationFunction::challenge and * NumLabelsLimitationFunction::challengeRelaxed. */ /*! \var NumLabelsLimitationFunction::indicatorVariableList_ * \brief A list of all indicator variables present in the function. */ /*! \fn NumLabelsLimitationFunction::LinearConstraintsIteratorType NumLabelsLimitationFunction::linearConstraintsBegin_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsBegin. */ /*! \fn NumLabelsLimitationFunction::LinearConstraintsIteratorType NumLabelsLimitationFunction::linearConstraintsEnd_impl() const * \brief Implementation of LinearConstraintFunctionBase::linearConstraintsEnd. */ /*! \fn NumLabelsLimitationFunction::IndicatorVariablesIteratorType NumLabelsLimitationFunction::indicatorVariablesOrderBegin_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderBegin. */ /*! \fn NumLabelsLimitationFunction::IndicatorVariablesIteratorType NumLabelsLimitationFunction::indicatorVariablesOrderEnd_impl() const * \brief Implementation of * LinearConstraintFunctionBase::indicatorVariablesOrderEnd. */ /*! \fn void NumLabelsLimitationFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challenge. */ /*! \fn void NumLabelsLimitationFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance = 0.0) const * \brief Implementation of LinearConstraintFunctionBase::challengeRelaxed. */ /*! \fn bool NumLabelsLimitationFunction::fillIndicatorVariableList() * \brief Helper function to fill * NumLabelsLimitationFunction::indicatorVariableList_ with all * indicator variables used by the function. */ /*! \fn bool NumLabelsLimitationFunction::createConstraints() * \brief Helper function to create all linear constraints which are implied by * the function. */ /****************** * implementation * ******************/ template inline NumLabelsLimitationFunction::NumLabelsLimitationFunction() : shape_(), numVariables_(), useSameNumLabels_(), maxNumLabels_(), maxNumUsedLabels_(), size_(), returnValid_(), returnInvalid_(), constraints_(), violatedConstraintsIds_(), violatedConstraintsWeights_(), indicatorVariableList_() { } template template inline NumLabelsLimitationFunction::NumLabelsLimitationFunction(SHAPE_ITERATOR_TYPE shapeBegin, SHAPE_ITERATOR_TYPE shapeEnd, const LabelType maxNumUsedLabels, const ValueType returnValid, const ValueType returnInvalid) : shape_(shapeBegin, shapeEnd), numVariables_(shape_.size()), useSameNumLabels_(numVariables_ > 0 ? std::equal(shape_.begin() + 1, shape_.end(), shape_.begin()) : true), maxNumLabels_(numVariables_ > 0 ? *std::max_element(shape_.begin(), shape_.end()) : 0), maxNumUsedLabels_(maxNumUsedLabels), size_(std::accumulate(shapeBegin, shapeEnd, 1, std::multiplies::value_type>())), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_(1), violatedConstraintsIds_(1), violatedConstraintsWeights_(1), indicatorVariableList_(maxNumLabels_) { // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template inline NumLabelsLimitationFunction::NumLabelsLimitationFunction(const IndexType numVariables, const LabelType numLabels, const LabelType maxNumUsedLabels, const ValueType returnValid, const ValueType returnInvalid) : shape_(), numVariables_(numVariables), useSameNumLabels_(true), maxNumLabels_(numLabels), maxNumUsedLabels_(maxNumUsedLabels), size_(unsignedIntegerPow(maxNumLabels_, numVariables_)), returnValid_(returnValid), returnInvalid_(returnInvalid), constraints_(1), violatedConstraintsIds_(1), violatedConstraintsWeights_(1), indicatorVariableList_(maxNumLabels_) { // fill indicator variable list fillIndicatorVariableList(); // create linear constraints createConstraints(); } template inline NumLabelsLimitationFunction::~NumLabelsLimitationFunction() { } template template inline typename NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::operator()(Iterator statesBegin) const { std::vector labelIsUsed(maxNumLabels_, false); LabelType maxNumLabelsFound = 0; const Iterator statesEnd = statesBegin + numVariables_; while(statesBegin != statesEnd) { const LabelType currentLabel = *statesBegin; OPENGM_ASSERT(currentLabel < maxNumLabels_); if(!labelIsUsed[currentLabel]) { labelIsUsed[currentLabel] = true; ++maxNumLabelsFound; if(maxNumLabelsFound > maxNumUsedLabels_) { return returnInvalid_; } } ++statesBegin; } return returnValid_; } template inline size_t NumLabelsLimitationFunction::shape(const size_t i) const { OPENGM_ASSERT(i < numVariables_); return (useSameNumLabels_ ? maxNumLabels_ : shape_[i]); } template inline size_t NumLabelsLimitationFunction::dimension() const { return numVariables_; } template inline size_t NumLabelsLimitationFunction::size() const { return size_; } template inline typename NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::min() const { return returnValid_ < returnInvalid_ ? returnValid_ : returnInvalid_; } template inline typename NumLabelsLimitationFunction::ValueType NumLabelsLimitationFunction::max() const { return returnValid_ > returnInvalid_ ? returnValid_ : returnInvalid_; } template inline MinMaxFunctor::ValueType> NumLabelsLimitationFunction::minMax() const { if(returnValid_ < returnInvalid_) { return MinMaxFunctor(returnValid_, returnInvalid_); } else { return MinMaxFunctor(returnInvalid_, returnValid_); } } template inline typename NumLabelsLimitationFunction::LinearConstraintsIteratorType NumLabelsLimitationFunction::linearConstraintsBegin_impl() const { return constraints_.begin(); } template inline typename NumLabelsLimitationFunction::LinearConstraintsIteratorType NumLabelsLimitationFunction::linearConstraintsEnd_impl() const { return constraints_.end(); } template inline typename NumLabelsLimitationFunction::IndicatorVariablesIteratorType NumLabelsLimitationFunction::indicatorVariablesOrderBegin_impl() const { return indicatorVariableList_.begin(); } template inline typename NumLabelsLimitationFunction::IndicatorVariablesIteratorType NumLabelsLimitationFunction::indicatorVariablesOrderEnd_impl() const { return indicatorVariableList_.end(); } template template inline void NumLabelsLimitationFunction::challenge_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { std::vector labelIsUsed(maxNumLabels_, false); ValueType maxNumLabelsFound = 0; const LABEL_ITERATOR labelingEnd = labelingBegin + numVariables_; while(labelingBegin != labelingEnd) { const LabelType currentLabel = *labelingBegin; OPENGM_ASSERT(currentLabel < maxNumLabels_); if(!labelIsUsed[currentLabel]) { labelIsUsed[currentLabel] = true; ++maxNumLabelsFound; if(maxNumLabelsFound == static_cast(maxNumLabels_)) { // all labels are used break; } } ++labelingBegin; } const ValueType weight = maxNumLabelsFound - static_cast(maxNumUsedLabels_); if(weight <= tolerance) { violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } else { violatedConstraintsIds_[0] = 0; violatedConstraintsWeights_[0] = weight; violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 1); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); return; } } template template inline void NumLabelsLimitationFunction::challengeRelaxed_impl(ViolatedLinearConstraintsIteratorType& violatedConstraintsBegin, ViolatedLinearConstraintsIteratorType& violatedConstraintsEnd, ViolatedLinearConstraintsWeightsIteratorType& violatedConstraintsWeightsBegin, LABEL_ITERATOR labelingBegin, const ValueType tolerance) const { double weight = -static_cast(maxNumUsedLabels_); for(LabelType i = 0; i < maxNumLabels_; ++i) { weight += labelingBegin[i]; } violatedConstraintsBegin = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); if(weight > tolerance) { violatedConstraintsIds_[0] = 0; violatedConstraintsWeights_[0] = weight; violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 1); violatedConstraintsWeightsBegin = violatedConstraintsWeights_.begin(); } else { violatedConstraintsEnd = ViolatedLinearConstraintsIteratorType(constraints_.begin(), violatedConstraintsIds_.begin(), 0); } } template inline void NumLabelsLimitationFunction::fillIndicatorVariableList() { for(LabelType i = 0; i < maxNumLabels_; ++i) { typename LinearConstraintType::IndicatorVariableType indicatorVariable; indicatorVariable.setLogicalOperatorType(LinearConstraintType::IndicatorVariableType::Or); for(IndexType j = 0; j < numVariables_; ++j) { if(useSameNumLabels_) { indicatorVariable.add(j, i); } else if(shape_[j] > i) { indicatorVariable.add(j, i); } } indicatorVariableList_[i] = indicatorVariable; } } template inline void NumLabelsLimitationFunction::createConstraints() { constraints_[0].setBound(maxNumUsedLabels_); constraints_[0].setConstraintOperator(LinearConstraintType::LinearConstraintOperatorType::LessEqual); for(LabelType i = 0; i < maxNumLabels_; ++i) { constraints_[0].add(indicatorVariableList_[i], 1.0); } } /// \cond HIDDEN_SYMBOLS template inline size_t FunctionSerialization >::indexSequenceSize(const NumLabelsLimitationFunction& src) { const size_t sameNumLabelsSize = 1; const size_t numVariablesSize = 1; const size_t shapeSize = src.useSameNumLabels_ ? 1 : src.shape_.size(); const size_t maxNumUsedLabelsSize = 1; const size_t totalIndexSize = sameNumLabelsSize + numVariablesSize + shapeSize + maxNumUsedLabelsSize; return totalIndexSize; } template inline size_t FunctionSerialization >::valueSequenceSize(const NumLabelsLimitationFunction& src) { const size_t returnSize = 2; //returnValid and returnInvalid const size_t totalValueSize = returnSize; return totalValueSize; } template template inline void FunctionSerialization >::serialize(const NumLabelsLimitationFunction& src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator) { // index output // shape *indexOutIterator = static_cast(src.useSameNumLabels_); ++indexOutIterator; *indexOutIterator = src.numVariables_; ++indexOutIterator; if(src.useSameNumLabels_) { *indexOutIterator = src.maxNumLabels_; ++indexOutIterator; } else { for(size_t i = 0; i < src.shape_.size(); ++i) { *indexOutIterator = src.shape_[i]; ++indexOutIterator; } } // max num used labels *indexOutIterator = src.maxNumUsedLabels_; // value output // return values *valueOutIterator = src.returnValid_; ++valueOutIterator; *valueOutIterator = src.returnInvalid_; } template template inline void FunctionSerialization >::deserialize(INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, NumLabelsLimitationFunction& dst) { typedef VALUE_TYPE ValueType; typedef INDEX_TYPE IndexType; typedef LABEL_TYPE LabelType; // index input // shape const bool useSameNumLabels = *indexInIterator; ++indexInIterator; const IndexType numVariables = *indexInIterator; ++indexInIterator; std::vector shape(indexInIterator, indexInIterator + (useSameNumLabels ? 1 : numVariables)); indexInIterator += (useSameNumLabels ? 1 : numVariables); // max num used labels const LabelType maxNumUsedLabels = *indexInIterator; // value input // valid value ValueType returnValid = *valueInIterator; ++valueInIterator; // invalid value ValueType returnInvalid = *valueInIterator; if(useSameNumLabels) { dst = NumLabelsLimitationFunction(numVariables, shape[0], maxNumUsedLabels, returnValid, returnInvalid); } else { dst = NumLabelsLimitationFunction(shape.begin(), shape.end(), maxNumUsedLabels, returnValid, returnInvalid); } } /// \endcond } // namespace opengm #endif /* OPENGM_NUM_LABELS_LIMITATION_FUNCTION_HXX_ */ opengm-2.3.6+20160905/include/opengm/functions/explicit_function.hxx000066400000000000000000000125031276346362400251260ustar00rootroot00000000000000#pragma once #ifndef OPENGM_EXPLICIT_FUNCTION_HXX #define OPENGM_EXPLICIT_FUNCTION_HXX #include "opengm/datastructures/marray/marray.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" namespace opengm { /// Function encoded as a dense multi-dimensional array, marray::Marray /// /// \ingroup functions template class ExplicitFunction : public marray::Marray, public FunctionBase, T, I, L> { public: typedef T ValueType; typedef L LabelType; typedef I IndexType; ExplicitFunction() : marray::Marray() {} /// construct a constant explicit function of order 0 ExplicitFunction(const T& value) : marray::Marray(value) {} ExplicitFunction(const ExplicitFunction& other) : marray::Marray(other) {} ExplicitFunction& operator=(const ExplicitFunction& other) { marray::Marray::operator=(other); return *this; } /// construct a function encoded by a value table (whose entries are initialized as 0) /// /// Example: A function depending on two variables with 3 and 4 labels, respectively. /// \code /// size_t shape[] = {3, 4}; /// ExplicitFunction f(shape, shape + 2}; /// \endcode /// template ExplicitFunction(SHAPE_ITERATOR shapeBegin, SHAPE_ITERATOR shapeEnd) : marray::Marray(shapeBegin, shapeEnd) {} /// construct a function encoded by a value table (whose entries are initialized with the same value) template ExplicitFunction(SHAPE_ITERATOR shapeBegin, SHAPE_ITERATOR shapeEnd, const T & value) : marray::Marray(shapeBegin, shapeEnd, value) {} }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration< ExplicitFunction >{ enum ID { Id=opengm::FUNCTION_TYPE_ID_OFFSET }; }; /// FunctionSerialization template class FunctionSerialization< ExplicitFunction >{ public: typedef typename ExplicitFunction::value_type ValueType; static size_t indexSequenceSize(const ExplicitFunction &); static size_t valueSequenceSize(const ExplicitFunction &); template static void serialize(const ExplicitFunction &, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR ); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, ExplicitFunction &); }; /// \endcond template inline size_t FunctionSerialization >::indexSequenceSize ( const ExplicitFunction & src ) { return src.dimension() +1; } template inline size_t FunctionSerialization >::valueSequenceSize ( const ExplicitFunction & src ) { return src.size(); } template template void FunctionSerialization< ExplicitFunction >::serialize ( const ExplicitFunction & src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { if(src.dimension()==0) { *indexOutIterator=0; *valueOutIterator=src(0); } else{ *indexOutIterator=src.dimension(); ++indexOutIterator; for(size_t i=0;i template void FunctionSerialization >::deserialize ( INDEX_INPUT_ITERATOR indexOutIterator, VALUE_INPUT_ITERATOR valueOutIterator, ExplicitFunction & dst ) { if(*indexOutIterator==0) { dst.assign(); dst=ExplicitFunction(*valueOutIterator); } else{ const size_t dim=*indexOutIterator; std::vector shape(dim); ++indexOutIterator; for(size_t i=0;i ExplicitFunction cloneAsExplicitFunction ( const FUNC &function ) { ExplicitFunction result; cloneAsExplicitFunction(function, result); return result; } template void cloneAsExplicitFunction ( const FUNC &function, ExplicitFunction &out ) { typedef ShapeWalker Walker; out.resize(function.functionShapeBegin(), function.functionShapeEnd()); Walker walker(function.functionShapeBegin(), function.dimension()); for (I i = 0; i < function.size(); ++i, ++walker) { out(walker.coordinateTuple().begin()) = function(walker.coordinateTuple().begin()); } } } // namespace opengm #endif // OPENGM_EXPLICIT_FUNCTION_HXX opengm-2.3.6+20160905/include/opengm/functions/fieldofexperts.hxx000066400000000000000000000164341276346362400244320ustar00rootroot00000000000000#pragma once #ifndef OPENGM_FoE_FUNCTION_HXX #define OPENGM_FoE_FUNCTION_HXX #include #include #include #include "opengm/opengm.hxx" #include "opengm/functions/function_registration.hxx" #include "opengm/functions/function_properties_base.hxx" #include "opengm/datastructures/marray/marray.hxx" namespace opengm { /// Field of Expert function /// /// \ingroup functions template class FoEFunction : public FunctionBase, T, size_t, size_t> { public: typedef T ValueType; typedef L LabelType; typedef I IndexType; FoEFunction(const std::vector&, const std::vector&, const L); template FoEFunction(IT, IT, const L, const I, const size_t); FoEFunction(); LabelType shape(const size_t) const; size_t size() const; size_t dimension() const; template ValueType operator()(ITERATOR) const; void setDefault(); protected: std::vector experts_; std::vector alphas_; L numLabels_; I order_; mutable std::vector l_; friend class FunctionSerialization > ; }; /// \cond HIDDEN_SYMBOLS /// FunctionRegistration template struct FunctionRegistration > { enum ID { Id = opengm::FUNCTION_TYPE_ID_OFFSET + 33 }; }; /// FunctionSerialization template class FunctionSerialization > { public: typedef typename FoEFunction::ValueType ValueType; static size_t indexSequenceSize(const FoEFunction&); static size_t valueSequenceSize(const FoEFunction&); template static void serialize(const FoEFunction&, INDEX_OUTPUT_ITERATOR, VALUE_OUTPUT_ITERATOR); template static void deserialize( INDEX_INPUT_ITERATOR, VALUE_INPUT_ITERATOR, FoEFunction&); }; /// \endcond /// constructor for demo function template inline FoEFunction::FoEFunction () { experts_.resize(0); alphas_.resize(0); numLabels_= 0; order_ = 0; l_.resize(order_); } template inline void FoEFunction::setDefault () { experts_.resize(3*4); alphas_.resize(3); const double a_alpha[3] = {0.586612685392731, 1.157638405566669, 0.846059486257292}; const double a_expert[3][4] = { {-0.0582774013402734, 0.0339010363051084, -0.0501593018104054, 0.0745568557931712}, {0.0492112815304123, -0.0307820846538285, -0.123247230948424, 0.104812330861557}, {0.0562633568728865, 0.0152832583489560, -0.0576215592718086, -0.0139673758425540} }; for(size_t e=0; e<3; ++e){ alphas_[e] = a_alpha[e]; OPENGM_ASSERT( alphas_[e] == a_alpha[e]); for(size_t i=0; i<4;++i){ experts_[e+i*3] = a_expert[e][i]; } } numLabels_= 256; order_ = 4; l_.resize(order_); } /// constructor /// \param e: Expert-matrix (dim = numExp x order) /// \param a: Vector weighting the experts /// \param numL: NumberOfLabels template inline FoEFunction::FoEFunction (const std::vector& e, const std::vector& a, const L numL) { experts_ = e; alphas_ = a; numLabels_ = numL; order_ = e.size()/a.size(); l_.resize(order_); OPENGM_ASSERT(order_*alphas_.size() == experts_.size()); } /// constructor /// \param e: Expert-iterator (dim = numExp x order) /// \param a: Iterator weighting the experts /// \param numL: NumberOfLabels template template inline FoEFunction::FoEFunction(IT ite, IT ita, const L numLabels, const I numVars, const size_t numExperts){ numLabels_ = numLabels; order_ = numVars; experts_.resize(numVars*numExperts); alphas_.resize(numExperts); l_.resize(order_); for(size_t i=0; i template inline T FoEFunction::operator() ( ITERATOR begin ) const { //copy/cast one time to avoid additional casts for (size_t j = 0; j < order_; ++j) { l_[j] = static_cast(*begin); ++begin; OPENGM_ASSERT(l_[j]< numLabels_); } ValueType val = 0.0; size_t i = 0; for (size_t e = 0; e < alphas_.size(); ++e) { ValueType dot = 0.0; for (size_t j = 0; j < order_; ++j,++i) { dot += experts_[i] * l_[j]; } val += alphas_[e] * std::log(1 + 0.5 * dot * dot); } return val; } template inline L FoEFunction::shape ( const size_t i ) const { OPENGM_ASSERT(i < dimension()); return numLabels_; } template inline size_t FoEFunction::dimension() const { return order_; } template inline size_t FoEFunction::size() const { size_t s=1; for(size_t i=0; i inline size_t FunctionSerialization >::indexSequenceSize ( const FoEFunction & src ) { return 3; } template inline size_t FunctionSerialization >::valueSequenceSize ( const FoEFunction & src ) { return src.experts_.size()+src.alphas_.size(); } template template inline void FunctionSerialization >::serialize ( const FoEFunction & src, INDEX_OUTPUT_ITERATOR indexOutIterator, VALUE_OUTPUT_ITERATOR valueOutIterator ) { for(size_t i=0; i template inline void FunctionSerialization >::deserialize ( INDEX_INPUT_ITERATOR indexInIterator, VALUE_INPUT_ITERATOR valueInIterator, FoEFunction & dst ) { size_t numExperts = *indexInIterator; ++indexInIterator; size_t order = *indexInIterator; ++indexInIterator; size_t numLabels = *indexInIterator; std::vector alphas(numExperts); std::vector experts(numExperts*order); for(size_t i=0; i(experts,alphas,numLabels); } } // namespace opengm #endif // #ifndef OPENGM_FoE_FUNCTION_HXX opengm-2.3.6+20160905/include/opengm/functions/function_properties.hxx000066400000000000000000000105311276346362400255000ustar00rootroot00000000000000#pragma once #ifndef OPENGM_FUNCTION_PROPERTIES_HXX #define OPENGM_FUNCTION_PROPERTIES_HXX #include #include "opengm/opengm.hxx" #include "opengm/utilities/shape_accessor.hxx" #include "opengm/utilities/accessor_iterator.hxx" #include "opengm/utilities/accumulation.hxx" #include "opengm/utilities/indexing.hxx" #include "opengm/utilities/functors.hxx" #include "opengm/operations/adder.hxx" #include "opengm/operations/and.hxx" #include "opengm/operations/or.hxx" #include "opengm/operations/minimizer.hxx" #include "opengm/operations/maximizer.hxx" #include "opengm/operations/adder.hxx" #include "opengm/operations/integrator.hxx" #include "opengm/operations/multiplier.hxx" #define OPENGM_FUNCTION_TYPEDEF_MACRO typedef typename FunctionType::ValueType ValueType;\ typedef typename FunctionType::IndexType IndexType;\ typedef typename FunctionType::LabelType LabelType;\ typedef typename FunctionType::FunctionShapeIteratorType FunctionShapeIteratorType namespace opengm { struct BinaryProperties{ enum Values{ IsPotts=0, IsSubmodular1=1, IsPositive=2 }; }; struct ValueProperties{ enum Values{ Sum=0, Product=1, Minimum=2, Maximum=3, FeasibleValue }; }; template class BinaryFunctionProperties; template class ValueFunctionProperties; namespace detail_properties{ template class AllValuesInAnyOrderFunctionProperties; template class AtLeastAllUniqueValuesFunctionProperties; } // Fallback implementation(s) of binary properties template class BinaryFunctionProperties { typedef FUNCTION FunctionType; OPENGM_FUNCTION_TYPEDEF_MACRO; public: static bool op(const FunctionType & f) { ShapeWalker shapeWalker(f.functionShapeBegin(), f.dimension()); ValueType vEqual = f(shapeWalker.coordinateTuple().begin()); ++shapeWalker; ValueType vNotEqual = f(shapeWalker.coordinateTuple().begin()); ++shapeWalker; for (IndexType i = 2; i < f.size(); ++i, ++shapeWalker) { // all labels are equal if (isEqualValueVector(shapeWalker.coordinateTuple())) { if (vEqual != f(shapeWalker.coordinateTuple().begin())) return false; } // all labels are not equal else { if (vNotEqual != f(shapeWalker.coordinateTuple().begin())) return false; } } return true; } }; // Fallback implementation(s) of (real) value properties // Some basic properties are derived from // "AllValuesInAnyOrderFunctionProperties" and // "AtLeastAllUniqueValuesFunctionProperties" template class ValueFunctionProperties : public detail_properties::AllValuesInAnyOrderFunctionProperties{ }; template class ValueFunctionProperties : public detail_properties::AllValuesInAnyOrderFunctionProperties{ }; template class ValueFunctionProperties : public detail_properties::AtLeastAllUniqueValuesFunctionProperties{ }; template class ValueFunctionProperties : public detail_properties::AtLeastAllUniqueValuesFunctionProperties{ }; namespace detail_properties{ template class AllValuesInAnyOrderFunctionProperties{ typedef FUNCTION FunctionType; OPENGM_FUNCTION_TYPEDEF_MACRO; public: static ValueType op(const FunctionType & f) { opengm::AccumulationFunctor functor; f.forAllValuesInAnyOrder(functor); return functor.value(); } }; template class AtLeastAllUniqueValuesFunctionProperties{ typedef FUNCTION FunctionType; OPENGM_FUNCTION_TYPEDEF_MACRO; public: static ValueType op(const FunctionType & f) { opengm::AccumulationFunctor functor; f.forAllValuesInAnyOrder(functor); return functor.value(); } }; } }// namespace opengm #endif //OPENGM_FUNCTION_PROPERTIES_HXX opengm-2.3.6+20160905/include/opengm/functions/function_properties_base.hxx000066400000000000000000000540351276346362400265010ustar00rootroot00000000000000#pragma once #ifndef OPENGM_FUNCTION_PROPERTIES_BASE_HXX #define OPENGM_FUNCTION_PROPERTIES_BASE_HXX #include #include "opengm/opengm.hxx" #include "opengm/utilities/shape_accessor.hxx" #include "opengm/utilities/accessor_iterator.hxx" #include "opengm/utilities/accumulation.hxx" #include "opengm/utilities/indexing.hxx" #include "opengm/utilities/functors.hxx" #include "opengm/operations/adder.hxx" #include "opengm/operations/and.hxx" #include "opengm/operations/or.hxx" #include "opengm/operations/minimizer.hxx" #include "opengm/operations/maximizer.hxx" #include "opengm/operations/adder.hxx" #include "opengm/operations/integrator.hxx" #include "opengm/operations/multiplier.hxx" #include "opengm/graphicalmodel/weights.hxx" #define OPENGM_FLOAT_TOL 0.000001 namespace opengm { template inline bool isNumericEqual(const T a, const T b) { if(meta::IsFloatingPoint::value) { if(a < b) { return b-a class FunctionBase { private: typedef VALUE ReturnType; typedef const VALUE& ReturnReferenceType; public: bool isPotts() const; bool isGeneralizedPotts() const; bool isSubmodular() const; bool isSquaredDifference() const; bool isTruncatedSquaredDifference() const; bool isAbsoluteDifference() const; bool isTruncatedAbsoluteDifference() const; bool isLinearConstraint() const; /// find minimum and maximum of the function in a single sweep /// \return class holding the minimum and the maximum MinMaxFunctor minMax() const; ReturnType min() const; ReturnType max() const; ReturnType sum() const; ReturnType product() const; /// accumulate all values of the function /// \tparam ACC Accumulator (e.g. Minimizer, Maximizer, ...) /// \return accumulated value template ReturnType accumulate() const; /// call a functor for each value of the function (in lexicographical order of the variable indices) /// /// Example: /// \code /// template /// struct MaxFunctor { /// void operator()(const T v) { /// if(v > max_) /// max_ = v; /// } /// T max_; /// }; /// MaxFunctor maxFunctor; /// maxFunctor.max_ = 0.0; /// function.forAllValuesInOrder(maxFunctor); /// \endcode /// /// \sa forAllValuesInAnyOrder, forAtLeastAllUniqueValues template void forAllValuesInOrder(FUNCTOR& functor) const; template void forAllValuesInSwitchedOrder(FUNCTOR& functor) const; /// call a functor for each value of the function (in un-specified order) /// /// \sa forAllValuesInOrder, forAtLeastAllUniqueValues template void forAllValuesInAnyOrder(FUNCTOR& functor) const; /// call a functor for at least all unique values of the function /// /// \sa forAllValuesInOrder, forAllValuesInAnyOrder template void forAtLeastAllUniqueValues(FUNCTOR& functor) const ; template void forAllValuesInOrderWithCoordinate(COORDINATE_FUNCTOR& functor) const; template void forAllValuesInAnyOrderWithCoordinate(COORDINATE_FUNCTOR& functor) const; template void forAtLeastAllUniqueValuesWithCoordinate(COORDINATE_FUNCTOR& functor) const ; bool operator==(const FUNCTION&) const; private: typedef FUNCTION FunctionType; typedef FunctionShapeAccessor FunctionShapeAccessorType; public: typedef AccessorIterator FunctionShapeIteratorType; FunctionShapeIteratorType functionShapeBegin() const; FunctionShapeIteratorType functionShapeEnd() const; size_t numberOfWeights()const{ return 0; } INDEX weightIndex(const size_t weightNumber)const{ throw RuntimeError("Function base has no parameters,this needs to be implemented in any function type"); } void setWeights(const opengm::learning::Weights& /*weights*/) const {} template VALUE weightGradient(size_t,ITERATOR) const {return 0;} }; template inline bool FunctionBase::operator== ( const FUNCTION& fb ) const{ const FunctionType& fa=*static_cast(this); const size_t dimA=fa.dimension(); // compare dimension if(dimA==fb.dimension()) { // compare shape for(size_t i=0;i shapeWalker(fa.functionShapeBegin(), dimA); for(INDEX i=0;i template inline void FunctionBase::forAllValuesInOrderWithCoordinate ( COORDINATE_FUNCTOR& functor ) const { const FunctionType& f=*static_cast(this); ShapeWalker shapeWalker(f.functionShapeBegin(), f.dimension()); for(INDEX i=0;i template inline void FunctionBase::forAllValuesInAnyOrderWithCoordinate ( COORDINATE_FUNCTOR& functor ) const{ this->forAllValuesInOrderWithCoordinate(functor); } template template inline void FunctionBase::forAtLeastAllUniqueValuesWithCoordinate ( COORDINATE_FUNCTOR& functor ) const { this->forAllValuesInAnyOrderWithCoordinate(functor); } template template inline void FunctionBase::forAllValuesInOrder ( FUNCTOR& functor ) const { const FunctionType& f=*static_cast(this); ShapeWalker shapeWalker(f.functionShapeBegin(), f.dimension()); for(INDEX i=0;i template inline void FunctionBase::forAllValuesInSwitchedOrder ( FUNCTOR& functor ) const { const FunctionType& f=*static_cast(this); ShapeWalkerSwitchedOrder shapeWalker(f.functionShapeBegin(), f.dimension()); for(INDEX i=0;i template inline void FunctionBase::forAllValuesInAnyOrder ( FUNCTOR& functor ) const { static_cast(this)->forAllValuesInOrder(functor); } template template inline void FunctionBase::forAtLeastAllUniqueValues ( FUNCTOR& functor ) const { static_cast(this)->forAllValuesInAnyOrder(functor); } template inline typename FunctionBase::FunctionShapeIteratorType FunctionBase::functionShapeBegin() const { const FunctionType& f=*static_cast(this); return FunctionShapeIteratorType(FunctionShapeAccessorType(f), 0); } template inline typename FunctionBase::FunctionShapeIteratorType FunctionBase::functionShapeEnd() const { const FunctionType& f=*static_cast(this); return FunctionShapeIteratorType(FunctionShapeAccessorType(f), f.dimension()); } template inline bool FunctionBase::isSquaredDifference() const{ const FunctionType& f=*static_cast(this); if(f.dimension()==2) { OPENGM_ASSERT(f.shape(0)>static_cast