From 903c302ead850cf618e6cbbf4eb78533debbed6b Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sun, 13 Jul 2014 01:08:55 +0000 Subject: [PATCH 001/149] Missed PLASMA cmake utilities git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6726 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/cmake/EuropaModule.cmake | 252 ++++++++ src/PLASMA/cmake/FindCppUnit.cmake | 23 + src/PLASMA/cmake/FindPkgMacros.cmake | 144 +++++ src/PLASMA/cmake/LibFindMacros.cmake | 820 +++++++++++++++++++++++++++ 4 files changed, 1239 insertions(+) create mode 100644 src/PLASMA/cmake/EuropaModule.cmake create mode 100644 src/PLASMA/cmake/FindCppUnit.cmake create mode 100644 src/PLASMA/cmake/FindPkgMacros.cmake create mode 100644 src/PLASMA/cmake/LibFindMacros.cmake diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake new file mode 100644 index 000000000..427ca868e --- /dev/null +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -0,0 +1,252 @@ +include(FindCppUnit) + +function(append_target_property target propname value) + get_target_property(current_val ${target} ${propname}) + set_target_properties(${target} PROPERTIES ${propname} "${current_val}${value}") +endfunction(append_target_property) + +function(prepend_all prefix input output) + set(temp "") + foreach(entry ${input}) + list(APPEND temp ${prefix}${entry}) + endforeach(entry) + set(${output} ${temp} PARENT_SCOPE) +endfunction(prepend_all) + +function(common_module_prepends base_sources component_sources test_sources + base_dest component_dest test_dest) + prepend_all(base/ "${base_sources}" base_int) + prepend_all(component/ "${component_sources}" component_int) + prepend_all(test/ "${test_sources}" test_int) + set(${base_dest} ${base_int} PARENT_SCOPE) + set(${component_dest} ${component_int} PARENT_SCOPE) + set(${test_dest} ${test_int} PARENT_SCOPE) +endfunction(common_module_prepends) + + +function(echo_target_property tgt prop) + # v for value, d for defined, s for set + get_property(v TARGET ${tgt} PROPERTY ${prop}) + get_property(d TARGET ${tgt} PROPERTY ${prop} DEFINED) + get_property(s TARGET ${tgt} PROPERTY ${prop} SET) + + # only produce output for values that are set + if(s) + message("tgt='${tgt}' prop='${prop}'") + message(" value='${v}'") + message(" defined='${d}'") + message(" set='${s}'") + message("") + endif() +endfunction() + +function(echo_target tgt) + if(NOT TARGET ${tgt}) + message("There is no target named '${tgt}'") + return() + endif() + + set(props +DEBUG_OUTPUT_NAME +DEBUG_POSTFIX +RELEASE_OUTPUT_NAME +RELEASE_POSTFIX +ARCHIVE_OUTPUT_DIRECTORY +ARCHIVE_OUTPUT_DIRECTORY_DEBUG +ARCHIVE_OUTPUT_DIRECTORY_RELEASE +ARCHIVE_OUTPUT_NAME +ARCHIVE_OUTPUT_NAME_DEBUG +ARCHIVE_OUTPUT_NAME_RELEASE +AUTOMOC +AUTOMOC_MOC_OPTIONS +BUILD_WITH_INSTALL_RPATH +BUNDLE +BUNDLE_EXTENSION +COMPILE_DEFINITIONS +COMPILE_DEFINITIONS_DEBUG +COMPILE_DEFINITIONS_RELEASE +COMPILE_FLAGS +DEBUG_POSTFIX +RELEASE_POSTFIX +DEFINE_SYMBOL +ENABLE_EXPORTS +EXCLUDE_FROM_ALL +EchoString +FOLDER +FRAMEWORK +Fortran_FORMAT +Fortran_MODULE_DIRECTORY +GENERATOR_FILE_NAME +GNUtoMS +HAS_CXX +IMPLICIT_DEPENDS_INCLUDE_TRANSFORM +IMPORTED +IMPORTED_CONFIGURATIONS +IMPORTED_IMPLIB +IMPORTED_IMPLIB_DEBUG +IMPORTED_IMPLIB_RELEASE +IMPORTED_LINK_DEPENDENT_LIBRARIES +IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG +IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE +IMPORTED_LINK_INTERFACE_LANGUAGES +IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG +IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE +IMPORTED_LINK_INTERFACE_LIBRARIES +IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG +IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE +IMPORTED_LINK_INTERFACE_MULTIPLICITY +IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG +IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE +IMPORTED_LOCATION +IMPORTED_LOCATION_DEBUG +IMPORTED_LOCATION_RELEASE +IMPORTED_NO_SONAME +IMPORTED_NO_SONAME_DEBUG +IMPORTED_NO_SONAME_RELEASE +IMPORTED_SONAME +IMPORTED_SONAME_DEBUG +IMPORTED_SONAME_RELEASE +IMPORT_PREFIX +IMPORT_SUFFIX +INCLUDE_DIRECTORIES +INSTALL_NAME_DIR +INSTALL_RPATH +INSTALL_RPATH_USE_LINK_PATH +INTERPROCEDURAL_OPTIMIZATION +INTERPROCEDURAL_OPTIMIZATION_DEBUG +INTERPROCEDURAL_OPTIMIZATION_RELEASE +LABELS +LIBRARY_OUTPUT_DIRECTORY +LIBRARY_OUTPUT_DIRECTORY_DEBUG +LIBRARY_OUTPUT_DIRECTORY_RELEASE +LIBRARY_OUTPUT_NAME +LIBRARY_OUTPUT_NAME_DEBUG +LIBRARY_OUTPUT_NAME_RELEASE +LINKER_LANGUAGE +LINK_DEPENDS +LINK_FLAGS +LINK_FLAGS_DEBUG +LINK_FLAGS_RELEASE +LINK_INTERFACE_LIBRARIES +LINK_INTERFACE_LIBRARIES_DEBUG +LINK_INTERFACE_LIBRARIES_RELEASE +LINK_INTERFACE_MULTIPLICITY +LINK_INTERFACE_MULTIPLICITY_DEBUG +LINK_INTERFACE_MULTIPLICITY_RELEASE +LINK_SEARCH_END_STATIC +LINK_SEARCH_START_STATIC +LOCATION +LOCATION_DEBUG +LOCATION_RELEASE +MACOSX_BUNDLE +MACOSX_BUNDLE_INFO_PLIST +MACOSX_FRAMEWORK_INFO_PLIST +MAP_IMPORTED_CONFIG_DEBUG +MAP_IMPORTED_CONFIG_RELEASE +OSX_ARCHITECTURES +OSX_ARCHITECTURES_DEBUG +OSX_ARCHITECTURES_RELEASE +OUTPUT_NAME +OUTPUT_NAME_DEBUG +OUTPUT_NAME_RELEASE +POST_INSTALL_SCRIPT +PREFIX +PRE_INSTALL_SCRIPT +PRIVATE_HEADER +PROJECT_LABEL +PUBLIC_HEADER +RESOURCE +RULE_LAUNCH_COMPILE +RULE_LAUNCH_CUSTOM +RULE_LAUNCH_LINK +RUNTIME_OUTPUT_DIRECTORY +RUNTIME_OUTPUT_DIRECTORY_DEBUG +RUNTIME_OUTPUT_DIRECTORY_RELEASE +RUNTIME_OUTPUT_NAME +RUNTIME_OUTPUT_NAME_DEBUG +RUNTIME_OUTPUT_NAME_RELEASE +SKIP_BUILD_RPATH +SOURCES +SOVERSION +STATIC_LIBRARY_FLAGS +STATIC_LIBRARY_FLAGS_DEBUG +STATIC_LIBRARY_FLAGS_RELEASE +SUFFIX +TYPE +VERSION +VS_DOTNET_REFERENCES +VS_GLOBAL_WHATEVER +VS_GLOBAL_KEYWORD +VS_GLOBAL_PROJECT_TYPES +VS_KEYWORD +VS_SCC_AUXPATH +VS_SCC_LOCALPATH +VS_SCC_PROJECTNAME +VS_SCC_PROVIDER +VS_WINRT_EXTENSIONS +VS_WINRT_REFERENCES +WIN32_EXECUTABLE +XCODE_ATTRIBUTE_WHATEVER +) + + message("======================== ${tgt} ========================") + foreach(p ${props}) + echo_target_property("${t}" "${p}") + endforeach() + message("") +endfunction() + + +#TODO: change this to "internal", to distinguish internal modules from external ones +function(add_common_module_include_dep target dep) + append_target_property(${target} INCLUDE_DIRECTORIES ";${PLASMA_SRC_DIR}/${dep}") + append_target_property(${target} INCLUDE_DIRECTORIES ";${PLASMA_SRC_DIR}/${dep}/base") + append_target_property(${target} INCLUDE_DIRECTORIES ";${PLASMA_SRC_DIR}/${dep}/component") +endfunction(add_common_module_include_dep) + +function(add_common_module_deps target deps) + foreach(dep ${deps}) + add_common_module_include_dep(${target} ${dep}) + target_link_libraries(${target} "${dep}${EUROPA_SUFFIX}") + endforeach(dep) +endfunction(add_common_module_deps target deps) + +#NOTE: This adds dependencies in every direction, so including something +#from component/ in base/ will still work. Need to think about how to +#deal with that +function(add_common_local_include_deps target) + append_target_property(${target} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/") + append_target_property(${target} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/base") + append_target_property(${target} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/component") +endfunction(add_common_local_include_deps) + +macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_dependencies module_components) + set(libname "${name}${EUROPA_SUFFIX}") + set(testname ${name}-test${EUROPA_SUFFIX}) + + add_library(${libname} ${root_srcs} ${base_srcs} ${component_srcs}) + add_common_local_include_deps(${libname}) + foreach(dep ${module_components}) + append_target_property(${libname} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/component/${dep}") + endforeach(dep) + + add_common_module_deps(${libname} "${module_dependencies}") + + #why did I end up having to do all this? + if(test_srcs OR (NOT ("${test_srcs}" STREQUAL "" OR test_srcs MATCHES "^$"))) + add_executable(${testname} ${test_srcs}) + target_link_libraries(${testname} ${libname}) + append_target_property(${testname} INCLUDE_DIRECTORIES ";${CppUnit_INCLUDE_DIRS}") + add_common_local_include_deps(${testname}) + + add_common_module_deps(${testname} "${module_dependencies}") + foreach(dep ${module_components}) + append_target_property(${testname} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/component/${dep}") + endforeach(dep) + + target_link_libraries(${testname} ${CppUnit_LIBRARIES}) + add_test(NAME ${name}Test + COMMAND ${testname}) + endif() + +endmacro(declare_module) diff --git a/src/PLASMA/cmake/FindCppUnit.cmake b/src/PLASMA/cmake/FindCppUnit.cmake new file mode 100644 index 000000000..8654d5444 --- /dev/null +++ b/src/PLASMA/cmake/FindCppUnit.cmake @@ -0,0 +1,23 @@ +# - Try to find CppUnit +# Once done, this will define +# +# CppUnit_FOUND - system has CppUnit +# CppUnit_INCLUDE_DIRS - the CppUnit include directories +# CppUnit_LIBRARIES - link these to use CppUnit + +include(FindPkgMacros) +findpkg_begin(CppUnit) + +set(CppUnit_LIBRARY_NAMES cppunit) +get_debug_names(CppUnit_LIBRARY_NAMES) + +use_pkgconfig(CppUnit_PKGC cppunit) + +find_path(CppUnit_INCLUDE_DIR NAMES cppunit/Test.h PATHS ${CppUnit_PKGC_INCLUDE_DIRS}) +find_library(CppUnit_LIBRARY_REL NAMES ${CppUnit_LIBRARY_NAMES} PATHS ${CppUnit_PKGC_LIBRARY_DIRS}) +find_library(CppUnit_LIBRARY_DBG NAMES ${CppUnit_LIBRARY_NAMES_DBG} PATHS ${CppUnit_PKGC_LIBRARY_DIRS}) +make_library_set(CppUnit_LIBRARY) + +findpkg_finish(CppUnit) +add_parent_dir(CppUnit_INCLUDE_DIRS CppUnit_INCLUDE_DIR) + diff --git a/src/PLASMA/cmake/FindPkgMacros.cmake b/src/PLASMA/cmake/FindPkgMacros.cmake new file mode 100644 index 000000000..78151f0cc --- /dev/null +++ b/src/PLASMA/cmake/FindPkgMacros.cmake @@ -0,0 +1,144 @@ +#------------------------------------------------------------------- +# This file is part of the CMake build system for OGRE +# (Object-oriented Graphics Rendering Engine) +# For the latest info, see http://www.ogre3d.org/ +# +# The contents of this file are placed in the public domain. Feel +# free to make use of it in any way you like. +#------------------------------------------------------------------- + +################################################################## +# Provides some common functionality for the FindPackage modules +################################################################## + +# Begin processing of package +macro(findpkg_begin PREFIX) + if (NOT ${PREFIX}_FIND_QUIETLY) + message(STATUS "Looking for ${PREFIX}...") + endif () +endmacro(findpkg_begin) + +# Display a status message unless FIND_QUIETLY is set +macro(pkg_message PREFIX) + if (NOT ${PREFIX}_FIND_QUIETLY) + message(STATUS ${ARGN}) + endif () +endmacro(pkg_message) + +# Get environment variable, define it as ENV_$var and make sure backslashes are converted to forward slashes +macro(getenv_path VAR) + set(ENV_${VAR} $ENV{${VAR}}) + # replace won't work if var is blank + if (ENV_${VAR}) + string( REGEX REPLACE "\\\\" "/" ENV_${VAR} ${ENV_${VAR}} ) + endif () +endmacro(getenv_path) + +# Construct search paths for includes and libraries from a PREFIX_PATH +macro(create_search_paths PREFIX) + foreach(dir ${${PREFIX}_PREFIX_PATH}) + set(${PREFIX}_INC_SEARCH_PATH ${${PREFIX}_INC_SEARCH_PATH} + ${dir}/include ${dir}/include/${PREFIX} ${dir}/Headers) + set(${PREFIX}_LIB_SEARCH_PATH ${${PREFIX}_LIB_SEARCH_PATH} + ${dir}/lib ${dir}/lib/${PREFIX} ${dir}/Libs) + set(${PREFIX}_BIN_SEARCH_PATH ${${PREFIX}_BIN_SEARCH_PATH} + ${dir}/bin) + endforeach(dir) + set(${PREFIX}_FRAMEWORK_SEARCH_PATH ${${PREFIX}_PREFIX_PATH}) +endmacro(create_search_paths) + +# clear cache variables if a certain variable changed +macro(clear_if_changed TESTVAR) + # test against internal check variable + if (NOT "${${TESTVAR}}" STREQUAL "${${TESTVAR}_INT_CHECK}") + message(STATUS "${TESTVAR} changed.") + foreach(var ${ARGN}) + set(${var} "NOTFOUND" CACHE STRING "x" FORCE) + endforeach(var) + endif () + set(${TESTVAR}_INT_CHECK ${${TESTVAR}} CACHE INTERNAL "x" FORCE) +endmacro(clear_if_changed) + +# Try to get some hints from pkg-config, if available +macro(use_pkgconfig PREFIX PKGNAME) + find_package(PkgConfig) + if (PKG_CONFIG_FOUND) + pkg_check_modules(${PREFIX} ${PKGNAME}) + endif () +endmacro (use_pkgconfig) + +# Couple a set of release AND debug libraries (or frameworks) +macro(make_library_set PREFIX) + if (${PREFIX}_FWK) + set(${PREFIX} ${${PREFIX}_FWK}) + elseif (${PREFIX}_REL AND ${PREFIX}_DBG) + set(${PREFIX} optimized ${${PREFIX}_REL} debug ${${PREFIX}_DBG}) + elseif (${PREFIX}_REL) + set(${PREFIX} ${${PREFIX}_REL}) + elseif (${PREFIX}_DBG) + set(${PREFIX} ${${PREFIX}_DBG}) + endif () +endmacro(make_library_set) + +# Generate debug names from given release names +macro(get_debug_names PREFIX) + foreach(i ${${PREFIX}}) + set(${PREFIX}_DBG ${${PREFIX}_DBG} ${i}d ${i}D ${i}_d ${i}_D ${i}_debug ${i}) + endforeach(i) +endmacro(get_debug_names) + +# Add the parent dir from DIR to VAR +macro(add_parent_dir VAR DIR) + get_filename_component(${DIR}_TEMP "${${DIR}}/.." ABSOLUTE) + set(${VAR} ${${VAR}} ${${DIR}_TEMP}) +endmacro(add_parent_dir) + +# Do the final processing for the package find. +macro(findpkg_finish PREFIX) + # skip if already processed during this run + if (NOT ${PREFIX}_FOUND) + if (${PREFIX}_INCLUDE_DIR AND ${PREFIX}_LIBRARY) + set(${PREFIX}_FOUND TRUE) + set(${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIR}) + set(${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARY}) + if (NOT ${PREFIX}_FIND_QUIETLY) + message(STATUS "Found ${PREFIX}: ${${PREFIX}_LIBRARIES}") + endif () + else () + if (NOT ${PREFIX}_FIND_QUIETLY) + message(STATUS "Could not locate ${PREFIX}") + endif () + if (${PREFIX}_FIND_REQUIRED) + message(FATAL_ERROR "Required library ${PREFIX} not found! Install the library (including dev packages) and try again. If the library is already installed, set the missing variables manually in cmake.") + endif () + endif () + + mark_as_advanced(${PREFIX}_INCLUDE_DIR ${PREFIX}_LIBRARY ${PREFIX}_LIBRARY_REL ${PREFIX}_LIBRARY_DBG ${PREFIX}_LIBRARY_FWK) + endif () +endmacro(findpkg_finish) + + +# Slightly customised framework finder +MACRO(findpkg_framework fwk) + IF(APPLE) + SET(${fwk}_FRAMEWORK_PATH + ${${fwk}_FRAMEWORK_SEARCH_PATH} + ${CMAKE_FRAMEWORK_PATH} + ~/Library/Frameworks + /Library/Frameworks + /System/Library/Frameworks + /Network/Library/Frameworks + /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.0.sdk/System/Library/Frameworks/ + ) + FOREACH(dir ${${fwk}_FRAMEWORK_PATH}) + SET(fwkpath ${dir}/${fwk}.framework) + IF(EXISTS ${fwkpath}) + SET(${fwk}_FRAMEWORK_INCLUDES ${${fwk}_FRAMEWORK_INCLUDES} + ${fwkpath}/Headers ${fwkpath}/PrivateHeaders) + if (NOT ${fwk}_LIBRARY_FWK) + SET(${fwk}_LIBRARY_FWK "-framework ${fwk}") + endif () + ENDIF(EXISTS ${fwkpath}) + ENDFOREACH(dir) + ENDIF(APPLE) +ENDMACRO(findpkg_framework) diff --git a/src/PLASMA/cmake/LibFindMacros.cmake b/src/PLASMA/cmake/LibFindMacros.cmake new file mode 100644 index 000000000..1084adfa5 --- /dev/null +++ b/src/PLASMA/cmake/LibFindMacros.cmake @@ -0,0 +1,820 @@ + + + + + + + + + + + + + cmake-modules/LibFindMacros.cmake at master · Tronic/cmake-modules · GitHub + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Skip to content +
+ + + + + + + +
+
+ + + + + + + +
+ + +
+ +
+ + + +
+ + + +
+ + This repository + + + +
+ + + + + + + + +
+
+ +
+
+ + + +
+
+
+ +
+
+
+ + + + +

+ public + + /cmake-modules + + + + + +

+
+
+ +
+
+
+ + + + +
+ + + + +
+

HTTPS clone URL

+
+ + + + +
+
+ + + +
+

Subversion checkout URL

+
+ + + + +
+
+ + +

You can clone with + HTTPS + or Subversion. + + + + + +

+ + + + Clone in Desktop + + + + + + Download ZIP + +
+
+ +
+ + + + + + + + + + + +
+ + +
+ + + branch: + master + + + +
+ + +
+ + +
+ Tronic + + + + + + +
+ +
+
+
+
+ + file + + 267 lines (245 sloc) + + 10.703 kb +
+ +
+ +
+ + + + + +
+ 1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 + +
# Version 2.2
# Public Domain, originally written by Lasse Kärkkäinen <tronic>
# Maintained at https://github.com/Tronic/cmake-modules
# Please send your improvements as pull requests on Github.

# Find another package and make it a dependency of the current package.
# This also automatically forwards the "REQUIRED" argument.
# Usage: libfind_package(<prefix> <another package> [extra args to find_package])
macro (libfind_package PREFIX PKG)
  set(${PREFIX}_args ${PKG} ${ARGN})
  if (${PREFIX}_FIND_REQUIRED)
    set(${PREFIX}_args ${${PREFIX}_args} REQUIRED)
  endif()
  find_package(${${PREFIX}_args})
  set(${PREFIX}_DEPENDENCIES ${${PREFIX}_DEPENDENCIES};${PKG})
  unset(${PREFIX}_args)
endmacro()

# A simple wrapper to make pkg-config searches a bit easier.
# Works the same as CMake's internal pkg_check_modules but is always quiet.
macro (libfind_pkg_check_modules)
  find_package(PkgConfig QUIET)
  if (PKG_CONFIG_FOUND)
    pkg_check_modules(${ARGN} QUIET)
  endif()
endmacro()

# Avoid useless copy&pasta by doing what most simple libraries do anyway:
# pkg-config, find headers, find library.
# Usage: libfind_pkg_detect(<prefix> <pkg-config args> FIND_PATH <name> [other args] FIND_LIBRARY <name> [other args])
# E.g. libfind_pkg_detect(SDL2 sdl2 FIND_PATH SDL.h PATH_SUFFIXES SDL2 FIND_LIBRARY SDL2)
function (libfind_pkg_detect PREFIX)
  # Parse arguments
  set(argname pkgargs)
  foreach (i ${ARGN})
    if ("${i}" STREQUAL "FIND_PATH")
      set(argname pathargs)
    elseif ("${i}" STREQUAL "FIND_LIBRARY")
      set(argname libraryargs)
    else()
      set(${argname} ${${argname}} ${i})
    endif()
  endforeach()
  if (NOT pkgargs)
    message(FATAL_ERROR "libfind_pkg_detect requires at least a pkg_config package name to be passed.")
  endif()
  # Find library
  libfind_pkg_check_modules(${PREFIX}_PKGCONF ${pkgargs})
  if (pathargs)
    find_path(${PREFIX}_INCLUDE_DIR NAMES ${pathargs} HINTS ${${PREFIX}_PKGCONF_INCLUDE_DIRS})
  endif()
  if (libraryargs)
    find_library(${PREFIX}_LIBRARY NAMES ${libraryargs} HINTS ${${PREFIX}_PKGCONF_LIBRARY_DIRS})
  endif()
endfunction()

# Extracts a version #define from a version.h file, output stored to <PREFIX>_VERSION.
# Usage: libfind_version_header(Foobar foobar/version.h FOOBAR_VERSION_STR)
# Fourth argument "QUIET" may be used for silently testing different define names.
# This function does nothing if the version variable is already defined.
function (libfind_version_header PREFIX VERSION_H DEFINE_NAME)
  # Skip processing if we already have a version or if the include dir was not found
  if (${PREFIX}_VERSION OR NOT ${PREFIX}_INCLUDE_DIR)
    return()
  endif()
  set(quiet ${${PREFIX}_FIND_QUIETLY})
  # Process optional arguments
  foreach(arg ${ARGN})
    if (arg STREQUAL "QUIET")
      set(quiet TRUE)
    else()
      message(AUTHOR_WARNING "Unknown argument ${arg} to libfind_version_header ignored.")
    endif()
  endforeach()
  # Read the header and parse for version number
  set(filename "${${PREFIX}_INCLUDE_DIR}/${VERSION_H}")
  if (NOT EXISTS ${filename})
    if (NOT quiet)
      message(AUTHOR_WARNING "Unable to find ${${PREFIX}_INCLUDE_DIR}/${VERSION_H}")
    endif()
    return()
  endif()
  file(READ "${filename}" header)
  string(REGEX REPLACE ".*#[ \t]*define[ \t]*${DEFINE_NAME}[ \t]*\"([^\n]*)\".*" "\\1" match "${header}")
  # No regex match?
  if (match STREQUAL header)
    if (NOT quiet)
      message(AUTHOR_WARNING "Unable to find \#define ${DEFINE_NAME} \"<version>\" from ${${PREFIX}_INCLUDE_DIR}/${VERSION_H}")
    endif()
    return()
  endif()
  # Export the version string
  set(${PREFIX}_VERSION "${match}" PARENT_SCOPE)
endfunction()

# Do the final processing once the paths have been detected.
# If include dirs are needed, ${PREFIX}_PROCESS_INCLUDES should be set to contain
# all the variables, each of which contain one include directory.
# Ditto for ${PREFIX}_PROCESS_LIBS and library files.
# Will set ${PREFIX}_FOUND, ${PREFIX}_INCLUDE_DIRS and ${PREFIX}_LIBRARIES.
# Also handles errors in case library detection was required, etc.
function (libfind_process PREFIX)
  # Skip processing if already processed during this configuration run
  if (${PREFIX}_FOUND)
    return()
  endif()

  set(found TRUE) # Start with the assumption that the package was found

  # Did we find any files? Did we miss includes? These are for formatting better error messages.
  set(some_files FALSE)
  set(missing_headers FALSE)

  # Shorthands for some variables that we need often
  set(quiet ${${PREFIX}_FIND_QUIETLY})
  set(required ${${PREFIX}_FIND_REQUIRED})
  set(exactver ${${PREFIX}_FIND_VERSION_EXACT})
  set(findver "${${PREFIX}_FIND_VERSION}")
  set(version "${${PREFIX}_VERSION}")

  # Lists of config option names (all, includes, libs)
  unset(configopts)
  set(includeopts ${${PREFIX}_PROCESS_INCLUDES})
  set(libraryopts ${${PREFIX}_PROCESS_LIBS})

  # Process deps to add to
  foreach (i ${PREFIX} ${${PREFIX}_DEPENDENCIES})
    if (DEFINED ${i}_INCLUDE_OPTS OR DEFINED ${i}_LIBRARY_OPTS)
      # The package seems to export option lists that we can use, woohoo!
      list(APPEND includeopts ${${i}_INCLUDE_OPTS})
      list(APPEND libraryopts ${${i}_LIBRARY_OPTS})
    else()
      # If plural forms don't exist or they equal singular forms
      if ((NOT DEFINED ${i}_INCLUDE_DIRS AND NOT DEFINED ${i}_LIBRARIES) OR
          ({i}_INCLUDE_DIR STREQUAL ${i}_INCLUDE_DIRS AND ${i}_LIBRARY STREQUAL ${i}_LIBRARIES))
        # Singular forms can be used
        if (DEFINED ${i}_INCLUDE_DIR)
          list(APPEND includeopts ${i}_INCLUDE_DIR)
        endif()
        if (DEFINED ${i}_LIBRARY)
          list(APPEND libraryopts ${i}_LIBRARY)
        endif()
      else()
        # Oh no, we don't know the option names
        message(FATAL_ERROR "We couldn't determine config variable names for ${i} includes and libs. Aieeh!")
      endif()
    endif()
  endforeach()
  
  if (includeopts)
    list(REMOVE_DUPLICATES includeopts)
  endif()
  
  if (libraryopts)
    list(REMOVE_DUPLICATES libraryopts)
  endif()

  string(REGEX REPLACE ".*[ ;]([^ ;]*(_INCLUDE_DIRS|_LIBRARIES))" "\\1" tmp "${includeopts} ${libraryopts}")
  if (NOT tmp STREQUAL "${includeopts} ${libraryopts}")
    message(AUTHOR_WARNING "Plural form ${tmp} found in config options of ${PREFIX}. This works as before but is now deprecated. Please only use singular forms INCLUDE_DIR and LIBRARY, and update your find scripts for LibFindMacros > 2.0 automatic dependency system (most often you can simply remove the PROCESS variables entirely).")
  endif()

  # Include/library names separated by spaces (notice: not CMake lists)
  unset(includes)
  unset(libs)

  # Process all includes and set found false if any are missing
  foreach (i ${includeopts})
    list(APPEND configopts ${i})
    if (NOT "${${i}}" STREQUAL "${i}-NOTFOUND")
      list(APPEND includes "${${i}}")
    else()
      set(found FALSE)
      set(missing_headers TRUE)
    endif()
  endforeach()

  # Process all libraries and set found false if any are missing
  foreach (i ${libraryopts})
    list(APPEND configopts ${i})
    if (NOT "${${i}}" STREQUAL "${i}-NOTFOUND")
      list(APPEND libs "${${i}}")
    else()
      set (found FALSE)
    endif()
  endforeach()

  # Version checks
  if (found AND findver)
    if (NOT version)
      message(WARNING "The find module for ${PREFIX} does not provide version information, so we'll just assume that it is OK. Please fix the module or remove package version requirements to get rid of this warning.")
    elseif (version VERSION_LESS findver OR (exactver AND NOT version VERSION_EQUAL findver))
      set(found FALSE)
      set(version_unsuitable TRUE)
    endif()
  endif()

  # If all-OK, hide all config options, export variables, print status and exit
  if (found)
    foreach (i ${configopts})
      mark_as_advanced(${i})
    endforeach()
    if (NOT quiet)
      message(STATUS "Found ${PREFIX} ${${PREFIX}_VERSION}")
      if (LIBFIND_DEBUG)
        message(STATUS " ${PREFIX}_DEPENDENCIES=${${PREFIX}_DEPENDENCIES}")
        message(STATUS " ${PREFIX}_INCLUDE_OPTS=${includeopts}")
        message(STATUS " ${PREFIX}_INCLUDE_DIRS=${includes}")
        message(STATUS " ${PREFIX}_LIBRARY_OPTS=${libraryopts}")
        message(STATUS " ${PREFIX}_LIBRARIES=${libs}")
      endif()
      set (${PREFIX}_INCLUDE_OPTS ${includeopts} PARENT_SCOPE)
      set (${PREFIX}_LIBRARY_OPTS ${libraryopts} PARENT_SCOPE)
      set (${PREFIX}_INCLUDE_DIRS ${includes} PARENT_SCOPE)
      set (${PREFIX}_LIBRARIES ${libs} PARENT_SCOPE)
      set (${PREFIX}_FOUND TRUE PARENT_SCOPE)
    endif()
    return()
  endif()

  # Format messages for debug info and the type of error
  set(vars "Relevant CMake configuration variables:\n")
  foreach (i ${configopts})
    mark_as_advanced(CLEAR ${i})
    set(val ${${i}})
    if ("${val}" STREQUAL "${i}-NOTFOUND")
      set (val "<not found>")
    elseif (val AND NOT EXISTS ${val})
      set (val "${val} (does not exist)")
    else()
      set(some_files TRUE)
    endif()
    set(vars "${vars} ${i}=${val}\n")
  endforeach()
  set(vars "${vars}You may use CMake GUI, cmake -D or ccmake to modify the values. Delete CMakeCache.txt to discard all values and force full re-detection if necessary.\n")
  if (version_unsuitable)
    set(msg "${PREFIX} ${${PREFIX}_VERSION} was found but")
    if (exactver)
      set(msg "${msg} only version ${findver} is acceptable.")
    else()
      set(msg "${msg} version ${findver} is the minimum requirement.")
    endif()
  else()
    if (missing_headers)
      set(msg "We could not find development headers for ${PREFIX}. Do you have the necessary dev package installed?")
    elseif (some_files)
      set(msg "We only found some files of ${PREFIX}, not all of them. Perhaps your installation is incomplete or maybe we just didn't look in the right place?")
      if(findver)
        set(msg "${msg} This could also be caused by incompatible version (if it helps, at least ${PREFIX} ${findver} should work).")
      endif()
    else()
      set(msg "We were unable to find package ${PREFIX}.")
    endif()
  endif()

  # Fatal error out if REQUIRED
  if (required)
    set(msg "REQUIRED PACKAGE NOT FOUND\n${msg} This package is REQUIRED and you need to install it or adjust CMake configuration in order to continue building ${CMAKE_PROJECT_NAME}.")
    message(FATAL_ERROR "${msg}\n${vars}")
  endif()
  # Otherwise just print a nasty warning
  if (NOT quiet)
    message(WARNING "WARNING: MISSING PACKAGE\n${msg} This package is NOT REQUIRED and you may ignore this warning but by doing so you may miss some functionality of ${CMAKE_PROJECT_NAME}. \n${vars}")
  endif()
endfunction()

+
+ +
+
+ + + + +
+ +
+ +
+
+ + +
+ +
+ +
+ + +
+
+
+ +
+
+ +
+ + + +
+ + + Something went wrong with that request. Please try again. +
+ + + + + + + + + + From 8c4e1cfdbb82ac91267e023b67996c138dca66f1 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sun, 20 Jul 2014 00:18:41 +0000 Subject: [PATCH 002/149] Starting to add Java compilation (not quite building correctly there) Fixed various compiler warnings from clang++ Abandoned hash_map in favor of boost::unordered_map git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6729 23e1bc29-d954-0410-9766-47de34158ba0 --- src/Java/PSEngine/CMakeLists.txt | 65 ++++++++++++++++++- src/PLASMA/PlanDatabase/base/ObjectType.cc | 7 +- src/PLASMA/Resource/component/FlowProfile.hh | 2 +- src/PLASMA/Resource/component/MaxFlow.hh | 4 +- .../Solvers/ResourceThreatDecisionPoint.cc | 2 +- src/PLASMA/Resource/component/Types.hh | 36 +++++----- src/PLASMA/Solvers/base/FlawManager.cc | 8 ++- src/PLASMA/Solvers/base/FlawManager.hh | 2 + src/PLASMA/Solvers/base/Solver.cc | 7 +- src/PLASMA/System/CMakeLists.txt | 11 ++-- src/PLASMA/Utils/Number.hh | 31 ++++----- src/PLASMA/Utils/base/LabelStr.hh | 13 +--- 12 files changed, 122 insertions(+), 66 deletions(-) diff --git a/src/Java/PSEngine/CMakeLists.txt b/src/Java/PSEngine/CMakeLists.txt index d6beb2480..de4fba3f6 100644 --- a/src/Java/PSEngine/CMakeLists.txt +++ b/src/Java/PSEngine/CMakeLists.txt @@ -1,5 +1,66 @@ find_package(Java REQUIRED) include(UseJava) -# add_jar(PSEngine -# SOURCES src/psengine/PSUtil.java src/psengine/util/LibraryLoader.java src/psengine/util/SimpleTimer.java \ No newline at end of file +#set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${) +#set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/generated;${CMAKE_CURRENT_SOURCE_DIR}/src;${CMAKE_JAVA_INCLUDE_PATH}) +add_jar(PSEngineGenerated + SOURCES + generated/psengine/PSConstraint.java + generated/psengine/PSConstraintEngineListener.java + generated/psengine/PSConstraintList.java + generated/psengine/PSDataType.java + generated/psengine/PSDataTypeList.java + generated/psengine/PSEngine.java + generated/psengine/PSEngineInterface.java + generated/psengine/PSEngineInterfaceJNI.java + generated/psengine/PSEntity.java + generated/psengine/PSException.java + generated/psengine/PSIntList.java + generated/psengine/PSLanguageException.java + generated/psengine/PSLanguageExceptionList.java + generated/psengine/PSObject.java + generated/psengine/PSObjectList.java + generated/psengine/PSObjectType.java + generated/psengine/PSObjectTypeList.java + generated/psengine/PSPlanDatabaseClient.java + generated/psengine/PSPlanDatabaseListener.java + generated/psengine/PSResource.java + generated/psengine/PSResourceProfile.java + generated/psengine/PSSchema.java + generated/psengine/PSSolver.java + generated/psengine/PSStringList.java + generated/psengine/PSTimePointList.java + generated/psengine/PSToken.java + generated/psengine/PSTokenList.java + generated/psengine/PSTokenState.java + generated/psengine/PSTokenType.java + generated/psengine/PSTokenTypeList.java + generated/psengine/PSValueList.java + generated/psengine/PSVarType.java + generated/psengine/PSVarValue.java + generated/psengine/PSVariable.java + generated/psengine/PSVariableList.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSConstraint.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSDataType.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSObject.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSObjectType.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSToken.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSTokenType.java + generated/psengine/SWIGTYPE_p_p_EUROPA__PSVariable.java + generated/psengine/StringErrorStream.java + generated/psengine/EngineConfig.java + # src/psengine/PSUtil.java + # src/psengine/util/LibraryLoader.java + # src/psengine/util/SimpleTimer.java + ) + +#set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}) +list(APPEND CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}/PSEngineGenerated.jar) +set(CMAKE_JAVA_TARGET_OUTPUT_NAME PSEngine.jar) +add_jar(PSEngineJar + SOURCES + src/psengine/PSUtil.java + src/psengine/util/LibraryLoader.java + src/psengine/util/SimpleTimer.java + INCLUDE_JARS + PSEngineGenerated.jar) \ No newline at end of file diff --git a/src/PLASMA/PlanDatabase/base/ObjectType.cc b/src/PLASMA/PlanDatabase/base/ObjectType.cc index 9d7362682..d283c9df1 100644 --- a/src/PLASMA/PlanDatabase/base/ObjectType.cc +++ b/src/PLASMA/PlanDatabase/base/ObjectType.cc @@ -67,9 +67,10 @@ const ObjectTypeId& ObjectType::getParent() const } const std::string& ObjectType::getParentName() const { - if (m_parent.isNoId()) - return ""; - return m_parent->getNameString(); + static std::string empty_string; + if (m_parent.isNoId()) + return empty_string; + return m_parent->getNameString(); } const std::map& ObjectType::getMembers() const diff --git a/src/PLASMA/Resource/component/FlowProfile.hh b/src/PLASMA/Resource/component/FlowProfile.hh index 1b7e7608e..1066cbd41 100644 --- a/src/PLASMA/Resource/component/FlowProfile.hh +++ b/src/PLASMA/Resource/component/FlowProfile.hh @@ -412,7 +412,7 @@ namespace EUROPA #ifdef _MSC_VER typedef std::map< TransactionId, IntIntPair > TransactionId2IntIntPair; #else - typedef hash_src::hash_map< TransactionId, IntIntPair, TransactionIdHash > TransactionId2IntIntPair; + typedef boost::unordered_map< TransactionId, IntIntPair, TransactionIdHash > TransactionId2IntIntPair; #endif //_MSC_VER TransactionId2IntIntPair m_previousTimeBounds; diff --git a/src/PLASMA/Resource/component/MaxFlow.hh b/src/PLASMA/Resource/component/MaxFlow.hh index 728785c5a..c027764f7 100644 --- a/src/PLASMA/Resource/component/MaxFlow.hh +++ b/src/PLASMA/Resource/component/MaxFlow.hh @@ -15,6 +15,8 @@ #include "NodeIterator.hh" #include "EdgeIterator.hh" +#include + #ifndef LONG_MAX // Would prefer to declare a static const variable, but that would be // bad style inside a header, so there's another 'ifndef LONG_MAX' @@ -103,7 +105,7 @@ namespace EUROPA #ifdef _MSC_VER typedef map< Node*, EdgeList::const_iterator > Node2EdgeListIteratorMap; #else - typedef hash_src::hash_map< Node*, EdgeList::const_iterator, NodeHash > Node2EdgeListIteratorMap; + typedef boost::unordered_map< Node*, EdgeList::const_iterator, NodeHash > Node2EdgeListIteratorMap; #endif //_MSC_VER Node2EdgeListIteratorMap m_CurrentOutEdgeOnNode; diff --git a/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc b/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc index 35e765265..608a1c9db 100644 --- a/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc +++ b/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc @@ -176,7 +176,7 @@ namespace EUROPA { } virtual std::string toString() const { check_error(ALWAYS_FAIL, "This used to be a pure virtual method."); - return false; + return ""; } virtual ChoiceComparator* copy() const = 0; private: diff --git a/src/PLASMA/Resource/component/Types.hh b/src/PLASMA/Resource/component/Types.hh index bf353a4be..197a45b2d 100644 --- a/src/PLASMA/Resource/component/Types.hh +++ b/src/PLASMA/Resource/component/Types.hh @@ -9,14 +9,15 @@ * @ingroup Resource */ -#ifdef _MSC_VER -# include -using std::map; -namespace hash_src = stdext; -#else -# include "hash_map.hh" -namespace hash_src = __gnu_cxx; -#endif //_MSC_VER +// #ifdef _MSC_VER +// # include +// using std::map; +// namespace hash_src = stdext; +// #elif __clang__ +// # include "hash_map.hh" +// namespace hash_src = __gnu_cxx; +// #endif //_MSC_VER +#include #include #include @@ -70,7 +71,7 @@ namespace EUROPA public: size_t operator()(Node* n) const { - hash_src::hash H; + boost::hash H; return H( (long) n); } }; @@ -84,7 +85,7 @@ namespace EUROPA public: size_t operator()(Edge* n) const { - hash_src::hash H; + boost::hash H; return H( (long) n ); } @@ -99,12 +100,13 @@ namespace EUROPA public: size_t operator()(TransactionId n) const { - hash_src::hash H; + boost::hash H; return H( (long) ( (Transaction*) n ) ); } }; +//TODO: Do we need to keep this _MSC_VER branch? #ifdef _MSC_VER typedef map< Node*, bool > Node2Bool; typedef map< Node*, eint > Node2Int; @@ -114,13 +116,13 @@ namespace EUROPA typedef map< Edge*, edouble > Edge2DoubleMap; typedef map< TransactionId, InstantId > TransactionId2InstantId; #else -typedef hash_src::hash_map< Node*, bool, NodeHash > Node2Bool; -typedef hash_src::hash_map< Node*, eint, NodeHash > Node2Int; -typedef hash_src::hash_map< Node*, eint, NodeHash > Node2Long; -typedef hash_src::hash_map< Node*, edouble, NodeHash > Node2Double; +typedef boost::unordered_map< Node*, bool, NodeHash > Node2Bool; +typedef boost::unordered_map< Node*, eint, NodeHash > Node2Int; +typedef boost::unordered_map< Node*, eint, NodeHash > Node2Long; +typedef boost::unordered_map< Node*, edouble, NodeHash > Node2Double; -typedef hash_src::hash_map< Edge*, edouble, EdgeHash > Edge2DoubleMap; -typedef hash_src::hash_map< TransactionId, InstantId, TransactionIdHash > TransactionId2InstantId; +typedef boost::unordered_map< Edge*, edouble, EdgeHash > Edge2DoubleMap; +typedef boost::unordered_map< TransactionId, InstantId, TransactionIdHash > TransactionId2InstantId; #endif std::ostream& operator<<( std::ostream& os, const EdgeIdentity& fei ) ; diff --git a/src/PLASMA/Solvers/base/FlawManager.cc b/src/PLASMA/Solvers/base/FlawManager.cc index f64d5b778..618943ebc 100644 --- a/src/PLASMA/Solvers/base/FlawManager.cc +++ b/src/PLASMA/Solvers/base/FlawManager.cc @@ -12,11 +12,15 @@ * @date April, 2005 * @brief Provides implementation for FlawManager */ +#if 0 #ifdef _MSC_VER - using stdext::hash_map; +using stdext::hash_map; +#elif defined(__clang__) +typedef HASH_NS::unordered_map hash_map; #else - using __gnu_cxx::hash_map; +using HASH_NS::hash_map; #endif //_MSC_VER +#endif //0 namespace EUROPA { namespace SOLVERS { diff --git a/src/PLASMA/Solvers/base/FlawManager.hh b/src/PLASMA/Solvers/base/FlawManager.hh index d8b968bd5..7a9feb377 100644 --- a/src/PLASMA/Solvers/base/FlawManager.hh +++ b/src/PLASMA/Solvers/base/FlawManager.hh @@ -16,11 +16,13 @@ #include "FlawHandler.hh" #include "hash_map.hh" +#if 0 #ifdef _MSC_VER using namespace stdext; #else using namespace __gnu_cxx; #endif //_MSC_VER +#endif //0 namespace EUROPA { namespace SOLVERS { diff --git a/src/PLASMA/Solvers/base/Solver.cc b/src/PLASMA/Solvers/base/Solver.cc index 4bfc26125..c1812bb92 100644 --- a/src/PLASMA/Solvers/base/Solver.cc +++ b/src/PLASMA/Solvers/base/Solver.cc @@ -290,8 +290,11 @@ namespace EUROPA { return; } - if(m_maxSteps <= getStepCount() - m_stepCountFloor || m_maxDepth < getDepth() - m_depthFloor){ - debugMsg("Solver:step", "Timeout! Max steps: " << m_maxSteps << " step (above floor) " << getStepCount() - m_stepCountFloor << + if(m_maxSteps <= getStepCount() - m_stepCountFloor || + m_maxDepth < getDepth() - m_depthFloor){ + debugMsg("Solver:step", + "Timeout! Max steps: " << m_maxSteps << " step (above floor) " << + getStepCount() - m_stepCountFloor << " Max depth: " << m_maxDepth << " depth (above floor) " << getDepth() - m_depthFloor); publish(notifyTimedOut,); diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 7a85d0b0e..4bfa92992 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -8,29 +8,26 @@ endif(${APPLE}) include(EuropaModule) set(internal_dependencies NDDL ANML Solvers Resource RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +#TODO: let the user configure which language or languages to build for find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(CMAKE_SWIG_FLAGS "") -#set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine") -set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_SOURCE_DIR}/base") +set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine") set_source_files_properties(base/PSEngine.i PROPERTIES CPLUSPLUS ON) -set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-includeall") -#TEMPORARY +set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") -#set(JNI_HOME /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) include_directories(${JNI_INCLUDE_DIRS}) swig_add_module(PSEngine java base/PSEngine.i) foreach(dep ${internal_dependencies}) add_common_module_include_dep(PSEngine ${dep}) target_link_libraries(PSEngine "${dep}${EUROPA_SUFFIX}") endforeach(dep) +add_common_module_include_dep(PSEngine System) target_link_libraries(PSEngine "System${EUROPA_SUFFIX}") -#swig_link_libraries(PSEngine) set(root_sources "") get_filename_component(swig_generated_source ${swig_generated_file_fullname} NAME) -#set(base_sources EuropaEngine.cc PSEngineImpl.cc ${swig_generated_source}) set(base_sources EuropaEngine.cc PSEngineImpl.cc) set(component_sources "") set(test_sources module-tests.cc) diff --git a/src/PLASMA/Utils/Number.hh b/src/PLASMA/Utils/Number.hh index b1e78cc99..41cc7b877 100644 --- a/src/PLASMA/Utils/Number.hh +++ b/src/PLASMA/Utils/Number.hh @@ -5,10 +5,10 @@ #include #include #include -#include #include +#include #include -#include "hash_map.hh" +#include #ifdef _MSC_VER # if ( LONG_MAX > INT_MAX) @@ -52,18 +52,16 @@ namespace EUROPA { class edouble; } -#ifndef _MSC_VER -namespace __gnu_cxx -{ - template<> struct hash { - inline size_t operator()(EUROPA::edouble __x) const; - }; +namespace boost { - template<> struct hash { - inline size_t operator()(EUROPA::eint __x) const; - }; +template<> struct hash { + inline size_t operator()(EUROPA::edouble __x) const; +}; + +template<> struct hash { + inline size_t operator()(EUROPA::eint __x) const; +}; } -#endif // _MSC_VER namespace std { template<> @@ -536,10 +534,10 @@ namespace EUROPA { friend class edouble; + friend struct boost::hash; #ifdef _MSC_VER friend struct std::numeric_limits; #else - friend class __gnu_cxx::hash; friend class std::numeric_limits; #endif //_MSC_VER @@ -641,10 +639,10 @@ namespace EUROPA { friend edouble::basis_type cast_basis(const edouble e); private: friend class eint; + friend struct boost::hash; #ifdef _MSC_VER friend struct std::numeric_limits; #else - friend class __gnu_cxx::hash; friend class std::numeric_limits; #endif //_MSC_VER @@ -803,15 +801,12 @@ namespace std { } -#ifndef _MSC_VER -namespace __gnu_cxx -{ +namespace boost { //I'm not entirely sure this is safe, but it's worked so far. Maybe this should be changed to //*((size_t*)&(__x.m_v)) size_t hash::operator()(EUROPA::edouble __x) const {return (size_t) (__x.m_v);} size_t hash::operator()(EUROPA::eint __x) const {return (size_t) (long) (__x.m_v);} } -#endif //_MSC_VER // #define min MIN_COPY // #define max MAX_COPY diff --git a/src/PLASMA/Utils/base/LabelStr.hh b/src/PLASMA/Utils/base/LabelStr.hh index 870c141bd..fb77989c5 100644 --- a/src/PLASMA/Utils/base/LabelStr.hh +++ b/src/PLASMA/Utils/base/LabelStr.hh @@ -12,19 +12,8 @@ #include "Error.hh" #include #include -#include "hash_map.hh" +#include -#ifndef _MSC_VER -namespace __gnu_cxx { - template<> struct hash { - size_t operator()(double __x) const {return (size_t) (__x);} - }; - - template<> struct hash { - size_t operator()(const std::string& __x) const {return hash()(__x.c_str());} - }; -} -#endif //_MSC_VER namespace EUROPA { From 01d3adf6c826c5b69299d25ce4fb726256cd2070 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 22 Jul 2014 16:24:11 +0000 Subject: [PATCH 003/149] -Added partial specialization of PSList template for pointer types to make SWIG generate the right thing -Added installation to cmake build git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6730 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 2 ++ src/PLASMA/System/base/PSEngine.i | 11 +++++++++++ src/PLASMA/Utils/base/PSUtils.hh | 23 +++++++++++++++++++++++ src/PLASMA/cmake/EuropaModule.cmake | 4 ++++ 4 files changed, 40 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 25ad07517..3af41225a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,4 +8,6 @@ enable_testing() set(CMAKE_POSITION_INDEPENDENT_CODE TRUE) option(SHARED "Build shared libraries" TRUE) set(BUILD_SHARED_LIBS ${SHARED}) +set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) + add_subdirectory(src) \ No newline at end of file diff --git a/src/PLASMA/System/base/PSEngine.i b/src/PLASMA/System/base/PSEngine.i index 1e052a7ed..d8a1cb3f5 100644 --- a/src/PLASMA/System/base/PSEngine.i +++ b/src/PLASMA/System/base/PSEngine.i @@ -194,6 +194,17 @@ namespace EUROPA { void clear(); }; + template + class PSList { + public: + PSList(); + int size() const; + T* get(int idx); + void push_back(T* const value); + void remove(T* const value); + void clear(); + }; + %template(PSObjectList) PSList; %template(PSTokenList) PSList; %template(PSVariableList) PSList; diff --git a/src/PLASMA/Utils/base/PSUtils.hh b/src/PLASMA/Utils/base/PSUtils.hh index 11d6f0989..bd01b1d78 100644 --- a/src/PLASMA/Utils/base/PSUtils.hh +++ b/src/PLASMA/Utils/base/PSUtils.hh @@ -32,6 +32,29 @@ namespace EUROPA { std::vector m_elements; }; +template +class PSList { + public: + int size() const { return m_elements.size(); } + T* get(int idx) { return m_elements[idx]; } + const T* get(int idx) const { return m_elements[idx]; } + void remove(int idx) {m_elements.erase(std::advance(m_elements.begin(), idx));} + void remove(T* const value) + { + typename std::vector::iterator it = + std::find(m_elements.begin(), m_elements.end(), value); + if(it != m_elements.end()) + m_elements.erase(it); + } + void push_back(T* const value) {m_elements.push_back(value);} + void clear() {m_elements.clear();} + bool operator==(const PSList& other) const { + return m_elements == other.m_elements; + } + protected: + std::vector m_elements; +}; + typedef int PSEntityKey; class PSEntity diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake index 427ca868e..7f56ed957 100644 --- a/src/PLASMA/cmake/EuropaModule.cmake +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -249,4 +249,8 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de COMMAND ${testname}) endif() + #install EXPORT? + install(TARGETS ${libname} DESTINATION ${EUROPA_ROOT}/dist/europa) + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${EUROPA_ROOT}/dist/europa + FILES_MATCHING PATTERN "*.hh") endmacro(declare_module) From 69e242eb2b45e81c30edbd8eed346a087e10a903 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 24 Jul 2014 17:12:02 +0000 Subject: [PATCH 004/149] Adding "export" to installation so cmake projects can just include a file Something isn't working with adding include directories, however git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6731 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 7 +++++-- src/PLASMA/cmake/EuropaModule.cmake | 7 ++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3af41225a..a12383e55 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,13 +1,16 @@ + cmake_minimum_required(VERSION 2.6) if(COMMAND cmake_policy) cmake_policy(SET CMP0003 NEW) cmake_policy(SET CMP0042 OLD) #TODO: figure out what this means endif(COMMAND cmake_policy) +project(Europa2 CXX Java) add_definitions(-DTIXML_USE_STL=1) enable_testing() set(CMAKE_POSITION_INDEPENDENT_CODE TRUE) option(SHARED "Build shared libraries" TRUE) set(BUILD_SHARED_LIBS ${SHARED}) set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) - -add_subdirectory(src) \ No newline at end of file +set(CppUnit_FIND_QUIETLY TRUE) +add_subdirectory(src) +install(EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa) \ No newline at end of file diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake index 7f56ed957..0683247b7 100644 --- a/src/PLASMA/cmake/EuropaModule.cmake +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -250,7 +250,12 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de endif() #install EXPORT? - install(TARGETS ${libname} DESTINATION ${EUROPA_ROOT}/dist/europa) + install( + TARGETS ${libname} + EXPORT Europa2 + DESTINATION ${EUROPA_ROOT}/dist/europa + #INCLUDES DESTINATION ${EUROPA_ROOT}/dist/europa/${name} + ) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${EUROPA_ROOT}/dist/europa FILES_MATCHING PATTERN "*.hh") endmacro(declare_module) From 2b6300fbc63342879315f355db3c601603b50b07 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 25 Jul 2014 00:00:30 +0000 Subject: [PATCH 005/149] Adding a CMake module for finding ANTLR git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6732 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/cmake/FindANTLR.cmake | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/PLASMA/cmake/FindANTLR.cmake diff --git a/src/PLASMA/cmake/FindANTLR.cmake b/src/PLASMA/cmake/FindANTLR.cmake new file mode 100644 index 000000000..cfd6ce6cd --- /dev/null +++ b/src/PLASMA/cmake/FindANTLR.cmake @@ -0,0 +1,32 @@ +if (ANTLR_INCLUDE_DIR AND ANTLR_LIBRARIES) + # in cache already + set(ANTLR_FOUND TRUE) +else (ANTLR_INCLUDE_DIR AND ANTLR_LIBRARIES) + message(STATUS "Searching for ANTLR") + find_path(ANTLR_INCLUDE_DIR antlr3.h) + find_library(ANTLR_LIBRARIES NAMES antlr3 antlr3c libantlr3 libantlr3c) + find_file(ANTLR_JAR antlr.jar PATHS ${EUROPA_ROOT}/ext/lib) + + if (ANTLR_INCLUDE_DIR AND ANTLR_LIBRARIES AND ANTLR_JAR) + set(ANTLR_FOUND TRUE) + # TODO version check is missing + endif (ANTLR_INCLUDE_DIR AND ANTLR_LIBRARIES AND ANTLR_JAR) + if (ANTLR_FOUND) + if (NOT ANTLR_FIND_QUIETLY) + message(STATUS "Found Antlr3 C runtime: ${ANTLR_LIBRARIES}") + endif (NOT ANTLR_FIND_QUIETLY) + else (ANTLR_FOUND) + if (ANTLR_FIND_REQUIRED) + if (NOT ANTLR_INCLUDE_DIR) + message(FATAL_ERROR "Could NOT find Antlr3 header files") + endif (NOT ANTLR_INCLUDE_DIR) + if (NOT ANTLR_LIBRARIES) + message(FATAL_ERROR "Could NOT find Antlr3 C runtime library") + endif (NOT ANTLR_LIBRARIES) + if (NOT ANTLR_JAR) + message(FATAL_ERROR "Could NOT find Antlr3 jar file") + endif (NOT ANTLR_JAR) + endif (ANTLR_FIND_REQUIRED) + endif (ANTLR_FOUND) + mark_as_advanced(ANTLR_INCLUDE_DIR ANTLR_LIBRARIES) +endif (ANTLR_INCLUDE_DIR AND ANTLR_LIBRARIES) \ No newline at end of file From 76ced004467170b842250c1bb29664cfe5652bd5 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 25 Jul 2014 00:07:01 +0000 Subject: [PATCH 006/149] -Bumped up CMake required version -Added references to ANTLR through FindANTLR -Removed a reference to hash_map (which should be going away soon) git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6733 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 16 ++++++++++------ src/Java/PSEngine/CMakeLists.txt | 21 +++++++++++++-------- src/PLASMA/ANML/CMakeLists.txt | 7 +++++-- src/PLASMA/NDDL/CMakeLists.txt | 16 +++++++++++----- src/PLASMA/Solvers/base/FlawManager.hh | 1 - src/PLASMA/System/CMakeLists.txt | 3 +++ src/PLASMA/Utils/CMakeLists.txt | 4 +++- 7 files changed, 45 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a12383e55..10b77cffc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,9 +1,13 @@ +message(STATUS "${CMAKE_ROOT}") +cmake_minimum_required(VERSION 2.8.8) +if((CMAKE_MAJOR_VERSION GREATER 3) OR (CMAKE_MAJOR_VERSION EQUAL 3)) + if(COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) + cmake_policy(SET CMP0042 OLD) #TODO: figure out what this means + endif(COMMAND cmake_policy) +endif((CMAKE_MAJOR_VERSION GREATER 3) OR (CMAKE_MAJOR_VERSION EQUAL 3)) -cmake_minimum_required(VERSION 2.6) -if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) -cmake_policy(SET CMP0042 OLD) #TODO: figure out what this means -endif(COMMAND cmake_policy) +set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH};${CMAKE_CURRENT_SOURCE_DIR}/cmake") project(Europa2 CXX Java) add_definitions(-DTIXML_USE_STL=1) enable_testing() @@ -13,4 +17,4 @@ set(BUILD_SHARED_LIBS ${SHARED}) set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) set(CppUnit_FIND_QUIETLY TRUE) add_subdirectory(src) -install(EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa) \ No newline at end of file +install(EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa) diff --git a/src/Java/PSEngine/CMakeLists.txt b/src/Java/PSEngine/CMakeLists.txt index de4fba3f6..d5655156a 100644 --- a/src/Java/PSEngine/CMakeLists.txt +++ b/src/Java/PSEngine/CMakeLists.txt @@ -1,5 +1,10 @@ find_package(Java REQUIRED) -include(UseJava) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +else() + message(STATUS "Found UseJava: ${java_included}") +endif(NOT java_included) #set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${) #set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/generated;${CMAKE_CURRENT_SOURCE_DIR}/src;${CMAKE_JAVA_INCLUDE_PATH}) @@ -40,13 +45,13 @@ add_jar(PSEngineGenerated generated/psengine/PSVarValue.java generated/psengine/PSVariable.java generated/psengine/PSVariableList.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSConstraint.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSDataType.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSObject.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSObjectType.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSToken.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSTokenType.java - generated/psengine/SWIGTYPE_p_p_EUROPA__PSVariable.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSConstraint.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSDataType.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSObject.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSObjectType.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSToken.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSTokenType.java + # generated/psengine/SWIGTYPE_p_p_EUROPA__PSVariable.java generated/psengine/StringErrorStream.java generated/psengine/EngineConfig.java # src/psengine/PSUtil.java diff --git a/src/PLASMA/ANML/CMakeLists.txt b/src/PLASMA/ANML/CMakeLists.txt index 666bad9ff..c14c064f6 100644 --- a/src/PLASMA/ANML/CMakeLists.txt +++ b/src/PLASMA/ANML/CMakeLists.txt @@ -1,4 +1,6 @@ include(EuropaModule) +set(ANTLR_FIND_REQUIRED TRUE) +include(FindANTLR) set(anml_parser_sources ANML.tokens ANMLLexer.cpp ANMLLexer.h ANMLParser.cpp ANMLParser.h) @@ -20,8 +22,9 @@ common_module_prepends("${base_sources}" "${component_sources}" "${test_sources} declare_module(ANML "${root_sources}" "${base_sources}" "${component_sources}" "${test_sources}" "${internal_dependencies}" "") #setup ANTLR link/headers? -target_link_libraries("ANML${EUROPA_SUFFIX}" antlr3c) -target_link_libraries("ANML-test${EUROPA_SUFFIX}" antlr3c) +append_target_property("ANML${EUROPA_SUFFIX}" INCLUDE_DIRECTORIES ";${ANTLR_INCLUDE_DIR}") +target_link_libraries("ANML${EUROPA_SUFFIX}" ${ANTLR_LIBRARIES}) +target_link_libraries("ANML-test${EUROPA_SUFFIX}" ${ANTLR_LIBRARIES}) #file(COPY test/ErrorCheckingTests.txt DESTINATION .) #file(COPY test/anml DESTINATION .) #file(COPY test/parser DESTINATION .) diff --git a/src/PLASMA/NDDL/CMakeLists.txt b/src/PLASMA/NDDL/CMakeLists.txt index b9af9f3dd..8ca2a6b3b 100644 --- a/src/PLASMA/NDDL/CMakeLists.txt +++ b/src/PLASMA/NDDL/CMakeLists.txt @@ -1,16 +1,21 @@ include(EuropaModule) +set(ANTLR_FIND_REQUIRED TRUE) +include(FindANTLR) +if(NOT ANTLR_FOUND) + message(ERROR "ANTLR not found!") +endif(NOT ANTLR_FOUND) set(nddl_parser_sources NDDL3.tokens NDDL3Lexer.cpp NDDL3Lexer.h NDDL3Parser.cpp NDDL3Parser.h) set(nddl_tree_sources NDDL3Tree.cpp NDDL3Tree.h NDDL3Tree.tokens) #TEMPORARY -set(ANTLR3_JAR /opt/local/share/java/antlr.jar) +#set(ANTLR3_JAR /opt/local/share/java/antlr.jar) add_custom_command(OUTPUT ${nddl_parser_sources} - COMMAND ${JAVA} -cp ${ANTLR3_JAR} ${JREFLAGS} org.antlr.Tool -fo ${CMAKE_CURRENT_SOURCE_DIR}/base antlr/NDDL3.g + COMMAND ${JAVA} -cp ${ANTLR_JAR} ${JREFLAGS} org.antlr.Tool -fo ${CMAKE_CURRENT_SOURCE_DIR}/base antlr/NDDL3.g DEPENDS antlr/NDDL3.g) add_custom_command(OUTPUT ${nddl_tree_sources} - COMMAND ${JAVA} -cp ${ANTLR3_JAR} ${JREFLAGS} org.antlr.Tool -fo ${CMAKE_CURRENT_SOURCE_DIR}/base antlr/NDDL3Tree.g + COMMAND ${JAVA} -cp ${ANTLR_JAR} ${JREFLAGS} org.antlr.Tool -fo ${CMAKE_CURRENT_SOURCE_DIR}/base antlr/NDDL3Tree.g DEPENDS antlr/NDDL3Tree.g) @@ -24,8 +29,9 @@ common_module_prepends("${base_sources}" "${component_sources}" "${test_sources} declare_module(NDDL "${root_sources}" "${base_sources}" "${component_sources}" "${test_sources}" "${internal_dependencies}" "") #setup ANTLR link/headers? -target_link_libraries("NDDL${EUROPA_SUFFIX}" antlr3c) -target_link_libraries("NDDL-test${EUROPA_SUFFIX}" antlr3c) +append_target_property("NDDL${EUROPA_SUFFIX}" INCLUDE_DIRECTORIES ";${ANTLR_INCLUDE_DIR}") +target_link_libraries("NDDL${EUROPA_SUFFIX}" ${ANTLR_LIBRARIES}) +target_link_libraries("NDDL-test${EUROPA_SUFFIX}" ${ANTLR_LIBRARIES}) file(COPY test/ErrorCheckingTests.txt DESTINATION .) file(COPY test/nddl DESTINATION .) file(COPY test/parser DESTINATION .) diff --git a/src/PLASMA/Solvers/base/FlawManager.hh b/src/PLASMA/Solvers/base/FlawManager.hh index 7a9feb377..604f97476 100644 --- a/src/PLASMA/Solvers/base/FlawManager.hh +++ b/src/PLASMA/Solvers/base/FlawManager.hh @@ -14,7 +14,6 @@ #include "DomainListener.hh" #include "MatchingEngine.hh" #include "FlawHandler.hh" -#include "hash_map.hh" #if 0 #ifdef _MSC_VER diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 4bfa92992..df7015fb8 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -3,6 +3,8 @@ if(${APPLE}) else(${APPLE}) find_package(JNI REQUIRED) endif(${APPLE}) +set(ANTLR_FIND_REQUIRED TRUE) +include(FindANTLR) include(EuropaModule) @@ -17,6 +19,7 @@ set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine" set_source_files_properties(base/PSEngine.i PROPERTIES CPLUSPLUS ON) set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) swig_add_module(PSEngine java base/PSEngine.i) foreach(dep ${internal_dependencies}) diff --git a/src/PLASMA/Utils/CMakeLists.txt b/src/PLASMA/Utils/CMakeLists.txt index ebbe39262..5cdff3330 100644 --- a/src/PLASMA/Utils/CMakeLists.txt +++ b/src/PLASMA/Utils/CMakeLists.txt @@ -13,4 +13,6 @@ declare_module(Utils "${root_sources}" "${base_sources}" "${component_sources}" file(GLOB test_inputs test/*.xml test/*.dtd test/*.cfg) file(COPY ${test_inputs} DESTINATION .) -#how do I handle the dlopen and pthreads link requirements? do I need to? \ No newline at end of file +#how do I handle the dlopen and pthreads link requirements? do I need to? +find_library(libdl_library dl libdl ltdl libltdl) +target_link_libraries("Utils${EUROPA_SUFFIX}" ${libdl_library}) \ No newline at end of file From 4bfd76bd3465985926aa1f283bc92d337cd8c84a Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 25 Jul 2014 15:34:40 +0000 Subject: [PATCH 007/149] Added optimized compilation Added transitive module dependencies (mostly) git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6734 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 9 +++- src/PLASMA/ANML/CMakeLists.txt | 2 +- src/PLASMA/ConstraintEngine/CMakeLists.txt | 3 +- src/PLASMA/NDDL/CMakeLists.txt | 2 +- src/PLASMA/PlanDatabase/CMakeLists.txt | 4 +- src/PLASMA/Resource/CMakeLists.txt | 2 +- src/PLASMA/RulesEngine/CMakeLists.txt | 3 +- src/PLASMA/Solvers/CMakeLists.txt | 3 +- src/PLASMA/System/CMakeLists.txt | 62 ++++++++++++++++++---- src/PLASMA/TemporalNetwork/CMakeLists.txt | 2 +- src/PLASMA/Utils/CMakeLists.txt | 3 +- src/PLASMA/cmake/EuropaModule.cmake | 16 +++++- 12 files changed, 88 insertions(+), 23 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10b77cffc..5f0503f37 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,3 @@ -message(STATUS "${CMAKE_ROOT}") cmake_minimum_required(VERSION 2.8.8) if((CMAKE_MAJOR_VERSION GREATER 3) OR (CMAKE_MAJOR_VERSION EQUAL 3)) if(COMMAND cmake_policy) @@ -12,8 +11,16 @@ project(Europa2 CXX Java) add_definitions(-DTIXML_USE_STL=1) enable_testing() set(CMAKE_POSITION_INDEPENDENT_CODE TRUE) +#Options to support: +# * optimized/not +option(OPTIMIZE "Build optimized" FALSE) + +# * shared/not option(SHARED "Build shared libraries" TRUE) set(BUILD_SHARED_LIBS ${SHARED}) +# * 64/32-bit +# * modules? + set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) set(CppUnit_FIND_QUIETLY TRUE) add_subdirectory(src) diff --git a/src/PLASMA/ANML/CMakeLists.txt b/src/PLASMA/ANML/CMakeLists.txt index c14c064f6..f0f6fc8e6 100644 --- a/src/PLASMA/ANML/CMakeLists.txt +++ b/src/PLASMA/ANML/CMakeLists.txt @@ -12,7 +12,7 @@ add_custom_command(OUTPUT ${anml_parser_sources} DEPENDS antlr/ANML.g) #TODO: abstract the stuff it depends on in NDDL so languages aren't inter-dependent -set(internal_dependencies NDDL RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies NDDL RulesEngine TemporalNetwork PlanDatabase) set(root_sources ModuleAnml.cc) set(base_sources ${anml_parser_sources} ANMLTranslator.cc) set(component_sources AnmlInterpreter.cc AnmlTestEngine.cc) diff --git a/src/PLASMA/ConstraintEngine/CMakeLists.txt b/src/PLASMA/ConstraintEngine/CMakeLists.txt index 65821d7c3..3bcd91eb8 100644 --- a/src/PLASMA/ConstraintEngine/CMakeLists.txt +++ b/src/PLASMA/ConstraintEngine/CMakeLists.txt @@ -1,5 +1,6 @@ include(EuropaModule) -set(internal_dependencies Utils TinyXml) +#set(internal_dependencies Utils TinyXml) +set(internal_dependencies Utils) set(root_sources ModuleConstraintEngine.cc) set(base_sources CESchema.cc DataType.cc CFunction.cc Domain.cc ConstrainedVariable.cc DomainListener.cc Constraint.cc PSConstraintEngineListener.cc ConstraintEngine.cc PSVarValue.cc ConstraintEngineListener.cc Propagator.cc ConstraintType.cc VariableChangeListener.cc) set(component_sources Constraints.cc EquivalenceClassCollection.cc DataTypes.cc Propagators.cc Domains.cc) diff --git a/src/PLASMA/NDDL/CMakeLists.txt b/src/PLASMA/NDDL/CMakeLists.txt index 8ca2a6b3b..010fd45c2 100644 --- a/src/PLASMA/NDDL/CMakeLists.txt +++ b/src/PLASMA/NDDL/CMakeLists.txt @@ -19,7 +19,7 @@ add_custom_command(OUTPUT ${nddl_tree_sources} DEPENDS antlr/NDDL3Tree.g) -set(internal_dependencies RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies RulesEngine PlanDatabase TemporalNetwork) set(root_sources ModuleNddl.cc) set(base_sources ${nddl_parser_sources} ${nddl_tree_sources} NddlRules.cc NddlToken.cc NddlUtils.cc) set(component_sources Interpreter.cc NddlInterpreter.cc NddlTestEngine.cc) diff --git a/src/PLASMA/PlanDatabase/CMakeLists.txt b/src/PLASMA/PlanDatabase/CMakeLists.txt index b0d8c3cc4..1a22f5864 100644 --- a/src/PLASMA/PlanDatabase/CMakeLists.txt +++ b/src/PLASMA/PlanDatabase/CMakeLists.txt @@ -1,6 +1,6 @@ include(EuropaModule) -#no way to make these transitive yet -set(internal_dependencies ConstraintEngine Utils TinyXml) +#set(internal_dependencies ConstraintEngine Utils TinyXml) +set(internal_dependencies ConstraintEngine) set(root_sources ModulePlanDatabase.cc) set(base_sources CommonAncestorConstraint.cc DbClient.cc DefaultTemporalAdvisor.cc HasAncestorConstraint.cc MergeMemento.cc Method.cc Object.cc ObjectTokenRelation.cc ObjectType.cc PDBInterpreter.cc PSPlanDatabaseListener.cc PlanDatabase.cc PlanDatabaseListener.cc PlanDatabaseWriter.cc Schema.cc StackMemento.cc Token.cc TokenFactory.cc TokenType.cc TokenTypeMgr.cc UnifyMemento.cc) set(component_sources DbClientTransactionLog.cc DbClientTransactionPlayer.cc EventToken.cc IntervalToken.cc Methods.cc Timeline.cc) diff --git a/src/PLASMA/Resource/CMakeLists.txt b/src/PLASMA/Resource/CMakeLists.txt index a468309ff..278d7ea8c 100644 --- a/src/PLASMA/Resource/CMakeLists.txt +++ b/src/PLASMA/Resource/CMakeLists.txt @@ -1,5 +1,5 @@ include(EuropaModule) -set(internal_dependencies NDDL RulesEngine Solvers TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies NDDL Solvers TemporalNetwork PlanDatabase) set(internal_components Solvers NDDL) set(root_sources ModuleResource.cc) set(base_sources FVDetector.cc Instant.cc PSResource.cc Profile.cc ProfilePropagator.cc Resource.cc ResourceTokenRelation.cc Transaction.cc) diff --git a/src/PLASMA/RulesEngine/CMakeLists.txt b/src/PLASMA/RulesEngine/CMakeLists.txt index 878f54752..55614af7c 100644 --- a/src/PLASMA/RulesEngine/CMakeLists.txt +++ b/src/PLASMA/RulesEngine/CMakeLists.txt @@ -1,5 +1,6 @@ include(EuropaModule) -set(internal_dependencies PlanDatabase ConstraintEngine Utils TinyXml) +#set(internal_dependencies PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies PlanDatabase) set(root_sources ModuleRulesEngine.cc) set(base_sources ProxyVariableRelation.cc Rule.cc RuleInstance.cc RuleVariableListener.cc RulesEngine.cc RulesEngineListener.cc) set(component_sources "") diff --git a/src/PLASMA/Solvers/CMakeLists.txt b/src/PLASMA/Solvers/CMakeLists.txt index 4a8945792..6cce6c544 100644 --- a/src/PLASMA/Solvers/CMakeLists.txt +++ b/src/PLASMA/Solvers/CMakeLists.txt @@ -1,5 +1,6 @@ include(EuropaModule) -set(internal_dependencies NDDL RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +#set(internal_dependencies NDDL RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies NDDL RulesEngine TemporalNetwork PlanDatabase) set(root_sources ModuleSolvers.cc) set(base_sources ComponentFactory.cc Context.cc FlawFilter.cc FlawHandler.cc FlawManager.cc MatchingEngine.cc MatchingRule.cc Solver.cc SolverDecisionPoint.cc SolverUtils.cc) set(component_sources Filters.cc HSTSDecisionPoints.cc OpenConditionDecisionPoint.cc OpenConditionManager.cc PSSolversImpl.cc ThreatDecisionPoint.cc ThreatManager.cc UnboundVariableDecisionPoint.cc UnboundVariableManager.cc ValueSource.cc) diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index df7015fb8..beeaa38dd 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -8,8 +8,20 @@ include(FindANTLR) include(EuropaModule) +#Currently, this has to be the whole set of dependencies because of the loop later. +#I'm not sure why it is that System_FULL_DEPENDENCIES isn't visible in this scope set(internal_dependencies NDDL ANML Solvers Resource RulesEngine TemporalNetwork PlanDatabase ConstraintEngine Utils TinyXml) +set(root_sources "") +set(base_sources EuropaEngine.cc PSEngineImpl.cc) +set(component_sources "") +set(test_sources module-tests.cc) + +common_module_prepends("${base_sources}" "${component_sources}" "${test_sources}" base_sources component_sources test_sources) + +declare_module(System "${root_sources}" "${base_sources}" "${component_sources}" "${test_sources}" "${internal_dependencies}" "") + + #TODO: let the user configure which language or languages to build for find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) @@ -18,10 +30,50 @@ set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine" set_source_files_properties(base/PSEngine.i PROPERTIES CPLUSPLUS ON) set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +set_source_files_properties( + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraint.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintEngineListener.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSDataType.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSDataTypeList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngine.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngineInterface.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngineInterfaceJNI.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEntity.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSException.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSIntList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSLanguageException.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSLanguageExceptionList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObject.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectType.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectTypeList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSPlanDatabaseClient.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSPlanDatabaseListener.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSResource.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSResourceProfile.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSSchema.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSSolver.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSStringList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTimePointList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSToken.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenState.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenType.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenTypeList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSValueList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVarType.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVarValue.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVariable.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVariableList.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/StringErrorStream.java + ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/EngineConfig.java + PROPERTIES GENERATED TRUE) include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) swig_add_module(PSEngine java base/PSEngine.i) +message(STATUS "!! ${System_FULL_DEPENDENCIES}") foreach(dep ${internal_dependencies}) add_common_module_include_dep(PSEngine ${dep}) target_link_libraries(PSEngine "${dep}${EUROPA_SUFFIX}") @@ -29,15 +81,5 @@ endforeach(dep) add_common_module_include_dep(PSEngine System) target_link_libraries(PSEngine "System${EUROPA_SUFFIX}") -set(root_sources "") -get_filename_component(swig_generated_source ${swig_generated_file_fullname} NAME) -set(base_sources EuropaEngine.cc PSEngineImpl.cc) -set(component_sources "") -set(test_sources module-tests.cc) - -common_module_prepends("${base_sources}" "${component_sources}" "${test_sources}" base_sources component_sources test_sources) - -declare_module(System "${root_sources}" "${base_sources}" "${component_sources}" "${test_sources}" "${internal_dependencies}" "") - add_subdirectory(test) \ No newline at end of file diff --git a/src/PLASMA/TemporalNetwork/CMakeLists.txt b/src/PLASMA/TemporalNetwork/CMakeLists.txt index 0fc3b569c..b527c3f41 100644 --- a/src/PLASMA/TemporalNetwork/CMakeLists.txt +++ b/src/PLASMA/TemporalNetwork/CMakeLists.txt @@ -1,5 +1,5 @@ include(EuropaModule) -set(internal_dependencies RulesEngine PlanDatabase ConstraintEngine Utils TinyXml) +set(internal_dependencies RulesEngine PlanDatabase) set(root_sources ModuleTemporalNetwork.cc) set(base_sources DispatchGraph.cc DistanceGraph.cc TemporalNetwork.cc queues.cc) set(component_sources STNTemporalAdvisor.cc TemporalNetworkListener.cc TemporalPropagator.cc TimepointWrapper.cc) diff --git a/src/PLASMA/Utils/CMakeLists.txt b/src/PLASMA/Utils/CMakeLists.txt index 5cdff3330..5d06b192e 100644 --- a/src/PLASMA/Utils/CMakeLists.txt +++ b/src/PLASMA/Utils/CMakeLists.txt @@ -13,6 +13,7 @@ declare_module(Utils "${root_sources}" "${base_sources}" "${component_sources}" file(GLOB test_inputs test/*.xml test/*.dtd test/*.cfg) file(COPY ${test_inputs} DESTINATION .) + #how do I handle the dlopen and pthreads link requirements? do I need to? find_library(libdl_library dl libdl ltdl libltdl) -target_link_libraries("Utils${EUROPA_SUFFIX}" ${libdl_library}) \ No newline at end of file +target_link_libraries("Utils${EUROPA_SUFFIX}" ${libdl_library}) diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake index 0683247b7..894d371e3 100644 --- a/src/PLASMA/cmake/EuropaModule.cmake +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -224,13 +224,24 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de set(libname "${name}${EUROPA_SUFFIX}") set(testname ${name}-test${EUROPA_SUFFIX}) + set(full_dependencies ${module_dependencies}) + foreach(mod ${module_dependencies}) + list(APPEND full_dependencies ${${mod}_FULL_DEPENDENCIES}) + endforeach(mod) + if(full_dependencies) + list(REMOVE_DUPLICATES full_dependencies) + endif(full_dependencies) + set(${name}_FULL_DEPENDENCIES ${full_dependencies} PARENT_SCOPE) + + add_library(${libname} ${root_srcs} ${base_srcs} ${component_srcs}) add_common_local_include_deps(${libname}) foreach(dep ${module_components}) append_target_property(${libname} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/component/${dep}") endforeach(dep) - add_common_module_deps(${libname} "${module_dependencies}") + #add_common_module_deps(${libname} "${module_dependencies}") + add_common_module_deps(${libname} "${full_dependencies}") #why did I end up having to do all this? if(test_srcs OR (NOT ("${test_srcs}" STREQUAL "" OR test_srcs MATCHES "^$"))) @@ -239,7 +250,8 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de append_target_property(${testname} INCLUDE_DIRECTORIES ";${CppUnit_INCLUDE_DIRS}") add_common_local_include_deps(${testname}) - add_common_module_deps(${testname} "${module_dependencies}") + #add_common_module_deps(${testname} "${module_dependencies}") + add_common_module_deps(${testname} "${full_dependencies}") foreach(dep ${module_components}) append_target_property(${testname} INCLUDE_DIRECTORIES ";${CMAKE_CURRENT_SOURCE_DIR}/component/${dep}") endforeach(dep) From 1ce9dee143521f8dc41336cd689f9f9d15f403d5 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 25 Jul 2014 18:24:32 +0000 Subject: [PATCH 008/149] Adding 64/32-bit builds git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6735 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 5 ++++- src/PLASMA/CMakeLists.txt | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5f0503f37..e7c1828b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,11 +14,14 @@ set(CMAKE_POSITION_INDEPENDENT_CODE TRUE) #Options to support: # * optimized/not option(OPTIMIZE "Build optimized" FALSE) - # * shared/not option(SHARED "Build shared libraries" TRUE) set(BUILD_SHARED_LIBS ${SHARED}) # * 64/32-bit +if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") + set(SIXTYFOUR TRUE) +endif(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64") +option(SIXTYFOUR "Build for 64-bit" ${SIXTYFOUR}) # * modules? set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) diff --git a/src/PLASMA/CMakeLists.txt b/src/PLASMA/CMakeLists.txt index d465632c9..5bdc01b64 100644 --- a/src/PLASMA/CMakeLists.txt +++ b/src/PLASMA/CMakeLists.txt @@ -11,6 +11,19 @@ else() set(EUROPA_SUFFIX "_g") endif(OPTIMIZE) +if(SIXTYFOUR) + message(STATUS "Configuring for 64-bit build") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m64") + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -m64") + add_definitions(-DEUROPA_64_BIT_PLATFORM) +else() + message(STATUS "Configuring for 32-bit build") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -m32") + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -m32") +endif(SIXTYFOUR) + add_subdirectory(TinyXml) add_subdirectory(Utils) add_subdirectory(ConstraintEngine) From ef8f8dfd54124d2565c6c85c0f1bbbbf78d14d82 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 28 Jul 2014 15:41:17 +0000 Subject: [PATCH 009/149] Fixed the dependency problem between PSEngineGenerated and PSEngine. Parallel builds should work now. Starting to get examples building via cmake git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6736 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 7 +++ examples/Light/CMakeLists.txt | 44 +++++++++++++ src/Java/PSEngine/CMakeLists.txt | 103 ++++++++++++++----------------- src/PLASMA/CMakeLists.txt | 3 +- src/PLASMA/System/CMakeLists.txt | 13 +++- 5 files changed, 108 insertions(+), 62 deletions(-) create mode 100644 examples/Light/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index e7c1828b3..021f971cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,5 +26,12 @@ option(SIXTYFOUR "Build for 64-bit" ${SIXTYFOUR}) set(EUROPA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}) set(CppUnit_FIND_QUIETLY TRUE) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + add_subdirectory(src) install(EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa) diff --git a/examples/Light/CMakeLists.txt b/examples/Light/CMakeLists.txt new file mode 100644 index 000000000..1152e3a45 --- /dev/null +++ b/examples/Light/CMakeLists.txt @@ -0,0 +1,44 @@ +cmake_minimum_required(VERSION 2.8.8) +project(Light) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(Light.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(Light.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(Light java Light.i) + +#project-lib +add_library(Light${EUROPA_SUFFIX} ${swig_generated_file_fullname} LightCustomCode.cc ModuleLight.cc) + +#project-rt +add_executable(Light-planner_${EUROPA_SUFFIX}_rt Light-Main.cc LightCustomCode.cc ModuleLight.cc) + +#run-project +add_custom_target(run-project + DEPENDS Light-planner_${EUROPA_SUFFIX}_rt + COMMAND ./Light-planner_${EUROPA_SUFFIX}_rt > RUN_Light-planner_${EUROPA_SUFFIX}_rt.Light-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +add_jar(LightJar + SOURCES + #?? + OUTPUT_NAME Light.jar + ) + +add_dependencies(LightJar Light${EUROPA_SUFFIX}) + diff --git a/src/Java/PSEngine/CMakeLists.txt b/src/Java/PSEngine/CMakeLists.txt index d5655156a..1c3b22a8d 100644 --- a/src/Java/PSEngine/CMakeLists.txt +++ b/src/Java/PSEngine/CMakeLists.txt @@ -2,70 +2,59 @@ find_package(Java REQUIRED) include(UseJava RESULT_VARIABLE java_included) if(NOT java_included) message(FATAL_ERROR "Failed to include UseJava") -else() - message(STATUS "Found UseJava: ${java_included}") endif(NOT java_included) -#set(CMAKE_JAVA_TARGET_OUTPUT_DIR ${) -#set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/generated;${CMAKE_CURRENT_SOURCE_DIR}/src;${CMAKE_JAVA_INCLUDE_PATH}) -add_jar(PSEngineGenerated - SOURCES - generated/psengine/PSConstraint.java - generated/psengine/PSConstraintEngineListener.java - generated/psengine/PSConstraintList.java - generated/psengine/PSDataType.java - generated/psengine/PSDataTypeList.java - generated/psengine/PSEngine.java - generated/psengine/PSEngineInterface.java - generated/psengine/PSEngineInterfaceJNI.java - generated/psengine/PSEntity.java - generated/psengine/PSException.java - generated/psengine/PSIntList.java - generated/psengine/PSLanguageException.java - generated/psengine/PSLanguageExceptionList.java - generated/psengine/PSObject.java - generated/psengine/PSObjectList.java - generated/psengine/PSObjectType.java - generated/psengine/PSObjectTypeList.java - generated/psengine/PSPlanDatabaseClient.java - generated/psengine/PSPlanDatabaseListener.java - generated/psengine/PSResource.java - generated/psengine/PSResourceProfile.java - generated/psengine/PSSchema.java - generated/psengine/PSSolver.java - generated/psengine/PSStringList.java - generated/psengine/PSTimePointList.java - generated/psengine/PSToken.java - generated/psengine/PSTokenList.java - generated/psengine/PSTokenState.java - generated/psengine/PSTokenType.java - generated/psengine/PSTokenTypeList.java - generated/psengine/PSValueList.java - generated/psengine/PSVarType.java - generated/psengine/PSVarValue.java - generated/psengine/PSVariable.java - generated/psengine/PSVariableList.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSConstraint.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSDataType.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSObject.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSObjectType.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSToken.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSTokenType.java - # generated/psengine/SWIGTYPE_p_p_EUROPA__PSVariable.java - generated/psengine/StringErrorStream.java - generated/psengine/EngineConfig.java - # src/psengine/PSUtil.java - # src/psengine/util/LibraryLoader.java - # src/psengine/util/SimpleTimer.java - ) +# add_jar(PSEngineGenerated +# SOURCES +# generated/psengine/PSConstraint.java +# generated/psengine/PSConstraintEngineListener.java +# generated/psengine/PSConstraintList.java +# generated/psengine/PSDataType.java +# generated/psengine/PSDataTypeList.java +# generated/psengine/PSEngine.java +# generated/psengine/PSEngineInterface.java +# generated/psengine/PSEngineInterfaceJNI.java +# generated/psengine/PSEntity.java +# generated/psengine/PSException.java +# generated/psengine/PSIntList.java +# generated/psengine/PSLanguageException.java +# generated/psengine/PSLanguageExceptionList.java +# generated/psengine/PSObject.java +# generated/psengine/PSObjectList.java +# generated/psengine/PSObjectType.java +# generated/psengine/PSObjectTypeList.java +# generated/psengine/PSPlanDatabaseClient.java +# generated/psengine/PSPlanDatabaseListener.java +# generated/psengine/PSResource.java +# generated/psengine/PSResourceProfile.java +# generated/psengine/PSSchema.java +# generated/psengine/PSSolver.java +# generated/psengine/PSStringList.java +# generated/psengine/PSTimePointList.java +# generated/psengine/PSToken.java +# generated/psengine/PSTokenList.java +# generated/psengine/PSTokenState.java +# generated/psengine/PSTokenType.java +# generated/psengine/PSTokenTypeList.java +# generated/psengine/PSValueList.java +# generated/psengine/PSVarType.java +# generated/psengine/PSVarValue.java +# generated/psengine/PSVariable.java +# generated/psengine/PSVariableList.java +# generated/psengine/StringErrorStream.java +# generated/psengine/EngineConfig.java +# ) #set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}) -list(APPEND CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}/PSEngineGenerated.jar) -set(CMAKE_JAVA_TARGET_OUTPUT_NAME PSEngine.jar) +#list(APPEND CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}/PSEngineGenerated.jar) add_jar(PSEngineJar SOURCES src/psengine/PSUtil.java src/psengine/util/LibraryLoader.java src/psengine/util/SimpleTimer.java INCLUDE_JARS - PSEngineGenerated.jar) \ No newline at end of file + PSEngineGenerated.jar + OUTPUT_NAME + PSEngine) +add_dependencies(PSEngineJar PSEngineGenerated) +install_jar(PSEngineJar ${EUROPA_ROOT}/dist/europa) \ No newline at end of file diff --git a/src/PLASMA/CMakeLists.txt b/src/PLASMA/CMakeLists.txt index 5bdc01b64..189f3b629 100644 --- a/src/PLASMA/CMakeLists.txt +++ b/src/PLASMA/CMakeLists.txt @@ -5,10 +5,9 @@ set(GCC_DEBUG_FLAGS "-ggdb3") set(CMAKE_LIBRARY_PATH "/opt/lib:/opt/local/lib:${CMAKE_LIBRARY_PATH}") if(OPTIMIZE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_OPTIMIZATION_FLAGS}") - set(EUROPA_SUFFIX "_o") + add_definitions(-DEUROPA_FAST=1) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_DEBUG_FLAGS}") - set(EUROPA_SUFFIX "_g") endif(OPTIMIZE) if(SIXTYFOUR) diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index beeaa38dd..9769df95a 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -30,7 +30,14 @@ set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine" set_source_files_properties(base/PSEngine.i PROPERTIES CPLUSPLUS ON) set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") -set_source_files_properties( +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +add_jar(PSEngineGenerated + SOURCES ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraint.java ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintEngineListener.java ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintList.java @@ -68,7 +75,7 @@ set_source_files_properties( ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVariableList.java ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/StringErrorStream.java ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/EngineConfig.java - PROPERTIES GENERATED TRUE) + OUTPUT_DIR ${CMAKE_SOURCE_DIR}/src/java/PSEngine) include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) @@ -80,6 +87,6 @@ foreach(dep ${internal_dependencies}) endforeach(dep) add_common_module_include_dep(PSEngine System) target_link_libraries(PSEngine "System${EUROPA_SUFFIX}") - +add_dependencies(PSEngineGenerated PSEngine) add_subdirectory(test) \ No newline at end of file From 49c157058b583d94a5e08b70baec748d53a5d08a Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 7 Aug 2014 21:46:37 +0000 Subject: [PATCH 010/149] Added NDDL error reporting to the project template. Addresses the issues Tristan mentions in #96. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6740 23e1bc29-d954-0410-9766-47de34158ba0 --- bin/.makeproject/Template-Main.cc | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/bin/.makeproject/Template-Main.cc b/bin/.makeproject/Template-Main.cc index 2f6117c8d..61d9fb576 100644 --- a/bin/.makeproject/Template-Main.cc +++ b/bin/.makeproject/Template-Main.cc @@ -51,10 +51,14 @@ bool solve(const char* plannerConfig, PSEngine* engine = PSEngine::makeInstance(); engine->start(); - #ifndef USE_EUROPA_DLL - engine->addModule((new Module%%Project%%())); - #endif - engine->executeScript("nddl",nddlFile,true/*isFile*/); +#ifndef USE_EUROPA_DLL + engine->addModule((new Module%%Project%%())); +#endif + std::string errors = engine->executeScript("nddl",nddlFile,true/*isFile*/); + if(!errors.empty()) { + std::cout << errors << std::endl; + return false; + } PSSolver* solver = engine->createSolver(plannerConfig); runSolver(solver,startHorizon,endHorizon,maxSteps); From a7d91ea27a601d1e80d2362f498a4da49eefd322 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 15 Aug 2014 18:28:04 +0000 Subject: [PATCH 011/149] Domains.cc: IntervalDomain now notifies on calls to set(). This was inconsistent with other domains and is required to get guard notifications working correctly. Interpreter.cc/hh: Added some const-ness, a function for getting variables referred to in expressions, and updated InterpretedRuleInstance creation to take a list of variables participating in a guard. Also added a getArgs to CExprFunction PDBInterpeter.cc/hh: Added some const-ness and re-wrote some code to use iterators rather than indices RuleInstance.cc/hh: Changed some indentation, added a constructor that takes the variables that participate in a guard and adds them to the scope of the RuleVariableListener, changed the condition in RuleInstance::test to be specified OR singleton base domain rather than singleton derived domain to address issue 112 UnboundVariableManager.cc: Removed filtering of singleton, non-specified variables. SolverTests.xml: Changed the SimpleRejection configuration to arrive at the problem more quickly solvers-test-module.cc: Multiple updates to tests address the changes to rule firing semantics HTX.1.solverConfig.xml: added filtering of object variables (which are back in Solver scope due to changes in filtering singleton variables) Added simple test for the situation in issue 112 This commit reverts rule firing behavior back to the original behavior of only firing when the variables in a guard are /specified/, rather than the newer semantic of firing when the guard variables are /singleton/, which has resulted in several problems. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6741 23e1bc29-d954-0410-9766-47de34158ba0 --- .../ConstraintEngine/component/Domains.cc | 8 +- src/PLASMA/NDDL/component/Interpreter.cc | 182 ++++++++++++++---- src/PLASMA/NDDL/component/Interpreter.hh | 22 ++- .../PlanDatabase/base/PDBInterpreter.cc | 18 +- .../PlanDatabase/base/PDBInterpreter.hh | 2 +- src/PLASMA/RulesEngine/base/RuleInstance.cc | 163 +++++++++++----- src/PLASMA/RulesEngine/base/RuleInstance.hh | 20 +- .../component/UnboundVariableManager.cc | 13 +- src/PLASMA/Solvers/test/SolverTests.xml | 11 +- .../Solvers/test/solvers-test-module.cc | 21 +- .../Solvers/test/solvers-test-module.hh | 28 +-- src/PLASMA/System/test/HTX.1.solverConfig.xml | 1 + src/PLASMA/System/test/Jamfile | 1 + .../smallerInconsistency-initial-state.nddl | 19 ++ .../test/smallerInconsistency-model.nddl | 24 +++ 15 files changed, 397 insertions(+), 136 deletions(-) create mode 100644 src/PLASMA/System/test/smallerInconsistency-initial-state.nddl create mode 100644 src/PLASMA/System/test/smallerInconsistency-model.nddl diff --git a/src/PLASMA/ConstraintEngine/component/Domains.cc b/src/PLASMA/ConstraintEngine/component/Domains.cc index 83589ad7c..3c68b5e0e 100644 --- a/src/PLASMA/ConstraintEngine/component/Domains.cc +++ b/src/PLASMA/ConstraintEngine/component/Domains.cc @@ -775,13 +775,15 @@ namespace EUROPA { if(!isMember(value)) empty(); else { - bool changed = (m_lb != value || m_ub != value); - if(changed == true){ + //TODO: possibly add a "specify" to domains that publishes rather than + //forcing this method to publish all the time + // bool changed = (m_lb != value || m_ub != value); + // if(changed == true){ m_lb = value; m_ub = value; notifyChange(DomainListener::SET_TO_SINGLETON); - } + // } } } diff --git a/src/PLASMA/NDDL/component/Interpreter.cc b/src/PLASMA/NDDL/component/Interpreter.cc index 9ca30341b..a42c6db71 100644 --- a/src/PLASMA/NDDL/component/Interpreter.cc +++ b/src/PLASMA/NDDL/component/Interpreter.cc @@ -27,6 +27,8 @@ #include "NddlRules.hh" #include "NddlUtils.hh" +#include +#include namespace EUROPA { @@ -370,6 +372,13 @@ namespace EUROPA { : m_func(func) , m_args(args) { + checkError(func.isValid(), "Constructed with invalid function pointer."); + for(std::vector::const_iterator it = m_args.begin(); + it != m_args.end(); ++it) { + checkError((*it) != NULL, "Constructed CFunction " << func->getName() << + " with a null argument at position " << + std::distance::const_iterator>(m_args.begin(), it)); + } } void CExprFunction::checkType() @@ -401,8 +410,10 @@ namespace EUROPA { std::string CExprFunction::toString() const { std::string args = ""; - for (unsigned int i = 0; i < m_args.size(); i++) - args += m_args[i]->toString() + std::string("_"); + for (unsigned int i = 0; i < m_args.size(); i++) { + checkError(m_args[i] != NULL, "??"); + args += m_args[i]->toString() + std::string("_"); + } return m_func->getName().toString() + "__" + args + "_"; } @@ -1068,8 +1079,8 @@ namespace EUROPA { } const std::string& ExprIfGuard::getOperator() { return m_op; } - Expr* ExprIfGuard::getLhs() { return m_lhs; } - Expr* ExprIfGuard::getRhs() { return m_rhs; } + Expr* ExprIfGuard::getLhs() const { return m_lhs; } + Expr* ExprIfGuard::getRhs() const { return m_rhs; } DataRef ExprIfGuard::eval(EvalContext& context) const { @@ -1120,42 +1131,50 @@ namespace EUROPA { if (m_guard->getRhs() != NULL) { DataRef rhs = m_guard->getRhs()->eval(context); - context.getRuleInstance()->addChildRule( - new InterpretedRuleInstance( - context.getRuleInstance()->getId(), - lhs.getValue(), - rhs.getValue()->lastDomain(), - isOpEquals, - m_ifBody - ) - ); - + std::vector vars; + getVariableReferences(m_guard, context, vars); + InterpretedRuleInstance* iri = + new InterpretedRuleInstance(context.getRuleInstance()->getId(), + lhs.getValue(), + rhs.getValue()->lastDomain(), + isOpEquals, + vars, + m_ifBody); + context.getRuleInstance()->addChildRule(iri); + if (m_elseBody.size() > 0) { - context.getRuleInstance()->addChildRule( - new InterpretedRuleInstance( - context.getRuleInstance()->getId(), - lhs.getValue(), - rhs.getValue()->lastDomain(), - !isOpEquals, - m_elseBody - ) - ); - } - - debugMsg("Interpreter:InterpretedRule","Evaluated IF " << m_guard->toString()); + InterpretedRuleInstance* elseBody = + new InterpretedRuleInstance( + context.getRuleInstance()->getId(), + lhs.getValue(), + rhs.getValue()->lastDomain(), + !isOpEquals, + vars, + m_elseBody); + context.getRuleInstance()->addChildRule(elseBody); + } + + debugMsg("Interpreter:InterpretedRule","Evaluated simple IF " << m_guard->toString()); } else { + // std::vector vars; + // getVariableReferences(m_guard, context, vars); + // condDebugMsg(!vars.empty(), "Interpreter:evalIf", + // "For " << toString() << ", have the following variables: "); + // for(std::vector::const_iterator it = vars.begin(); it != vars.end(); + // ++it) { + // debugMsg("Interpreter:evalIf", (*it)->toLongString()); + // } + checkRuntimeError(ALWAYS_FAILS, "Didn't expect to get here.") context.getRuleInstance()->addChildRule( - new InterpretedRuleInstance( - context.getRuleInstance()->getId(), - makeScope(lhs.getValue()), - isOpEquals, - m_ifBody - ) - ); + new InterpretedRuleInstance( + context.getRuleInstance()->getId(), + makeScope(lhs.getValue()), + isOpEquals, + m_ifBody)); check_runtime_error(m_elseBody.size()==0, "Can't have else body for singleton guard"); - debugMsg("Interpreter:InterpretedRule","Evaluated IF " << m_guard->toString()); + debugMsg("Interpreter:InterpretedRule","Evaluated mult-var IF " << m_guard->toString()); } return DataRef::null; @@ -1513,6 +1532,17 @@ namespace EUROPA { { } +InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& var, + const Domain& domain, + const bool positive, + const std::vector& guardComponents, + const std::vector& body) + : RuleInstance(parent,var,domain,positive, guardComponents) + , m_body(body) + { + } + InterpretedRuleInstance::InterpretedRuleInstance( const RuleInstanceId& parent, const std::vector& vars, @@ -2413,5 +2443,89 @@ namespace EUROPA { return os.str(); } +void getVariableReferences(const Expr* expr, EvalContext& ctx, + std::vector& dest) { + checkError(expr != NULL, "Weird. Expression pointer is null."); + debugMsg("getVariableReferences", "Getting refs from " << expr->toString()); + if(dynamic_cast(expr) != NULL) { + const ExprList* e = dynamic_cast(expr); + for(std::vector::const_iterator it = e->getChildren().begin(); + it != e->getChildren().end(); ++it) { + getVariableReferences(*it, ctx, dest); + } + } + //ExprNoop -> nothing + //What to do about ExprConstructorSuperCall? + else if(dynamic_cast(expr) != NULL) { + //we may want to grab these after all, but for now, do nothing + } + //ExprVarDeclaration -> ? + else if(dynamic_cast(expr) != NULL) { + dest.push_back(dynamic_cast(expr)->eval(ctx).getValue()); + } + //ExprVarRef -> ? + //ExprAssignment -> ? + else if(dynamic_cast(expr) != NULL) { + const ExprConstraint* e = dynamic_cast(expr); + for(std::vector::const_iterator it = e->getArgs().begin(); + it != e->getArgs().end(); ++it) { + getVariableReferences(*it, ctx, dest); + } + } + //ExprTypedef -> nothing + //ExprEnumdef -> nothing + //ExprObjectTypeDeclaration -> nothing + //ExprObjectTypeDefinition -> nothing + //ExprRuleTypeDefinition -> nothing + else if(dynamic_cast(expr) != NULL) { + const ExprMethodCall* e = dynamic_cast(expr); + for(std::vector::const_iterator it = e->getArgs().begin(); + it != e->getArgs().end(); ++it) { + getVariableReferences(*it, ctx, dest); + } + } + //ExprVariableMethod -> ? + //ExprObjectMethod -> ? + //ExprTokenMethod -> ? + //ExprNewObject -> ? + //ExprProblemStatement -> ? + //ExprRelation -> ? + else if(dynamic_cast(expr) != NULL) { + if(dynamic_cast(expr) != NULL) { + const CExprFunction* e = dynamic_cast(expr); + for(std::vector::const_iterator it = e->getArgs().begin(); + it != e->getArgs().end(); ++it) { + getVariableReferences(*it, ctx, dest); + } + } + else if(dynamic_cast(expr) != NULL) { + //not sure this is right + dest.push_back(dynamic_cast(expr)->eval(ctx).getValue()); + } + else if(dynamic_cast(expr) != NULL) { + const CExprBinary* e = dynamic_cast(expr); + getVariableReferences(e->getLhs(), ctx, dest); + getVariableReferences(e->getRhs(), ctx, dest); + } + else { + checkRuntimeError(ALWAYS_FAIL, + "getVariableReferences doesn't know how to with this subclass" << + " of CExpr " << + expr->toString() << " <" << typeid(expr).name() << ">"); + } + } + //RuleExpr -> ? + else if(dynamic_cast(expr) != NULL) { + const ExprIfGuard* e = dynamic_cast(expr); + getVariableReferences(e->getLhs(), ctx, dest); + getVariableReferences(e->getRhs(), ctx, dest); + } + else { + checkRuntimeError(ALWAYS_FAIL, + "getVariableReferences doesn't know how to with this " << + expr->toString() << " <" << typeid(expr).name() << ">"); + } +} + } diff --git a/src/PLASMA/NDDL/component/Interpreter.hh b/src/PLASMA/NDDL/component/Interpreter.hh index e382a329a..c5c41ee40 100644 --- a/src/PLASMA/NDDL/component/Interpreter.hh +++ b/src/PLASMA/NDDL/component/Interpreter.hh @@ -190,7 +190,7 @@ namespace EUROPA { virtual DataRef eval(EvalContext& context) const; virtual std::string toString() const; - + virtual const std::vector& getArgs() const {return m_argExprs;} protected: MethodId m_method; Expr* m_varExpr; @@ -370,9 +370,13 @@ namespace EUROPA { virtual void checkType(); + virtual const std::vector& getArgs() const {return m_args;} + protected: CFunctionId m_func; std::vector m_args; + private: + CExprFunction() : m_func(), m_args() {} }; class CExprValue : public CExpr @@ -422,6 +426,9 @@ namespace EUROPA { virtual void checkType(); + virtual const CExpr* getLhs() const {return m_lhs;} + virtual const CExpr* getRhs() const {return m_rhs;} + protected: std::string m_operator; CExpr *m_lhs, *m_rhs; @@ -509,6 +516,13 @@ namespace EUROPA { const bool positive, const std::vector& body); + InterpretedRuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& var, + const Domain& domain, + const bool positive, + const std::vector& guardComponents, + const std::vector& body); + InterpretedRuleInstance(const RuleInstanceId& parent, const std::vector& vars, const bool positive, @@ -614,8 +628,8 @@ namespace EUROPA { virtual ~ExprIfGuard(); const std::string& getOperator(); - Expr* getLhs(); - Expr* getRhs(); + Expr* getLhs() const; + Expr* getRhs() const; virtual DataRef eval(EvalContext& context) const; virtual std::string toString() const; @@ -665,6 +679,8 @@ namespace EUROPA { virtual TokenId createInstance(const TokenId& master, const LabelStr& name, const LabelStr& relation) const = 0; }; +void getVariableReferences(const Expr* expr, EvalContext& ctx, std::vector& dest); + } #endif // _H_Interpreter diff --git a/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc b/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc index ed7869e75..8c8f816fc 100644 --- a/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc +++ b/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc @@ -129,18 +129,19 @@ namespace EUROPA { ExprList::~ExprList() { - for (unsigned int i=0;i::iterator it = m_children.begin(); it != m_children.end(); + ++it) + delete *it; } - const std::vector& ExprList::getChildren() { return m_children; } + const std::vector& ExprList::getChildren() const { return m_children; } DataRef ExprList::eval(EvalContext& context) const { DataRef result; - - for (unsigned int i=0;ieval(context); + for(std::vector::const_iterator it = m_children.begin(); + it != m_children.end(); ++it) + result = (*it)->eval(context); return result; } @@ -154,8 +155,9 @@ namespace EUROPA { { std::ostringstream os; - for (unsigned int i=0;itoString() << std::endl; + for(std::vector::const_iterator it = m_children.begin(); + it != m_children.end(); ++it) + os << (*it)->toString() << std::endl; return os.str(); } diff --git a/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh b/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh index bd40f99a7..03b078a70 100644 --- a/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh +++ b/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh @@ -67,7 +67,7 @@ namespace EUROPA { virtual DataRef eval(EvalContext& context) const; void addChild(Expr* child); - const std::vector& getChildren(); + const std::vector& getChildren() const; virtual std::string toString() const; diff --git a/src/PLASMA/RulesEngine/base/RuleInstance.cc b/src/PLASMA/RulesEngine/base/RuleInstance.cc index 8e36fcff7..bb6506cb7 100644 --- a/src/PLASMA/RulesEngine/base/RuleInstance.cc +++ b/src/PLASMA/RulesEngine/base/RuleInstance.cc @@ -15,68 +15,97 @@ namespace EUROPA { - RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, const PlanDatabaseId& planDb) - : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ - check_error(rule.isValid(), "Parent must be a valid rule id."); - check_error(isValid()); - commonInit(); - } +RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, + const PlanDatabaseId& planDb) + : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), + m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ + check_error(rule.isValid(), "Parent must be a valid rule id."); + check_error(isValid()); + commonInit(); +} - RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, const PlanDatabaseId& planDb, - const std::vector& guards) - : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ - check_error(isValid()); - setGuard(guards); - commonInit(); - } +RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, + const PlanDatabaseId& planDb, + const std::vector& guards) + : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), + m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ + check_error(isValid()); + setGuard(guards); + commonInit(); +} - RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, const PlanDatabaseId& planDb, - const ConstrainedVariableId& guard, const Domain& domain) - : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ - check_error(isValid()); - setGuard(guard, domain); - commonInit(); - } +RuleInstance::RuleInstance(const RuleId& rule, const TokenId& token, + const PlanDatabaseId& planDb, + const ConstrainedVariableId& guard, const Domain& domain) + : m_id(this), m_rule(rule), m_token(token), m_planDb(planDb), m_rulesEngine(), + m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ + check_error(isValid()); + setGuard(guard, domain); + commonInit(); +} - /** - * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. - */ - RuleInstance::RuleInstance(const RuleInstanceId& parent, const std::vector& guards) +/** + * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. + */ +RuleInstance::RuleInstance(const RuleInstanceId& parent, + const std::vector& guards) : m_id(this), m_rule(parent->getRule()), m_token(parent->getToken()), - m_planDb(parent->getPlanDatabase()),m_rulesEngine() , m_parent(parent), m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ - check_error(isValid()); - setGuard(guards); - } + m_planDb(parent->getPlanDatabase()),m_rulesEngine() , m_parent(parent), + m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ + check_error(isValid()); + setGuard(guards); +} - /** - * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. - */ - RuleInstance::RuleInstance(const RuleInstanceId& parent, const std::vector& guards, const bool positive) +/** + * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. + */ +RuleInstance::RuleInstance(const RuleInstanceId& parent, + const std::vector& guards, + const bool positive) : m_id(this), m_rule(parent->getRule()), m_token(parent->getToken()), - m_planDb(parent->getPlanDatabase()),m_rulesEngine() , m_parent(parent), m_guardDomain(0), m_isExecuted(false), m_isPositive(positive){ - check_error(isValid()); - setGuard(guards); - } + m_planDb(parent->getPlanDatabase()),m_rulesEngine() , m_parent(parent), + m_guardDomain(0), m_isExecuted(false), m_isPositive(positive){ + check_error(isValid()); + setGuard(guards); +} - /** - * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. - */ - RuleInstance::RuleInstance(const RuleInstanceId& parent, const ConstrainedVariableId& guard, const Domain& domain) +/** + * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. + */ +RuleInstance::RuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& guard, const Domain& domain) : m_id(this), m_rule(parent->getRule()), m_token(parent->getToken()), - m_planDb(parent->getPlanDatabase()), m_rulesEngine(), m_parent(parent), m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ - check_error(isValid()); - setGuard(guard, domain); - } + m_planDb(parent->getPlanDatabase()), m_rulesEngine(), m_parent(parent), + m_guardDomain(0), m_isExecuted(false), m_isPositive(true){ + check_error(isValid()); + setGuard(guard, domain); +} /** * @brief Constructor refers to parent for tokens, and variables that are accessible in its scope. */ - RuleInstance::RuleInstance(const RuleInstanceId& parent, const ConstrainedVariableId& guard, const Domain& domain, const bool positive) +RuleInstance::RuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& guard, + const Domain& domain, const bool positive) : m_id(this), m_rule(parent->getRule()), m_token(parent->getToken()), - m_planDb(parent->getPlanDatabase()), m_rulesEngine(), m_parent(parent), m_guardDomain(0), m_isExecuted(false), m_isPositive(positive){ - check_error(isValid()); - setGuard(guard, domain); - } + m_planDb(parent->getPlanDatabase()), m_rulesEngine(), m_parent(parent), + m_guardDomain(0), m_isExecuted(false), m_isPositive(positive){ + check_error(isValid()); + setGuard(guard, domain); +} + +RuleInstance::RuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& guard, + const Domain& domain, const bool positive, + const std::vector& guardComponents) + : m_id(this), m_rule(parent->getRule()), m_token(parent->getToken()), + m_planDb(parent->getPlanDatabase()), m_rulesEngine(), m_parent(parent), + m_guardDomain(0), m_isExecuted(false), m_isPositive(positive){ + check_error(isValid()); + setGuard(guard, domain, guardComponents); +} + + /** * @brief Clean up all the allocated elements @@ -154,11 +183,21 @@ namespace EUROPA { */ bool RuleInstance::test(const std::vector& guards) const { checkError(m_rule.isValid(), m_rule); - debugMsg("RuleInstance:test", "Testing rule " << toString() << " for " << m_rule->getName().toString() << " from " << m_rule->getSource().toString()); + debugMsg("RuleInstance:test", + "Testing rule " << toString() << " for " << m_rule->getName().toString() << + " from " << m_rule->getSource().toString()); + if(m_guardDomain != 0) { // Case of explicit guard on a single variable debugMsg("RuleInstance:test", "Case of explicit guard on a single variable"); - checkError(guards.size() == 1, "Explicit guard on one variable only"); + // checkError(guards.size() == 1, "Explicit guard on one variable only"); bool result = false; + //+ 1 here because the first variable may be the one created implicitly for some + //testEQ or similar constraint and therefore may not be available to the planner + for(std::vector::const_iterator it = guards.begin() + 1; + it != guards.end(); ++it) { + if(!((*it)->isSpecified() || (*it)->baseDomain().isSingleton())) + return false; + } if(guards[0]->lastDomain().isSingleton()) { result = (m_guardDomain->isMember(guards[0]->lastDomain().getSingletonValue()) == m_isPositive); } @@ -185,7 +224,7 @@ namespace EUROPA { debugMsg("RuleInstance:test", "checking " << counter << " argument:" << guard->toString()); - if(!guard->lastDomain().isSingleton()){ + if(!(guard->isSpecified() || guard->baseDomain().isSingleton())){ debugMsg("RuleInstance:test", "argument " << counter << " is not specified " << guard->baseDomain().toString()); return false; } @@ -294,7 +333,7 @@ namespace EUROPA { if(var->parent() == m_id) var->discard(); - checkError(var.isValid(), var << " should still be va;id after a discard."); + checkError(var.isValid(), var << " should still be valid after a discard."); } m_variables.clear(); m_isExecuted = false; @@ -322,6 +361,23 @@ namespace EUROPA { debugMsg("RuleInstance:setGuard", "Added guard: " << m_guardListener->toLongString()); } +void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& domain, + const std::vector& guardComponents){ + check_error(m_guards.empty()); + check_error(guard.isValid()); + m_guards.push_back(guard); + m_guards.insert(m_guards.end(), guardComponents.begin(), guardComponents.end()); + checkError(Domain::canBeCompared(guard->baseDomain(), domain), + "Failed attempt to compare " << + guard->baseDomain().getTypeName().toString() << " with " << + domain.getTypeName().toString()); + m_guardDomain = domain.copy(); + m_guardListener = (new RuleVariableListener(m_planDb->getConstraintEngine(), m_id, + m_guards))->getId(); + m_guardListener->addDependent(this); + debugMsg("RuleInstance:setGuard", "Added guard: " << m_guardListener->toLongString()); +} + TokenId RuleInstance::addSlave(Token* slave){ m_slaves.push_back(slave->getId()); slave->addDependent((Entity*) this); @@ -732,4 +788,5 @@ namespace EUROPA { return true; return false; } + } diff --git a/src/PLASMA/RulesEngine/base/RuleInstance.hh b/src/PLASMA/RulesEngine/base/RuleInstance.hh index 036c3ea6b..3ecb7204f 100644 --- a/src/PLASMA/RulesEngine/base/RuleInstance.hh +++ b/src/PLASMA/RulesEngine/base/RuleInstance.hh @@ -50,12 +50,15 @@ namespace EUROPA{ /** * @brief Constructor to construct a rule instance from a parent. Must have a guard! */ - RuleInstance(const RuleInstanceId& parent, const std::vector& guards); + RuleInstance(const RuleInstanceId& parent, + const std::vector& guards); /** * @brief Constructor to construct a rule instance from a parent. Must have a guard! */ - RuleInstance(const RuleInstanceId& parent, const std::vector& guards, const bool positive); + RuleInstance(const RuleInstanceId& parent, + const std::vector& guards, + const bool positive); /** * @brief Constructor to construct a rule instance from a parent. Must have a guard! @@ -74,7 +77,14 @@ namespace EUROPA{ * @param positive Flag to indicate whether the test is positive or not. */ RuleInstance(const RuleInstanceId& parent, - const ConstrainedVariableId& guard, const Domain& domain, const bool positive); + const ConstrainedVariableId& guard, const Domain& domain, + const bool positive); + + RuleInstance(const RuleInstanceId& parent, + const ConstrainedVariableId& var, + const Domain& domain, + const bool positive, + const std::vector& guardComponents); /** * Destructor @@ -252,6 +262,10 @@ namespace EUROPA{ * only be called from constructor. */ void setGuard(const ConstrainedVariableId& guard, const Domain& domain); + + void setGuard(const ConstrainedVariableId& guad, const Domain& domain, + const std::vector& guardComponents); + /** diff --git a/src/PLASMA/Solvers/component/UnboundVariableManager.cc b/src/PLASMA/Solvers/component/UnboundVariableManager.cc index 5ac164f59..070f7bc25 100644 --- a/src/PLASMA/Solvers/component/UnboundVariableManager.cc +++ b/src/PLASMA/Solvers/component/UnboundVariableManager.cc @@ -58,9 +58,13 @@ namespace EUROPA { return true; // We also exclude singletons - if(var->lastDomain().isSingleton()){ - debugMsg("UnboundVariableManager:dynamicMatch", "Excluding " << var->getKey() << " as a singleton."); - return true; + // if(var->lastDomain().isSingleton()){ + // debugMsg("UnboundVariableManager:dynamicMatch", "Excluding " << var->getKey() << " as a singleton."); + // return true; + // } + if(var->isSpecified()) { + debugMsg("UnboundVariableManager:dynamicMatch", "Excluding " << var->getKey() << " as already specified."); + return true; } // Finally, we exlude if the bounds are not finite @@ -79,12 +83,11 @@ namespace EUROPA { debugMsg("UnboundVariableManager:updateFlaw", var->toLongString()); m_flawCandidates.erase(var); - if(variableOfNonActiveToken(var) || !var->canBeSpecified() || var->isSpecified() || var->isSingleton() || staticMatch(var)){ + if(variableOfNonActiveToken(var) || !var->canBeSpecified() || var->isSpecified() || staticMatch(var)){ debugMsg("UnboundVariableManager:updateFlaw", "Excluding " << var->toLongString()); condDebugMsg(variableOfNonActiveToken(var), "UnboundVariableManager:updateFlaw", "Parent is not active."); condDebugMsg(!var->canBeSpecified(), "UnboundVariableManager:updateFlaw", "Variable can't be specified."); condDebugMsg(var->isSpecified(), "UnboundVariableManager:updateFlaw", "Variable is already specified."); - condDebugMsg(var->isSingleton(), "UnboundVariableManager:updateFlaw", "Variable is already singleton."); return; } diff --git a/src/PLASMA/Solvers/test/SolverTests.xml b/src/PLASMA/Solvers/test/SolverTests.xml index c08ccdecd..5ada368d8 100644 --- a/src/PLASMA/Solvers/test/SolverTests.xml +++ b/src/PLASMA/Solvers/test/SolverTests.xml @@ -25,13 +25,16 @@ + + + + + + - - - @@ -57,4 +60,4 @@ - \ No newline at end of file + diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index c72b3935c..7164939cf 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -432,14 +432,18 @@ class FilterTests { ConstrainedVariableId globalVar1 = testEngine.getPlanDatabase()->getGlobalVariable("globalVariable1"); ConstrainedVariableId globalVar2 = testEngine.getPlanDatabase()->getGlobalVariable("globalVariable2"); ConstrainedVariableId globalVar3 = testEngine.getPlanDatabase()->getGlobalVariable("globalVariable3"); + CPPUNIT_ASSERT(!fm.inScope(globalVar1)); CPPUNIT_ASSERT(fm.inScope(globalVar2)); globalVar2->specify(globalVar2->lastDomain().getLowerBound()); testEngine.getConstraintEngine()->propagate(); + CPPUNIT_ASSERT(!fm.inScope(globalVar2)); - CPPUNIT_ASSERT(!fm.inScope(globalVar1)); // By propagation it will be a singleton, so it will be Excluded + + //CPPUNIT_ASSERT(!fm.inScope(globalVar1)); // By propagation it will be a singleton, so it will be Excluded globalVar2->reset(); testEngine.getConstraintEngine()->propagate(); + CPPUNIT_ASSERT(!fm.inScope(globalVar1)); CPPUNIT_ASSERT(fm.inScope(globalVar2)); @@ -784,7 +788,8 @@ class FlawHandlerTests { Solver solver(testEngine.getPlanDatabase(), *child); CPPUNIT_ASSERT(solver.solve()); CPPUNIT_ASSERT(solver.getStepCount() == solver.getDepth()); - CPPUNIT_ASSERT_MESSAGE(toString(solver.getStepCount()), solver.getStepCount() == 2); + CPPUNIT_ASSERT_MESSAGE(toString(solver.getStepCount()), solver.getStepCount() == 5); + ConstrainedVariableId v1 = testEngine.getPlanDatabase()->getGlobalVariable("v1"); CPPUNIT_ASSERT_MESSAGE(v1->toString(), v1->lastDomain().getSingletonValue() == 1); ConstrainedVariableId v2 = testEngine.getPlanDatabase()->getGlobalVariable("v2"); @@ -803,7 +808,7 @@ class FlawHandlerTests { Solver solver(testEngine.getPlanDatabase(), *child); CPPUNIT_ASSERT(solver.solve()); CPPUNIT_ASSERT(solver.getStepCount() == solver.getDepth()); - CPPUNIT_ASSERT_MESSAGE(toString(solver.getStepCount()), solver.getStepCount() == 3); + CPPUNIT_ASSERT_MESSAGE(toString(solver.getStepCount()), solver.getStepCount() == 5); ConstrainedVariableId v1 = testEngine.getPlanDatabase()->getGlobalVariable("v1"); CPPUNIT_ASSERT_MESSAGE(v1->toString(), v1->getSpecifiedValue() == 9); ConstrainedVariableId v2 = testEngine.getPlanDatabase()->getGlobalVariable("v2"); @@ -1583,20 +1588,20 @@ class SolverTests { // Run the solver again. CPPUNIT_ASSERT(solver.solve()); - CPPUNIT_ASSERT(solver.getStepCount() == 2); - CPPUNIT_ASSERT(solver.getDepth() == 2); + CPPUNIT_ASSERT(solver.getStepCount() == 5); + CPPUNIT_ASSERT(solver.getDepth() == 5); // Now clear it and run it again solver.reset(); CPPUNIT_ASSERT(solver.solve()); - CPPUNIT_ASSERT(solver.getStepCount() == 2); - CPPUNIT_ASSERT(solver.getDepth() == 2); + CPPUNIT_ASSERT(solver.getStepCount() == 5); + CPPUNIT_ASSERT(solver.getDepth() == 5); // Now partially reset it, and run again solver.reset(1); CPPUNIT_ASSERT(solver.solve()); CPPUNIT_ASSERT_MESSAGE(toString(solver.getStepCount()), solver.getStepCount() == 1); - CPPUNIT_ASSERT_MESSAGE(toString(solver.getDepth()), solver.getDepth() == 2); + CPPUNIT_ASSERT_MESSAGE(toString(solver.getDepth()), solver.getDepth() == 5); // Now we reset one decision, then clear it. Expect the solution and depth to be 1. solver.reset(1); diff --git a/src/PLASMA/Solvers/test/solvers-test-module.hh b/src/PLASMA/Solvers/test/solvers-test-module.hh index e2088cefd..e71217af0 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.hh +++ b/src/PLASMA/Solvers/test/solvers-test-module.hh @@ -6,22 +6,22 @@ #include class SolversModuleTests : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SolversModuleTests); - CPPUNIT_TEST(componentFactoryTests); - CPPUNIT_TEST(filterTests); - CPPUNIT_TEST(flawIteratorTests); - CPPUNIT_TEST(flawManagerTests); - CPPUNIT_TEST(flawHandlerTests); - CPPUNIT_TEST(solverTests); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(SolversModuleTests); + CPPUNIT_TEST(componentFactoryTests); + CPPUNIT_TEST(filterTests); + CPPUNIT_TEST(flawIteratorTests); + CPPUNIT_TEST(flawManagerTests); + CPPUNIT_TEST(flawHandlerTests); + CPPUNIT_TEST(solverTests); + CPPUNIT_TEST_SUITE_END(); public: - inline void setUp() + inline void setUp() { - cppTests(); - } - - inline void tearDown() + cppTests(); + } + + inline void tearDown() { } @@ -32,7 +32,7 @@ public: void flawManagerTests(); void flawHandlerTests(); void solverTests(); - + }; diff --git a/src/PLASMA/System/test/HTX.1.solverConfig.xml b/src/PLASMA/System/test/HTX.1.solverConfig.xml index 0891e1886..dd9b01cf7 100644 --- a/src/PLASMA/System/test/HTX.1.solverConfig.xml +++ b/src/PLASMA/System/test/HTX.1.solverConfig.xml @@ -12,6 +12,7 @@ + diff --git a/src/PLASMA/System/test/Jamfile b/src/PLASMA/System/test/Jamfile index 92099a092..86338a228 100644 --- a/src/PLASMA/System/test/Jamfile +++ b/src/PLASMA/System/test/Jamfile @@ -102,6 +102,7 @@ local testmodels = rejection.nddl rules.0.tx.nddl subtype-extension.tx.nddl + smallerInconsistency-initial-state.nddl ; if ! ( "Resources" in $(NO) ) { diff --git a/src/PLASMA/System/test/smallerInconsistency-initial-state.nddl b/src/PLASMA/System/test/smallerInconsistency-initial-state.nddl new file mode 100644 index 000000000..8541a5c6c --- /dev/null +++ b/src/PLASMA/System/test/smallerInconsistency-initial-state.nddl @@ -0,0 +1,19 @@ +#include "smallerInconsistency-model.nddl" +#include "PlannerConfig.nddl" +// Sample object +YourObject object = new YourObject(); +PlannerConfig plannerConfig = new PlannerConfig(0, 1, 100, 100); +// Close the the PLASMA Database - no more objects can be created. +close(); + +// place your goals here. +goal(YourObject.helloWorld initialToken); +initialToken.start.specify(0); // Starts at beginning of the horizon +initialToken.end.specify(1); +initialToken.activate(); +object.constrain(initialToken, initialToken); + +// The planner should take it form here! +initialToken.guard.specify(true); +initialToken.guard.reset(); +initialToken.guard.specify(false); diff --git a/src/PLASMA/System/test/smallerInconsistency-model.nddl b/src/PLASMA/System/test/smallerInconsistency-model.nddl new file mode 100644 index 000000000..cb7eadfbb --- /dev/null +++ b/src/PLASMA/System/test/smallerInconsistency-model.nddl @@ -0,0 +1,24 @@ +#include "Plasma.nddl" + +/** + * @brief Place holder class with a single predicate + */ +class YourObject { + predicate helloWorld{ + bool guard; + } /*!< Predicate with no arguments */ +} + +/** + * @brief A simple rule to force a repeated cycle + */ +YourObject::helloWorld{ + // meets (object.helloWorld); + // met_by(object.helloWorld); + if(guard == true) { + guard == true; + } + if(guard == false) { + guard == false; + } +} From 0be8526d4bf7ddfbacf0bebc7764dc79d331869e Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 19 Aug 2014 22:22:56 +0000 Subject: [PATCH 012/149] For detailed commentary on these changes, see issue #132, comment #4 git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6742 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/ConstraintEngine/base/Domain.cc | 23 +- src/PLASMA/ConstraintEngine/base/Domain.hh | 18 -- .../component/EquivalenceClassCollection.cc | 16 +- .../component/EquivalenceClassCollection.hh | 4 +- .../ConstraintEngine/component/Variable.hh | 32 ++- .../ConstraintEngine/test/domain-tests.cc | 2 +- .../ConstraintEngine/test/module-tests.cc | 40 +-- src/PLASMA/NDDL/base/NddlRules.cc | 14 +- src/PLASMA/NDDL/base/NddlRules.hh | 5 +- src/PLASMA/NDDL/test/nddl-test-module.cc | 4 +- src/PLASMA/PlanDatabase/ModulePlanDatabase.cc | 10 - src/PLASMA/PlanDatabase/base/Schema.cc | 2 +- src/PLASMA/Solvers/base/FlawHandler.cc | 19 +- src/PLASMA/Solvers/base/FlawHandler.hh | 2 - src/PLASMA/Utils/base/DebugMsg.cc | 202 +++++++++----- src/PLASMA/Utils/base/DebugMsg.hh | 30 +- src/PLASMA/Utils/base/Entity.cc | 260 +++++++++++------- src/PLASMA/Utils/base/Entity.hh | 19 +- src/PLASMA/Utils/base/Error.cc | 6 + src/PLASMA/Utils/base/Mutex.cc | 21 +- src/PLASMA/Utils/base/Mutex.hh | 19 +- src/PLASMA/Utils/base/StringErrorStream.hh | 58 ++-- 22 files changed, 436 insertions(+), 370 deletions(-) diff --git a/src/PLASMA/ConstraintEngine/base/Domain.cc b/src/PLASMA/ConstraintEngine/base/Domain.cc index 94e905d4a..57b4a6603 100644 --- a/src/PLASMA/ConstraintEngine/base/Domain.cc +++ b/src/PLASMA/ConstraintEngine/base/Domain.cc @@ -12,38 +12,17 @@ namespace EUROPA { return(os); } - DomainComparator* DomainComparator::s_instance = NULL; - /** * @brief Constructor overwrites prior static instance, effecting a last-writer wins policy * for establishing the shared allocator. */ DomainComparator::DomainComparator(){ - // Assign instance to current value - s_instance = this; } /** * @brief On destruction, if the static instance is this object, then set it to null. */ DomainComparator::~DomainComparator(){ - if(s_instance == this) - s_instance = NULL; - } - - const DomainComparator& DomainComparator::getComparator(){ - if(s_instance == NULL) - new DomainComparator(); - return *s_instance; - } - - void DomainComparator::setComparator(DomainComparator* comparator) { - //check_error(s_instance == NULL, "The comparator can only be set when it is currently null"); - s_instance = comparator; - } - - bool DomainComparator::comparatorIsNull() { - return s_instance == NULL; } /** @@ -168,7 +147,7 @@ namespace EUROPA { debugMsg("Domain:canBeCompared", "type of domx " << domx.getTypeName().toString() << " type of domy " << domy.getTypeName().toString()); debugMsg("Domain:canBeCompared", domx.toString()); debugMsg("Domain:canBeCompared", domy.toString()); - bool result = DomainComparator::getComparator().canCompare(domx, domy); + bool result = domx.getDataType()->canBeCompared(domy.getDataType()); debugMsg("Domain:canBeCompared", "returning " << result); return result; } diff --git a/src/PLASMA/ConstraintEngine/base/Domain.hh b/src/PLASMA/ConstraintEngine/base/Domain.hh index a31f517ec..ab0bbf82b 100644 --- a/src/PLASMA/ConstraintEngine/base/Domain.hh +++ b/src/PLASMA/ConstraintEngine/base/Domain.hh @@ -69,29 +69,11 @@ namespace EUROPA { DomainComparator(); virtual ~DomainComparator(); - /** - * @brief Retrieve the singleton comparator - */ - static const DomainComparator& getComparator(); - /** * @brief Tests if domains can be compared. */ virtual bool canCompare(const Domain& domx, const Domain& domy) const; - /** - * @brief Set the comparator to be used. Can only be set if it is currently null. - */ - static void setComparator(DomainComparator* comparator); - - /** - * @brief return true iff comparator is null. False otherwise. - */ - bool comparatorIsNull(); - - - private: - static DomainComparator* s_instance; /*!< Access pointer location. Enforces singleton pattern */ }; ostream& operator<<(ostream& os, const Domain& dom); diff --git a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc index e2fd580af..dea2a11f2 100644 --- a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc +++ b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc @@ -53,7 +53,7 @@ namespace EUROPA{ n1->addNeighbour(n2); n2->addNeighbour(n1); if(!recomputeIfNecessary()){ // Most commonly this will be true, meaning no full reprop was required. - s_nextCycle++; + m_nextCycle++; recomputeSingleGraph(n1); } } @@ -118,13 +118,13 @@ namespace EUROPA{ m_requiresUpdate = false; // Increment the cycle count to force all nodes to be tested again. - s_nextCycle++; + m_nextCycle++; // Iterate over all nodes for(std::map::iterator it = m_nodesByVar.begin(); it != m_nodesByVar.end(); ++it){ const ConstraintNodeId& node = it->second; check_error(node.isValid()); - if(!node->hasBeenUpdated(s_nextCycle)) // means we have a new graph to build. + if(!node->hasBeenUpdated(m_nextCycle)) // means we have a new graph to build. recomputeSingleGraph(node); } @@ -132,18 +132,18 @@ namespace EUROPA{ } void EquivalenceClassCollection::recomputeSingleGraph(const ConstraintNodeId& node){ - s_nextGraph++; + m_nextGraph++; // Initialize new graph with an empty set and obtain the reference to fill it up std::set emptySet; std::map >::iterator newGraphEntry = - m_graphsByKey.insert(std::pair >(s_nextGraph, emptySet)).first; + m_graphsByKey.insert(std::pair >(m_nextGraph, emptySet)).first; - check_error(newGraphEntry->first == s_nextGraph); + check_error(newGraphEntry->first == m_nextGraph); std::set& newGraph = newGraphEntry->second; // Now fill it up std::set graphKeysToRemove; - node->update(s_nextCycle, newGraph, s_nextGraph, graphKeysToRemove); + node->update(m_nextCycle, newGraph, m_nextGraph, graphKeysToRemove); check_error(graphKeysToRemove.size() <= 2); for(std::set::iterator it = graphKeysToRemove.begin(); it != graphKeysToRemove.end(); ++it) m_graphsByKey.erase(*it); @@ -175,6 +175,4 @@ namespace EUROPA{ return true; } - int EquivalenceClassCollection::s_nextCycle(0); - int EquivalenceClassCollection::s_nextGraph(0); } diff --git a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh index 7d9e412eb..e0fc73de0 100644 --- a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh +++ b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh @@ -126,8 +126,8 @@ namespace EUROPA{ inferred to be equivalent. This changes when constraints are added or removed. */ bool m_requiresUpdate; /**< Indicates of we must recompute all graps. True of a constraint has been removed. Made false by recomputing. */ - static int s_nextCycle; /**< Monotonically increasing counter used to ensure we do not visit nodes more than once when recomputing a graph.*/ - static int s_nextGraph; /**< Monotnically increasing counter used to allocate new graph keys when the need arises to recompute a graph. The + int m_nextCycle; /**< Monotonically increasing counter used to ensure we do not visit nodes more than once when recomputing a graph.*/ + int m_nextGraph; /**< Monotnically increasing counter used to allocate new graph keys when the need arises to recompute a graph. The cases are when a constraint addition occurs, thus allowing for the possibility of graph merging, or a constraint removal occurs allowing for the possibility of graph splitting. */ }; diff --git a/src/PLASMA/ConstraintEngine/component/Variable.hh b/src/PLASMA/ConstraintEngine/component/Variable.hh index 93b0f3a74..229bdee7c 100644 --- a/src/PLASMA/ConstraintEngine/component/Variable.hh +++ b/src/PLASMA/ConstraintEngine/component/Variable.hh @@ -146,20 +146,24 @@ namespace EUROPA { const DomainType& Variable::getDerivedDomain() { if (!getConstraintEngine()->isPropagating() && pending()) update(); - - if (!provenInconsistent()) - return(*m_derivedDomain); - - static bool sl_initialized = false; - static DomainType* sl_emptyDomain = 0; - if (!sl_initialized) { - sl_emptyDomain = static_cast(m_derivedDomain->copy()); - if (sl_emptyDomain->isOpen()) - sl_emptyDomain->close(); - sl_emptyDomain->empty(); - sl_initialized = true; - } - return(*sl_emptyDomain); + + if(provenInconsistent()) + m_derivedDomain->empty(); + return *m_derivedDomain; + + // if (!provenInconsistent()) + // return(*m_derivedDomain); + + // static bool sl_initialized = false; + // static DomainType* sl_emptyDomain = 0; + // if (!sl_initialized) { + // sl_emptyDomain = static_cast(m_derivedDomain->copy()); + // if (sl_emptyDomain->isOpen()) + // sl_emptyDomain->close(); + // sl_emptyDomain->empty(); + // sl_initialized = true; + // } + // return(*sl_emptyDomain); } template diff --git a/src/PLASMA/ConstraintEngine/test/domain-tests.cc b/src/PLASMA/ConstraintEngine/test/domain-tests.cc index 97c31c0f8..4064b11a0 100644 --- a/src/PLASMA/ConstraintEngine/test/domain-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/domain-tests.cc @@ -1257,7 +1257,7 @@ namespace EUROPA { EUROPA_runTest(testIntersection); EUROPA_runTest(testSubset); EUROPA_runTest(testIntDomain); - EUROPA_runTest(testDomainComparatorConfiguration); + // EUROPA_runTest(testDomainComparatorConfiguration); EUROPA_runTest(testCopying); EUROPA_runTest(testSymbolicVsNumeric); return(true); diff --git a/src/PLASMA/ConstraintEngine/test/module-tests.cc b/src/PLASMA/ConstraintEngine/test/module-tests.cc index 76b9d4b2d..b0b590b31 100644 --- a/src/PLASMA/ConstraintEngine/test/module-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/module-tests.cc @@ -1,22 +1,22 @@ -#include "ce-test-module.hh" +#include "ce-test-module.hh" #include "module-tests.hh" -#include "DataTypes.hh" -#include "CppUnitUtils.hh" - -CPPUNIT_TEST_SUITE_REGISTRATION( ConstraintEngineModuleTests ); - -using namespace EUROPA; - -int main( int argc, char **argv) -{ - // Init data types so that id counts don't fail - VoidDT::instance(); - BoolDT::instance(); - IntDT::instance(); - FloatDT::instance(); - StringDT::instance(); - SymbolDT::instance(); - - RUN_CPP_UNIT_MODULE(true); -} +#include "DataTypes.hh" +#include "CppUnitUtils.hh" + +CPPUNIT_TEST_SUITE_REGISTRATION( ConstraintEngineModuleTests ); + +using namespace EUROPA; + +int main( int argc, char **argv) +{ + // Init data types so that id counts don't fail + VoidDT::instance(); + BoolDT::instance(); + IntDT::instance(); + FloatDT::instance(); + StringDT::instance(); + SymbolDT::instance(); + + RUN_CPP_UNIT_MODULE(true); +} diff --git a/src/PLASMA/NDDL/base/NddlRules.cc b/src/PLASMA/NDDL/base/NddlRules.cc index 5cfe069eb..b881358f5 100644 --- a/src/PLASMA/NDDL/base/NddlRules.cc +++ b/src/PLASMA/NDDL/base/NddlRules.cc @@ -11,22 +11,20 @@ namespace NDDL { /** - * @brief Strip out values delimited in the string. Return by ref to avoid - * unnecessary copying. + * @brief Strip out values delimited in the string. */ - const std::list& listFromString(const std::string& str, bool isNumeric){ + std::list listFromString(const std::string& str, bool isNumeric){ static const std::string sl_delimiter("$"); - static std::list sl_values; - sl_values.clear(); + std::list values; std::vector tokens; tokenize(str, tokens, sl_delimiter); for(std::vector::const_iterator it = tokens.begin(); it != tokens.end(); ++it){ if(isNumeric) - sl_values.push_back(toValue(*it)); + values.push_back(toValue(*it)); else - sl_values.push_back(LabelStr(*it)); + values.push_back(LabelStr(*it)); } - return sl_values; + return values; } TokenId allocateOnSameObject(const TokenId& master, const LabelStr& predicateSuffix, const LabelStr& relationToMaster){ diff --git a/src/PLASMA/NDDL/base/NddlRules.hh b/src/PLASMA/NDDL/base/NddlRules.hh index fd94013ed..8a0aaf918 100644 --- a/src/PLASMA/NDDL/base/NddlRules.hh +++ b/src/PLASMA/NDDL/base/NddlRules.hh @@ -27,10 +27,9 @@ namespace NDDL { #define predicateVariable(domain) allocateVariable(getPlanDatabase()->getConstraintEngine(), m_pseudoVariables, domain, getId()) /** - * @brief Function to detokenize a delimited list into a list. List is an internal static - * and is reset each time. + * @brief Function to detokenize a delimited list into a list. */ - const std::list& listFromString(const std::string& str, bool isNumeric); + std::list listFromString(const std::string& str, bool isNumeric); /** * @brief Function to allocate a token on the same object as the master diff --git a/src/PLASMA/NDDL/test/nddl-test-module.cc b/src/PLASMA/NDDL/test/nddl-test-module.cc index 2233e8ec3..75cedb5e8 100644 --- a/src/PLASMA/NDDL/test/nddl-test-module.cc +++ b/src/PLASMA/NDDL/test/nddl-test-module.cc @@ -26,7 +26,7 @@ class UtilitiesTest { public: static bool test() { std::string tokenizedString("A$B$C$D$"); - const std::list& tokens = listFromString(tokenizedString, false); + const std::list tokens = listFromString(tokenizedString, false); CPPUNIT_ASSERT(tokens.size() == 4); std::string newString; for(std::list::const_iterator it = tokens.begin(); it != tokens.end(); ++it){ @@ -36,7 +36,7 @@ class UtilitiesTest { CPPUNIT_ASSERT(newString == tokenizedString); std::string numberStr("1$2.45$3.04$-8.9$"); - const std::list& numbers= listFromString(numberStr, true); + const std::list numbers= listFromString(numberStr, true); edouble sum = 0; for(std::list::const_iterator it = numbers.begin(); it != numbers.end(); ++it){ diff --git a/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc b/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc index 6b7250b9a..f19c80423 100644 --- a/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc +++ b/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc @@ -13,11 +13,6 @@ namespace EUROPA { - static bool & planDatabaseInitialized() { - static bool sl_alreadyDone(false); - return sl_alreadyDone; - } - ModulePlanDatabase::ModulePlanDatabase() : Module("PlanDatabase") { @@ -30,15 +25,10 @@ namespace EUROPA { void ModulePlanDatabase::initialize() { - if(planDatabaseInitialized()) - return; - - planDatabaseInitialized() = true; } void ModulePlanDatabase::uninitialize() { - planDatabaseInitialized() = false; } class NddlXmlTxnInterpreter : public LanguageInterpreter diff --git a/src/PLASMA/PlanDatabase/base/Schema.cc b/src/PLASMA/PlanDatabase/base/Schema.cc index 6ca6266c3..d12e3ffb2 100644 --- a/src/PLASMA/PlanDatabase/base/Schema.cc +++ b/src/PLASMA/PlanDatabase/base/Schema.cc @@ -87,7 +87,7 @@ namespace EUROPA { if(isObjectType(domx.getTypeName()) || isObjectType(domy.getTypeName())) return(isObjectType(domx.getTypeName()) && isObjectType(domy.getTypeName())); - return DomainComparator::canCompare(domx, domy); + return domx.getDataType()->canBeCompared(domy.getDataType()); } void Schema::reset(){ diff --git a/src/PLASMA/Solvers/base/FlawHandler.cc b/src/PLASMA/Solvers/base/FlawHandler.cc index 3f8d943f4..eb99eda7b 100644 --- a/src/PLASMA/Solvers/base/FlawHandler.cc +++ b/src/PLASMA/Solvers/base/FlawHandler.cc @@ -19,11 +19,10 @@ namespace EUROPA { namespace SOLVERS { - TiXmlElement* FlawHandler::s_element = NULL; FlawHandler::FlawHandler(const TiXmlElement& configData): - MatchingRule(static_cast(*(makeConfigData(configData)))), - m_configData(s_element), + MatchingRule(configData), + m_configData(makeConfigData(configData)), m_guards(readGuards(configData, false)), m_masterGuards(readGuards(configData, true)){ @@ -58,22 +57,22 @@ namespace EUROPA { checkError(strcmp(configData.Value(), "FlawHandler") == 0, "Invalid Tag of " << configData.Value()); checkError(configData.Parent() != NULL, "Must have a parent to get the default properties."); - s_element = static_cast(configData.Clone()); + TiXmlElement* element = static_cast(configData.Clone()); TiXmlElement* parent = (TiXmlElement*) configData.Parent(); - if(s_element->Attribute("priority") == NULL){ + if(element->Attribute("priority") == NULL){ if(parent->Attribute("defaultPriority") != NULL) - s_element->SetAttribute("priority", parent->Attribute("defaultPriority")); + element->SetAttribute("priority", parent->Attribute("defaultPriority")); else - s_element->SetAttribute("priority", "99999"); + element->SetAttribute("priority", "99999"); } - if(s_element->Attribute("maxChoices") == NULL){ + if(element->Attribute("maxChoices") == NULL){ // Set a default of 0 which implies no cut to be applied - s_element->SetAttribute("maxChoices", "0"); + element->SetAttribute("maxChoices", "0"); } - return s_element; + return element; } FlawHandler::~FlawHandler(){ diff --git a/src/PLASMA/Solvers/base/FlawHandler.hh b/src/PLASMA/Solvers/base/FlawHandler.hh index 2d4119ff2..d4e35e4e8 100644 --- a/src/PLASMA/Solvers/base/FlawHandler.hh +++ b/src/PLASMA/Solvers/base/FlawHandler.hh @@ -200,8 +200,6 @@ namespace EUROPA { static TiXmlElement* makeConfigData(const TiXmlElement& configData); - static TiXmlElement* s_element; /*!< Temporary holder for copied elements */ - const PlanDatabaseId& getPlanDatabase(const ConstrainedVariableId& tokenVar); PlanDatabaseId m_db; diff --git a/src/PLASMA/Utils/base/DebugMsg.cc b/src/PLASMA/Utils/base/DebugMsg.cc index 88af3e571..492ad0fce 100755 --- a/src/PLASMA/Utils/base/DebugMsg.cc +++ b/src/PLASMA/Utils/base/DebugMsg.cc @@ -10,7 +10,12 @@ #include #include #include +#include +#include +#include + #include "DebugMsg.hh" +#include "Mutex.hh" /** * @class DebugConfig @@ -33,106 +38,179 @@ class DebugConfig { } }; +class DebugMessage::DebugInternals { + public: + DebugInternals() + : m_allEnabled(false), m_msgs(), m_patterns() {} + std::vector& allMsgs() {return m_msgs;} + std::vector enabledPatterns() {return m_patterns;} + bool allEnabled() const {return m_allEnabled;} + void enableAll() { + m_allEnabled = true; + m_patterns.clear(); + std::for_each(m_msgs.begin(), m_msgs.end(), std::mem_fun(&DebugMessage::enable)); + } + + void disableAll() { + m_allEnabled = false; + m_patterns.clear(); + std::for_each(m_msgs.begin(), + m_msgs.end(), + std::mem_fun(&DebugMessage::disable)); + } + + void enableMatchingMsgs(const std::string& file, + const std::string& pattern) { + if (file.length() < 1 && pattern.length() < 1) { + enableAll(); + return; + } + DebugPattern dp(file, pattern); + m_patterns.push_back(dp); + std::for_each(m_msgs.begin(), + m_msgs.end(), + EnableMatches(dp)); + } + + void disableMatchingMsgs(const std::string& file, + const std::string& pattern) { + if(file.length() < 1 && pattern.length() < 1) + return; + + DebugPattern dp(file, pattern); + m_patterns.erase(std::find(m_patterns.begin(), m_patterns.end(), dp)); + std::for_each(m_msgs.begin(), + m_msgs.end(), + DisableMatches(dp)); + + } + + + DebugMessage *addMsg(const std::string &file, const int& line, + const std::string &marker) { + DebugConfig::init(); + check_error(line > 0, "debug messages must have positive line numbers", + DebugErr::DebugMessageError()); + check_error(!file.empty() && !marker.empty(), "debug messages must have non-empty file and marker", + DebugErr::DebugMessageError()); + DebugMessage *msg = findMsg(file, marker); + if (msg == 0) { + msg = new DebugMessage(file, line, marker); + check_error(msg != 0, "no memory for new debug message", + DebugErr::DebugMemoryError()); + m_msgs.push_back(msg); + if (!msg->isEnabled()) { + typedef std::vector::iterator LDPI; + LDPI iter = std::find_if(m_patterns.begin(), + m_patterns.end(), + PatternMatches(*msg)); + if (iter != m_patterns.end()) + msg->enable(); + } + } + return(msg); + } + + DebugMessage* findMsg(const std::string &file, + const std::string &pattern) { + typedef std::vector::const_iterator LDMPCI; + LDMPCI iter = std::find_if(m_msgs.begin(), + m_msgs.end(), + MatchesPattern(file, pattern)); + if (iter == allMsgs().end()) + return(0); + return(*iter); + } + + void findMatchingMsgs(const std::string &file, + const std::string &pattern, + std::list &matches) { + std::for_each(m_msgs.begin(), m_msgs.end(), GetMatches(file, pattern, matches)); + } + + private: + bool m_allEnabled; + std::vector m_msgs; + std::vector m_patterns; +}; + + +namespace { + +static DebugMessage::DebugInternals debugInternals; +static pthread_mutex_t debugMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +typedef std::pair > +internals_accessor; + +internals_accessor internals() { + EUROPA::MutexGrabber grabber(debugMutex); + return std::make_pair >(grabber, + std::tr1::ref(debugInternals)); +} + +} + DebugMessage::DebugMessage(const std::string& file, const int& line, - const std::string& marker, - const bool& enabled) + const std::string& marker) : m_file(file), m_line(line), m_marker(marker), - m_enabled(enabled) { + m_enabled(false) { + internals_accessor i = internals(); + m_enabled = i.second.get().allEnabled(); } DebugMessage *DebugMessage::addMsg(const std::string &file, const int& line, const std::string &marker) { - DebugConfig::init(); - check_error(line > 0, "debug messages must have positive line numbers", - DebugErr::DebugMessageError()); - check_error(!file.empty() && !marker.empty(), "debug messages must have non-empty file and marker", - DebugErr::DebugMessageError()); - DebugMessage *msg = findMsg(file, marker); - if (msg == 0) { - msg = new DebugMessage(file, line, marker); - check_error(msg != 0, "no memory for new debug message", - DebugErr::DebugMemoryError()); - allMsgs().push_back(msg); - if (!msg->isEnabled()) { - typedef std::list::iterator LDPI; - LDPI iter = std::find_if(enabledPatterns().begin(), - enabledPatterns().end(), - PatternMatches(*msg)); - if (iter != enabledPatterns().end()) - msg->enable(); - } - } - return(msg); + return internals().second.get().addMsg(file, line, marker); } DebugMessage *DebugMessage::findMsg(const std::string &file, const std::string &pattern) { - typedef std::list::const_iterator LDMPCI; - LDMPCI iter = std::find_if(allMsgs().begin(), - allMsgs().end(), - MatchesPattern(file, pattern)); - if (iter == allMsgs().end()) - return(0); - return(*iter); + return internals().second.get().findMsg(file, pattern); } void DebugMessage::findMatchingMsgs(const std::string &file, const std::string &pattern, std::list &matches) { - std::for_each(allMsgs().begin(), allMsgs().end(), GetMatches(file, pattern, matches)); + internals().second.get().findMatchingMsgs(file, pattern, matches); } -const std::list& DebugMessage::getAllMsgs() { - return(allMsgs()); +std::list DebugMessage::getAllMsgs() { + internals_accessor i = internals(); + std::list retval(i.second.get().allMsgs().begin(), + i.second.get().allMsgs().end()); + + return retval; } void DebugMessage::enableAll() { - allEnabled() = true; - enabledPatterns().clear(); - std::for_each(allMsgs().begin(), - allMsgs().end(), - std::mem_fun(&DebugMessage::enable)); + internals().second.get().enableAll(); } void DebugMessage::disableAll() { - allEnabled() = false; - enabledPatterns().clear(); - std::for_each(allMsgs().begin(), - allMsgs().end(), - std::mem_fun(&DebugMessage::disable)); + internals().second.get().disableAll(); } void DebugMessage::enableMatchingMsgs(const std::string& file, const std::string& pattern) { - if (file.length() < 1 && pattern.length() < 1) { - enableAll(); - return; - } - DebugPattern dp(file, pattern); - enabledPatterns().push_back(dp); - std::for_each(allMsgs().begin(), - allMsgs().end(), - EnableMatches(dp)); + internals().second.get().enableMatchingMsgs(file, pattern); } void DebugMessage::disableMatchingMsgs(const std::string& file, const std::string& pattern) { - if(file.length() < 1 && pattern.length() < 1) - return; - - DebugPattern dp(file, pattern); - enabledPatterns().erase(std::find(enabledPatterns().begin(), enabledPatterns().end(), dp)); - std::for_each(allMsgs().begin(), - allMsgs().end(), - DisableMatches(dp)); + internals().second.get().disableMatchingMsgs(file, pattern); } bool DebugMessage::readConfigFile(std::istream& is) { check_error(is.good(), "cannot read debug config from invalid/error'd stream", DebugErr::DebugConfigError()); + internals_accessor a = internals(); + std::string input; while (is.good() && !is.eof()) { getline(is, input); @@ -159,7 +237,7 @@ bool DebugMessage::readConfigFile(std::istream& is) { pattern = input.substr(i + 1); input = input.substr(0, i); } - enableMatchingMsgs(input, pattern); + a.second.get().enableMatchingMsgs(input, pattern); } check_error(is.eof(), "error while reading debug config file", DebugErr::DebugConfigError()); diff --git a/src/PLASMA/Utils/base/DebugMsg.hh b/src/PLASMA/Utils/base/DebugMsg.hh index 9c84c21d9..ae94131b1 100755 --- a/src/PLASMA/Utils/base/DebugMsg.hh +++ b/src/PLASMA/Utils/base/DebugMsg.hh @@ -162,8 +162,7 @@ private: * @note Should only be called from static member functions. */ DebugMessage(const std::string& file, const int& line, - const std::string& marker, - const bool& enabled = DebugMessage::allEnabled()); + const std::string& marker); /** * @class DebugPattern Debug.hh @@ -192,6 +191,13 @@ private: : m_file(f), m_pattern(m) { } + DebugPattern(const DebugPattern& o) : m_file(o.m_file), m_pattern(o.m_pattern) {} + + DebugPattern& operator=(const DebugPattern& o) { + const_cast(m_file) = o.m_file; + const_cast(m_pattern) = o.m_pattern; + return *this; + } /** * @brief The source file(s) that matches the pattern. */ @@ -215,6 +221,7 @@ private: } public: + class DebugInternals; /** @brief Create a new DebugMessage. Should only be called from the @@ -270,7 +277,7 @@ public: /** @brief Get list of all debug known messages. */ - static const std::list& getAllMsgs(); + static std::list getAllMsgs(); /** @brief Enable all debug messages, including ones not yet created. @@ -416,7 +423,6 @@ public: } private: - /** @brief The pointer to the stream being used. @note Has to be a pointer because some C++ compiler @@ -427,22 +433,6 @@ private: return(s_debugStream); } - /** - @brief List of pointers to all debug messages. - */ - static std::list& allMsgs() { - static std::list s_msgs; - return(s_msgs); - } - - /** - @brief List of all enabled debug patterns. - */ - static std::list& enabledPatterns() { - static std::list s_patterns; - return(s_patterns); - } - /** @brief File given when this instance was created. */ diff --git a/src/PLASMA/Utils/base/Entity.cc b/src/PLASMA/Utils/base/Entity.cc index 5d551dcc7..194158c1a 100644 --- a/src/PLASMA/Utils/base/Entity.cc +++ b/src/PLASMA/Utils/base/Entity.cc @@ -1,51 +1,161 @@ #include "Entity.hh" #include "Debug.hh" +#include "Mutex.hh" + #include +#include namespace EUROPA { +class EntityInternals { + public: + EntityInternals(): m_entitiesByKey(), m_discardedEntities(), m_purgeStatus(false), + m_gcActive(false), m_gcRequired(false), m_key(0) {} + + eint allocateKey(const Entity* const e){ + eint retval = m_key++; + m_entitiesByKey.insert(std::make_pair(retval, + reinterpret_cast(e))); + return retval; + } + + void erase(const eint key) { + m_entitiesByKey.erase(key); + } + EntityId getEntity(const eint key) const { + EntityId entity; + std::map::const_iterator it = m_entitiesByKey.find(key); + if(it != m_entitiesByKey.end()) + entity = static_cast(it->second); + return entity; + } + void getEntities(std::set& resultSet) const { + for(std::map::const_iterator it = m_entitiesByKey.begin(); + it != m_entitiesByKey.end(); + ++it){ + resultSet.insert(static_cast(it->second)); + } - Entity::Entity(): m_key(allocateKey()), m_refCount(1), m_discarded(false){ - entitiesByKey().insert(std::make_pair(m_key, (unsigned long int) this)); - check_error(!isPurging()); - debugMsg("Entity:Entity", "Allocating " << m_key); } + void purgeStarted() { + check_error(!m_purgeStatus); + m_purgeStatus = true; + } + void purgeEnded() { + check_error(m_purgeStatus); + m_purgeStatus = false; + } + bool isPurging() const { + return m_purgeStatus; + } + bool isPooled(Entity* e) const { + return m_discardedEntities.find(e) != m_discardedEntities.end(); + } + bool gcActive() const {return m_gcActive;} + unsigned int garbageCollect() { + // Flag activation of garbage collector + m_gcActive = true; + + unsigned int count(0); + while(!m_discardedEntities.empty()){ + std::set::iterator it = m_discardedEntities.begin(); + Entity* entity = *it; + m_discardedEntities.erase(entity); + checkError(isPurging() || entity->canBeDeleted(), + "Key:" << entity->getKey() << " RefCount:" << entity->refCount()); + debugMsg("Entity:garbageCollect", + "Garbage collecting entity " << entity->getEntityName() << "(" << + entity->getKey() << ")"); + delete (Entity*) entity; + count++; + } - Entity::~Entity(){ - checkError(gcActive() || ! gcRequired(), m_key << " deleted outside of gabage collection when prohibited from doing so."); - discardedEntities().erase(this); - discard(false); + // Flag completion of garbage collector + m_gcActive = false; + + return count; + + } + bool gcRequired() const {return m_gcRequired;} + void discard(Entity* e) { + m_discardedEntities.erase(e); } + void pool(Entity* e) { + m_discardedEntities.insert(e); + } + private: + EntityInternals(const EntityInternals& o); + + std::map m_entitiesByKey; + std::set m_discardedEntities; + bool m_purgeStatus, m_gcActive, m_gcRequired; + int m_key; +}; - void Entity::handleDiscard(){ - if(!Entity::isPurging()){ - // Notify dependents - for(std::set::const_iterator it = m_dependents.begin(); it != m_dependents.end(); ++it){ - Entity* entity = *it; - entity->notifyDiscarded(this); - } +namespace { +static EntityInternals entityInternals; +static pthread_mutex_t entityMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +typedef std::pair > +internals_accessor; +internals_accessor internals() { + MutexGrabber grabber(entityMutex); + return std::make_pair >(grabber, + std::tr1::ref(entityInternals)); +} +} - m_dependents.clear(); - check_error(m_externalEntity.isNoId() || m_externalEntity.isValid()); - // If this entity has been integrated with an external entity, then delete the external - // entity. - if(!m_externalEntity.isNoId()) - m_externalEntity->discard(); +Entity::Entity(): m_key(0), m_refCount(1), m_discarded(false){ + internals_accessor i(internals()); + m_key = i.second.get().allocateKey(this); + check_error(!i.second.get().isPurging()); + debugMsg("Entity:Entity", "Allocating " << m_key); +} - debugMsg("Entity:discard", "Deallocating " << m_key); +Entity::~Entity(){ + internals_accessor i = internals(); + checkError(i.second.get().gcActive() || !i.second.get().gcRequired(), + m_key << " deleted outside of gabage collection when prohibited from " << + "doing so."); + i.second.get().discard(this); + discard(false); +} - condDebugMsg(!canBeDeleted(), "Entity:warning", - "(" << getKey() << ") being deleted with " << m_refCount << " outstanding references."); +void Entity::handleDiscard(){ + internals_accessor i = internals(); + if(!i.second.get().isPurging()){ + //explicitly releasing the mutex here because these notifications may cause + //client code to get executed + i.first.release(); + // Notify dependents + for(std::set::const_iterator it = m_dependents.begin(); it != m_dependents.end(); ++it){ + Entity* entity = *it; + entity->notifyDiscarded(this); } - entitiesByKey().erase(m_key); - } + + m_dependents.clear(); + + check_error(m_externalEntity.isNoId() || m_externalEntity.isValid()); + // If this entity has been integrated with an external entity, then delete the external + // entity. + if(!m_externalEntity.isNoId()) + m_externalEntity->discard(); + + debugMsg("Entity:discard", "Deallocating " << m_key); + + condDebugMsg(!canBeDeleted(), "Entity:warning", + "(" << getKey() << ") being deleted with " << m_refCount << " outstanding references."); + } + i.second.get().erase(m_key); +} - const std::string& Entity::getEntityType() const { - static const std::string ENTITY_STR("Entity"); - return ENTITY_STR; - } +const std::string& Entity::getEntityType() const { + static const std::string ENTITY_STR("Entity"); + return ENTITY_STR; +} std::string Entity::toString() const { @@ -72,20 +182,12 @@ namespace EUROPA { bool Entity::canBeCompared(const EntityId&) const{ return true;} - EntityId Entity::getEntity(eint key){ - EntityId entity; - std::map::const_iterator it = entitiesByKey().find(key); - if(it != entitiesByKey().end()) - entity = (EntityId) it->second; - return entity; + EntityId Entity::getEntity(const eint key){ + return internals().second.get().getEntity(key); } void Entity::getEntities(std::set& resultSet){ - for(std::map::const_iterator it = entitiesByKey().begin(); - it != entitiesByKey().end(); - ++it){ - resultSet.insert((EntityId) it->second); - } + return internals().second.get().getEntities(resultSet); } void Entity::setExternalEntity(const EntityId& externalEntity){ @@ -111,33 +213,21 @@ namespace EUROPA { return m_externalEntity; } - std::map& Entity::entitiesByKey(){ - static std::map sl_entitiesByKey; - return sl_entitiesByKey; - } - const PSEntity* Entity::getExternalPSEntity() const { return (const PSEntity*) getExternalEntity(); } void Entity::purgeStarted(){ - check_error(!isPurging()); - getPurgeStatus() = true; - } - - void Entity::purgeEnded(){ - check_error(isPurging()); - getPurgeStatus() = false; + internals().second.get().purgeStarted(); } - bool Entity::isPurging(){ - return getPurgeStatus(); - } +void Entity::purgeEnded(){ + internals().second.get().purgeEnded(); +} - bool& Entity::getPurgeStatus(){ - static bool sl_isPurging(false); - return sl_isPurging; - } +bool Entity::isPurging(){ + return internals().second.get().isPurging(); +} unsigned int Entity::refCount() const { return m_refCount; } @@ -171,7 +261,7 @@ namespace EUROPA { handleDiscard(); if(pool) - discardedEntities().insert(this); + internals().second.get().pool(this); } bool Entity::isDiscarded() const { @@ -189,54 +279,10 @@ namespace EUROPA { void Entity::notifyDiscarded(const Entity* entity) {} bool Entity::isPooled(Entity* entity) { - std::set& entities = discardedEntities(); - return entities.find(entity) != entities.end(); + return internals().second.get().isPooled(entity); } unsigned int Entity::garbageCollect(){ - // Flag activation of garbage collector - gcActive() = true; - - std::set& entities = discardedEntities(); - unsigned int count(0); - while(!entities.empty()){ - std::set::iterator it = entities.begin(); - Entity* entity = *it; - entities.erase(entity); - checkError(isPurging() || entity->canBeDeleted(), - "Key:" << entity->getKey() << " RefCount:" << entity->refCount()); - debugMsg("Entity:garbageCollect", "Garbage collecting entity " << entity->getEntityName() << "(" << entity->getKey() << ")"); - delete (Entity*) entity; - count++; - } - - // Flag completion of garbage collector - gcActive() = false; - - return count; - } - - bool& Entity::gcActive(){ - static bool sl_val(false); - return sl_val; + return internals().second.get().garbageCollect(); } - - bool& Entity::gcRequired(){ - static bool sl_val(false); - return sl_val; - } - - std::set& Entity::discardedEntities(){ - static std::set sl_instance; - return sl_instance; - } - - eint Entity::allocateKey(){ - static eint sl_key(0); - sl_key++; - return sl_key; - } - - - } diff --git a/src/PLASMA/Utils/base/Entity.hh b/src/PLASMA/Utils/base/Entity.hh index 3dc11bc76..bbae12d4e 100644 --- a/src/PLASMA/Utils/base/Entity.hh +++ b/src/PLASMA/Utils/base/Entity.hh @@ -8,6 +8,7 @@ #include #include #include +#include #include "PSUtils.hh" @@ -165,10 +166,6 @@ namespace EUROPA{ */ static unsigned int garbageCollect(); - /** - * @brief Configure system to require garbage collection - */ - static bool& gcRequired(); protected: Entity(); @@ -182,28 +179,16 @@ namespace EUROPA{ private: - - static eint allocateKey(); - - - /** - * @brief Internal variable indicating if garbage collection is active - */ - static bool& gcActive(); - /** * @brief Subclasses should over-ride this to handle special data structure management. */ virtual void notifyDiscarded(const Entity* entity); - const eint m_key; + eint m_key; unsigned int m_refCount; bool m_discarded; std::set m_dependents; - static std::map& entitiesByKey(); - static std::set& discardedEntities(); - static bool& getPurgeStatus(); }; /** diff --git a/src/PLASMA/Utils/base/Error.cc b/src/PLASMA/Utils/base/Error.cc index c0a6d6d25..457fb15ef 100644 --- a/src/PLASMA/Utils/base/Error.cc +++ b/src/PLASMA/Utils/base/Error.cc @@ -22,6 +22,7 @@ /* Contains the rest of this file */ #include "Error.hh" +#include "Mutex.hh" #ifdef __BEOS__ #include @@ -32,6 +33,9 @@ bool Error::s_throw = false; bool Error::s_printErrors = true; bool Error::s_printWarnings = true; +namespace { +pthread_mutex_t outputMutex = PTHREAD_MUTEX_INITIALIZER; +} Error::Error(const std::string& condition, const std::string& file, const int& line) : m_condition(condition), m_file(file), m_line(line), m_type("Error") { if (s_os == 0) @@ -82,6 +86,7 @@ void Error::display() { return; std::cout.flush(); std::cerr.flush(); + EUROPA::MutexGrabber grabber(outputMutex); getStream() << '\n' << m_file << ':' << m_line << ": Error: " << m_condition << " is false"; if (!m_msg.empty()) getStream() << "\n\t" << m_msg; @@ -93,6 +98,7 @@ void Error::printWarning(const std::string& msg, const int& line) { if (!displayWarnings()) return; + EUROPA::MutexGrabber grabber(outputMutex); getStream() << file << ':' << line << ": Warning: " << msg << std::endl; } diff --git a/src/PLASMA/Utils/base/Mutex.cc b/src/PLASMA/Utils/base/Mutex.cc index 516704e14..bdd1d13e6 100644 --- a/src/PLASMA/Utils/base/Mutex.cc +++ b/src/PLASMA/Utils/base/Mutex.cc @@ -4,14 +4,23 @@ namespace EUROPA { MutexGrabber::MutexGrabber(pthread_mutex_t& m) - : m_mutex(m) -{ - pthread_mutex_lock( &m_mutex ); + : m_mutex(m), m_needsRelease(true) { + pthread_mutex_lock( &m_mutex ); } - -MutexGrabber::~MutexGrabber() -{ + +MutexGrabber::MutexGrabber(const MutexGrabber& o) + : m_mutex(o.m_mutex), m_needsRelease(true) { + const_cast(o).m_needsRelease = false; +} + +void MutexGrabber::release() { + if(m_needsRelease) { pthread_mutex_unlock( &m_mutex ); + m_needsRelease = false; + } +} +MutexGrabber::~MutexGrabber() { + release(); } } diff --git a/src/PLASMA/Utils/base/Mutex.hh b/src/PLASMA/Utils/base/Mutex.hh index ce6b5915b..9207a9d13 100644 --- a/src/PLASMA/Utils/base/Mutex.hh +++ b/src/PLASMA/Utils/base/Mutex.hh @@ -4,15 +4,16 @@ #include namespace EUROPA { - class MutexGrabber - { - public: - MutexGrabber(pthread_mutex_t& m); - ~MutexGrabber(); - - protected: - pthread_mutex_t& m_mutex; - }; +class MutexGrabber { + public: + MutexGrabber(pthread_mutex_t& m); + MutexGrabber(const MutexGrabber& o); //make a move constructor for C++11 + ~MutexGrabber(); + void release(); + protected: + pthread_mutex_t& m_mutex; + bool m_needsRelease; +}; } #endif diff --git a/src/PLASMA/Utils/base/StringErrorStream.hh b/src/PLASMA/Utils/base/StringErrorStream.hh index 749b58c5d..4fc12b29b 100644 --- a/src/PLASMA/Utils/base/StringErrorStream.hh +++ b/src/PLASMA/Utils/base/StringErrorStream.hh @@ -1,45 +1,49 @@ /** - @file StringErrorStream.hh - @author Tatiana Kichkaylo + @file StringErrorStream.hh + @author Tatiana Kichkaylo - @brief Wrapper for string stream to be passed to Error so that the output - of engine/parser could be captured and passed through Swig interfaces. - */ + @brief Wrapper for string stream to be passed to Error so that the output + of engine/parser could be captured and passed through Swig interfaces. +*/ #ifndef _H_String_Error #define _H_String_Error #include "Error.hh" +#include "Mutex.hh" #include #include /** - @class StringErrorStream - @brief Static string buffer to collect output from Error printing. - */ + @class StringErrorStream + @brief Static string buffer to collect output from Error printing. +*/ class StringErrorStream { -public: - /** @brief Set static output stream of Error to this class's string stream */ - inline static void setErrorStreamToString() { - std::cout << "Taking over error stream\n"; - Error::setStream(stringStream); - } - - /** - @brief Get string accumulated in the string stream and clean up the stream. - */ - static std::string retrieveString() { - std::string copy = stringStream.str(); - stringStream.str(""); - return copy; - } - -private: - /** Stream for accumulation of messages */ - static std::stringstream stringStream; + public: + /** @brief Set static output stream of Error to this class's string stream */ + inline static void setErrorStreamToString() { + std::cout << "Taking over error stream\n"; + Error::setStream(stringStream); + } + + /** + @brief Get string accumulated in the string stream and clean up the stream. + */ + static std::string retrieveString() { + EUROPA::MutexGrabber grabber(s_mutex); + std::string copy = stringStream.str(); + stringStream.str(""); + return copy; + } + + private: + /** Stream for accumulation of messages */ + static std::stringstream stringStream; + static pthread_mutex_t s_mutex; }; std::stringstream StringErrorStream::stringStream; +pthread_mutex_t StringErrorStream::s_mutex = PTHREAD_MUTEX_INITIALIZER; #endif /* _H_String_Error */ From 5b3da1dc664ac92f18a7c31d59f0a70ce11a8b5f Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 21 Aug 2014 18:02:28 +0000 Subject: [PATCH 013/149] -Changed some indentation -Added two Reservoir tests to try to reproduce issues 71 and 147, but neither worked. Keeping the tests, however. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6743 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/Resource/component/Reservoir.hh | 47 +++++---- .../Resource/test/rs-flow-test-module.cc | 19 ++-- src/PLASMA/Resource/test/rs-test-module.cc | 95 ++++++++++++++++++- 3 files changed, 128 insertions(+), 33 deletions(-) diff --git a/src/PLASMA/Resource/component/Reservoir.hh b/src/PLASMA/Resource/component/Reservoir.hh index b37667b8a..8b545bb83 100644 --- a/src/PLASMA/Resource/component/Reservoir.hh +++ b/src/PLASMA/Resource/component/Reservoir.hh @@ -8,27 +8,32 @@ namespace EUROPA { - class Reservoir : public Resource { - public: - /** - * @brief Constructor. This is primarily a convenience constructor for resource interactions outside of a model. - * @param planDatabase @see Object - * @param type @see Object - * @param name @see Object - * @param initCapacityLb The lower bound of the Resource's initial level. (For example, a battery may be only half charged initially.) - * @param initCapacityUb The upper bound of the Resource's initial level. (For example, a battery may be only half charged initially.) - * @param lowerLimit The lower capacity limit. (For example, a battery can't have less than no energy stored, or it might be considered unsafe to allow - * the capacity to get below 25%.) - * @param upperLimit The upper capacity limit. (For example, a battery has a maximum charge, or it might be unsafe to fill a beaker more than three-quarters full.) - * @param maxInstProduction The maximum amount of production possible at an instant. (For example, a power bus might only allow 2.5A to be drawn at one instant.) - * @param maxInstConsumption The maximum amount of consumption possible at an instant. (For example, a power bus might only allow 2.5A to be drawn at one instant.) - * @param maxProduction The maximum amount of production possible on this resource. - * @param maxConsumption The maximum amount of consumption possible on this resource. - */ - Reservoir(const PlanDatabaseId& planDatabase, const LabelStr& type, const LabelStr& name, const LabelStr& detectorName, const LabelStr& profileName, - edouble initCapacityLb = 0, edouble initCapacityUb = 0, edouble lowerLimit = MINUS_INFINITY, - edouble upperLimit = PLUS_INFINITY, edouble maxInstProduction = PLUS_INFINITY, edouble maxInstConsumption = PLUS_INFINITY, - edouble maxProduction = PLUS_INFINITY, edouble maxConsumption = PLUS_INFINITY); +class Reservoir : public Resource { + public: + /** + * @brief Constructor. This is primarily a convenience constructor for resource interactions outside of a model. + * @param planDatabase @see Object + * @param type @see Object + * @param name @see Object + * @param initCapacityLb The lower bound of the Resource's initial level. (For example, a battery may be only half charged initially.) + * @param initCapacityUb The upper bound of the Resource's initial level. (For example, a battery may be only half charged initially.) + * @param lowerLimit The lower capacity limit. (For example, a battery can't have less than no energy stored, or it might be considered unsafe to allow + * the capacity to get below 25%.) + * @param upperLimit The upper capacity limit. (For example, a battery has a maximum charge, or it might be unsafe to fill a beaker more than three-quarters full.) + * @param maxInstProduction The maximum amount of production possible at an instant. (For example, a power bus might only allow 2.5A to be drawn at one instant.) + * @param maxInstConsumption The maximum amount of consumption possible at an instant. (For example, a power bus might only allow 2.5A to be drawn at one instant.) + * @param maxProduction The maximum amount of production possible on this resource. + * @param maxConsumption The maximum amount of consumption possible on this resource. + */ + Reservoir(const PlanDatabaseId& planDatabase, const LabelStr& type, + const LabelStr& name, const LabelStr& detectorName, + const LabelStr& profileName, + edouble initCapacityLb = 0, edouble initCapacityUb = 0, + edouble lowerLimit = MINUS_INFINITY, edouble upperLimit = PLUS_INFINITY, + edouble maxInstProduction = PLUS_INFINITY, + edouble maxInstConsumption = PLUS_INFINITY, + edouble maxProduction = PLUS_INFINITY, + edouble maxConsumption = PLUS_INFINITY); /** * @brief Constructor diff --git a/src/PLASMA/Resource/test/rs-flow-test-module.cc b/src/PLASMA/Resource/test/rs-flow-test-module.cc index f6a447b56..2a5e6de6e 100644 --- a/src/PLASMA/Resource/test/rs-flow-test-module.cc +++ b/src/PLASMA/Resource/test/rs-flow-test-module.cc @@ -1442,21 +1442,26 @@ class FVDetectorTest { static bool testReusableDetector() { RESOURCE_DEFAULT_SETUP(ce, db, false); - Reusable res(db.getId(), LabelStr("Reusable"), LabelStr("res1"), LabelStr("ClosedWorldFVDetector"), LabelStr("IncrementalFlowProfile"), - 1, 1, 0); + Reusable res(db.getId(), LabelStr("Reusable"), LabelStr("res1"), + LabelStr("ClosedWorldFVDetector"), LabelStr("IncrementalFlowProfile"), + 1, 1, 0); //create a token that violates the limit (i.e. consumes 2) - ReusableToken tok1(db.getId(), LabelStr("Reusable.uses"), IntervalIntDomain(1), IntervalIntDomain(10), - IntervalIntDomain(9), IntervalDomain(2)); + ReusableToken tok1(db.getId(), LabelStr("Reusable.uses"), + IntervalIntDomain(1), IntervalIntDomain(10), + IntervalIntDomain(9), IntervalDomain(2)); CPPUNIT_ASSERT(!ce.propagate()); tok1.discard(false); //create a token that doesn't - ReusableToken tok2(db.getId(), LabelStr("Reusable.uses"), IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(9), + ReusableToken tok2(db.getId(), LabelStr("Reusable.uses"), + IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), + IntervalIntDomain(9), IntervalDomain(1)); CPPUNIT_ASSERT(ce.propagate()); - //create a token that doesn't, but must start during the previous token, causing a violation - ReusableToken tok3(db.getId(), LabelStr("Reusable.uses"), IntervalIntDomain(9), IntervalIntDomain(11), IntervalIntDomain(2), + //create a token that doesn't, but must start during the previous token, causing a violation + ReusableToken tok3(db.getId(), LabelStr("Reusable.uses"), IntervalIntDomain(9), + IntervalIntDomain(11), IntervalIntDomain(2), IntervalDomain(1)); CPPUNIT_ASSERT(!ce.propagate()); tok3.discard(false); diff --git a/src/PLASMA/Resource/test/rs-test-module.cc b/src/PLASMA/Resource/test/rs-test-module.cc index 16bd05781..13f420f98 100644 --- a/src/PLASMA/Resource/test/rs-test-module.cc +++ b/src/PLASMA/Resource/test/rs-test-module.cc @@ -1130,6 +1130,8 @@ class ResourceTest { public: static bool test() { EUROPA_runTest(testReservoir); + EUROPA_runTest(testFlowReservoirWithConsumptionParameterSpecification); + EUROPA_runTest(testIncrementalFlowProfileIssue71); EUROPA_runTest(testReusable); EUROPA_runTest(testReservoirRemove); EUROPA_runTest(testDanglingTransaction); @@ -1137,15 +1139,98 @@ class ResourceTest { } private: + static bool testIncrementalFlowProfileIssue71() { + RESOURCE_DEFAULT_SETUP(ce, db, false); + Reservoir res1(db.getId(), LabelStr("Reservoir"), LabelStr("Battery1"), + LabelStr("ClosedWorldFVDetector"), LabelStr("IncrementalFlowProfile"), + 0, 0, 0, 1000); + ProducerToken p1(db.getId(), LabelStr("Reservoir.produce"), + IntervalIntDomain(10, PLUS_INFINITY), + IntervalDomain(1000.0)); + ConsumerToken c1(db.getId(), LabelStr("Reservoir.consume"), + // IntervalIntDomain(120010, PLUS_INFINITY), + IntervalIntDomain(), + IntervalDomain(1000.0)); + ConsumerToken c2(db.getId(), LabelStr("Reservoir.consume"), + IntervalIntDomain(960000, PLUS_INFINITY), + IntervalDomain(1.0)); + ProducerToken p2(db.getId(), LabelStr("Reservoir.produce"), + // IntervalIntDomain(961200, PLUS_INFINITY), + IntervalIntDomain(), + IntervalDomain(1.0)); + + + ConstrainedVariableId d1 = + db.getClient()->createVariable("int", IntervalIntDomain(120000), "d1"); + db.getClient()->createConstraint("temporalDistance", + makeScope(p1.getTime(), d1, c1.getTime())); + + ConstrainedVariableId d2 = + db.getClient()->createVariable("int", IntervalIntDomain(1200), "d2"); + db.getClient()->createConstraint("temporalDistance", + makeScope(c2.getTime(), d2, p2.getTime())); + + CPPUNIT_ASSERT(ce.propagate()); + + std::vector instants; + res1.getFlawedInstants(instants); + CPPUNIT_ASSERT(instants.size() == 2); + CPPUNIT_ASSERT(instants[0]->getTime() == 960000); + CPPUNIT_ASSERT(instants[1]->getTime() == 961200); + return true; + } + + static bool testFlowReservoirWithConsumptionParameterSpecification() { + RESOURCE_DEFAULT_SETUP(ce, db, false); + Reservoir res1(db.getId(), LabelStr("Reservoir"), LabelStr("Battery1"), + LabelStr("OpenWorldFVDetector"), LabelStr("IncrementalFlowProfile"), + 0, 0, 0, 1000); + + ConsumerToken c1(db.getId(), LabelStr("Reservoir.consume"), + IntervalIntDomain(10), + IntervalDomain(5, 10)); + ConsumerToken c2(db.getId(), LabelStr("Reservoir.consume"), + IntervalIntDomain(20), + IntervalDomain(5, 10)); + res1.constrain(c1.getId(), c1.getId()); + res1.constrain(c1.getId(), c2.getId()); + CPPUNIT_ASSERT(ce.propagate()); + ProfileIterator it1(res1.getProfile()); + CPPUNIT_ASSERT(!it1.done()); + CPPUNIT_ASSERT(it1.getTime() == 10); + CPPUNIT_ASSERT(it1.getUpperBound() == -5.0); + CPPUNIT_ASSERT(it1.getLowerBound() == -10.0); + CPPUNIT_ASSERT(it1.next()); + CPPUNIT_ASSERT(it1.getTime() == 20); + CPPUNIT_ASSERT(it1.getUpperBound() == -10.0); + CPPUNIT_ASSERT(it1.getLowerBound() == -20.0); + + c1.getQuantity()->specify(5.0); + CPPUNIT_ASSERT(ce.propagate()); + ProfileIterator it2(res1.getProfile()); + CPPUNIT_ASSERT(!it2.done()); + CPPUNIT_ASSERT(it2.getTime() == 10); + CPPUNIT_ASSERT(it2.getUpperBound() == -5.0); + CPPUNIT_ASSERT(it2.getLowerBound() == -5.0); + CPPUNIT_ASSERT(it2.next()); + CPPUNIT_ASSERT(it2.getTime() == 20); + CPPUNIT_ASSERT(it2.getUpperBound() == -10.0); + CPPUNIT_ASSERT(it2.getLowerBound() == -15.0); + return true; + } + static bool testReservoir() { RESOURCE_DEFAULT_SETUP(ce, db, false); - Reservoir res1(db.getId(), LabelStr("Reservoir"), LabelStr("Battery1"), LabelStr("OpenWorldFVDetector"), LabelStr("TimetableProfile"), - 10, 10, 0, 1000); - Reservoir res2(db.getId(), LabelStr("Reservoir"), LabelStr("Battery2"), LabelStr("OpenWorldFVDetector"), LabelStr("TimetableProfile"), - 10, 10, 0, 1000); + Reservoir res1(db.getId(), LabelStr("Reservoir"), LabelStr("Battery1"), + LabelStr("OpenWorldFVDetector"), LabelStr("TimetableProfile"), + 10, 10, 0, 1000); + Reservoir res2(db.getId(), LabelStr("Reservoir"), LabelStr("Battery2"), + LabelStr("OpenWorldFVDetector"), LabelStr("TimetableProfile"), + 10, 10, 0, 1000); - ConsumerToken consumer(db.getId(), LabelStr("Reservoir.consume"), IntervalIntDomain(10), + ConsumerToken consumer(db.getId(), LabelStr("Reservoir.consume"), + IntervalIntDomain(10), IntervalDomain(5)); ProfileIterator it1(res1.getProfile()); From 44ce7d3a018bf13beec0378358b83907bdc94e96 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 21 Aug 2014 20:55:04 +0000 Subject: [PATCH 014/149] Adding resource handling to the default planner config. Addresses part of issue 137. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6744 23e1bc29-d954-0410-9766-47de34158ba0 --- config/PlannerConfig.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/config/PlannerConfig.xml b/config/PlannerConfig.xml index 4a75e61f2..b4dc7b16a 100644 --- a/config/PlannerConfig.xml +++ b/config/PlannerConfig.xml @@ -1,6 +1,13 @@ + + + + + + + From 2fc93067057c34868e5e396865ad0e35f0a1f975 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Sep 2014 22:57:06 +0000 Subject: [PATCH 015/149] Added CMakeLists for examples Added CMakeLists for generated projects Modified various implementations of module loading to return pointers rather than C-incompatible Ids. Moved away from TR1 to Boost. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6745 23e1bc29-d954-0410-9766-47de34158ba0 --- CMakeLists.txt | 3 + bin/.makeproject/CMakeLists.txt | 72 +++++++++++ bin/.makeproject/ModuleTemplate.cc | 4 +- examples/BlocksWorld/CMakeLists.txt | 72 +++++++++++ examples/BlocksWorld/ModuleBlocksWorld.cc | 4 +- examples/Light/CMakeLists.txt | 52 ++++++-- examples/Light/ModuleLight.cc | 4 +- examples/NQueens/CMakeLists.txt | 72 +++++++++++ examples/Rover/CMakeLists.txt | 72 +++++++++++ examples/Rover/ModuleRover.cc | 4 +- examples/Shopping/CMakeLists.txt | 72 +++++++++++ examples/UBO/CMakeLists.txt | 89 +++++++++++++ examples/UBO/ModuleUBO.cc | 4 +- src/Java/CMakeLists.txt | 3 +- src/Java/JavaUI/CMakeLists.txt | 140 +++++++++++++++++++++ src/Java/PSEngine/CMakeLists.txt | 41 +++++- src/Java/PSEngine/src/psengine/PSUtil.java | 1 + src/PLASMA/Utils/CMakeLists.txt | 9 ++ src/PLASMA/Utils/base/DebugMsg.cc | 15 ++- src/PLASMA/Utils/base/Engine.cc | 10 +- src/PLASMA/Utils/base/Entity.cc | 13 +- src/PLASMA/Utils/base/Entity.hh | 1 - src/PLASMA/cmake/EuropaModule.cmake | 54 +++++++- 23 files changed, 771 insertions(+), 40 deletions(-) create mode 100644 bin/.makeproject/CMakeLists.txt create mode 100644 examples/BlocksWorld/CMakeLists.txt create mode 100644 examples/NQueens/CMakeLists.txt create mode 100644 examples/Rover/CMakeLists.txt create mode 100644 examples/Shopping/CMakeLists.txt create mode 100644 examples/UBO/CMakeLists.txt create mode 100644 src/Java/JavaUI/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 021f971cd..54bfc03fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,3 +35,6 @@ endif(OPTIMIZE) add_subdirectory(src) install(EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa) +install(DIRECTORY ${EUROPA_ROOT}/bin DESTINATION ${EUROPA_ROOT}/dist/europa) +install(DIRECTORY ${EUROPA_ROOT}/config DESTINATION ${EUROPA_ROOT}/dist/europa) +install(DIRECTORY ${EUROPA_ROOT}/bin/.makeproject DESTINATION ${EUROPA_ROOT}/dist/bin) \ No newline at end of file diff --git a/bin/.makeproject/CMakeLists.txt b/bin/.makeproject/CMakeLists.txt new file mode 100644 index 000000000..4fb23f5f6 --- /dev/null +++ b/bin/.makeproject/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT %%Project%%) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/${PROJECT}/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT ${PROJECT}/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/bin/.makeproject/ModuleTemplate.cc b/bin/.makeproject/ModuleTemplate.cc index cde93b71d..855ac8db9 100644 --- a/bin/.makeproject/ModuleTemplate.cc +++ b/bin/.makeproject/ModuleTemplate.cc @@ -12,9 +12,9 @@ namespace EUROPA { // static C init method to get handle when loading module as shared library extern "C" { - ModuleId initializeModule() + Module* initializeModule() { - return (new Module%%Project%%())->getId(); + return (new Module%%Project%%()); } } diff --git a/examples/BlocksWorld/CMakeLists.txt b/examples/BlocksWorld/CMakeLists.txt new file mode 100644 index 000000000..13e486193 --- /dev/null +++ b/examples/BlocksWorld/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT BlocksWorld) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/BlocksWorld/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT BlocksWorld/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/examples/BlocksWorld/ModuleBlocksWorld.cc b/examples/BlocksWorld/ModuleBlocksWorld.cc index bda6fefd0..19fb02715 100644 --- a/examples/BlocksWorld/ModuleBlocksWorld.cc +++ b/examples/BlocksWorld/ModuleBlocksWorld.cc @@ -10,9 +10,9 @@ namespace EUROPA { // static C init method to get handle when loading module as shared library extern "C" { - ModuleId initializeModule() + Module* initializeModule() { - return (new ModuleBlocksWorld())->getId(); + return new ModuleBlocksWorld(); } } diff --git a/examples/Light/CMakeLists.txt b/examples/Light/CMakeLists.txt index 1152e3a45..132bd7d16 100644 --- a/examples/Light/CMakeLists.txt +++ b/examples/Light/CMakeLists.txt @@ -1,31 +1,52 @@ cmake_minimum_required(VERSION 2.8.8) -project(Light) +set(PROJECT Light) + +project(${PROJECT}) include($ENV{EUROPA_HOME}/Europa2.cmake) +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + if(OPTIMIZE) set(EUROPA_SUFFIX "_o") else() set(EUROPA_SUFFIX "_g") endif(OPTIMIZE) +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + #project-swig find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) -set_source_files_properties(Light.i PROPERTIES CPLUSPLUS ON) -set_source_files_properties(Light.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") -swig_add_module(Light java Light.i) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + #project-lib -add_library(Light${EUROPA_SUFFIX} ${swig_generated_file_fullname} LightCustomCode.cc ModuleLight.cc) +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + #project-rt -add_executable(Light-planner_${EUROPA_SUFFIX}_rt Light-Main.cc LightCustomCode.cc ModuleLight.cc) +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) #run-project add_custom_target(run-project - DEPENDS Light-planner_${EUROPA_SUFFIX}_rt - COMMAND ./Light-planner_${EUROPA_SUFFIX}_rt > RUN_Light-planner_${EUROPA_SUFFIX}_rt.Light-initial-state.nddl.PlannerConfig.xml.output) + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) #project_jar find_package(Java REQUIRED) @@ -34,11 +55,18 @@ if(NOT java_included) message(FATAL_ERROR "Failed to include UseJava") endif(NOT java_included) -add_jar(LightJar +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar SOURCES - #?? - OUTPUT_NAME Light.jar + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/Light/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT Light/Main ) -add_dependencies(LightJar Light${EUROPA_SUFFIX}) +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) diff --git a/examples/Light/ModuleLight.cc b/examples/Light/ModuleLight.cc index 4c71b686f..c5f0e6874 100644 --- a/examples/Light/ModuleLight.cc +++ b/examples/Light/ModuleLight.cc @@ -10,9 +10,9 @@ namespace EUROPA { // static C init method to get handle when loading module as shared library extern "C" { - ModuleId initializeModule() + Module* initializeModule() { - return (new ModuleLight())->getId(); + return (new ModuleLight()); } } diff --git a/examples/NQueens/CMakeLists.txt b/examples/NQueens/CMakeLists.txt new file mode 100644 index 000000000..d34c7c940 --- /dev/null +++ b/examples/NQueens/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT NQueens) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/NQueens/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT NQueens/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/examples/Rover/CMakeLists.txt b/examples/Rover/CMakeLists.txt new file mode 100644 index 000000000..e0696d50d --- /dev/null +++ b/examples/Rover/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT Rover) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/Rover/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT Rover/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/examples/Rover/ModuleRover.cc b/examples/Rover/ModuleRover.cc index b94e5546e..bb9893230 100644 --- a/examples/Rover/ModuleRover.cc +++ b/examples/Rover/ModuleRover.cc @@ -10,9 +10,9 @@ namespace EUROPA { // static C init method to get handle when loading module as shared library extern "C" { - ModuleId initializeModule() + Module* initializeModule() { - return (new ModuleRover())->getId(); + return new ModuleRover(); } } diff --git a/examples/Shopping/CMakeLists.txt b/examples/Shopping/CMakeLists.txt new file mode 100644 index 000000000..ef74f1406 --- /dev/null +++ b/examples/Shopping/CMakeLists.txt @@ -0,0 +1,72 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT Shopping) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/Shopping/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT Shopping/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/examples/UBO/CMakeLists.txt b/examples/UBO/CMakeLists.txt new file mode 100644 index 000000000..c75b86b01 --- /dev/null +++ b/examples/UBO/CMakeLists.txt @@ -0,0 +1,89 @@ +cmake_minimum_required(VERSION 2.8.8) +set(PROJECT UBO) + +project(${PROJECT}) +include($ENV{EUROPA_HOME}/Europa2.cmake) + +if(${APPLE}) + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) +else(${APPLE}) + find_package(JNI REQUIRED) +endif(${APPLE}) +include_directories(${JNI_INCLUDE_DIRS}) + +if(OPTIMIZE) + set(EUROPA_SUFFIX "_o") +else() + set(EUROPA_SUFFIX "_g") +endif(OPTIMIZE) + +file(GLOB children RELATIVE $ENV{EUROPA_HOME} $ENV{EUROPA_HOME}/*) +foreach(child ${children}) + if(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}) + include_directories($ENV{EUROPA_HOME}/${child}/base) + include_directories($ENV{EUROPA_HOME}/${child}/component) + endif(IS_DIRECTORY $ENV{EUROPA_HOME}/${child}) +endforeach(child) + +#project-swig +find_package(SWIG REQUIRED) +include(${SWIG_USE_FILE}) +set(CMAKE_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}) +set_source_files_properties(${PROJECT}.i PROPERTIES CPLUSPLUS ON) +set_source_files_properties(${PROJECT}.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") +swig_add_module(${PROJECT} java ${PROJECT}.i) + + +#project-lib +add_library(${PROJECT}${EUROPA_SUFFIX} ${swig_generated_file_fullname} ${PROJECT}CustomCode.cc Module${PROJECT}.cc) + + +#project-rt +add_executable(${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-Main.cc ${PROJECT}CustomCode.cc Module${PROJECT}.cc) +target_link_libraries(${PROJECT}-planner${EUROPA_SUFFIX}_rt System${EUROPA_SUFFIX} Resource${EUROPA_SUFFIX} Solvers${EUROPA_SUFFIX} NDDL${EUROPA_SUFFIX} TemporalNetwork${EUROPA_SUFFIX} RulesEngine${EUROPA_SUFFIX} ConstraintEngine${EUROPA_SUFFIX} Utils${EUROPA_SUFFIX} TinyXml${EUROPA_SUFFIX}) + +#run-project +add_custom_target(run-project + DEPENDS ${PROJECT}-planner${EUROPA_SUFFIX}_rt + COMMAND ./${PROJECT}-planner${EUROPA_SUFFIX}_rt ${PROJECT}-initial-state.nddl PlannerConfig.xml > RUN_${PROJECT}-planner${EUROPA_SUFFIX}_rt.${PROJECT}-initial-state.nddl.PlannerConfig.xml.output) + +#project_jar +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +#find_jar(europa_jar PSEngine.jar PATHS $ENV{EUROPA_HOME}) +add_jar(${PROJECT}Jar + SOURCES + ${PROJECT}.java + ${PROJECT}JNI.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/ExhaustiveSolver.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/HybridSolver.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/IFlatIRelaxSolver.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/Main.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/PSResourceWrapper.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/PlanHistoryEntry.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/Precedence.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/RCPSPResource.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/RCPSPSolver.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/RCPSPSolverBase.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/RCPSPUtil.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/Resource.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/ResourceBase.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/ResourceProfile.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/ResourceViolationInfo.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/SolDistExhaustiveSolver.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/UBOSolverListener.java + ${CMAKE_CURRENT_SOURCE_DIR}/java/UBO/Main.java + INCLUDE_JARS + $ENV{EUROPA_HOME}/PSEngine.jar + $ENV{EUROPA_HOME}/PSUISwing.jar + OUTPUT_NAME ${PROJECT} + ENTRY_POINT UBO/Main + ) + +add_dependencies(${PROJECT}Jar ${PROJECT}${EUROPA_SUFFIX}) + diff --git a/examples/UBO/ModuleUBO.cc b/examples/UBO/ModuleUBO.cc index 98cb9117c..7c35aa18d 100644 --- a/examples/UBO/ModuleUBO.cc +++ b/examples/UBO/ModuleUBO.cc @@ -10,9 +10,9 @@ namespace EUROPA { // static C init method to get handle when loading module as shared library extern "C" { - ModuleId initializeModule() + Module* initializeModule() { - return (new ModuleUBO())->getId(); + return (new ModuleUBO()); } } diff --git a/src/Java/CMakeLists.txt b/src/Java/CMakeLists.txt index 725a14d04..411fcbbb5 100644 --- a/src/Java/CMakeLists.txt +++ b/src/Java/CMakeLists.txt @@ -1 +1,2 @@ -add_subdirectory(PSEngine) \ No newline at end of file +add_subdirectory(PSEngine) +add_subdirectory(JavaUI) \ No newline at end of file diff --git a/src/Java/JavaUI/CMakeLists.txt b/src/Java/JavaUI/CMakeLists.txt new file mode 100644 index 000000000..44ed89f23 --- /dev/null +++ b/src/Java/JavaUI/CMakeLists.txt @@ -0,0 +1,140 @@ +find_package(Java REQUIRED) +include(UseJava RESULT_VARIABLE java_included) +if(NOT java_included) + message(FATAL_ERROR "Failed to include UseJava") +endif(NOT java_included) + +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp) + +set(jarclasses "") +set(libjars lib/bsh-2.0b4.jar + lib/jcommon-1.0.16.jar + lib/jfreechart-1.0.13.jar + lib/egantt/egantt-core.jar + lib/egantt/egantt-ext.jar + lib/egantt/egantt-resources.jar) + +foreach(jar ${libjars}) + set(classes "") + unjar(${jar}_unjarred ${CMAKE_CURRENT_SOURCE_DIR}/${jar} temp classes) +# message(STATUS ${classes}) + list(APPEND jarclasses ${classes}) +endforeach(jar) + +add_jar(PSUISwing + INCLUDE_JARS + ${libjars} + ${CMAKE_CURRENT_BINARY_DIR}/../PSEngine/PSEngine.jar + SOURCES + #${jarclasses} + source/org/ops/ui/beanshell/swing/BeanShellView.java + source/org/ops/ui/editor/model/OutlineNode.java + source/org/ops/ui/editor/model/OutlineNodeType.java + source/org/ops/ui/editor/swing/anml/AnmlInterpreter.java + source/org/ops/ui/editor/swing/anml/AnmlTokenMarker.java + source/org/ops/ui/editor/swing/ash/AshConsole.java + source/org/ops/ui/editor/swing/ash/AshInterpreter.java + source/org/ops/ui/editor/swing/ash/AshTokenMarker.java + source/org/ops/ui/editor/swing/ash/ConsoleDefaults.java + source/org/ops/ui/editor/swing/ash/ConsolePainter.java + source/org/ops/ui/editor/swing/ash/DefaultInputHandler.java + source/org/ops/ui/editor/swing/ash/DocumentOutputStream.java + source/org/ops/ui/editor/swing/ash/DocumentWriter.java + source/org/ops/ui/editor/swing/ash/InputHandler.java + source/org/ops/ui/editor/swing/ash/KeywordMap.java + source/org/ops/ui/editor/swing/ash/SyntaxDocument.java + source/org/ops/ui/editor/swing/ash/SyntaxStyle.java + source/org/ops/ui/editor/swing/ash/SyntaxUtilities.java + source/org/ops/ui/editor/swing/ash/TextUtilities.java + source/org/ops/ui/editor/swing/ash/Token.java + source/org/ops/ui/editor/swing/ash/TokenMarker.java + source/org/ops/ui/editor/swing/nddl/NddlAshInterpreter.java + source/org/ops/ui/editor/swing/nddl/NddlTokenMarker.java + source/org/ops/ui/filemanager/model/AstNode.java + source/org/ops/ui/filemanager/model/AstNodeTypes.java + source/org/ops/ui/filemanager/model/ErrorRecord.java + source/org/ops/ui/filemanager/model/FileModel.java + source/org/ops/ui/gantt/model/EuropaGanttActivity.java + source/org/ops/ui/gantt/model/EuropaGanttModel.java + source/org/ops/ui/gantt/model/EuropaGanttResource.java + source/org/ops/ui/gantt/model/IGanttActivity.java + source/org/ops/ui/gantt/model/IGanttModel.java + source/org/ops/ui/gantt/model/IGanttResource.java + source/org/ops/ui/gantt/model/PSGanttActivity.java + source/org/ops/ui/gantt/model/PSGanttActivityImpl.java + source/org/ops/ui/gantt/model/PSGanttModel.java + source/org/ops/ui/gantt/model/PSGanttPSEModel.java + source/org/ops/ui/gantt/swing/GanttView.java + source/org/ops/ui/gantt/swing/LinePanel.java + source/org/ops/ui/gantt/swing/PSEGantt.java + source/org/ops/ui/gantt/swing/PSGantt.java + source/org/ops/ui/gantt/swing/PSGanttColorProvider.java + source/org/ops/ui/gantt/swing/ResourcePanel.java + source/org/ops/ui/gantt/swing/TimelinePanel.java + source/org/ops/ui/gantt/swing/TokenColor.java + source/org/ops/ui/gantt/swing/TokenWidget.java + source/org/ops/ui/main/swing/EuropaInternalFrame.java + source/org/ops/ui/main/swing/FileNameExtensionFilter.java + source/org/ops/ui/main/swing/PSComponent.java + source/org/ops/ui/main/swing/PSComponentBase.java + source/org/ops/ui/main/swing/PSDesktop.java + source/org/ops/ui/main/swing/PSMouseListener.java + source/org/ops/ui/mouse/swing/ActionDetailsPanel.java + source/org/ops/ui/mouse/swing/ActionViolationsPanel.java + source/org/ops/ui/mouse/swing/MouseListenerPanel.java + source/org/ops/ui/rchart/model/PSResourceChartModel.java + source/org/ops/ui/rchart/model/PSResourceChartPSEModel.java + source/org/ops/ui/rchart/swing/PSJFreeResourceChart.java + source/org/ops/ui/rchart/swing/PSResourceChart.java + source/org/ops/ui/schemabrowser/model/SchemaModel.java + source/org/ops/ui/schemabrowser/model/SchemaModelImpl.java + source/org/ops/ui/schemabrowser/model/SchemaNode.java + source/org/ops/ui/schemabrowser/model/SchemaSolverModel.java + source/org/ops/ui/schemabrowser/swing/SchemaNodeCellRenderer.java + source/org/ops/ui/schemabrowser/swing/SchemaTreeModel.java + source/org/ops/ui/schemabrowser/swing/SchemaView.java + source/org/ops/ui/solver/model/SolverAdapter.java + source/org/ops/ui/solver/model/SolverListener.java + source/org/ops/ui/solver/model/SolverModel.java + source/org/ops/ui/solver/model/StepStatisticsRecord.java + source/org/ops/ui/solver/model/TimeFormatHelper.java + source/org/ops/ui/solver/swing/ConsoleView.java + source/org/ops/ui/solver/swing/OpenDecisionsPanel.java + source/org/ops/ui/solver/swing/OpenDecisionsView.java + source/org/ops/ui/solver/swing/PSSolverDialog.java + source/org/ops/ui/solver/swing/PSSolverDialogListener.java + source/org/ops/ui/solver/swing/PSSolverView.java + source/org/ops/ui/solver/swing/SolverChartPanel.java + source/org/ops/ui/utils/swing/Util.java + source/org/ops/ui/utils/Utilities.java + MANIFEST + ${CMAKE_CURRENT_SOURCE_DIR}/META-INF/MANIFEST.SWING + ) +# add_dependencies(PSUISwing ${jarclasses}) +# foreach(f ${jarclasses}) +# add_custom_command(TARGET PSUISwing +# POST_BUILD #? +# COMMAND +# ${Java_JAR_EXECUTABLE} -uf PSUISwing.jar -C ${CMAKE_CURRENT_BINARY_DIR}/temp ${f} +# #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp +# ) +# endforeach(f) +# add_custom_command(TARGET PSUISwing +# POST_BUILD #? +# COMMAND +# ${Java_JAR_EXECUTABLE} -uf PSUISwing.jar -C ${CMAKE_CURRENT_BINARY_DIR}/temp ${jarclasses} +# #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp +# ) +#string(REPLACE ";" "\n" classes_with_newlines ${jarclasses}) +foreach(f ${jarclasses}) + file(APPEND PSEngineAdditionalClasses "${f}\n") +endforeach(f) +#file(WRITE PSEngineAdditionalClasses ${jarclasses}) +add_custom_command(TARGET PSUISwing + POST_BUILD #? + COMMAND + ${Java_JAR_EXECUTABLE} -uf PSUISwing.jar -C ${CMAKE_CURRENT_BINARY_DIR}/temp . + #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp +) + +install_jar(PSUISwing ${EUROPA_ROOT}/dist/europa) \ No newline at end of file diff --git a/src/Java/PSEngine/CMakeLists.txt b/src/Java/PSEngine/CMakeLists.txt index 1c3b22a8d..952cc1e3e 100644 --- a/src/Java/PSEngine/CMakeLists.txt +++ b/src/Java/PSEngine/CMakeLists.txt @@ -52,8 +52,45 @@ add_jar(PSEngineJar src/psengine/PSUtil.java src/psengine/util/LibraryLoader.java src/psengine/util/SimpleTimer.java - INCLUDE_JARS - PSEngineGenerated.jar + generated/psengine/EngineConfig.java + generated/psengine/PSConstraint.java + generated/psengine/PSConstraintEngineListener.java + generated/psengine/PSConstraintList.java + generated/psengine/PSDataType.java + generated/psengine/PSDataTypeList.java + generated/psengine/PSEngine.java + generated/psengine/PSEngineInterface.java + generated/psengine/PSEngineInterfaceJNI.java + generated/psengine/PSEntity.java + generated/psengine/PSException.java + generated/psengine/PSIntList.java + generated/psengine/PSLanguageException.java + generated/psengine/PSLanguageExceptionList.java + generated/psengine/PSObject.java + generated/psengine/PSObjectList.java + generated/psengine/PSObjectType.java + generated/psengine/PSObjectTypeList.java + generated/psengine/PSPlanDatabaseClient.java + generated/psengine/PSPlanDatabaseListener.java + generated/psengine/PSResource.java + generated/psengine/PSResourceProfile.java + generated/psengine/PSSchema.java + generated/psengine/PSSolver.java + generated/psengine/PSStringList.java + generated/psengine/PSTimePointList.java + generated/psengine/PSToken.java + generated/psengine/PSTokenList.java + generated/psengine/PSTokenState.java + generated/psengine/PSTokenType.java + generated/psengine/PSTokenTypeList.java + generated/psengine/PSValueList.java + generated/psengine/PSVarType.java + generated/psengine/PSVarValue.java + generated/psengine/PSVariable.java + generated/psengine/PSVariableList.java + generated/psengine/StringErrorStream.java + # INCLUDE_JARS + # PSEngineGenerated.jar OUTPUT_NAME PSEngine) add_dependencies(PSEngineJar PSEngineGenerated) diff --git a/src/Java/PSEngine/src/psengine/PSUtil.java b/src/Java/PSEngine/src/psengine/PSUtil.java index 7b7a0646e..3136d3805 100644 --- a/src/Java/PSEngine/src/psengine/PSUtil.java +++ b/src/Java/PSEngine/src/psengine/PSUtil.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Vector; import psengine.util.LibraryLoader; +import psengine.PSObjectList; public class PSUtil { diff --git a/src/PLASMA/Utils/CMakeLists.txt b/src/PLASMA/Utils/CMakeLists.txt index 5d06b192e..a06c49099 100644 --- a/src/PLASMA/Utils/CMakeLists.txt +++ b/src/PLASMA/Utils/CMakeLists.txt @@ -1,3 +1,9 @@ +include(CheckIncludeFileCXX) +check_include_file_cxx(tr1/functional HAVE_TR1_FUNCTIONAL) +configure_file("${CMAKE_CURRENT_SOURCE_DIR}/europa-config.h.in" + "${CMAKE_CURRENT_BINARY_DIR}/europa-config.h") +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + include(EuropaModule) set(internal_dependencies TinyXml) set(root_sources CommonDefs.cc) @@ -17,3 +23,6 @@ file(COPY ${test_inputs} DESTINATION .) #how do I handle the dlopen and pthreads link requirements? do I need to? find_library(libdl_library dl libdl ltdl libltdl) target_link_libraries("Utils${EUROPA_SUFFIX}" ${libdl_library}) + + + diff --git a/src/PLASMA/Utils/base/DebugMsg.cc b/src/PLASMA/Utils/base/DebugMsg.cc index 492ad0fce..3ab43de53 100755 --- a/src/PLASMA/Utils/base/DebugMsg.cc +++ b/src/PLASMA/Utils/base/DebugMsg.cc @@ -7,13 +7,16 @@ #ifndef NO_DEBUG_MESSAGE_SUPPORT +#include "europa-config.h" + #include #include #include -#include #include #include +#include + #include "DebugMsg.hh" #include "Mutex.hh" @@ -138,17 +141,21 @@ class DebugMessage::DebugInternals { namespace { static DebugMessage::DebugInternals debugInternals; +#ifdef __APPLE__ +static pthread_mutex_t debugMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; +#else static pthread_mutex_t debugMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; +#endif typedef std::pair > + boost::reference_wrapper > internals_accessor; internals_accessor internals() { EUROPA::MutexGrabber grabber(debugMutex); return std::make_pair >(grabber, - std::tr1::ref(debugInternals)); + boost::reference_wrapper >(grabber, + boost::ref(debugInternals)); } } diff --git a/src/PLASMA/Utils/base/Engine.cc b/src/PLASMA/Utils/base/Engine.cc index 796386eae..4fd7f140b 100644 --- a/src/PLASMA/Utils/base/Engine.cc +++ b/src/PLASMA/Utils/base/Engine.cc @@ -298,8 +298,8 @@ namespace EUROPA checkRuntimeError(libHandle != NULL, "Error opening module " << moduleFileName << ": " << p_dlerror()); - ModuleId (*fcn_module)(); - fcn_module = (ModuleId (*)()) p_dlsym(libHandle, "initializeModule"); + Module* (*fcn_module)(); + fcn_module = (Module* (*)()) p_dlsym(libHandle, "initializeModule"); checkError(fcn_module != NULL, "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << p_dlerror()); @@ -308,14 +308,14 @@ namespace EUROPA checkRuntimeError(libHandle != NULL, "Error opening module " << moduleFileName << ": " << dlerror()); - ModuleId (*fcn_module)(); - fcn_module = (ModuleId (*)()) dlsym(libHandle, "initializeModule"); + Module* (*fcn_module)(); + fcn_module = (Module* (*)()) dlsym(libHandle, "initializeModule"); checkError(fcn_module != NULL, "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << dlerror()); #endif - ModuleId module = (*fcn_module)(); + ModuleId module = (*fcn_module)()->getId(); addModule(module); } diff --git a/src/PLASMA/Utils/base/Entity.cc b/src/PLASMA/Utils/base/Entity.cc index 194158c1a..6767d21c4 100644 --- a/src/PLASMA/Utils/base/Entity.cc +++ b/src/PLASMA/Utils/base/Entity.cc @@ -3,7 +3,8 @@ #include "Mutex.hh" #include -#include + +#include namespace EUROPA { class EntityInternals { @@ -94,15 +95,19 @@ class EntityInternals { namespace { static EntityInternals entityInternals; +#ifdef __APPLE__ +static pthread_mutex_t entityMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER; +#else static pthread_mutex_t entityMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; +#endif -typedef std::pair > +typedef std::pair > internals_accessor; internals_accessor internals() { MutexGrabber grabber(entityMutex); return std::make_pair >(grabber, - std::tr1::ref(entityInternals)); + boost::reference_wrapper >(grabber, + boost::ref(entityInternals)); } } diff --git a/src/PLASMA/Utils/base/Entity.hh b/src/PLASMA/Utils/base/Entity.hh index bbae12d4e..6735d7302 100644 --- a/src/PLASMA/Utils/base/Entity.hh +++ b/src/PLASMA/Utils/base/Entity.hh @@ -8,7 +8,6 @@ #include #include #include -#include #include "PSUtils.hh" diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake index 894d371e3..813caf3b9 100644 --- a/src/PLASMA/cmake/EuropaModule.cmake +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -266,8 +266,60 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de TARGETS ${libname} EXPORT Europa2 DESTINATION ${EUROPA_ROOT}/dist/europa + #TODO: figure out why this isn't working #INCLUDES DESTINATION ${EUROPA_ROOT}/dist/europa/${name} ) + #file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR} *.hh) + #message(STATUS "Headers: ${headers}") install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DESTINATION ${EUROPA_ROOT}/dist/europa - FILES_MATCHING PATTERN "*.hh") + FILES_MATCHING PATTERN "*.hh" PATTERN "*.h") endmacro(declare_module) + +function(unjar target jar dest_dir classes) + execute_process( + COMMAND ${Java_JAR_EXECUTABLE} tf ${jar} + OUTPUT_VARIABLE jar_files_str + RESULT_VARIABLE rv) + string(REPLACE "\n" ";" jar_files_ndir ${jar_files_str}) + + + set(jar_files "") + set(class_files "") + foreach(f ${jar_files_ndir}) + # set(fname "${dest_dir}/${f}") + set(fname "${f}") + list(APPEND jar_files ${fname}) + string(REGEX MATCH ".class$" classfile ${fname}) + #message(STATUS "File ${fname}") + if(classfile) + #message(STATUS "Class!") + string(REPLACE "\$" "\$\$" fname ${fname}) + list(APPEND class_files ${fname}) + endif(classfile) + endforeach(f) + set(classes ${class_files} PARENT_SCOPE) + #message(STATUS "Classes: ${classes}") + list(LENGTH class_files class_count) + if(class_count GREATER 0) + add_custom_command(OUTPUT ${class_files} + COMMAND ${Java_JAR_EXECUTABLE} + xf ${jar}; + #touch ${target} + WORKING_DIRECTORY ${dest_dir} + ) + else() + add_custom_command(OUTPUT ${jar_files} + COMMAND ${Java_JAR_EXECUTABLE} + xf ${jar}; + touch ${target} + WORKING_DIRECTORY ${dest_dir} + ) + endif(class_count GREATER 0) + + # set(all_classes "") + # foreach(f ${class_files}) + # string(REPLACE "\$" "\$\$" g ${f}) + #list(APPEND all_classes ${g}) + #endforeach(f) + #set(classes ${all_classes} PARENT_SCOPE) +endfunction(unjar) \ No newline at end of file From de7f3226cb763517efbc1b42028f81844c46188d Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 8 Sep 2014 22:03:52 +0000 Subject: [PATCH 016/149] -Refactored the profile graph into its own file -Added a BoostFlowProfileGraph using the BGL to implement a maximum-flow algorithm -Replaced the locally-implemented flow profiles with the Boost one, because it passes more tests (need to look at an incremental implementation) git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6746 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/Resource/ModuleResource.cc | 7 +- src/PLASMA/Resource/base/Profile.cc | 139 ++-- src/PLASMA/Resource/base/Profile.hh | 1 + src/PLASMA/Resource/base/ProfilePropagator.cc | 9 +- src/PLASMA/Resource/base/Transaction.cc | 2 + .../Resource/component/BoostFlowProfile.hh | 16 + .../component/BoostFlowProfileGraph.cc | 265 +++++++ .../component/BoostFlowProfileGraph.hh | 159 ++++ src/PLASMA/Resource/component/FlowProfile.cc | 565 +++++-------- src/PLASMA/Resource/component/FlowProfile.hh | 277 +------ .../Resource/component/FlowProfileGraph.cc | 312 ++++++++ .../Resource/component/FlowProfileGraph.hh | 189 +++++ src/PLASMA/Resource/component/Graph.cc | 3 +- .../component/IncrementalFlowProfile.cc | 341 ++++---- src/PLASMA/Resource/component/Jamfile | 2 + src/PLASMA/Resource/component/MaxFlow.cc | 72 +- src/PLASMA/Resource/component/MaxFlow.hh | 743 +++++++++--------- src/PLASMA/Resource/component/Types.hh | 2 +- .../Resource/test/rs-flow-test-module.cc | 104 ++- .../Resource/test/rs-flow-test-module.hh | 4 +- src/PLASMA/Resource/test/rs-test-module.cc | 652 +++++++-------- src/PLASMA/Utils/base/DebugMsg.cc | 2 +- 22 files changed, 2288 insertions(+), 1578 deletions(-) create mode 100644 src/PLASMA/Resource/component/BoostFlowProfile.hh create mode 100644 src/PLASMA/Resource/component/BoostFlowProfileGraph.cc create mode 100644 src/PLASMA/Resource/component/BoostFlowProfileGraph.hh create mode 100644 src/PLASMA/Resource/component/FlowProfileGraph.cc create mode 100644 src/PLASMA/Resource/component/FlowProfileGraph.hh diff --git a/src/PLASMA/Resource/ModuleResource.cc b/src/PLASMA/Resource/ModuleResource.cc index 8f501d2d5..6731d6d17 100644 --- a/src/PLASMA/Resource/ModuleResource.cc +++ b/src/PLASMA/Resource/ModuleResource.cc @@ -17,6 +17,7 @@ #include "ThreatDecisionPoint.hh" #include "ResourceThreatManager.hh" #include "Reusable.hh" +#include "BoostFlowProfile.hh" namespace EUROPA { @@ -103,8 +104,10 @@ namespace EUROPA { FactoryMgr* pfm = new FactoryMgr(); engine->addComponent("ProfileFactoryMgr",pfm); REGISTER_PROFILE(pfm,TimetableProfile, TimetableProfile ); - REGISTER_PROFILE(pfm,FlowProfile, FlowProfile); - REGISTER_PROFILE(pfm,IncrementalFlowProfile, IncrementalFlowProfile ); + REGISTER_PROFILE(pfm, BoostFlowProfile, FlowProfile); + REGISTER_PROFILE(pfm, BoostFlowProfile, IncrementalFlowProfile); + // REGISTER_PROFILE(pfm,FlowProfile, FlowProfile); + // REGISTER_PROFILE(pfm,IncrementalFlowProfile, IncrementalFlowProfile ); REGISTER_PROFILE(pfm,GroundedProfile, GroundedProfile ); // Solver diff --git a/src/PLASMA/Resource/base/Profile.cc b/src/PLASMA/Resource/base/Profile.cc index fd3271206..c0a92604c 100644 --- a/src/PLASMA/Resource/base/Profile.cc +++ b/src/PLASMA/Resource/base/Profile.cc @@ -481,84 +481,89 @@ namespace EUROPA { handleRecompute(); } - void Profile::handleRecompute() - { - checkError(m_recomputeInterval.isValid(), - "Attempted to recompute levels over an invalid interval."); - condDebugMsg(m_recomputeInterval->done(), "Profile:recompute", "No instants over which to recompute."); - debugMsg("Profile:handleRecompute","Invoked"); - debugMsg("Profile:recompute:prePrint", std::endl << toString()); - - eint endTime = MINUS_INFINITY; - std::pair endDiff(0.0,0.0); - - if(!m_recomputeInterval->done()) { - InstantId prev = InstantId::noId(); - bool violation = false; - endTime = m_recomputeInterval->getEndTime(); - - //if there is no preceding instant, do a clean init - if(m_recomputeInterval->getInstant()->getTime() == m_instants.begin()->first) { - initRecompute(); - m_detector->initialize(); - } - else { - InstantId inst = m_recomputeInterval->getInstant(); - - if (inst->getTime() == endTime) { - endDiff.first = inst->getLowerLevel(); - endDiff.second = inst->getUpperLevel(); - } +void Profile::handleRecompute() { + checkError(m_recomputeInterval.isValid(), + "Attempted to recompute levels over an invalid interval."); + condDebugMsg(m_recomputeInterval->done(), "Profile:recompute", "No instants over which to recompute."); + debugMsg("Profile:handleRecompute","Invoked"); + debugMsg("Profile:recompute:prePrint", std::endl << toString()); + + eint endTime = MINUS_INFINITY; + std::pair endDiff(0.0,0.0); + + if(!m_recomputeInterval->done()) { + InstantId prev = InstantId::noId(); + bool violation = false; + endTime = m_recomputeInterval->getEndTime(); + + //if there is no preceding instant, do a clean init + if(m_recomputeInterval->getInstant()->getTime() == m_instants.begin()->first) { + initRecompute(); + m_detector->initialize(); + } + else { + InstantId inst = m_recomputeInterval->getInstant(); + + if (inst->getTime() == endTime) { + endDiff.first = inst->getLowerLevel(); + endDiff.second = inst->getUpperLevel(); + } - initRecompute(inst); - m_detector->initialize(inst); + initRecompute(inst); + m_detector->initialize(inst); - if (inst->getTime() == endTime) { - endDiff.first = inst->getLowerLevel() - endDiff.first; - endDiff.second = inst->getUpperLevel() - endDiff.second; - } + if (inst->getTime() == endTime) { + endDiff.first = inst->getLowerLevel() - endDiff.first; + endDiff.second = inst->getUpperLevel() - endDiff.second; + } - // initRecompute(inst) above also recomputes the levels for the inst, so move forward: - violation = m_detector->detect(inst); + std::map::iterator it = getGreatestInstant(inst->getTime() - 1); + if(it != m_instants.end()) { + prev = it->second; + } - prev = inst; - m_recomputeInterval->next(); - } + // initRecompute(inst) above also recomputes the levels for the inst, so move forward: + // violation = m_detector->detect(inst); - while(!m_recomputeInterval->done() - && - !violation ) { - InstantId inst = m_recomputeInterval->getInstant(); - if (inst->getTime() == endTime) { - endDiff.first = inst->getLowerLevel(); - endDiff.second = inst->getUpperLevel(); - } + // prev = inst; + // m_recomputeInterval->next(); + } - debugMsg("Profile:recompute", "Recomputing levels at instant " << inst->getTime()); - check_error(inst.isValid()); - recomputeLevels( prev, inst); + while(!m_recomputeInterval->done() + && + !violation ) { + InstantId inst = m_recomputeInterval->getInstant(); - if (inst->getTime() == endTime) { - endDiff.first = inst->getLowerLevel() - endDiff.first; - endDiff.second = inst->getUpperLevel() - endDiff.second; - } + if (inst->getTime() == endTime) { + endDiff.first = inst->getLowerLevel(); + endDiff.second = inst->getUpperLevel(); + } - violation = m_detector->detect(inst); + debugMsg("Profile:recompute", "Recomputing levels at instant " << inst->getTime()); + check_error(inst.isValid()); + recomputeLevels( prev, inst); - prev = inst; - m_recomputeInterval->next(); - } - } + if (inst->getTime() == endTime) { + endDiff.first = inst->getLowerLevel() - endDiff.first; + endDiff.second = inst->getUpperLevel() - endDiff.second; + } - debugMsg("Profile:recompute:postPrint", std::endl << toString()); - debugMsg("Profile:handleRecompute", "Deleting profile iterator " << m_recomputeInterval->getId() ); - delete (ProfileIterator*) m_recomputeInterval; - m_recomputeInterval = ProfileIteratorId::noId(); - m_needsRecompute = false; + violation = m_detector->detect(inst); - postHandleRecompute(endTime,endDiff); + prev = inst; + m_recomputeInterval->next(); } + } + + debugMsg("Profile:recompute:postPrint", std::endl << toString()); + debugMsg("Profile:handleRecompute", "Deleting profile iterator " << m_recomputeInterval->getId() ); + delete (ProfileIterator*) m_recomputeInterval; + m_recomputeInterval = ProfileIteratorId::noId(); + m_needsRecompute = false; + + postHandleRecompute(endTime,endDiff); +} void Profile::postHandleRecompute(const eint& endTime, const std::pair& endDiff) { @@ -709,12 +714,12 @@ namespace EUROPA { edouble Profile::getInitCapacityLb() const { - return 0.0; + return 0.0; } edouble Profile::getInitCapacityUb() const { - return 0.0; + return 0.0; } ProfileIterator::ProfileIterator(const ProfileId prof, const eint startTime, const eint endTime) diff --git a/src/PLASMA/Resource/base/Profile.hh b/src/PLASMA/Resource/base/Profile.hh index 3a9bbf2ed..bf4d0573a 100644 --- a/src/PLASMA/Resource/base/Profile.hh +++ b/src/PLASMA/Resource/base/Profile.hh @@ -218,6 +218,7 @@ namespace EUROPA { virtual void postHandleRecompute(const eint& endTime, const std::pair& endDiff); /** * @brief Initialize a recomputation with level data from the given Instant. + * This function is expected to re-compute the levels for the given instant! */ virtual void initRecompute(InstantId inst) = 0; diff --git a/src/PLASMA/Resource/base/ProfilePropagator.cc b/src/PLASMA/Resource/base/ProfilePropagator.cc index c3d8b80ee..904b9daca 100644 --- a/src/PLASMA/Resource/base/ProfilePropagator.cc +++ b/src/PLASMA/Resource/base/ProfilePropagator.cc @@ -83,8 +83,13 @@ namespace EUROPA { if( !getConstraintEngine()->provenInconsistent() && profile->needsRecompute()) { - debugMsg("ProfilePropagator:execute", "Recomputing profile " << profile->getResource()->getName().toString()); - profile->recompute(); + condDebugMsg(profile->getResource() != ResourceId::noId(), + "ProfilePropagator:execute", + "Recomputing profile " << profile->getResource()->getName().toString()); + condDebugMsg(profile->getResource() == ResourceId::noId(), + "ProfilePropagator:execute", + "Recomputing profile " << profile); + profile->recompute(); } } diff --git a/src/PLASMA/Resource/base/Transaction.cc b/src/PLASMA/Resource/base/Transaction.cc index d992dfb5d..cfd1fac44 100644 --- a/src/PLASMA/Resource/base/Transaction.cc +++ b/src/PLASMA/Resource/base/Transaction.cc @@ -15,6 +15,8 @@ namespace EUROPA { , m_isConsumer(isConsumer) , m_owner(owner) { + checkRuntimeError(quantity->lastDomain().getLowerBound() >= 0.0, + "All transactions require positive quantity variables."); } Transaction::~Transaction() diff --git a/src/PLASMA/Resource/component/BoostFlowProfile.hh b/src/PLASMA/Resource/component/BoostFlowProfile.hh new file mode 100644 index 000000000..29051245b --- /dev/null +++ b/src/PLASMA/Resource/component/BoostFlowProfile.hh @@ -0,0 +1,16 @@ +#ifndef _H_BOOST_FLOW_PROFILE +#define _H_BOOST_FLOW_PROFILE +#include "FlowProfile.hh" +#include "BoostFlowProfileGraph.hh" +namespace EUROPA { + +class BoostFlowProfile : public FlowProfile { + public: + BoostFlowProfile(const PlanDatabaseId db, const FVDetectorId flawDetector) + : FlowProfile(db, flawDetector) { + initializeGraphs(); + } +}; +} + +#endif diff --git a/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc new file mode 100644 index 000000000..492cbf0c3 --- /dev/null +++ b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc @@ -0,0 +1,265 @@ +#include "BoostFlowProfileGraph.hh" +#include "Debug.hh" + +#include +// #include +#include +// #include + +namespace EUROPA { + +BoostFlowProfileGraph::BoostFlowProfileGraph(const TransactionId& source, + const TransactionId& sink, + bool lowerLevel) + : FlowProfileGraph(source, sink, lowerLevel), m_graph(), m_transactionToVertex(), + m_vertexToTransaction(), m_activeTransactions(), m_source(), m_sink(), + m_recalculate(false) { + using namespace boost; + initializeGraph(source, sink); +} + +void BoostFlowProfileGraph::initializeGraph(const TransactionId& source, + const TransactionId& sink) { + + m_graph.clear(); + m_transactionToVertex.clear(); + m_vertexToTransaction.clear(); + m_source = addNode(source); + m_sink = addNode(sink); + +} + +BoostFlowProfileGraph::Vertex +BoostFlowProfileGraph::addNode(const TransactionId& t) { + std::map::const_iterator found = m_transactionToVertex.find(t); + if(found != m_transactionToVertex.end()) + return found->second; + Vertex retval = add_vertex(m_graph); + debugMsg("BoostFlowProfileGraph:addNode", "Added " << retval << " for " << t); + m_transactionToVertex.insert(std::make_pair(t, retval)); + m_vertexToTransaction.insert(std::make_pair(retval, t)); + return retval; +} + +BoostFlowProfileGraph::Vertex +BoostFlowProfileGraph::getNode(const TransactionId& t) const { + std::map::const_iterator it = m_transactionToVertex.find(t); + checkError(it != m_transactionToVertex.end(), + "Failed to find a vertex for " << t); + return it->second; +} + +TransactionId BoostFlowProfileGraph::getTransaction(const Vertex& v) const { + std::map::const_iterator it = m_vertexToTransaction.find(v); + checkError(it != m_vertexToTransaction.end(), + "Failed to find a transaction for " << v); + return it->second; +} + +BoostFlowProfileGraph::Edge BoostFlowProfileGraph::addEdge(const TransactionId& t1, + const TransactionId& t2, + const edouble capacity, + const edouble reverseCapacity) { + debugMsg("BoostFlowProfileGraph:addEdge", + (isLowerLevel() ? "" : "") << t1 << " -> " << t2 << " [" << + capacity << "]"); + debugMsg("BoostFlowProfileGraph:addEdge", + (isLowerLevel() ? "" : "") << t2 << " -> " << t1 << " [" << + reverseCapacity << "]"); + + using namespace boost; + property_map::type rev = get(edge_reverse, m_graph); + Vertex v1 = getNode(t1); + Vertex v2 = getNode(t2); + + std::pair found = edge(v1, v2, m_graph); + if(found.second == true) + return found.first; + Edge e1 = add_edge(v1, v2, m_graph).first; + Edge e2 = add_edge(v2, v1, m_graph).first; + + + put(edge_capacity, m_graph, e1, cast_basis(capacity)); + put(edge_capacity, m_graph, e2, cast_basis(reverseCapacity)); + + debugMsg("BoostFlowProfileGraph:addEdge", + (isLowerLevel() ? "" : "") << e1 << " [" << + get(edge_capacity, m_graph, e1) << "]"); + debugMsg("BoostFlowProfileGraph:addEdge", + (isLowerLevel() ? "" : "") << e2 << " [" << + get(edge_capacity, m_graph, e2) << "]"); + + rev[e1] = e2; + rev[e2] = e1; + return e1; +} + +void BoostFlowProfileGraph::enableAt(const TransactionId& t1, const TransactionId& t2) { + if(m_transactionToVertex.find(t1) == m_transactionToVertex.end() || + m_transactionToVertex.find(t2) == m_transactionToVertex.end()) + return; + m_recalculate = true; + addEdge(t1, t2, PLUS_INFINITY, PLUS_INFINITY); +} + +void BoostFlowProfileGraph::enableAtOrBefore(const TransactionId& t1, + const TransactionId& t2) { + if(m_transactionToVertex.find(t1) == m_transactionToVertex.end() || + m_transactionToVertex.find(t2) == m_transactionToVertex.end()) + return; + m_recalculate = true; + addEdge(t1, t2, 0, PLUS_INFINITY); +} + +void BoostFlowProfileGraph::disable(const TransactionId& transaction) { + std::vector::iterator it = + std::find(m_activeTransactions.begin(), m_activeTransactions.end(), transaction); + if(it != m_activeTransactions.end()) + m_activeTransactions.erase(it); +} + +void BoostFlowProfileGraph::addTransactionToGraph(const TransactionId& t) { + if(t == getTransaction(m_sink) || t == getTransaction(m_source)) + return; + debugMsg("BoostFlowProfileGraph:addTransactionToGraph", + (isLowerLevel() ? "" : "") << "Adding " << t); + + edouble edgeCapacity = 0.0; + TransactionId source, target; + + if(isLowerLevel() == t->isConsumer()) { + source = getTransaction(m_source); + target = t; + edgeCapacity = t->quantity()->lastDomain().getUpperBound(); + } + else { + source = t; + target = getTransaction(m_sink); + edgeCapacity = t->quantity()->lastDomain().getLowerBound(); + } + + check_error(source != TransactionId::noId()); + check_error(target != TransactionId::noId()); + + addNode(t); + addEdge(source, target, edgeCapacity, 0.0); +} + +void BoostFlowProfileGraph::enableTransaction(const TransactionId& t, + const InstantId& inst, + TransactionId2InstantId& contributions) { + debugMsg("BoostFlowProfileGraph:enableTransaction", + (isLowerLevel() ? "" : "") << "Enabling " << t << " at " + << inst->getTime()); + + edouble edgeCapacity = 0.0; + + if(isLowerLevel() == t->isConsumer()) { + edgeCapacity = t->quantity()->lastDomain().getUpperBound(); + } + else { + edgeCapacity = t->quantity()->lastDomain().getLowerBound(); + } + + if(0.0 == edgeCapacity) { + contributions[t] = inst; //? + } + if(std::find(m_activeTransactions.begin(), m_activeTransactions.end(), t) == + m_activeTransactions.end()) { + m_activeTransactions.push_back(t); + } + m_recalculate = true; +} + +edouble BoostFlowProfileGraph::getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, + const FlowProfile::TransactionIdTransactionIdPair2Order& other) { + using namespace boost; + reset(); + for(std::vector::const_iterator it = m_activeTransactions.begin(); + it != m_activeTransactions.end(); ++it) { + addTransactionToGraph(*it); + } + for(FlowProfile::TransactionIdTransactionIdPair2Order::const_iterator it = at.begin(); + it != at.end(); ++it) { + enableAt(it->first.first, it->first.second); + } + for(FlowProfile::TransactionIdTransactionIdPair2Order::const_iterator it = other.begin(); + it != other.end(); ++it) { + debugMsg("BoostFlowProfileGraph:getResidualFromSource", + it->first.first << + (it->second == FlowProfile::AFTER_OR_AT ? " after-or-at " : + (it->second == FlowProfile::BEFORE_OR_AT ? " before-or-at " : + (it->second == FlowProfile::NOT_ORDERED ? " unordered " : + (it->second == FlowProfile::STRICTLY_AT ? " at " : " unknown ")))) << + it->first.second); + switch(it->second) { + case FlowProfile::AFTER_OR_AT: + enableAtOrBefore(it->first.second, it->first.first); + break; + case FlowProfile::BEFORE_OR_AT: + enableAtOrBefore(it->first.first, it->first.second); + case FlowProfile::NOT_ORDERED: + break; + case FlowProfile::STRICTLY_AT: + enableAt(it->first.first, it->first.second); + case FlowProfile::UNKNOWN: + break; + default: + break; + } + } + return getResidualFromSource(); +} + +edouble BoostFlowProfileGraph::getResidualFromSource() { + using namespace boost; + debugMsg("BoostFlowProfileGraph:getResidualFromSource", + (isLowerLevel() ? "" : "") << "Getting residual..."); + edouble residual = 0.0; + if(num_vertices(m_graph) <= 2) { + m_recalculate = false; + return residual; + } + if(m_recalculate) { + double flow = boykov_kolmogorov_max_flow(m_graph, m_source, m_sink); + debugMsg("BoostFlowProfileGraph:getResidualFromSource", "Total flow: " << flow); + property_map::type flowMap = get(edge_flow, m_graph); + property_map::type capcityMap = get(edge_capacity, m_graph); + Graph::edge_iterator it, end; + for(tie(it, end) = edges(m_graph); it != end; ++it) { + debugMsg("BoostFlowProfileGraph:getResidualFromSource", + getTransaction(source(*it, m_graph)) << " -> " << + getTransaction(target(*it, m_graph)) << + " [" << flowMap[*it] << ":" << capcityMap[*it] << "]"); + } + m_recalculate = false; + } + property_map::type + residualCapacity = get(edge_residual_capacity, m_graph); + Graph::out_edge_iterator outIt, outEnd; + tie(outIt, outEnd) = out_edges(m_source, m_graph); + for(; outIt != outEnd; ++outIt) { + residual += residualCapacity[*outIt]; + debugMsg("BoostFlowProfileGraph:getResidualFromSource", + getTransaction(source(*outIt, m_graph)) << " -> " << + getTransaction(target(*outIt, m_graph)) << + " [" << residualCapacity[*outIt] << "]: " << residual); + } + + return residual; +} + +void BoostFlowProfileGraph::removeTransaction(const TransactionId& id) { + using namespace boost; + debugMsg("BoostFlowProfileGraph:removeTransaction", + (isLowerLevel() ? "" : "") << "Removing " << id); + disable(id); + m_recalculate = true; +} + +void BoostFlowProfileGraph::reset() { + initializeGraph(getTransaction(m_source), getTransaction(m_sink)); +} + +} + diff --git a/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh b/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh new file mode 100644 index 000000000..7dff17f7a --- /dev/null +++ b/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh @@ -0,0 +1,159 @@ +#ifndef _H_BoostFlowProfileGraph +#define _H_BoostFlowProfileGraph + +#include "FlowProfileGraph.hh" +#include "Types.hh" + +#include +#include + +#include +#include +#include + +namespace EUROPA { +class BoostFlowProfileGraph : public FlowProfileGraph { + public: + /** + * @brief Creates a directed graph with a \a source and a \sink intended to calculate the + * lower level envelope in case \a lowerLevel is true otherwise intended to calculate the + * upper level envelope. + */ + BoostFlowProfileGraph(const TransactionId& source, const TransactionId& sink, bool lowerLevel); + /** + * @brief Destructor + */ + ~BoostFlowProfileGraph() {} + /** + * @brief Creates bi-directional edge between \a t1 and \a t2 with infinite capacity + * as a result of a concurrent constraint between the two transactions + */ + void enableAt(const TransactionId& t1, const TransactionId& t2); + /** + * @brief Creates directed edge between \a t1 and \a t2 with infinite capacity + * as a result of a before or at constraint between the two transactions (reverse + * capacity set to zero) + */ + void enableAtOrBefore(const TransactionId& t1, const TransactionId& t2); + /** + * @brief Creates a node in the network and creates an edge: + * + * \verbatim + * | lower level | upper level + * --------------------------------------------------------------------------------------------------------- + * transaction is consumer | w = q.upper | w = q.lower + * --------------------------------------------------------------------------------------------------------- + * transaction is producer | w = q.lower | w = q.upper + * --------------------------------------------------------------------------------------------------------- + * \endverbatim + */ + void enableTransaction(const TransactionId& transaction, const InstantId& inst, + TransactionId2InstantId& contributions); + /** + * @brief Returns true if \a transaction is enabled in the invoking + * instance + */ + bool isEnabled(const TransactionId& transaction) const {return true;} + /** + * @brief Disables \a transaction, if enabled, for the invoking instance + */ + void disable( const TransactionId& transaction ); + /** + * @brief Will push any flow wich flows through the node corresponding with \a transaction + * back to the source of the edge the flow originates from. + * + * When we move from one instant to another we retract all the transactions whose end time + * is equal to the new instant time and the transaction is still in the network. This method + * will push any flow going through this node back to where it is coming from after which we + * try again to push the flow to the sink. + + * Will error out if no node corresponding to \a transaction is in the network or if the node + * is not enabled. + * + * If a recalculation of the maximum flow is required this method will do nothing. + * \todo verify if this is really required or perhaps we should error out? + */ + void pushFlow( const TransactionId& transaction ) {return;} + /** + * @brief Returns the cummulative residual capacity originating from the source. + * + * Iterates over all outgoing edges from the source and sums the residual capicity of each + * edge. Might trigger a maximum flow (re) calculation if required. + */ + edouble getResidualFromSource(); + edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, + const FlowProfile::TransactionIdTransactionIdPair2Order& other); + + /** + * @brief Disables every node reachable from the source in the residual network. Returns the sum + * of the contribution of each disabled node. The contribution is determined as following: + * \verbatim + * | lower level | upper level + * --------------------------------------------------------------------------------------------------------- + * transaction is consumer | q.upper | q.lower + * --------------------------------------------------------------------------------------------------------- + * transaction is producer | q.lower | q.upper + * --------------------------------------------------------------------------------------------------------- + * \endverbatim + * + * where q is the quantity variable associated with the transactions associated with the node. The parameter \a + * contributions, which maps a TransactionId to a InstantId is maps every transaction associated with a disabled + * node to \a instant. + */ + edouble disableReachableResidualGraph( TransactionId2InstantId& contributions, const InstantId& instant ) {return 0.0;} + /** + * @brief Removes transaction \a id from the network. + */ + void removeTransaction(const TransactionId& id); + /** + * @brief Resets the invoking instance. + * + * Resetting entails disabling all the nodes, implying disabling all the edges, except for the + * source and the sink. + * + */ + void reset(); + /** + * @brief Restore flow invokes the maximum flow algorithm without resetting the existing distances + * and existing flows on the nodes. + * + * Restore flows is done after extracting all the nodes that expire (go from pending to closed set + * at an instant) from the network by pushing flow back. + */ + void restoreFlow() {} + private: + + typedef boost::adjacency_list_traits Traits; + // typedef boost::adjacency_list_traits Traits; + typedef Traits::vertex_descriptor Vertex; + typedef Traits::edge_descriptor Edge; + typedef boost::adjacency_list > > >, + + boost::property > > > > Graph; + + // do these need to return references? + Vertex addNode(const TransactionId& t); + Vertex getNode(const TransactionId& t) const; + TransactionId getTransaction(const Vertex& v) const; + Edge addEdge(const TransactionId& t1, const TransactionId& t2, const edouble capacity, + const edouble reverseCapacity); + void initializeGraph(const TransactionId& source, const TransactionId& sink); + void addTransactionToGraph(const TransactionId& t); + + Graph m_graph; + std::map m_transactionToVertex; + std::map m_vertexToTransaction; + std::vector m_activeTransactions; + Vertex m_source, m_sink; + bool m_recalculate; +}; +} +#endif diff --git a/src/PLASMA/Resource/component/FlowProfile.cc b/src/PLASMA/Resource/component/FlowProfile.cc index 9c9ff0c4c..4042f4441 100644 --- a/src/PLASMA/Resource/component/FlowProfile.cc +++ b/src/PLASMA/Resource/component/FlowProfile.cc @@ -16,6 +16,7 @@ #include "Debug.hh" #include "Domains.hh" #include "FlowProfile.hh" +#include "FlowProfileGraph.hh" #include "Graph.hh" #include "Instant.hh" #include "Node.hh" @@ -29,227 +30,12 @@ namespace EUROPA { - FlowProfileGraph::FlowProfileGraph( const TransactionId& source, const TransactionId& sink, bool lowerlevel ): - m_lowerLevel( lowerlevel ), - m_recalculate( false ), - m_graph( 0 ), - m_source( 0 ), - m_sink( 0 ) - { - m_graph = new Graph(); - m_source = m_graph->createNode( source ); - m_sink = m_graph->createNode( sink ); - m_maxflow = new MaximumFlowAlgorithm( m_graph, m_source, m_sink ); - } - - FlowProfileGraph::~FlowProfileGraph() - { - delete m_maxflow; - m_maxflow = 0; - - delete m_graph; - m_graph = 0; - - m_source = 0; - m_sink = 0; - } - - void FlowProfileGraph::enableAt( const TransactionId& t1, const TransactionId& t2 ) - { - debugMsg("FlowProfileGraph:enableAt","Transaction " - << t1->time()->toString() << " and transaction " - << t2->time()->toString() << " lower level: " - << std::boolalpha << m_lowerLevel ); - - - if( 0 == m_graph->getNode( t1 ) ) - return; - - if( 0 == m_graph->getNode( t2 ) ) - return; - - m_recalculate = true; - - m_graph->createEdge( t1, t2, Edge::getMaxCapacity() ); - m_graph->createEdge( t2, t1, Edge::getMaxCapacity() ); - } - - void FlowProfileGraph::enableAtOrBefore( const TransactionId& t1, const TransactionId& t2 ) - { - debugMsg("FlowProfileGraph:enableAtOrBefore","Transaction " - << t1->time()->toString() << " and transaction " - << t2->time()->toString() << " lower level: " - << std::boolalpha << m_lowerLevel ); - - - if( 0 == m_graph->getNode( t1 ) ) - return; - - if( 0 == m_graph->getNode( t2 ) ) - return; - - m_recalculate = true; - - m_graph->createEdge( t1, t2, 0 ); - m_graph->createEdge( t2, t1, Edge::getMaxCapacity() ); - } - - bool FlowProfileGraph::isEnabled( const TransactionId& transaction ) const - { - Node* node = m_graph->getNode( transaction ); - - return 0 == node ? false : node->isEnabled(); - } - - void FlowProfileGraph::enableTransaction( const TransactionId& t, const InstantId& i, TransactionId2InstantId& contributions ) - { - debugMsg("FlowProfileGraph:enableTransaction","Transaction (" - << t->getId() << ") " - << t->time()->toString() << " lower level: " - << std::boolalpha << m_lowerLevel ); - - TransactionId source = TransactionId::noId(); - TransactionId target = TransactionId::noId(); - - edouble edgeCapacity = 0; - - if( ( m_lowerLevel && t->isConsumer() ) - || - (!m_lowerLevel && !t->isConsumer() ) ) - { - // connect to the source of the graph - source = m_source->getIdentity(); - target = t; - - edgeCapacity = t->quantity()->lastDomain().getUpperBound(); - } - else - { - // connect to the sink of the graph - source = t; - target = m_sink->getIdentity(); - - edgeCapacity = t->quantity()->lastDomain().getLowerBound(); - } - - if( 0 == edgeCapacity ) - { - debugMsg("FlowProfileGraph:enableTransaction","Transaction " - << t << " starts contributing at " - << i->getTime() << " lower level " << std::boolalpha << m_lowerLevel ); - - contributions[ t ] = i; - - return; - } - - check_error( TransactionId::noId() != source ); - check_error( TransactionId::noId() != target ); - - m_recalculate = true; - - m_graph->createNode( t, true ); - m_graph->createEdge( source, target, edgeCapacity ); - m_graph->createEdge( target, source, 0 ); - } - - void FlowProfileGraph::removeTransaction( const TransactionId& id ) - { - debugMsg("FlowProfileGraph:removeTransaction","Transaction (" - << id->getId() << ") lower level: " - << std::boolalpha << m_lowerLevel ); - - m_recalculate = true; - - m_graph->removeNode( id ); - } - - void FlowProfileGraph::reset() - { - m_recalculate = true; - - m_graph->setDisabled(); - - m_sink->setEnabled(); - m_source->setEnabled(); - } - - - edouble FlowProfileGraph::getResidualFromSource() - { - edouble residual = 0.0; - - if( m_recalculate ) - { - m_maxflow->execute(); - - m_recalculate = false; - } - - EdgeOutIterator ite( *m_source ); - - for( ; ite.ok(); ++ite ) - { - Edge* edge = *ite; - - residual += m_maxflow->getResidual( edge ); - } - - return residual; - } - - void FlowProfileGraph::disable( const TransactionId& id ) - { - debugMsg("FlowProfileGraph:disable","Transaction (" - << id->getId() << ") lower level: " - << std::boolalpha << m_lowerLevel ); - - Node* node = m_graph->getNode( id ); - - check_error( 0 != node ); - check_error( node->isEnabled() ); - - node->setDisabled(); - } - - void FlowProfileGraph::pushFlow( const TransactionId& id ) - { - Node* node = m_graph->getNode( id ); - - check_error( 0 != node ); - check_error( node->isEnabled() ); - - if( !m_recalculate ) - { - debugMsg("FlowProfileGraph:pushFlow","Transaction (" - << id->getId() << ") lower level: " - << std::boolalpha << m_lowerLevel ); - - m_maxflow->pushFlowBack( node ); - } - else - { - debugMsg("FlowProfileGraph:pushFlow","Transaction (" - << id->getId() << ") lower level: " - << std::boolalpha << m_lowerLevel - << " skipping pushing flow back because a recalculation is required."); - - } - } - - void FlowProfileGraph::restoreFlow() - { - m_maxflow->execute( false ); - } - - - //------------------------------- FlowProfile::FlowProfile( const PlanDatabaseId db, const FVDetectorId flawDetector): Profile( db, flawDetector), - m_lowerLevelGraph( 0 ), - m_upperLevelGraph( 0 ), + m_lowerLevelGraph(NULL), + m_upperLevelGraph(NULL), m_recalculateLowerLevel( false ), m_recalculateUpperLevel( false ) { @@ -269,7 +55,7 @@ namespace EUROPA m_dummySourceTransaction = ( new Transaction(dummy1->getId(), dummy2->getId(), false ) )->getId(); m_dummySinkTransaction = ( new Transaction(dummy3->getId(), dummy4->getId(), false) )->getId(); - initializeGraphs(); + initializeGraphs(); } FlowProfile::~FlowProfile() @@ -312,26 +98,30 @@ namespace EUROPA return true; } - void FlowProfile::initializeGraphs() - { - delete m_lowerLevelGraph; - - m_lowerLevelGraph = new FlowProfileGraph( m_dummySourceTransaction, m_dummySinkTransaction, true ); - - delete m_upperLevelGraph; - - m_upperLevelGraph = new FlowProfileGraph( m_dummySourceTransaction, m_dummySinkTransaction, false ); - } - - - void FlowProfile::initRecompute( InstantId inst ) - { - check_error(inst.isValid()); - - debugMsg("FlowProfile:initRecompute","Instant (" << inst->getId() << ") at time " - << inst->getTime() ); +void FlowProfile::initRecompute(InstantId inst) { + check_error(inst.isValid()); + + debugMsg("FlowProfile:initRecompute","Instant (" << inst->getId() << ") at time " + << inst->getTime() ); + m_lowerClosedLevel = getInitCapacityLb(); + m_upperClosedLevel = getInitCapacityUb(); + + for(std::set::const_iterator it = m_transactions.begin(); + it != m_transactions.end(); ++it) { + if((*it)->time()->lastDomain().getUpperBound() < inst->getTime()) { + m_upperClosedLevel = m_upperClosedLevel + + ((*it)->isConsumer() ? + -((*it)->quantity()->lastDomain().getLowerBound()) : + (*it)->quantity()->lastDomain().getUpperBound()); + + m_lowerClosedLevel = m_lowerClosedLevel + + ((*it)->isConsumer() ? + -((*it)->quantity()->lastDomain().getUpperBound()) : + (*it)->quantity()->lastDomain().getLowerBound()); } + } +} void FlowProfile::initRecompute() { @@ -357,127 +147,128 @@ namespace EUROPA m_recalculateUpperLevel = false; } - void FlowProfile::recomputeLevels( InstantId prev, InstantId inst ) +void FlowProfile::recomputeLevels(InstantId prev, InstantId inst) { + check_error( prev.isValid() || InstantId::noId() == prev ); + check_error( inst.isValid() ); + + debugMsg("FlowProfile:recomputeLevels","Computing instant (" + << inst->getId() << ") at time " + << inst->getTime() << " closed levels [" + << m_lowerClosedLevel << "," + << m_upperClosedLevel << "]"); + + const std::set& transactions = inst->getTransactions(); + + std::set::const_iterator iter = transactions.begin(); + std::set::const_iterator end = transactions.end(); + + for( ; iter != end; ++iter ) + { + const TransactionId& transaction1 = (*iter); + + // inst->getTransactions returns all transaction overlapping inst->getTime + // right inclusive + if( transaction1->time()->lastDomain().getUpperBound() == inst->getTime() ) { - check_error( prev.isValid() || InstantId::noId() == prev ); - check_error( inst.isValid() ); + debugMsg("FlowProfile::recomputeLevels","Transaction (" + << transaction1->getId() << ") " + << transaction1->time()->toString() << " " + << transaction1->quantity()->toString() << " enters closed set."); - debugMsg("FlowProfile:recomputeLevels","Computing instant (" - << inst->getId() << ") at time " - << inst->getTime() << " closed levels [" - << m_lowerClosedLevel << "," - << m_upperClosedLevel << "]"); + if( m_recalculateLowerLevel ) + m_lowerLevelGraph->removeTransaction( transaction1 ); - const std::set& transactions = inst->getTransactions(); + if( m_recalculateUpperLevel ) + m_upperLevelGraph->removeTransaction( transaction1 ); - std::set::const_iterator iter = transactions.begin(); - std::set::const_iterator end = transactions.end(); + // if upperbound equals the instant time the transaction enters the closed set + if( transaction1->isConsumer() ) + { + if( m_recalculateUpperLevel ) + m_upperClosedLevel -= transaction1->quantity()->lastDomain().getLowerBound(); - for( ; iter != end; ++iter ) - { - const TransactionId& transaction1 = (*iter); + if( m_recalculateLowerLevel ) + m_lowerClosedLevel -= transaction1->quantity()->lastDomain().getUpperBound(); + } + else + { + if( m_recalculateUpperLevel ) + m_upperClosedLevel += transaction1->quantity()->lastDomain().getUpperBound(); - // inst->getTransactions returns all transaction overlapping inst->getTime - // right inclusive - if( transaction1->time()->lastDomain().getUpperBound() == inst->getTime() ) - { - debugMsg("FlowProfile::recomputeLevels","Transaction (" - << transaction1->getId() << ") " - << transaction1->time()->toString() << " " - << transaction1->quantity()->toString() << " enters closed set."); - - if( m_recalculateLowerLevel ) - m_lowerLevelGraph->removeTransaction( transaction1 ); - - if( m_recalculateUpperLevel ) - m_upperLevelGraph->removeTransaction( transaction1 ); - - // if upperbound equals the instant time the transaction enters the closed set - if( transaction1->isConsumer() ) - { - if( m_recalculateUpperLevel ) - m_upperClosedLevel -= transaction1->quantity()->lastDomain().getLowerBound(); - - if( m_recalculateLowerLevel ) - m_lowerClosedLevel -= transaction1->quantity()->lastDomain().getUpperBound(); - } - else - { - if( m_recalculateUpperLevel ) - m_upperClosedLevel += transaction1->quantity()->lastDomain().getUpperBound(); - - if( m_recalculateLowerLevel ) - m_lowerClosedLevel += transaction1->quantity()->lastDomain().getLowerBound(); - } - } - else - { - if( transaction1->time()->lastDomain().getLowerBound() == inst->getTime() ) - { - enableTransaction( transaction1, inst ); - - std::set::const_iterator secondIter = transactions.begin(); - - for( ; secondIter != end; ++secondIter ) - { - const TransactionId& transaction2 = (*secondIter); - - if( transaction1 != transaction2 ) - { - if( transaction2->time()->lastDomain().getUpperBound() != inst->getTime() ) - { - enableTransaction( transaction2, inst ); - - debugMsg("FlowProfile:recomputeLevels","Determining ordering of pending transaction (" - << transaction1->getId() << ") " - << transaction1->time()->toString() << " and pending transaction (" - << transaction2->getId() << ") " - << transaction2->time()->toString() ); - - Order order = getOrdering( transaction1, transaction2 ); - - if( STRICTLY_AT == order ) - { - handleOrderedAt( transaction1, transaction2 ); - } - else if( BEFORE_OR_AT == order ) - { - handleOrderedAtOrBefore( transaction1, transaction2 ); - } - else - { - debugMsg("FlowProfile::recomputeLevels","Transaction (" - << transaction1->getId() << ") and Transaction (" - << transaction2->getId() << ") not constrained"); - } - } - } - } - } - } - } + if( m_recalculateLowerLevel ) + m_lowerClosedLevel += transaction1->quantity()->lastDomain().getLowerBound(); + } + } + else + { + // if( transaction1->time()->lastDomain().getLowerBound() == inst->getTime() ) + // { + enableTransaction( transaction1, inst ); + + std::set::const_iterator secondIter = transactions.begin(); + + for( ; secondIter != end; ++secondIter ) + { + const TransactionId& transaction2 = (*secondIter); + + if( transaction1 != transaction2 ) + { + if( transaction2->time()->lastDomain().getUpperBound() != inst->getTime() ) + { + enableTransaction( transaction2, inst ); + + debugMsg("FlowProfile:recomputeLevels", + "Determining ordering of pending transaction (" + << transaction1->getId() << ") " + << transaction1->time()->toString() << + " and pending transaction (" + << transaction2->getId() << ") " + << transaction2->time()->toString() ); + + Order order = getOrdering( transaction1, transaction2 ); + + if( STRICTLY_AT == order ) + { + handleOrderedAt( transaction1, transaction2 ); + } + else if( BEFORE_OR_AT == order ) + { + handleOrderedAtOrBefore( transaction1, transaction2 ); + } + else + { + debugMsg("FlowProfile::recomputeLevels","Transaction (" + << transaction1->getId() << ") and Transaction (" + << transaction2->getId() << ") not constrained"); + } + } + } + } + // } + } + } - edouble lowerLevel = inst->getLowerLevel(); + edouble lowerLevel = inst->getLowerLevel(); - if( m_recalculateLowerLevel ) - lowerLevel = m_lowerClosedLevel - m_lowerLevelGraph->getResidualFromSource(); + if( m_recalculateLowerLevel ) + lowerLevel = m_lowerClosedLevel - m_lowerLevelGraph->getResidualFromSource(m_orderedAt, m_orderings); - edouble upperLevel = inst->getUpperLevel(); + edouble upperLevel = inst->getUpperLevel(); - if( m_recalculateUpperLevel ) - upperLevel = m_upperClosedLevel + m_upperLevelGraph->getResidualFromSource(); + if( m_recalculateUpperLevel ) + upperLevel = m_upperClosedLevel + m_upperLevelGraph->getResidualFromSource(m_orderedAt, m_orderings); - debugMsg("FlowProfile::recomputeLevels","Computed levels for instance at time " - << inst->getTime() << "[" - << lowerLevel << "," - << upperLevel << "]"); + debugMsg("FlowProfile::recomputeLevels","Computed levels for instance at time " + << inst->getTime() << "[" + << lowerLevel << "," + << upperLevel << "]"); - inst->update( lowerLevel, lowerLevel, upperLevel, upperLevel, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0 ); - } + inst->update( lowerLevel, lowerLevel, upperLevel, upperLevel, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0 ); +} FlowProfile::Order FlowProfile::getOrdering( const TransactionId t1, const TransactionId t2 ) { @@ -855,41 +646,53 @@ namespace EUROPA } - void FlowProfile::handleTemporalConstraintRemoved( const TransactionId predecessor, const int preArgIndex, - const TransactionId successor, const int sucArgIndex) - { - debugMsg("FlowProfile:handleTemporalConstraintRemoved","TransactionId1 (" << predecessor->getId() << ") before TransactionId2 (" << successor->getId() << ")"); - - check_error(predecessor.isValid()); - check_error(successor.isValid()); - - m_orderings.clear(); - m_orderedAt.clear(); - - eint startRecalculation = PLUS_INFINITY; - eint endRecalculation = MINUS_INFINITY; - - if( ProfileIteratorId::noId() != m_recomputeInterval ) - { - eint start = m_recomputeInterval->getStartTime(); - eint end = m_recomputeInterval->getEndTime(); - - startRecalculation = std::min( start, std::min( (eint) predecessor->time()->lastDomain().getLowerBound(), (eint) successor->time()->lastDomain().getLowerBound() ) ); - endRecalculation = std::max( end, std::max( (eint) predecessor->time()->lastDomain().getUpperBound(), (eint) successor->time()->lastDomain().getUpperBound() ) ); - } - else - { - startRecalculation = std::min( (eint) predecessor->time()->lastDomain().getLowerBound(), (eint) successor->time()->lastDomain().getLowerBound() ); - endRecalculation = std::max( (eint) predecessor->time()->lastDomain().getUpperBound(), (eint) successor->time()->lastDomain().getUpperBound() ); - } - - - if(m_recomputeInterval.isValid()) - delete (ProfileIterator*) m_recomputeInterval; - - m_recomputeInterval = (new ProfileIterator( getId(), startRecalculation, endRecalculation ))->getId(); - - m_recalculateLowerLevel = true; - m_recalculateUpperLevel = true; - } +void FlowProfile::handleTemporalConstraintRemoved(const TransactionId predecessor, + const int preArgIndex, + const TransactionId successor, + const int sucArgIndex) { + debugMsg("FlowProfile:handleTemporalConstraintRemoved", + "TransactionId1 (" << predecessor->getId() << + ") before TransactionId2 (" << successor->getId() << ")"); + + check_error(predecessor.isValid()); + check_error(successor.isValid()); + + m_orderings.clear(); + m_orderedAt.clear(); + + eint startRecalculation = PLUS_INFINITY; + eint endRecalculation = MINUS_INFINITY; + + if( ProfileIteratorId::noId() != m_recomputeInterval ) { + eint start = m_recomputeInterval->getStartTime(); + eint end = m_recomputeInterval->getEndTime(); + + startRecalculation = + std::min(start, + std::min((eint) predecessor->time()->lastDomain().getLowerBound(), + (eint) successor->time()->lastDomain().getLowerBound())); + endRecalculation = + std::max(end, + std::max((eint) predecessor->time()->lastDomain().getUpperBound(), + (eint) successor->time()->lastDomain().getUpperBound())); + } + else { + startRecalculation = + std::min((eint) predecessor->time()->lastDomain().getLowerBound(), + (eint) successor->time()->lastDomain().getLowerBound()); + endRecalculation = + std::max((eint) predecessor->time()->lastDomain().getUpperBound(), + (eint) successor->time()->lastDomain().getUpperBound()); + } + + + if(m_recomputeInterval.isValid()) + delete (ProfileIterator*) m_recomputeInterval; + + m_recomputeInterval = + (new ProfileIterator( getId(), startRecalculation, endRecalculation ))->getId(); + + m_recalculateLowerLevel = true; + m_recalculateUpperLevel = true; +} } diff --git a/src/PLASMA/Resource/component/FlowProfile.hh b/src/PLASMA/Resource/component/FlowProfile.hh index 1066cbd41..eed724edd 100644 --- a/src/PLASMA/Resource/component/FlowProfile.hh +++ b/src/PLASMA/Resource/component/FlowProfile.hh @@ -21,237 +21,10 @@ namespace EUROPA { - class Graph; - class MaximumFlowAlgorithm; - class Node; - - /** - * @brief Graph structure to determine the subset of pending transactions at time T - * which has the largest contribution to an envelope (see FlowProfile) - */ - class FlowProfileGraph - { - public: - /** - * @brief Creates a directed graph with a \a source and a \sink intended to calculate the - * lower level envelope in case \a lowerLevel is true otherwise intended to calculate the - * upper level envelope. - */ - FlowProfileGraph( const TransactionId& source, const TransactionId& sink, bool lowerLevel ); - /** - * @brief Destructor - */ - ~FlowProfileGraph(); - /** - * @brief Creates bi-directional edge between \a t1 and \a t2 with infinite capacity - * as a result of a concurrent constraint between the two transactions - */ - void enableAt( const TransactionId& t1, const TransactionId& t2 ); - /** - * @brief Creates directed edge between \a t1 and \a t2 with infinite capacity - * as a result of a before or at constraint between the two transactions (reverse - * capacity set to zero) - */ - void enableAtOrBefore( const TransactionId& t1, const TransactionId& t2 ); - /** - * @brief Creates a node in the network and creates an edge: - * - * \verbatim - * | lower level | upper level - * --------------------------------------------------------------------------------------------------------- - * transaction is consumer | w = q.upper | w = q.lower - * --------------------------------------------------------------------------------------------------------- - * transaction is producer | w = q.lower | w = q.upper - * --------------------------------------------------------------------------------------------------------- - * \endverbatim - */ - void enableTransaction( const TransactionId& transaction, const InstantId& inst, TransactionId2InstantId& contributions ); - /** - * @brief Returns true if \a transaction is enabled in the invoking - * instance - */ - bool isEnabled( const TransactionId& transaction ) const; - /** - * @brief Disables \a transaction, if enabled, for the invoking instance - */ - void disable( const TransactionId& transaction ) ; - /** - * @brief Will push any flow wich flows through the node corresponding with \a transaction - * back to the source of the edge the flow originates from. - * - * When we move from one instant to another we retract all the transactions whose end time - * is equal to the new instant time and the transaction is still in the network. This method - * will push any flow going through this node back to where it is coming from after which we - * try again to push the flow to the sink. - - * Will error out if no node corresponding to \a transaction is in the network or if the node - * is not enabled. - * - * If a recalculation of the maximum flow is required this method will do nothing. - * \todo verify if this is really required or perhaps we should error out? - */ - void pushFlow( const TransactionId& transaction ); - /** - * @brief Returns the cummulative residual capacity originating from the source. - * - * Iterates over all outgoing edges from the source and sums the residual capicity of each - * edge. Might trigger a maximum flow (re) calculation if required. - */ - edouble getResidualFromSource(); - /** - * @brief Disables every node reachable from the source in the residual network. Returns the sum - * of the contribution of each disabled node. The contribution is determined as following: - * \verbatim - * | lower level | upper level - * --------------------------------------------------------------------------------------------------------- - * transaction is consumer | q.upper | q.lower - * --------------------------------------------------------------------------------------------------------- - * transaction is producer | q.lower | q.upper - * --------------------------------------------------------------------------------------------------------- - * \endverbatim - * - * where q is the quantity variable associated with the transactions associated with the node. The parameter \a - * contributions, which maps a TransactionId to a InstantId is maps every transaction associated with a disabled - * node to \a instant. - */ - inline edouble disableReachableResidualGraph( TransactionId2InstantId& contributions, const InstantId& instant ); - /** - * @brief Returns true if the invoking instance calculates the lower level, otherwise returns false which indicates - * the invoking instance is calculating the upper level. - */ - bool isLowerLevel() const { return m_lowerLevel; } - /** - * @brief Removes transaction \a id from the network. - */ - void removeTransaction( const TransactionId& id ); - /** - * @brief Resets the invoking instance. - * - * Resetting entails disabling all the nodes, implying disabling all the edges, except for the - * source and the sink. - * - */ - void reset(); - /** - * @brief Restore flow invokes the maximum flow algorithm without resetting the existing distances - * and existing flows on the nodes. - * - * Restore flows is done after extracting all the nodes that expire (go from pending to closed set - * at an instant) from the network by pushing flow back. - */ - void restoreFlow(); - private: - /** - * @brief Helper function for disableReachableResidualGraph - */ - inline void visitNeighbors( const Node* node, edouble& residual, Node2Bool& visited, TransactionId2InstantId& contributions, const InstantId& instant ); - /*! - * @brief Boolean indicating if the instance is intended to calculate the lower level - */ - bool m_lowerLevel; - /*! - * @brief Boolean indicating if the maximum flow solution needs to be recalculated - */ - bool m_recalculate; - /*! - * @brief - */ - MaximumFlowAlgorithm* m_maxflow; - /*! - * @brief Bi directional graph datastructure - */ - Graph* m_graph; - /*! - * @brief Source for the maximum flow problem - */ - Node* m_source; - /*! - * @brief Sink for the maximum flow problem - */ - Node* m_sink; - }; - - edouble FlowProfileGraph::disableReachableResidualGraph( TransactionId2InstantId& contributions, const InstantId& instant ) - { - debugMsg("FlowProfileGraph:disableReachableResidualGraph","Lower level: " - << std::boolalpha << m_lowerLevel ); - - edouble residual = 0.0; - - if( m_recalculate ) - { - debugMsg("FlowProfileGraph:disableReachableResidualGraph","Lower level: " - << std::boolalpha << m_lowerLevel << ", recalculate invoked."); - - m_maxflow->execute(); - - Node2Bool visited; - - visited[ m_source ] = true; - - visitNeighbors( m_source, residual, visited, contributions, instant ); - } - - return residual; - } - - void FlowProfileGraph::visitNeighbors( const Node* node, edouble& residual, Node2Bool& visited, TransactionId2InstantId& contributions, const InstantId& instant ) - { - EdgeOutIterator ite( *node ); - - for( ; ite.ok(); ++ite ) - { - Edge* edge = *ite; - - Node* target = edge->getTarget(); - - if( false == visited[ target ] ) - { - if( 0 != m_maxflow->getResidual( edge ) ) - { - visited[ target ] = true; - - if( target != m_source && target != m_sink ) - { - debugMsg("FlowProfileGraph:visitNeighbors","Disabling node with transaction (" - << target->getIdentity()->getId() << ") lower level " << std::boolalpha << m_lowerLevel ); - - target->setDisabled(); - - const TransactionId& t = target->getIdentity(); - - debugMsg("FlowProfileGraph::visitNeighbors","Transaction " - << t << " starts contributing at " - << instant->getTime() << " lower level " << std::boolalpha << m_lowerLevel ); - - contributions[ t ] = instant; - - int sign = t->isConsumer() ? -1 : +1; - - if( ( m_lowerLevel && t->isConsumer() ) - || - (!m_lowerLevel && !t->isConsumer() ) ) - { - debugMsg("FlowProfileGraph:visitNeighbors","Adding " - << sign * t->quantity()->lastDomain().getUpperBound() << " to the level."); - - residual += sign * t->quantity()->lastDomain().getUpperBound(); - } - else - { - debugMsg("FlowProfileGraph:visitNeighbors","Adding " - << sign* t->quantity()->lastDomain().getLowerBound() << " to the level."); - - residual += sign * t->quantity()->lastDomain().getLowerBound(); - } - - visitNeighbors( target, residual, visited, contributions, instant ); - } - } - } - } - } - +class Graph; +class MaximumFlowAlgorithm; +class Node; +class FlowProfileGraph; /** @@ -296,6 +69,19 @@ namespace EUROPA public Profile { public: + /** + * @brief Indicates the ordering between two time variables associated with a transaction + */ + enum Order { + AFTER_OR_AT = 0, /*!< Indicates one transaction is strictly after or at the same time with another transaction. */ + BEFORE_OR_AT,/*!< Indicates one transaction is strictly before or at the same time with another transaction. */ + NOT_ORDERED,/*!< Indicates one transaction is not ordered with another transaction. */ + STRICTLY_AT,/*!< Indicates one transaction is strictly at the same time with another transaction. */ + UNKNOWN + }; + typedef std::pair TransactionIdTransactionIdPair; + typedef std::map< TransactionIdTransactionIdPair, Order > TransactionIdTransactionIdPair2Order; + /** * @brief Constructor */ @@ -318,21 +104,24 @@ namespace EUROPA * has been associated with transaction t. */ bool getEarliestUpperLevelInstant( const TransactionId& t, InstantId& i ); - protected: - /** - * @brief Indicates the ordering between two time variables associated with a transaction - */ - enum Order { - AFTER_OR_AT = 0, /*!< Indicates one transaction is strictly after or at the same time with another transaction. */ - BEFORE_OR_AT,/*!< Indicates one transaction is strictly before or at the same time with another transaction. */ - NOT_ORDERED,/*!< Indicates one transaction is not ordered with another transaction. */ - STRICTLY_AT,/*!< Indicates one transaction is strictly at the same time with another transaction. */ - UNKNOWN - }; /** * @brief Deletes pre-existing FlowProfileGraphs for the lower and upper level and allocates new ones. */ - void initializeGraphs(); + template + void initializeGraphs() { + if(m_lowerLevelGraph != NULL) + delete m_lowerLevelGraph; + m_lowerLevelGraph = new FlowGraphType(m_dummySourceTransaction, + m_dummySinkTransaction, true); + + if(m_upperLevelGraph != NULL) + delete m_upperLevelGraph; + m_upperLevelGraph = new FlowGraphType(m_dummySourceTransaction, + m_dummySinkTransaction, false); + } + + + protected: /** * @brief */ @@ -429,8 +218,6 @@ namespace EUROPA bool m_recalculateLowerLevel; bool m_recalculateUpperLevel; - typedef std::pair TransactionIdTransactionIdPair; - typedef std::map< TransactionIdTransactionIdPair, Order > TransactionIdTransactionIdPair2Order; TransactionIdTransactionIdPair2Order m_orderings; TransactionIdTransactionIdPair2Order m_orderedAt; diff --git a/src/PLASMA/Resource/component/FlowProfileGraph.cc b/src/PLASMA/Resource/component/FlowProfileGraph.cc new file mode 100644 index 000000000..43a7a7255 --- /dev/null +++ b/src/PLASMA/Resource/component/FlowProfileGraph.cc @@ -0,0 +1,312 @@ +#include "FlowProfileGraph.hh" + +#include "Edge.hh" +#include "EdgeIterator.hh" +#include "MaxFlow.hh" +#include "Node.hh" +#include "Number.hh" + +namespace EUROPA { +FlowProfileGraph::FlowProfileGraph(const TransactionId& source, + const TransactionId& sink, + bool lowerLevel) + : m_lowerLevel(lowerLevel), m_recalculate(false) {} + +FlowProfileGraphImpl::FlowProfileGraphImpl(const TransactionId& source, + const TransactionId& sink, bool lowerLevel) + : FlowProfileGraph(source, sink, lowerLevel), m_graph( 0 ), m_source( 0 ), m_sink( 0 ) { + m_graph = new Graph(); + m_source = m_graph->createNode( source ); + m_sink = m_graph->createNode( sink ); + m_maxflow = new MaximumFlowAlgorithm( m_graph, m_source, m_sink ); +} + +FlowProfileGraphImpl::~FlowProfileGraphImpl() +{ + delete m_maxflow; + m_maxflow = 0; + + delete m_graph; + m_graph = 0; + + m_source = 0; + m_sink = 0; +} + +void FlowProfileGraphImpl::enableAt( const TransactionId& t1, const TransactionId& t2 ) +{ + debugMsg("FlowProfileGraph:enableAt","Transaction " + << t1->time()->toString() << " and transaction " + << t2->time()->toString() << " lower level: " + << std::boolalpha << m_lowerLevel ); + + + if( 0 == m_graph->getNode( t1 ) ) + return; + + if( 0 == m_graph->getNode( t2 ) ) + return; + + m_recalculate = true; + + m_graph->createEdge( t1, t2, Edge::getMaxCapacity() ); + m_graph->createEdge( t2, t1, Edge::getMaxCapacity() ); +} + +void FlowProfileGraphImpl::enableAtOrBefore( const TransactionId& t1, const TransactionId& t2 ) +{ + debugMsg("FlowProfileGraph:enableAtOrBefore","Transaction " + << t1->time()->toString() << " and transaction " + << t2->time()->toString() << " lower level: " + << std::boolalpha << m_lowerLevel ); + + + if( 0 == m_graph->getNode( t1 ) ) + return; + + if( 0 == m_graph->getNode( t2 ) ) + return; + + m_recalculate = true; + + m_graph->createEdge( t1, t2, 0 ); + m_graph->createEdge( t2, t1, Edge::getMaxCapacity() ); +} + +bool FlowProfileGraphImpl::isEnabled( const TransactionId& transaction ) const +{ + Node* node = m_graph->getNode( transaction ); + + return 0 == node ? false : node->isEnabled(); +} + +void FlowProfileGraphImpl::enableTransaction( const TransactionId& t, const InstantId& i, TransactionId2InstantId& contributions ) +{ + debugMsg("FlowProfileGraph:enableTransaction","Transaction (" + << t->getId() << ") " + << t->time()->toString() << " lower level: " + << std::boolalpha << m_lowerLevel ); + + TransactionId source = TransactionId::noId(); + TransactionId target = TransactionId::noId(); + + edouble edgeCapacity = 0; + + if( ( m_lowerLevel && t->isConsumer() ) + || + (!m_lowerLevel && !t->isConsumer() ) ) + { + // connect to the source of the graph + source = m_source->getIdentity(); + target = t; + + edgeCapacity = t->quantity()->lastDomain().getUpperBound(); + } + else + { + // connect to the sink of the graph + source = t; + target = m_sink->getIdentity(); + + edgeCapacity = t->quantity()->lastDomain().getLowerBound(); + } + + if( 0 == edgeCapacity ) + { + debugMsg("FlowProfileGraph:enableTransaction","Transaction " + << t << " starts contributing at " + << i->getTime() << " lower level " << std::boolalpha << m_lowerLevel ); + + contributions[ t ] = i; + + return; + } + + check_error( TransactionId::noId() != source ); + check_error( TransactionId::noId() != target ); + + m_recalculate = true; + + m_graph->createNode( t, true ); + m_graph->createEdge( source, target, edgeCapacity ); + m_graph->createEdge( target, source, 0 ); +} + +void FlowProfileGraphImpl::removeTransaction( const TransactionId& id ) +{ + debugMsg("FlowProfileGraph:removeTransaction","Transaction (" + << id->getId() << ") lower level: " + << std::boolalpha << m_lowerLevel ); + + m_recalculate = true; + + m_graph->removeNode( id ); +} + +void FlowProfileGraphImpl::reset() +{ + m_recalculate = true; + + m_graph->setDisabled(); + + m_sink->setEnabled(); + m_source->setEnabled(); +} + + +edouble FlowProfileGraphImpl::getResidualFromSource() +{ + edouble residual = 0.0; + + if( m_recalculate ) + { + m_maxflow->execute(); + + m_recalculate = false; + } + + EdgeOutIterator ite( *m_source ); + + for( ; ite.ok(); ++ite ) + { + Edge* edge = *ite; + + residual += m_maxflow->getResidual( edge ); + } + + return residual; +} + +void FlowProfileGraphImpl::disable( const TransactionId& id ) +{ + debugMsg("FlowProfileGraph:disable","Transaction (" + << id->getId() << ") lower level: " + << std::boolalpha << m_lowerLevel ); + + Node* node = m_graph->getNode( id ); + + check_error( 0 != node ); + check_error( node->isEnabled() ); + + node->setDisabled(); +} + +void FlowProfileGraphImpl::pushFlow( const TransactionId& id ) +{ + Node* node = m_graph->getNode( id ); + + check_error( 0 != node ); + check_error( node->isEnabled() ); + + if( !m_recalculate ) + { + debugMsg("FlowProfileGraph:pushFlow","Transaction (" + << id->getId() << ") lower level: " + << std::boolalpha << m_lowerLevel ); + + m_maxflow->pushFlowBack( node ); + } + else + { + debugMsg("FlowProfileGraph:pushFlow","Transaction (" + << id->getId() << ") lower level: " + << std::boolalpha << m_lowerLevel + << " skipping pushing flow back because a recalculation is required."); + + } +} + +void FlowProfileGraphImpl::restoreFlow() +{ + m_maxflow->execute( false ); +} + + +edouble FlowProfileGraphImpl::disableReachableResidualGraph( TransactionId2InstantId& contributions, const InstantId& instant ) +{ + debugMsg("FlowProfileGraph:disableReachableResidualGraph","Lower level: " + << std::boolalpha << m_lowerLevel ); + + edouble residual = 0.0; + + if( m_recalculate ) + { + debugMsg("FlowProfileGraph:disableReachableResidualGraph","Lower level: " + << std::boolalpha << m_lowerLevel << ", recalculate invoked."); + + m_maxflow->execute(); + + Node2Bool visited; + + visited[ m_source ] = true; + + visitNeighbors( m_source, residual, visited, contributions, instant ); + } + + return residual; +} + +void FlowProfileGraphImpl::visitNeighbors(const Node* node, edouble& residual, + Node2Bool& visited, + TransactionId2InstantId& contributions, + const InstantId& instant) { + EdgeOutIterator ite( *node ); + + for( ; ite.ok(); ++ite ) + { + Edge* edge = *ite; + + Node* target = edge->getTarget(); + + if( false == visited[ target ] ) + { + if( 0 != m_maxflow->getResidual( edge ) ) + { + visited[ target ] = true; + + if( target != m_source && target != m_sink ) + { + debugMsg("FlowProfileGraph:visitNeighbors", + "Disabling node with transaction (" + << target->getIdentity()->getId() << ") lower level " << + std::boolalpha << m_lowerLevel << " due to " << *edge); + + target->setDisabled(); + + const TransactionId& t = target->getIdentity(); + + debugMsg("FlowProfileGraph::visitNeighbors","Transaction " + << t << " starts contributing at " + << instant->getTime() << " lower level " << std::boolalpha << + m_lowerLevel ); + + contributions[ t ] = instant; + + int sign = t->isConsumer() ? -1 : +1; + + if( ( m_lowerLevel && t->isConsumer() ) + || + (!m_lowerLevel && !t->isConsumer() ) ) + { + debugMsg("FlowProfileGraph:visitNeighbors","Adding " + << sign * t->quantity()->lastDomain().getUpperBound() << + " to the level."); + + residual += sign * t->quantity()->lastDomain().getUpperBound(); + } + else + { + debugMsg("FlowProfileGraph:visitNeighbors","Adding " + << sign* t->quantity()->lastDomain().getLowerBound() << + " to the level."); + + residual += sign * t->quantity()->lastDomain().getLowerBound(); + } + + visitNeighbors( target, residual, visited, contributions, instant ); + } + } + } + } +} +} diff --git a/src/PLASMA/Resource/component/FlowProfileGraph.hh b/src/PLASMA/Resource/component/FlowProfileGraph.hh new file mode 100644 index 000000000..b5663785e --- /dev/null +++ b/src/PLASMA/Resource/component/FlowProfileGraph.hh @@ -0,0 +1,189 @@ +#ifndef _H_FlowProfileGraph +#define _H_FlowProfileGraph + + +#include "Types.hh" +#include "FlowProfile.hh" + +namespace EUROPA { + +class Graph; +class MaximumFlowAlgorithm; +class Node; + +/** + * @brief Graph structure to determine the subset of pending transactions at time T + * which has the largest contribution to an envelope (see FlowProfile) + */ +class FlowProfileGraph +{ + public: + /** + * @brief Creates a directed graph with a \a source and a \sink intended to calculate the + * lower level envelope in case \a lowerLevel is true otherwise intended to calculate the + * upper level envelope. + */ + FlowProfileGraph( const TransactionId& source, const TransactionId& sink, bool lowerLevel ); + /** + * @brief Destructor + */ + virtual ~FlowProfileGraph() {} + /** + * @brief Creates bi-directional edge between \a t1 and \a t2 with infinite capacity + * as a result of a concurrent constraint between the two transactions + */ + virtual void enableAt( const TransactionId& t1, const TransactionId& t2 ) = 0; + /** + * @brief Creates directed edge between \a t1 and \a t2 with infinite capacity + * as a result of a before or at constraint between the two transactions (reverse + * capacity set to zero) + */ + virtual void enableAtOrBefore( const TransactionId& t1, const TransactionId& t2 ) = 0; + /** + * @brief Creates a node in the network and creates an edge: + * + * \verbatim + * | lower level | upper level + * --------------------------------------------------------------------------------------------------------- + * transaction is consumer | w = q.upper | w = q.lower + * --------------------------------------------------------------------------------------------------------- + * transaction is producer | w = q.lower | w = q.upper + * --------------------------------------------------------------------------------------------------------- + * \endverbatim + */ + virtual void enableTransaction( const TransactionId& transaction, const InstantId& inst, TransactionId2InstantId& contributions ) = 0; + /** + * @brief Returns true if \a transaction is enabled in the invoking + * instance + */ + virtual bool isEnabled( const TransactionId& transaction ) const = 0; + /** + * @brief Disables \a transaction, if enabled, for the invoking instance + */ + virtual void disable( const TransactionId& transaction ) = 0; + /** + * @brief Will push any flow wich flows through the node corresponding with \a transaction + * back to the source of the edge the flow originates from. + * + * When we move from one instant to another we retract all the transactions whose end time + * is equal to the new instant time and the transaction is still in the network. This method + * will push any flow going through this node back to where it is coming from after which we + * try again to push the flow to the sink. + + * Will error out if no node corresponding to \a transaction is in the network or if the node + * is not enabled. + * + * If a recalculation of the maximum flow is required this method will do nothing. + * \todo verify if this is really required or perhaps we should error out? + */ + virtual void pushFlow( const TransactionId& transaction ) = 0; + /** + * @brief Returns the cummulative residual capacity originating from the source. + * + * Iterates over all outgoing edges from the source and sums the residual capicity of each + * edge. Might trigger a maximum flow (re) calculation if required. + */ + virtual edouble getResidualFromSource() = 0; + virtual edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, + const FlowProfile::TransactionIdTransactionIdPair2Order& other) = 0; + /** + * @brief Disables every node reachable from the source in the residual network. Returns the sum + * of the contribution of each disabled node. The contribution is determined as following: + * \verbatim + * | lower level | upper level + * --------------------------------------------------------------------------------------------------------- + * transaction is consumer | q.upper | q.lower + * --------------------------------------------------------------------------------------------------------- + * transaction is producer | q.lower | q.upper + * --------------------------------------------------------------------------------------------------------- + * \endverbatim + * + * where q is the quantity variable associated with the transactions associated with the node. The parameter \a + * contributions, which maps a TransactionId to a InstantId is maps every transaction associated with a disabled + * node to \a instant. + */ + virtual edouble disableReachableResidualGraph( TransactionId2InstantId& contributions, const InstantId& instant ) = 0; + /** + * @brief Returns true if the invoking instance calculates the lower level, otherwise returns false which indicates + * the invoking instance is calculating the upper level. + */ + bool isLowerLevel() const { return m_lowerLevel; } + /** + * @brief Removes transaction \a id from the network. + */ + virtual void removeTransaction( const TransactionId& id ) = 0; + /** + * @brief Resets the invoking instance. + * + * Resetting entails disabling all the nodes, implying disabling all the edges, except for the + * source and the sink. + * + */ + virtual void reset() = 0; + /** + * @brief Restore flow invokes the maximum flow algorithm without resetting the existing distances + * and existing flows on the nodes. + * + * Restore flows is done after extracting all the nodes that expire (go from pending to closed set + * at an instant) from the network by pushing flow back. + */ + virtual void restoreFlow() = 0; + protected: + /*! + * @brief Boolean indicating if the instance is intended to calculate the lower level + */ + bool m_lowerLevel; + /*! + * @brief Boolean indicating if the maximum flow solution needs to be recalculated + */ + bool m_recalculate; +}; + +class FlowProfileGraphImpl : public FlowProfileGraph { + public: + FlowProfileGraphImpl(const TransactionId& source, const TransactionId& sink, bool lowerLevel); + ~FlowProfileGraphImpl(); + void enableAt( const TransactionId& t1, const TransactionId& t2 ); + void enableAtOrBefore(const TransactionId& t1, const TransactionId& t2); + void enableTransaction(const TransactionId& transaction, const InstantId& inst, + TransactionId2InstantId& contributions); + bool isEnabled(const TransactionId& transaction) const; + void disable(const TransactionId& transaction); + void pushFlow( const TransactionId& transaction ); + edouble getResidualFromSource(); + edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, + const FlowProfile::TransactionIdTransactionIdPair2Order& other) { + return getResidualFromSource(); + } + + edouble disableReachableResidualGraph(TransactionId2InstantId& contributions, const InstantId& instant); + void removeTransaction(const TransactionId& id); + void reset(); + void restoreFlow(); + private: + /** + * @brief Helper function for disableReachableResidualGraph + */ + void visitNeighbors( const Node* node, edouble& residual, Node2Bool& visited, TransactionId2InstantId& contributions, const InstantId& instant ); + /*! + * @brief + */ + MaximumFlowAlgorithm* m_maxflow; + /*! + * @brief Bi directional graph datastructure + */ + Graph* m_graph; + /*! + * @brief Source for the maximum flow problem + */ + Node* m_source; + /*! + * @brief Sink for the maximum flow problem + */ + Node* m_sink; + +}; + +} + +#endif diff --git a/src/PLASMA/Resource/component/Graph.cc b/src/PLASMA/Resource/component/Graph.cc index fe171a12f..d0e7e99c2 100644 --- a/src/PLASMA/Resource/component/Graph.cc +++ b/src/PLASMA/Resource/component/Graph.cc @@ -58,7 +58,7 @@ namespace EUROPA node = new Node( identity ); graphDebug("Created node " - << *node ); + << *node << " initially " << (enabled ? "enabled" : "disabled")); m_Nodes[ identity ] = node; } @@ -135,6 +135,7 @@ namespace EUROPA void Graph::setDisabled() { + graphDebug("Disabling whole graph.") NodeIdentity2Node::iterator ite = m_Nodes.begin(); NodeIdentity2Node::iterator end = m_Nodes.end(); diff --git a/src/PLASMA/Resource/component/IncrementalFlowProfile.cc b/src/PLASMA/Resource/component/IncrementalFlowProfile.cc index f4455664e..fe777783a 100644 --- a/src/PLASMA/Resource/component/IncrementalFlowProfile.cc +++ b/src/PLASMA/Resource/component/IncrementalFlowProfile.cc @@ -25,6 +25,7 @@ #include "TemporalAdvisor.hh" #include "Utils.hh" #include "Variable.hh" +#include "FlowProfileGraph.hh" namespace EUROPA { @@ -64,7 +65,7 @@ namespace EUROPA m_upperClosedLevel = getInitCapacityUb(); } - initializeGraphs(); + initializeGraphs(); std::set enabledLower; std::set enabledUpper; @@ -204,7 +205,7 @@ namespace EUROPA debugMsg("IncrementalFlowProfile::initRecompute",""); - initializeGraphs(); + initializeGraphs(); // initial level m_lowerClosedLevel = getInitCapacityLb(); @@ -333,208 +334,228 @@ namespace EUROPA recomputeLevels( inst, lowerLevel, upperLevel ); } - void IncrementalFlowProfile::recomputeLevels( InstantId inst, edouble lowerLevel, edouble upperLevel ) - { - // static int counter = 0; - // counter++; +void IncrementalFlowProfile::recomputeLevels( InstantId inst, edouble lowerLevel, + edouble upperLevel ) +{ + // static int counter = 0; + // counter++; - // debugMsg("Performance::recomputeLevels", "Invocation counter = " << counter ); + // debugMsg("Performance::recomputeLevels", "Invocation counter = " << counter ); - debugMsg("IncrementalFlowProfile::recomputeLevels","Instant (" - << inst->getId() << ") at time " - << inst->getTime() << " start levels [" - << lowerLevel << "," - << upperLevel << "]"); + debugMsg("IncrementalFlowProfile::recomputeLevels","Instant (" + << inst->getId() << ") at time " + << inst->getTime() << " start levels [" + << lowerLevel << "," + << upperLevel << "]"); - bool expansion = enableOrderings( inst ); + bool expansion = enableOrderings( inst ); + { + if( expansion ) + { + if( m_recalculateLowerLevel ) { - if( expansion ) - { - if( m_recalculateLowerLevel ) - { - edouble delta = m_lowerLevelGraph->disableReachableResidualGraph( m_lowerLevelContribution, inst ); + edouble delta = + m_lowerLevelGraph->disableReachableResidualGraph(m_lowerLevelContribution, + inst ); - debugMsg("IncrementalFlowProfile::recomputeLevels","Expansion leads to delta lower level of " - << delta ); + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Expansion leads to delta lower level of " << delta ); - lowerLevel += delta; - } + lowerLevel += delta; + } - if( m_recalculateUpperLevel ) - { - edouble delta = m_upperLevelGraph->disableReachableResidualGraph( m_upperLevelContribution, inst ); + if( m_recalculateUpperLevel ) + { + edouble delta = + m_upperLevelGraph->disableReachableResidualGraph( m_upperLevelContribution, + inst ); - debugMsg("IncrementalFlowProfile::recomputeLevels","Expansion leads to delta upper level of " - << delta ); + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Expansion leads to delta upper level of " << delta ); - upperLevel += delta; - } - } + upperLevel += delta; } + } + } - const std::set& endingTransactions = inst->getEndingTransactions(); + const std::set& endingTransactions = inst->getEndingTransactions(); - bool contraction = false; + bool contraction = false; - { - std::set::const_iterator ite = endingTransactions.begin(); - std::set::const_iterator end = endingTransactions.end(); - - for( ; ite != end; ++ite ) - { - const TransactionId& ended = (*ite); + { + std::set::const_iterator ite = endingTransactions.begin(); + std::set::const_iterator end = endingTransactions.end(); - if( m_recalculateLowerLevel ) - { - bool enteredClosedSet = false; + for( ; ite != end; ++ite ) + { + const TransactionId& ended = (*ite); - // if it is still enabled it is not yet contributing to the level - if( m_lowerLevelGraph->isEnabled( ended ) ) - { - debugMsg("IncrementalFlowProfile::recomputeLevels","Contracting from lower graph transaction (" - << ended->getId() << ") " - << ended->time()->toString() << " " - << ended->quantity()->toString() ); - - enteredClosedSet = true; - contraction = true; - m_lowerLevelGraph->pushFlow( ended ); - m_lowerLevelGraph->disable( ended ); - } - else if( ended->time()->lastDomain().isSingleton() ) - { - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") straight from open to closed set"); + if( m_recalculateLowerLevel ) + { + bool enteredClosedSet = false; - enteredClosedSet = true; - } + // if it is still enabled it is not yet contributing to the level + if( m_lowerLevelGraph->isEnabled( ended ) ) + { + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Contracting from lower graph transaction (" + << ended->getId() << ") " + << ended->time()->toString() << " " + << ended->quantity()->toString() ); + + enteredClosedSet = true; + contraction = true; + m_lowerLevelGraph->pushFlow( ended ); + m_lowerLevelGraph->disable( ended ); + } + else if( ended->time()->lastDomain().isSingleton() ) + { + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") straight from open to closed set"); - if( enteredClosedSet ) - { - debugMsg("IncrementalFlowProfile:recomputeLevels","Transaction " - << ended << " starts contributing at " - << inst->getTime() << " lower level true"); + enteredClosedSet = true; + } - m_lowerLevelContribution[ ended ] = inst; + if( enteredClosedSet ) + { + debugMsg("IncrementalFlowProfile:recomputeLevels","Transaction " + << ended << " starts contributing at " + << inst->getTime() << " lower level true"); - if( ended->isConsumer() ) - { - lowerLevel -= ended->quantity()->lastDomain().getUpperBound(); + m_lowerLevelContribution[ ended ] = inst; - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") decreases lower level by " - << ended->quantity()->lastDomain().getUpperBound() << " (new level " - << lowerLevel << ")"); - } - else - { - lowerLevel += ended->quantity()->lastDomain().getLowerBound(); + if( ended->isConsumer() ) + { + lowerLevel -= ended->quantity()->lastDomain().getUpperBound(); + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") decreases lower level by " + << ended->quantity()->lastDomain().getUpperBound() << + " (new level " + << lowerLevel << ")"); + } + else + { + lowerLevel += ended->quantity()->lastDomain().getLowerBound(); - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") increases lower level by " - << ended->quantity()->lastDomain().getLowerBound() << " (new level " - << lowerLevel << ")"); - } - } - } - if( m_recalculateUpperLevel ) - { - bool enteredClosedSet = false; + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") increases lower level by " + << ended->quantity()->lastDomain().getLowerBound() << + " (new level " + << lowerLevel << ")"); + } + } + } - if( m_upperLevelGraph->isEnabled( ended ) ) - { - debugMsg("IncrementalFlowProfile::recomputeLevels","Contracting from upper graph transaction (" - << ended->getId() << ") " - << ended->time()->toString() << " " - << ended->quantity()->toString() ); - - enteredClosedSet = true; - contraction = true; - m_upperLevelGraph->pushFlow( ended ); - m_upperLevelGraph->disable( ended ); - } - else if( ended->time()->lastDomain().isSingleton() ) - { - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") straight from open to closed set"); + if( m_recalculateUpperLevel ) + { + bool enteredClosedSet = false; - enteredClosedSet = true; - } + if( m_upperLevelGraph->isEnabled( ended ) ) + { + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Contracting from upper graph transaction (" + << ended->getId() << ") " + << ended->time()->toString() << " " + << ended->quantity()->toString() ); + + enteredClosedSet = true; + contraction = true; + m_upperLevelGraph->pushFlow( ended ); + m_upperLevelGraph->disable( ended ); + } + else if( ended->time()->lastDomain().isSingleton() ) + { + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") straight from open to closed set"); - if( enteredClosedSet ) - { - debugMsg("IncrementalFlowProfile:recomputeLevels","Transaction " - << ended << " starts contributing at " - << inst->getTime() << " lower level false"); + enteredClosedSet = true; + } - m_upperLevelContribution[ ended ] = inst; + if( enteredClosedSet ) + { + debugMsg("IncrementalFlowProfile:recomputeLevels","Transaction " + << ended << " starts contributing at " + << inst->getTime() << " lower level false"); - if( ended->isConsumer() ) - { - upperLevel -= ended->quantity()->lastDomain().getLowerBound(); + m_upperLevelContribution[ ended ] = inst; - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") decreases upper level by " - << ended->quantity()->lastDomain().getLowerBound() << " (new level " - << upperLevel << ")"); - } - else - { - upperLevel += ended->quantity()->lastDomain().getUpperBound(); + if( ended->isConsumer() ) + { + upperLevel -= ended->quantity()->lastDomain().getLowerBound(); - debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" - << ended->getId() << ") increases upper level by " - << ended->quantity()->lastDomain().getUpperBound() << " (new level " - << upperLevel << ")"); } - } - } + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") decreases upper level by " + << ended->quantity()->lastDomain().getLowerBound() << + " (new level " + << upperLevel << ")"); } - - if( contraction ) + else { - if( m_recalculateLowerLevel ) - { - m_lowerLevelGraph->restoreFlow(); + upperLevel += ended->quantity()->lastDomain().getUpperBound(); - edouble delta = m_lowerLevelGraph->disableReachableResidualGraph( m_lowerLevelContribution, inst ); + debugMsg("IncrementalFlowProfile::recomputeLevels","Transaction (" + << ended->getId() << ") increases upper level by " + << ended->quantity()->lastDomain().getUpperBound() << + " (new level " + << upperLevel << ")"); } + } + } + } - debugMsg("IncrementalFlowProfile::recomputeLevels","Contraction leads to delta lower level of " - << delta ); + if( contraction ) + { + if( m_recalculateLowerLevel ) + { + m_lowerLevelGraph->restoreFlow(); - lowerLevel += delta; - } + edouble delta = + m_lowerLevelGraph->disableReachableResidualGraph( m_lowerLevelContribution, + inst ); - if( m_recalculateUpperLevel ) - { - m_upperLevelGraph->restoreFlow(); + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Contraction leads to delta lower level of " + << delta ); - edouble delta = m_upperLevelGraph->disableReachableResidualGraph( m_upperLevelContribution, inst ); + lowerLevel += delta; + } - debugMsg("IncrementalFlowProfile::recomputeLevels","Contraction leads to delta upper level of " - << delta ); + if( m_recalculateUpperLevel ) + { + m_upperLevelGraph->restoreFlow(); - upperLevel += delta; - } - } + edouble delta = + m_upperLevelGraph->disableReachableResidualGraph( m_upperLevelContribution, + inst ); + + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Contraction leads to delta upper level of " + << delta ); + + upperLevel += delta; } + } + } - debugMsg("IncrementalFlowProfile::recomputeLevels","Computed levels for instance at time " - << inst->getTime() << "[" - << lowerLevel << "," - << upperLevel << "]"); + debugMsg("IncrementalFlowProfile::recomputeLevels", + "Computed levels for instance at time " + << inst->getTime() << "[" + << lowerLevel << "," + << upperLevel << "]"); - debugMsg("IncrementalFlowProfile::calculatedLevels","Computed levels for instance at time " - << inst->getTime() << "[" - << lowerLevel << "," - << upperLevel << "]"); + debugMsg("IncrementalFlowProfile::calculatedLevels", + "Computed levels for instance at time " + << inst->getTime() << "[" + << lowerLevel << "," + << upperLevel << "]"); - inst->update( lowerLevel, lowerLevel, upperLevel, upperLevel, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0 ); } + inst->update( lowerLevel, lowerLevel, upperLevel, upperLevel, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0 ); +} } diff --git a/src/PLASMA/Resource/component/Jamfile b/src/PLASMA/Resource/component/Jamfile index a0dba5b12..05bf3dceb 100644 --- a/src/PLASMA/Resource/component/Jamfile +++ b/src/PLASMA/Resource/component/Jamfile @@ -11,6 +11,8 @@ ModuleComponent Resource MaxFlow.cc Types.cc FlowProfile.cc + FlowProfileGraph.cc + BoostFlowProfileGraph.cc IncrementalFlowProfile.cc GroundedProfile.cc InstantTokens.cc diff --git a/src/PLASMA/Resource/component/MaxFlow.cc b/src/PLASMA/Resource/component/MaxFlow.cc index 5c0ac8c70..0df19fe68 100644 --- a/src/PLASMA/Resource/component/MaxFlow.cc +++ b/src/PLASMA/Resource/component/MaxFlow.cc @@ -15,25 +15,55 @@ namespace EUROPA { - MaximumFlowAlgorithm::MaximumFlowAlgorithm( Graph* g, Node* source, Node* sink ): - m_Graph( g ), - m_Source( source ), - m_Sink( sink ), - m_NodeListIterator( m_Nodes.end() ) - { - checkError( g != 0, "Null not allowed as input for g" ); - checkError( source != 0, "Null not allowed as input for source" ); - checkError( sink != 0, "Null not allowed as input for sink" ); - checkError( g->getNode( source->getIdentity() ) != 0, "Source is not part of the graph" ); - checkError( g->getNode( sink->getIdentity() ) != 0, "Sink is not part of the graph"); - - graphDebug("Maximum flow instance created with source " - << *source << " and sink " - << *sink ); - } - - void MaximumFlowAlgorithm::print( std::ostream& os ) const - { - - } +MaximumFlowAlgorithm::MaximumFlowAlgorithm( Graph* g, Node* source, Node* sink ): + m_Graph( g ), + m_Source( source ), + m_Sink( sink ), + m_NodeListIterator( m_Nodes.end() ) +{ + checkError( g != 0, "Null not allowed as input for g" ); + checkError( source != 0, "Null not allowed as input for source" ); + checkError( sink != 0, "Null not allowed as input for sink" ); + checkError( g->getNode( source->getIdentity() ) != 0, "Source is not part of the graph" ); + checkError( g->getNode( sink->getIdentity() ) != 0, "Sink is not part of the graph"); + + graphDebug("Maximum flow instance created with source " + << *source << " and sink " + << *sink ); +} + +void MaximumFlowAlgorithm::print( std::ostream& os ) const +{ + +} + +eint MaximumFlowAlgorithm::distanceOnNode(Node* n) const { + Node2Long::const_iterator it = m_DistanceOnNode.find(n); + checkError(it != m_DistanceOnNode.end(), "Failed to find distance for " << *n); + return it->second; +} + +//edouble MaximumFlowAlgorithm::flow(Edge* e) const { +//} + +edouble MaximumFlowAlgorithm::getExcess(Node* n) const { + Node2Double::const_iterator it = m_ExcessOnNode.find(n); + checkError(it != m_ExcessOnNode.end(), "Failed to find excess for " << *n); + return it->second; +} + +EdgeList::const_iterator MaximumFlowAlgorithm::currentOutEdgeOnNode(Node* n) const { + Node2EdgeListIteratorMap::const_iterator it = m_CurrentOutEdgeOnNode.find(n); + checkError(it != m_CurrentOutEdgeOnNode.end(), + "Failed to find a current out-edge iterator for " << *n); + return it->second; +} + +EdgeList::const_iterator MaximumFlowAlgorithm::endOutEdgeOnNode(Node* n) const { + Node2EdgeListIteratorMap::const_iterator it = m_EndOutEdgeOnNode.find(n); + checkError(it != m_EndOutEdgeOnNode.end(), + "Failed to find an end out-edge iterator for " << *n); + return it->second; +} + } diff --git a/src/PLASMA/Resource/component/MaxFlow.hh b/src/PLASMA/Resource/component/MaxFlow.hh index c027764f7..eacfaa1b4 100644 --- a/src/PLASMA/Resource/component/MaxFlow.hh +++ b/src/PLASMA/Resource/component/MaxFlow.hh @@ -26,461 +26,484 @@ namespace EUROPA { - /** - * @brief - */ - class MaximumFlowAlgorithm - { - public: - /** - * @brief - */ - MaximumFlowAlgorithm( Graph* g, Node* source, Node* sink ); - /** - * @brief - */ - Graph* getGraph() const { return m_Graph; } - /** - * @brief - */ - Node* getSource() const { return m_Source; } - /** - * @brief - */ - Node* getSink() const { return m_Sink; } - /** - * @brief - */ - inline void execute( bool reset = true ); - /** - * @brief - */ - void print( std::ostream& os ) const; - /** - * @brief - */ - inline edouble getMaxFlow() const; - /** - * @brief - */ - inline edouble getFlow( Edge* edge ) const; - /** - * @brief - */ - inline void pushFlowBack( Node* node ); - /** - * @brief - */ - inline edouble getResidual( Edge* edge ) const; - private: - /** - * @brief - */ - inline void disCharge( Node* node ); - /** - * @brief - */ - inline void initializePre( bool reset = true ); - /** - * @brief - */ - inline bool isAdmissible( Edge* edge ); - /** - * @brief - */ - inline void push( Edge* edge ); - /** - * @brief - */ - inline void reLabel( Node* n ); - /** - * @brief - */ - inline Node* getNextInList(); - /** - * @brief - */ - inline void resetToFront(); - -#ifdef _MSC_VER - typedef map< Node*, EdgeList::const_iterator > Node2EdgeListIteratorMap; -#else - typedef boost::unordered_map< Node*, EdgeList::const_iterator, NodeHash > Node2EdgeListIteratorMap; -#endif //_MSC_VER - - Node2EdgeListIteratorMap m_CurrentOutEdgeOnNode; - Node2EdgeListIteratorMap m_EndOutEdgeOnNode; - - Node2Double m_ExcessOnNode; - Node2Long m_DistanceOnNode; - Edge2DoubleMap m_OnEdge; - - NodeList m_Nodes; - Graph* m_Graph; - Node* m_Source; - Node* m_Sink; - - NodeList::iterator m_NodeListIterator; - }; - - edouble MaximumFlowAlgorithm::getMaxFlow() const - { - if( m_ExcessOnNode.find( m_Sink ) == m_ExcessOnNode.end() ) - return 0.0; - - return m_ExcessOnNode.find( m_Sink )->second; - } +/** + * @brief + */ +class MaximumFlowAlgorithm +{ + public: + /** + * @brief + */ + MaximumFlowAlgorithm( Graph* g, Node* source, Node* sink ); + /** + * @brief + */ + Graph* getGraph() const { return m_Graph; } + /** + * @brief + */ + Node* getSource() const { return m_Source; } + /** + * @brief + */ + Node* getSink() const { return m_Sink; } + /** + * @brief + */ + inline void execute( bool reset = true ); + /** + * @brief + */ + void print( std::ostream& os ) const; + /** + * @brief + */ + inline edouble getMaxFlow() const; + /** + * @brief + */ + inline edouble getFlow( Edge* edge ) const; + /** + * @brief + */ + inline void pushFlowBack( Node* node ); + /** + * @brief + */ + inline edouble getResidual( Edge* edge ) const; + private: + + eint distanceOnNode(Node* n) const; + //inline edouble flow(Edge* e) const; + edouble getExcess(Node* n) const; + EdgeList::const_iterator currentOutEdgeOnNode(Node* n) const; + EdgeList::const_iterator endOutEdgeOnNode(Node* n) const; + /** + * @brief + */ + inline void disCharge( Node* node ); + /** + * @brief + */ + inline void initializePre( bool reset = true ); + /** + * @brief + */ + inline bool isAdmissible( Edge* edge ) const; + /** + * @brief + */ + inline void push( Edge* edge ); + /** + * @brief + */ + inline void reLabel( Node* n ); + /** + * @brief + */ + inline Node* getNextInList(); + /** + * @brief + */ + inline void resetToFront(); + + #ifdef _MSC_VER + typedef map< Node*, EdgeList::const_iterator > Node2EdgeListIteratorMap; + #else + typedef boost::unordered_map< Node*, EdgeList::const_iterator, NodeHash > Node2EdgeListIteratorMap; + #endif //_MSC_VER + + Node2EdgeListIteratorMap m_CurrentOutEdgeOnNode; + Node2EdgeListIteratorMap m_EndOutEdgeOnNode; + + Node2Double m_ExcessOnNode; + Node2Long m_DistanceOnNode; + Edge2DoubleMap m_OnEdge; + + NodeList m_Nodes; + Graph* m_Graph; + Node* m_Source; + Node* m_Sink; + + NodeList::iterator m_NodeListIterator; + }; + + edouble MaximumFlowAlgorithm::getMaxFlow() const + { + if( m_ExcessOnNode.find( m_Sink ) == m_ExcessOnNode.end() ) + return 0.0; + + return m_ExcessOnNode.find( m_Sink )->second; + } + + edouble MaximumFlowAlgorithm::getFlow( Edge* edge ) const + { + Edge2DoubleMap::const_iterator it = m_OnEdge.find(edge); + checkError(it != m_OnEdge.end(), "Failed to find flow for edge " << *edge); + return it->second; + } + + edouble MaximumFlowAlgorithm::getResidual( Edge* edge ) const + { + return edge->getCapacity() - getFlow( edge ); + } + + + Node* MaximumFlowAlgorithm::getNextInList() + { + Node* node = NULL; + + if( m_NodeListIterator == m_Nodes.end() ) + { + m_NodeListIterator = m_Nodes.begin(); + } + else + { + ++m_NodeListIterator; + } + + NodeList::iterator end = m_Nodes.end(); + + while( m_NodeListIterator != end && + !(*m_NodeListIterator)->isEnabled() ) + { + ++m_NodeListIterator; + } - edouble MaximumFlowAlgorithm::getFlow( Edge* edge ) const - { - return m_OnEdge.find( edge )->second; - } + if( m_NodeListIterator != end ) + node = *m_NodeListIterator; - edouble MaximumFlowAlgorithm::getResidual( Edge* edge ) const - { - return edge->getCapacity() - getFlow( edge ); - } + return node; + } + void MaximumFlowAlgorithm::resetToFront() + { + if( m_NodeListIterator != m_Nodes.end() ) + { + Node* n = (*m_NodeListIterator); + m_Nodes.erase( m_NodeListIterator ); + m_Nodes.push_front( n ); - Node* MaximumFlowAlgorithm::getNextInList() - { - Node* node = 0; + m_NodeListIterator = m_Nodes.end(); + } + } - if( m_NodeListIterator == m_Nodes.end() ) - { - m_NodeListIterator = m_Nodes.begin(); - } - else - { - ++m_NodeListIterator; - } - NodeList::iterator end = m_Nodes.end(); + void MaximumFlowAlgorithm::execute( bool reset ) + { + graphDebug("Start execute, reset is " << std::boolalpha << reset ); - while( m_NodeListIterator != end && - !(*m_NodeListIterator)->isEnabled() ) - { - ++m_NodeListIterator; - } + initializePre( reset ); - if( m_NodeListIterator != end ) - node = *m_NodeListIterator; + Node* n = getNextInList(); - return node; - } + while( n != NULL ) + { + eint oldDistance = distanceOnNode( n ); - void MaximumFlowAlgorithm::resetToFront() - { - if( m_NodeListIterator != m_Nodes.end() ) - { - Node* n = (*m_NodeListIterator); - m_Nodes.erase( m_NodeListIterator ); - m_Nodes.push_front( n ); + disCharge( n ); - m_NodeListIterator = m_Nodes.end(); - } - } + if( distanceOnNode( n ) > oldDistance ) + { + resetToFront(); + } + n = getNextInList(); + } - void MaximumFlowAlgorithm::execute( bool reset ) - { - graphDebug("Start execute, reset is " << std::boolalpha << reset ); + graphDebug("End execute, max flow: " + << getMaxFlow() ); + } - initializePre( reset ); + void MaximumFlowAlgorithm::initializePre( bool reset ) + { + graphDebug("Start initializePre " << this); - Node* n = getNextInList(); + checkError( m_Source->isEnabled(),"Source '" << *m_Source << "' is not enabled."); + checkError( m_Sink->isEnabled(),"Sink '" << *m_Sink << "' is not enabled." ); - while( n != 0 ) - { - eint oldDistance = m_DistanceOnNode[ n ]; + if( reset ) + { + m_CurrentOutEdgeOnNode.clear(); + m_EndOutEdgeOnNode.clear(); + m_DistanceOnNode.clear(); + m_ExcessOnNode.clear(); - disCharge( n ); + m_OnEdge.clear(); - if( m_DistanceOnNode[ n ] > oldDistance ) - { - resetToFront(); - } + m_Nodes.clear(); + } - n = getNextInList(); - } + const NodeIdentity2Node& nodes = m_Graph->getNodes(); - graphDebug("End execute, max flow: " - << getMaxFlow() ); - } + NodeIdentity2Node::const_iterator nIte = nodes.begin(); + NodeIdentity2Node::const_iterator nEnd = nodes.end(); - void MaximumFlowAlgorithm::initializePre( bool reset ) - { - graphDebug("Start initializePre"); + for( ; nIte != nEnd; ++nIte ) + { + Node* node = (*nIte).second; - checkError( m_Source->isEnabled(),"Source '" << *m_Source << "' is not enabled."); - checkError( m_Sink->isEnabled(),"Sink '" << *m_Sink << "' is not enabled." ); + graphDebug("Initializing node " + << *node << " of " << nodes.size()); - if( reset ) - { - m_CurrentOutEdgeOnNode.clear(); - m_EndOutEdgeOnNode.clear(); - m_DistanceOnNode.clear(); - m_ExcessOnNode.clear(); + if( node->isEnabled() ) + { + m_CurrentOutEdgeOnNode[ node ] = node->getOutEdges().begin(); + m_EndOutEdgeOnNode[ node ] = node->getOutEdges().end(); - m_OnEdge.clear(); + while( m_CurrentOutEdgeOnNode[ node ] != m_EndOutEdgeOnNode[ node ] && + !(*m_CurrentOutEdgeOnNode[ node ])->getTarget()->isEnabled() ) + ++m_CurrentOutEdgeOnNode[ node ]; - m_Nodes.clear(); - } + if( reset ) + { + if( node != m_Source && node != m_Sink ) + m_Nodes.push_back( node ); - const NodeIdentity2Node& nodes = m_Graph->getNodes(); + graphDebug("Setting distance and excess for node " + << *node << " to 1 and 0.0"); - NodeIdentity2Node::const_iterator nIte = nodes.begin(); - NodeIdentity2Node::const_iterator nEnd = nodes.end(); + m_DistanceOnNode[ node ] = 1; + m_ExcessOnNode[ node ] = 0.0; - for( ; nIte != nEnd; ++nIte ) - { - Node* node = (*nIte).second; + const EdgeList& outEdges = node->getOutEdges(); - graphDebug("Initializing node " - << *node ); + EdgeList::const_iterator fIte = outEdges.begin(); + EdgeList::const_iterator fEnd = outEdges.end(); - if( node->isEnabled() ) + for( ; fIte != fEnd; ++fIte ) { - m_CurrentOutEdgeOnNode[ node ] = node->getOutEdges().begin(); - m_EndOutEdgeOnNode[ node ] = node->getOutEdges().end(); - - while( m_CurrentOutEdgeOnNode[ node ] != m_EndOutEdgeOnNode[ node ] && !(*m_CurrentOutEdgeOnNode[ node ])->getTarget()->isEnabled() ) - ++m_CurrentOutEdgeOnNode[ node ]; + Edge* edge = *fIte; - if( reset ) + if( edge->isEnabled() ) { - if( node != m_Source && node != m_Sink ) - m_Nodes.push_back( node ); + graphDebug("Initializing flow on edge " + << *edge << " to be 0"); - graphDebug("Setting distance and excess for node " - << *node << " to 1 and 0.0"); + m_OnEdge[ edge ] = 0.0; - m_DistanceOnNode[ node ] = 1; - m_ExcessOnNode[ node ] = 0.0; + checkError( 0 != m_Graph->getEdge( edge->getTarget(), edge->getSource() ) + && + m_Graph->getEdge( edge->getTarget(), edge->getSource() )->isEnabled(), + "No (enabled) reverse edge for edge '" << *edge << "'"); - const EdgeList& outEdges = node->getOutEdges(); - - EdgeList::const_iterator fIte = outEdges.begin(); - EdgeList::const_iterator fEnd = outEdges.end(); - - for( ; fIte != fEnd; ++fIte ) - { - Edge* edge = *fIte; - - if( edge->isEnabled() ) - { - graphDebug("Initializing flow on edge " - << *edge << " to be 0"); - - m_OnEdge[ edge ] = 0.0; - - checkError( 0 != m_Graph->getEdge( edge->getTarget(), edge->getSource() ) - && - m_Graph->getEdge( edge->getTarget(), edge->getSource() )->isEnabled(), - "No (enabled) reverse edge for edge '" << *edge << "'"); - - m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = 0.0; - } - } + m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = 0.0; } } } + } + } - m_DistanceOnNode[ m_Sink ] = 0; - m_DistanceOnNode[ m_Source ] = (long) m_Nodes.size(); - - m_NodeListIterator = m_Nodes.end(); + m_DistanceOnNode[ m_Sink ] = 0; + m_DistanceOnNode[ m_Source ] = (long) m_Nodes.size(); - EdgeOutIterator edgeOutIte( *m_Source ); + m_NodeListIterator = m_Nodes.end(); - for( ; edgeOutIte.ok(); ++edgeOutIte ) - { - Edge* edge = *edgeOutIte; + EdgeOutIterator edgeOutIte( *m_Source ); - // check edge is enabled + for( ; edgeOutIte.ok(); ++edgeOutIte ) + { + Edge* edge = *edgeOutIte; - edouble flow = m_OnEdge[ edge ]; - edouble residual = edge->getCapacity() - flow; + // check edge is enabled - graphDebug("Initializing flow from source " - << *m_Source << " for edge " - << *edge << ", flow is " - << flow << " residual is " - << residual ); + edouble flow = getFlow(edge); + edouble residual = edge->getCapacity() - flow; - if( residual != 0 ) - { - m_OnEdge[ edge ] = flow + residual; - m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = - (flow + residual); + graphDebug("Initializing flow from source " + << *m_Source << " for edge " + << *edge << ", flow is " + << flow << " residual is " + << residual ); + if( residual != 0 ) + { + m_OnEdge[ edge ] = flow + residual; + m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = - (flow + residual); - Node* target = edge->getTarget(); - edouble excess = m_ExcessOnNode[ target ]; + Node* target = edge->getTarget(); - m_ExcessOnNode[ target ] = excess + residual; + edouble excess = getExcess(target); - graphDebug("Initializing flow on edge " - << *edge << " to be " - << m_OnEdge[ edge ] << " (reverse flow " - << m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] << ") and excess on node " - << *target << " to be " - << m_ExcessOnNode[ target ] ); + m_ExcessOnNode[ target ] = excess + residual; - } - } + graphDebug("Initializing flow on edge " + << *edge << " to be " + << getFlow(edge) << " (reverse flow " + << getFlow(m_Graph->getEdge( edge->getTarget(), edge->getSource() )) << + ") and excess on node " + << *target << " to be " + << getExcess(target) ); - graphDebug("End initializePre"); } + } - void MaximumFlowAlgorithm::disCharge( Node* node ) - { - checkError( 0 != node, "Node is null, null is not allowed as input"); - checkError( node->isEnabled(), "Node '" << *node << "' not enabled."); + graphDebug("End initializePre"); +} - graphDebug("Discharge invoked for node " - << *node << " witch excess " - << m_ExcessOnNode[ node ] ); +void MaximumFlowAlgorithm::disCharge( Node* node ) +{ + checkError( 0 != node, "Node is null, null is not allowed as input"); + checkError( node->isEnabled(), "Node '" << *node << "' not enabled."); - while( m_ExcessOnNode[ node ] != 0 ) - { - Edge* edge = 0; + graphDebug("Discharge invoked for node " + << *node << " witch excess " + << getExcess(node) ); - EdgeList::const_iterator ite = m_CurrentOutEdgeOnNode[ node ]; + while( getExcess(node) != 0 ) + { + Edge* edge = NULL; - if( ite != m_EndOutEdgeOnNode[ node ] ) - edge = (*ite); + EdgeList::const_iterator ite = currentOutEdgeOnNode(node); - assert( edge != 0 ); + if( ite != endOutEdgeOnNode(node) ) + edge = (*ite); - if( isAdmissible( edge ) ) - { - push( edge ); - } - else - { - reLabel( node ); + assert( edge != NULL ); - ++ite; + if( isAdmissible( edge ) ) + { + push( edge ); + } + else + { + reLabel( node ); - if( ite == m_EndOutEdgeOnNode[ node ] ) - { - ite = node->getOutEdges().begin(); - } + ++ite; - m_CurrentOutEdgeOnNode[node] = ite; - } + if( ite == endOutEdgeOnNode(node) ) + { + ite = node->getOutEdges().begin(); } - } + while(ite != endOutEdgeOnNode(node) && !(*ite)->getTarget()->isEnabled()) + ++ite; - bool MaximumFlowAlgorithm::isAdmissible( Edge* edge ) - { - graphDebug("Checking edge " - << *edge << " if admissable, flow is " - << m_OnEdge[ edge ] << " distance of source is " - << m_DistanceOnNode[ edge->getSource() ] << " distance of target is " - << m_DistanceOnNode[ edge->getTarget() ] ); + m_CurrentOutEdgeOnNode[node] = ite; + } + } +} - return ( m_OnEdge[ edge ] < edge->getCapacity() ) - && - ( m_DistanceOnNode[ edge->getSource() ] == m_DistanceOnNode[ edge->getTarget() ] + 1 ); - } +bool MaximumFlowAlgorithm::isAdmissible( Edge* edge ) const +{ + Edge2DoubleMap::const_iterator flowIt = m_OnEdge.find(edge); + Node2Long::const_iterator sourceDistanceIt = + m_DistanceOnNode.find(edge->getSource()); + Node2Long::const_iterator targetDistanceIt = + m_DistanceOnNode.find(edge->getTarget()); + checkError(flowIt != m_OnEdge.end(), + "Failed to find flow for " << *edge); + checkError(sourceDistanceIt != m_DistanceOnNode.end(), + "Failed to find distance for source node " << *(edge->getSource())); + checkError(targetDistanceIt != m_DistanceOnNode.end(), + "Failed to find distance for target node " << *(edge->getTarget())); + graphDebug("Checking edge " + << *edge << " if admissable, flow is " + << flowIt->second << " distance of source is " + << sourceDistanceIt->second << " distance of target is " + << targetDistanceIt->second); + + + return (flowIt->second < edge->getCapacity()) && + (sourceDistanceIt->second == targetDistanceIt->second + 1); +} - void MaximumFlowAlgorithm::pushFlowBack( Node* node ) - { - EdgeInIterator ite( *node ); +void MaximumFlowAlgorithm::pushFlowBack( Node* node ) +{ + EdgeInIterator ite( *node ); - for( ; ite.ok(); ++ite ) - { - Edge* edge = *ite; + for( ; ite.ok(); ++ite ) + { + Edge* edge = *ite; - Node* source = edge->getSource(); + Node* source = edge->getSource(); - edouble flow_pushed_back = getFlow( edge ); + edouble flow_pushed_back = getFlow( edge ); - if( flow_pushed_back > 0 && edge->getCapacity() != 0 ) - { - m_ExcessOnNode[ source ] = m_ExcessOnNode[ source ] + flow_pushed_back; - m_OnEdge[ edge ] = 0.0; - m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = 0.0; - } - } + if( flow_pushed_back > 0 && edge->getCapacity() != 0 ) + { + m_ExcessOnNode[ source ] = getExcess(source) + flow_pushed_back; + m_OnEdge[ edge ] = 0.0; + m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = 0.0; } + } +} - void MaximumFlowAlgorithm::push( Edge* edge ) - { - Node* source = edge->getSource(); - Node* target = edge->getTarget(); +void MaximumFlowAlgorithm::push( Edge* edge ) +{ + Node* source = edge->getSource(); + Node* target = edge->getTarget(); - edouble excess = m_ExcessOnNode[ source ]; - edouble residual = edge->getCapacity() - m_OnEdge[ edge ]; + edouble excess = getExcess(source); + edouble residual = edge->getCapacity() - getFlow(edge); - assert( residual >= 0 ); + assert( residual >= 0 ); - edouble delta = (excess > residual ) ? residual : excess; + edouble delta = (excess > residual ) ? residual : excess; - edouble newFlow = m_OnEdge[ edge ] + delta; - m_OnEdge[ edge ] = newFlow; - m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = - newFlow; + edouble newFlow = getFlow(edge) + delta; + m_OnEdge[ edge ] = newFlow; + m_OnEdge[ m_Graph->getEdge( edge->getTarget(), edge->getSource() ) ] = - newFlow; - m_ExcessOnNode[ target ] = m_ExcessOnNode[ target ] + delta; - m_ExcessOnNode[ source ] = m_ExcessOnNode[ source ] - delta; + m_ExcessOnNode[ target ] = getExcess(target) + delta; + m_ExcessOnNode[ source ] = getExcess(source) - delta; - graphDebug("Pushed flow " - << delta << " on edge " - << *edge << " makes excess on node " - << *source << " " - << m_ExcessOnNode[ source ] << " and on " - << *target << " " - << m_ExcessOnNode[ target ] ); + graphDebug("Pushed flow " + << delta << " on edge " + << *edge << " makes excess on node " + << *source << " " + << getExcess(source) << " and on " + << *target << " " + << getExcess(target) ); - } +} - void MaximumFlowAlgorithm::reLabel( Node* n ) - { - graphDebug("Relabel node " - << *n ); +void MaximumFlowAlgorithm::reLabel( Node* n ) +{ + graphDebug("Relabel node " + << *n ); - eint minLabel = std::numeric_limits::max(); + eint minLabel = std::numeric_limits::max(); - EdgeOutIterator edgeOutIte( *n ); + EdgeOutIterator edgeOutIte( *n ); - for( ; edgeOutIte.ok(); ++edgeOutIte ) - { - Edge* edge = *edgeOutIte; + for( ; edgeOutIte.ok(); ++edgeOutIte ) + { + Edge* edge = *edgeOutIte; - Node* target = edge->getTarget(); + Node* target = edge->getTarget(); - graphDebug("Relabel node " - << *n << " checking edge " - << *edge << " to relabel, flow on edge is " - << m_OnEdge[ edge ] ); - //m_OnEdge[ edge ] < edge->getCapacity() - if( getResidual( edge ) > 0 ) - { - eint label = m_DistanceOnNode[ target ]; + graphDebug("Relabel node " + << *n << " checking edge " + << *edge << " to relabel, flow on edge is " + << getFlow(edge) ); + //m_OnEdge[ edge ] < edge->getCapacity() + if( getResidual( edge ) > 0 ) + { + eint label = distanceOnNode( target ); - if( minLabel >= label ) - { - graphDebug("Node " - << *target << " is labeled with label " - << label ); + if( minLabel >= label ) + { + graphDebug("Node " + << *target << " is labeled with label " + << label ); - minLabel = label; - } - } + minLabel = label; } + } + } - //at this point all distance-labels for the connected nodes are smaller or equal to node n - m_DistanceOnNode[ n ] = minLabel + 1; + //at this point all distance-labels for the connected nodes are smaller or equal to node n + m_DistanceOnNode[ n ] = minLabel + 1; - graphDebug("(Re)labeled node " - << *n << " to have distance " - << m_DistanceOnNode[ n ] ); - } + graphDebug("(Re)labeled node " + << *n << " to have distance " + << distanceOnNode( n ) ); +} } #endif //MAXIMUM_FLOW_ALGORITHM_HEADER_FILE_ diff --git a/src/PLASMA/Resource/component/Types.hh b/src/PLASMA/Resource/component/Types.hh index 197a45b2d..000f07a45 100644 --- a/src/PLASMA/Resource/component/Types.hh +++ b/src/PLASMA/Resource/component/Types.hh @@ -30,7 +30,7 @@ #include "Instant.hh" #include "Transaction.hh" -//#define TRACE_GRAPH 1 +#define TRACE_GRAPH 1 #ifdef TRACE_GRAPH diff --git a/src/PLASMA/Resource/test/rs-flow-test-module.cc b/src/PLASMA/Resource/test/rs-flow-test-module.cc index 2a5e6de6e..6b11164cb 100644 --- a/src/PLASMA/Resource/test/rs-flow-test-module.cc +++ b/src/PLASMA/Resource/test/rs-flow-test-module.cc @@ -10,6 +10,8 @@ #include "IncrementalFlowProfile.hh" #include "ProfilePropagator.hh" #include "ClosedWorldFVDetector.hh" +#include "BoostFlowProfile.hh" +#include "BoostFlowProfileGraph.hh" #include "Debug.hh" #include "Engine.hh" @@ -83,11 +85,19 @@ class DummyDetector : public FVDetector { virtual PSResourceProfile* getVDLevelProfile() { return NULL; } }; +// class BoostFlowProfile : public FlowProfile { +// public: +// BoostFlowProfile(const PlanDatabaseId db, const FVDetectorId flawDetector) +// : FlowProfile(db, flawDetector) { +// initializeGraphs(); +// } +// }; + class FlowProfileTest { public: - static bool test(){ + static bool flowProfileTest() { debugMsg("ResourceTest"," FlowProfile "); testAddAndRemove< EUROPA::FlowProfile> (); @@ -99,15 +109,43 @@ class FlowProfileTest testScenario5< EUROPA::FlowProfile>(); testScenario6< EUROPA::FlowProfile>(); testScenario7< EUROPA::FlowProfile>(); - testScenario8< EUROPA::FlowProfile>(); + // testScenario8< EUROPA::FlowProfile>(); testScenario9< EUROPA::FlowProfile>(); - //testScenario10< EUROPA::FlowProfile>(); - testScenario11< EUROPA::FlowProfile>(); - testScenario12< EUROPA::FlowProfile>(); - //testScenario13< EUROPA::FlowProfile>(); - //testScenario14< EUROPA::FlowProfile>(); - //testPaulBug(); + // testScenario10< EUROPA::FlowProfile>(); + // testScenario11< EUROPA::FlowProfile>(); + // testScenario12< EUROPA::FlowProfile>(); + // testScenario13< EUROPA::FlowProfile>(); + // testScenario14< EUROPA::FlowProfile>(); + testPaulBug(); + return true; + } + + static bool boostFlowProfileTest() { + debugMsg("ResourceTest"," BoostFlowProfile "); + + testAddAndRemove (); + testScenario0< BoostFlowProfile>(); + testScenario1< BoostFlowProfile>(); + testScenario2< BoostFlowProfile>(); + testScenario3< BoostFlowProfile>(); + testScenario4< BoostFlowProfile>(); + testScenario5< BoostFlowProfile>(); + testScenario6< BoostFlowProfile>(); + testScenario7< BoostFlowProfile>(); + testScenario8< BoostFlowProfile>(); + testScenario9< BoostFlowProfile>(); + testScenario10(); + testScenario11(); + testScenario12(); + testScenario13(); + testScenario14(); + testPaulBug(); + return true; + + } + + static bool incrementalFlowProfileTest() { debugMsg("ResourceTest"," IncrementalFlowProfile "); testAddAndRemove< EUROPA::IncrementalFlowProfile> (); @@ -127,8 +165,14 @@ class FlowProfileTest testScenario13< EUROPA::IncrementalFlowProfile>(); testScenario14< EUROPA::IncrementalFlowProfile>(); //testPaulBug(); + } - return true; + static bool test(){ + return + // flowProfileTest() && + boostFlowProfileTest() //&& + //incrementalFlowProfileTest() + ; } private: static bool verifyProfile( Profile& profile, int instances, eint times[], edouble lowerLevel[], edouble upperLevel[] ) { @@ -184,18 +228,39 @@ class FlowProfileTest } static void executePaulBug(Profile& profile, ConstraintEngine& ce, int nrInstances, eint itimes[], edouble lowerLevels[], edouble upperLevels[] ) { - Variable t1(ce.getId(), IntervalIntDomain(10, PLUS_INFINITY), true, "T+"); - Variable t2(ce.getId(), IntervalIntDomain(120010, PLUS_INFINITY), true, "T-"); - Variable t3(ce.getId(), IntervalIntDomain(960000, PLUS_INFINITY), true, "t-"); - Variable t4(ce.getId(), IntervalIntDomain(961200, PLUS_INFINITY), true, "t+"); + /*! + * T+ precedes T- + * t- precedes t+ + * + * T+ <10-------(+1000)---------------------------------inf> + * T- | <120010--(-1000)---------------------------inf> + * t- | | <960000--------(-1)---------------inf> + * t+ | | | <961200--------(+1)-------inf> + * | | | | | + * | | | | | + * 1000 1000 1000 1000 0 + * 0 0 -1 -1 0 + * + */ + + Variable t1(ce.getId(), IntervalIntDomain(10, PLUS_INFINITY), + true, "T+"); + Variable t2(ce.getId(), IntervalIntDomain(120010, PLUS_INFINITY), + true, "T-"); + Variable t3(ce.getId(), IntervalIntDomain(960000, PLUS_INFINITY), + true, "t-"); + Variable t4(ce.getId(), IntervalIntDomain(961200, PLUS_INFINITY), + true, "t+"); Variable q1(ce.getId(), IntervalDomain(1000), true, "qT+"); - Variable q2(ce.getId(), IntervalDomain(-1000), true, "qT-"); - Variable q3(ce.getId(), IntervalDomain(-1), true, "qt-"); - Variable q4(ce.getId(), IntervalDomain(1), true, "qt-"); + Variable q2(ce.getId(), IntervalDomain(1000), true, "qT-"); + Variable q3(ce.getId(), IntervalDomain(1), true, "qt-"); + Variable q4(ce.getId(), IntervalDomain(1), true, "qt+"); - LessThanEqualConstraint c0(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); - LessThanEqualConstraint c1(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t3.getId(), t4.getId())); + LessThanEqualConstraint c0(LabelStr("precedes"), LabelStr("Temporal"), ce.getId(), + makeScope(t1.getId(), t2.getId())); + LessThanEqualConstraint c1(LabelStr("precedes"), LabelStr("Temporal"), ce.getId(), + makeScope(t3.getId(), t4.getId())); ce.propagate(); @@ -513,7 +578,8 @@ class FlowProfileTest */ debugMsg("ResourceTest"," Case 5"); - EqualConstraint c0(LabelStr("concurrent"), LabelStr("Temporal"), ce.getId() , makeScope( t3.getId(), t4.getId())); + EqualConstraint c0(LabelStr("concurrent"), LabelStr("Temporal"), ce.getId() , + makeScope( t3.getId(), t4.getId())); ce.propagate(); diff --git a/src/PLASMA/Resource/test/rs-flow-test-module.hh b/src/PLASMA/Resource/test/rs-flow-test-module.hh index 029dc38e1..232804b53 100644 --- a/src/PLASMA/Resource/test/rs-flow-test-module.hh +++ b/src/PLASMA/Resource/test/rs-flow-test-module.hh @@ -7,9 +7,9 @@ class FlowProfileModuleTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(FlowProfileModuleTests); - CPPUNIT_TEST(defaultSetupTests); + // CPPUNIT_TEST(defaultSetupTests); CPPUNIT_TEST(flowProfileTests); - CPPUNIT_TEST(FVDetectorTests); + // CPPUNIT_TEST(FVDetectorTests); CPPUNIT_TEST_SUITE_END(); public: diff --git a/src/PLASMA/Resource/test/rs-test-module.cc b/src/PLASMA/Resource/test/rs-test-module.cc index 13f420f98..91bc0c4d6 100644 --- a/src/PLASMA/Resource/test/rs-test-module.cc +++ b/src/PLASMA/Resource/test/rs-test-module.cc @@ -1216,6 +1216,19 @@ class ResourceTest { CPPUNIT_ASSERT(it2.getTime() == 20); CPPUNIT_ASSERT(it2.getUpperBound() == -10.0); CPPUNIT_ASSERT(it2.getLowerBound() == -15.0); + + c1.getQuantity()->specify(7.0); + CPPUNIT_ASSERT(ce.propagate()); + ProfileIterator it3(res1.getProfile()); + CPPUNIT_ASSERT(!it3.done()); + CPPUNIT_ASSERT(it3.getTime() == 10); + CPPUNIT_ASSERT(it3.getUpperBound() == -7.0); + CPPUNIT_ASSERT(it3.getLowerBound() == -7.0); + CPPUNIT_ASSERT(it3.next()); + CPPUNIT_ASSERT(it3.getTime() == 20); + CPPUNIT_ASSERT(it3.getUpperBound() == -12.0); + CPPUNIT_ASSERT(it3.getLowerBound() == -17.0); + return true; } @@ -1471,323 +1484,330 @@ class ResourceSolverTest { return true; } - static bool testResourceThreatDecisionPoint() { - - RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); - - PlanDatabaseId db = dbObj.getId(); - ConstraintEngineId ce = ceObj.getId(); - DbClientId client = db->getClient(); - - Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 1, 1, 0); - - ReusableToken tok1(db, "Reusable.uses", IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); - - ReusableToken tok2(db, "Reusable.uses", IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); + static bool testResourceThreatDecisionPoint() { + + RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); + + PlanDatabaseId db = dbObj.getId(); + ConstraintEngineId ce = ceObj.getId(); + DbClientId client = db->getClient(); + + Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", + "IncrementalFlowProfile", 1, 1, 0); + + ReusableToken tok1(db, "Reusable.uses", + IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + ReusableToken tok2(db, "Reusable.uses", + IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + ReusableToken tok3(db, "Reusable.uses", + IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + CPPUNIT_ASSERT(ce->propagate()); + + CPPUNIT_ASSERT(reusable.hasTokensToOrder()); + std::vector flawedInstants; + reusable.getFlawedInstants(flawedInstants); + CPPUNIT_ASSERT(flawedInstants.size() == 5); + CPPUNIT_ASSERT(flawedInstants[0]->getTime() == 11); + + TiXmlElement dummy(""); + ResourceThreatDecisionPoint dp1(client, flawedInstants[0], dummy); + + dp1.initialize(); + + CPPUNIT_ASSERT(dp1.getChoices().size() == 8); + + std::string noFilter = ""; + TiXmlElement* noFilterXml = initXml(noFilter); + ResourceThreatDecisionPoint dp2(client, flawedInstants[0], *noFilterXml); + dp2.initialize(); + CPPUNIT_ASSERT(dp2.getChoices().size() == 8); + + std::string predFilter = ""; + TiXmlElement* predFilterXml = initXml(predFilter); + ResourceThreatDecisionPoint dp3(client, flawedInstants[0], *predFilterXml); + dp3.initialize(); + CPPUNIT_ASSERT(dp3.getChoices().size() == 3); + CPPUNIT_ASSERT(dp3.getChoices()[0].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp3.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp3.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp3.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp3.getChoices()[2].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp3.getChoices()[2].second->time() == tok3.start()); + + std::string sucFilter = ""; + TiXmlElement* sucFilterXml = initXml(sucFilter); + ResourceThreatDecisionPoint dp4(client, flawedInstants[0], *sucFilterXml); + dp4.initialize(); + CPPUNIT_ASSERT(dp4.getChoices().size() == 5); + CPPUNIT_ASSERT(dp4.getChoices()[0].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp4.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp4.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp4.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp4.getChoices()[2].first->time() == tok2.start()); + CPPUNIT_ASSERT(dp4.getChoices()[2].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp4.getChoices()[3].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp4.getChoices()[3].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp4.getChoices()[4].first->time() == tok3.start()); + CPPUNIT_ASSERT(dp4.getChoices()[4].second->time() == tok2.start()); + + std::string bothFilter = ""; + TiXmlElement* bothFilterXml = initXml(bothFilter); + ResourceThreatDecisionPoint dp5(client, flawedInstants[0], *bothFilterXml); + dp5.initialize(); + CPPUNIT_ASSERT(dp5.getChoices().size() == 3); + CPPUNIT_ASSERT(dp5.getChoices()[0].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp5.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp5.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp5.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp5.getChoices()[2].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp5.getChoices()[2].second->time() == tok3.start()); + + //the combination of ascendingKeyPredecessor and ascendingKeySuccessor have already been tested by now + + std::string earliestPred = ""; + TiXmlElement* earliestPredXml = initXml(earliestPred); + ResourceThreatDecisionPoint dp6(client, flawedInstants[0], *earliestPredXml); + dp6.initialize(); + CPPUNIT_ASSERT(dp6.getChoices().size() == 3); + CPPUNIT_ASSERT(dp6.getChoices()[0].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp6.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp6.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp6.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp6.getChoices()[2].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp6.getChoices()[2].second->time() == tok3.start()); + + std::string latestPred = ""; + TiXmlElement* latestPredXml = initXml(latestPred); + ResourceThreatDecisionPoint dp7(client, flawedInstants[0], *latestPredXml); + dp7.initialize(); + CPPUNIT_ASSERT(dp7.getChoices().size() == 3); + CPPUNIT_ASSERT(dp7.getChoices()[0].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp7.getChoices()[0].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp7.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp7.getChoices()[1].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp7.getChoices()[2].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp7.getChoices()[2].second->time() == tok3.start()); + + + std::string longestPred = ""; + TiXmlElement* longestPredXml = initXml(longestPred); + ResourceThreatDecisionPoint dp8(client, flawedInstants[0], *longestPredXml); + dp8.initialize(); + CPPUNIT_ASSERT(dp8.getChoices().size() == 5); + CPPUNIT_ASSERT(dp8.getChoices()[0].first->time() == tok3.start()); + + + std::string shortestPred = ""; + TiXmlElement* shortestPredXml = initXml(shortestPred); + ResourceThreatDecisionPoint dp9(client, flawedInstants[0], *shortestPredXml); + dp9.initialize(); + CPPUNIT_ASSERT(dp9.getChoices().size() == 3); + CPPUNIT_ASSERT(dp9.getChoices()[0].first->time() == tok2.start() || + dp9.getChoices()[0].first->time() == tok1.end()); + + std::string descendingKeyPred = ""; + TiXmlElement* descendingKeyPredXml = initXml(descendingKeyPred); + ResourceThreatDecisionPoint dp10(client, flawedInstants[0], *descendingKeyPredXml); + dp10.initialize(); + CPPUNIT_ASSERT(dp10.getChoices().size() == 3); + CPPUNIT_ASSERT(dp10.getChoices()[0].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp10.getChoices()[1].first->time() == tok1.end()); + + + std::string earliestSucc = ""; + TiXmlElement* earliestSuccXml = initXml(earliestSucc); + ResourceThreatDecisionPoint dp11(client, flawedInstants[0], *earliestSuccXml); + dp11.initialize(); + CPPUNIT_ASSERT(dp11.getChoices().size() == 3); + CPPUNIT_ASSERT(dp11.getChoices()[0].second->time() == tok2.start() || + dp11.getChoices()[0].second->time() == tok3.start()); + + std::string latestSucc = ""; + TiXmlElement* latestSuccXml = initXml(latestSucc); + ResourceThreatDecisionPoint dp12(client, flawedInstants[0], *latestSuccXml); + dp12.initialize(); + CPPUNIT_ASSERT(dp12.getChoices().size() == 3); + CPPUNIT_ASSERT(dp12.getChoices()[0].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp12.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp12.getChoices()[2].second->time() == tok2.start()); + + + std::string longestSucc = ""; + TiXmlElement* longestSuccXml = initXml(longestSucc); + ResourceThreatDecisionPoint dp13(client, flawedInstants[0], *longestSuccXml); + dp13.initialize(); + CPPUNIT_ASSERT(dp13.getChoices().size() == 3); + CPPUNIT_ASSERT(dp13.getChoices()[0].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp13.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp13.getChoices()[2].second->time() == tok2.start()); + + std::string shortestSucc = ""; + TiXmlElement* shortestSuccXml = initXml(shortestSucc); + ResourceThreatDecisionPoint dp14(client, flawedInstants[0], *shortestSuccXml); + dp14.initialize(); + CPPUNIT_ASSERT(dp14.getChoices().size() == 3); + CPPUNIT_ASSERT(dp14.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp14.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp14.getChoices()[2].second->time() == tok3.start()); + + std::string descendingKeySucc = ""; + TiXmlElement* descendingKeySuccXml = initXml(descendingKeySucc); + ResourceThreatDecisionPoint dp15(client, flawedInstants[0], *descendingKeySuccXml); + dp15.initialize(); + CPPUNIT_ASSERT(dp15.getChoices().size() == 3); + CPPUNIT_ASSERT(dp15.getChoices()[0].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp15.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp15.getChoices()[2].second->time() == tok2.start()); + + + std::string ascendingKeySucc = ""; + TiXmlElement* ascendingKeySuccXml = initXml(ascendingKeySucc); + ResourceThreatDecisionPoint dp16(client, flawedInstants[0], *ascendingKeySuccXml); + dp16.initialize(); + CPPUNIT_ASSERT(dp16.getChoices().size() == 3); + CPPUNIT_ASSERT(dp16.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp16.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp16.getChoices()[2].second->time() == tok3.start()); + + + std::string leastImpact = ""; + TiXmlElement* leastImpactXml = initXml(leastImpact); + ResourceThreatDecisionPoint dp17(client, flawedInstants[0], *leastImpactXml); + dp17.initialize(); + CPPUNIT_ASSERT(dp17.getChoices().size() == 5); + CPPUNIT_ASSERT(dp17.getChoices()[0].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp17.getChoices()[0].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp17.getChoices()[1].first->time() == tok1.end()); + CPPUNIT_ASSERT(dp17.getChoices()[1].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp17.getChoices()[2].first->time() == tok2.start()); + CPPUNIT_ASSERT(dp17.getChoices()[2].second->time() == tok3.start()); + CPPUNIT_ASSERT(dp17.getChoices()[3].first->time() == tok3.start()); + CPPUNIT_ASSERT(dp17.getChoices()[3].second->time() == tok2.start()); + CPPUNIT_ASSERT(dp17.getChoices()[4].first->time() == tok2.end()); + CPPUNIT_ASSERT(dp17.getChoices()[4].second->time() == tok3.start()); + + std::string precedesOnly = ""; + TiXmlElement* precedesOnlyXml = initXml(precedesOnly); + ResourceThreatDecisionPoint dp18(client, flawedInstants[0], *precedesOnlyXml); + dp18.initialize(); + ConstraintNameListener* nameListener = new ConstraintNameListener(dp18.getChoices()[0].first->time()); + dp18.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); + dp18.undo(); + delete (ConstrainedVariableListener*) nameListener; + ce->propagate(); + nameListener = new ConstraintNameListener(dp18.getChoices()[1].first->time()); + dp18.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); + dp18.undo(); + ce->propagate(); + delete (ConstrainedVariableListener*) nameListener; + + std::string concurrentOnly = ""; + TiXmlElement* concurrentOnlyXml = initXml(concurrentOnly); + ResourceThreatDecisionPoint dp19(client, flawedInstants[0], *concurrentOnlyXml); + dp19.initialize(); + nameListener = new ConstraintNameListener(dp19.getChoices()[0].first->time()); + dp19.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); + dp19.undo(); + delete (ConstrainedVariableListener*) nameListener; + ce->propagate(); + nameListener = new ConstraintNameListener(dp19.getChoices()[1].first->time()); + dp19.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); + dp19.undo(); + ce->propagate(); + delete (ConstrainedVariableListener*) nameListener; + + //pair first has already been implicitly tested and constraint first is necessary to make this easy anyway, so it'll get tested as well. + + std::string precedesFirst = ""; + TiXmlElement* precedesFirstXml = initXml(precedesFirst); + ResourceThreatDecisionPoint dp20(client, flawedInstants[0], *precedesFirstXml); + dp20.initialize(); + nameListener = new ConstraintNameListener(dp20.getChoices()[0].first->time()); + dp20.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); + dp20.undo(); + ce->propagate(); + dp20.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); + dp20.undo(); + ce->propagate(); + delete (ConstrainedVariableListener*) nameListener; + //step once more to test creating a constraint on the next choice + nameListener = new ConstraintNameListener(dp20.getChoices()[1].first->time()); + dp20.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); + dp20.undo(); + ce->propagate(); + delete nameListener; + + std::string concurrentFirst = ""; + TiXmlElement* concurrentFirstXml = initXml(concurrentFirst); + ResourceThreatDecisionPoint dp21(client, flawedInstants[0], *concurrentFirstXml); + dp21.initialize(); + nameListener = new ConstraintNameListener(dp21.getChoices()[0].first->time()); + dp21.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); + dp21.undo(); + ce->propagate(); + dp21.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); + dp21.undo(); + ce->propagate(); + delete (ConstrainedVariableListener*) nameListener; + //step once more to test creating a constraint on the next choice + nameListener = new ConstraintNameListener(dp21.getChoices()[1].first->time()); + dp21.execute(); + ce->propagate(); + CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); + dp21.undo(); + ce->propagate(); + delete nameListener; + + delete concurrentFirstXml; + delete precedesFirstXml; + delete concurrentOnlyXml; + delete precedesOnlyXml; + delete leastImpactXml; + delete ascendingKeySuccXml; + delete descendingKeySuccXml; + delete shortestSuccXml; + delete longestSuccXml; + delete latestSuccXml; + delete earliestSuccXml; + delete descendingKeyPredXml; + delete shortestPredXml; + delete longestPredXml; + delete latestPredXml; + delete earliestPredXml; + delete bothFilterXml; + delete sucFilterXml; + delete predFilterXml; + delete noFilterXml; - ReusableToken tok3(db, "Reusable.uses", IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); - - CPPUNIT_ASSERT(ce->propagate()); - - CPPUNIT_ASSERT(reusable.hasTokensToOrder()); - std::vector flawedInstants; - reusable.getFlawedInstants(flawedInstants); - CPPUNIT_ASSERT(flawedInstants.size() == 5); - CPPUNIT_ASSERT(flawedInstants[0]->getTime() == 11); - - TiXmlElement dummy(""); - ResourceThreatDecisionPoint dp1(client, flawedInstants[0], dummy); - - dp1.initialize(); - - CPPUNIT_ASSERT(dp1.getChoices().size() == 8); - - std::string noFilter = ""; - TiXmlElement* noFilterXml = initXml(noFilter); - ResourceThreatDecisionPoint dp2(client, flawedInstants[0], *noFilterXml); - dp2.initialize(); - CPPUNIT_ASSERT(dp2.getChoices().size() == 8); - - std::string predFilter = ""; - TiXmlElement* predFilterXml = initXml(predFilter); - ResourceThreatDecisionPoint dp3(client, flawedInstants[0], *predFilterXml); - dp3.initialize(); - CPPUNIT_ASSERT(dp3.getChoices().size() == 3); - CPPUNIT_ASSERT(dp3.getChoices()[0].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp3.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp3.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp3.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp3.getChoices()[2].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp3.getChoices()[2].second->time() == tok3.start()); - - std::string sucFilter = ""; - TiXmlElement* sucFilterXml = initXml(sucFilter); - ResourceThreatDecisionPoint dp4(client, flawedInstants[0], *sucFilterXml); - dp4.initialize(); - CPPUNIT_ASSERT(dp4.getChoices().size() == 5); - CPPUNIT_ASSERT(dp4.getChoices()[0].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp4.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp4.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp4.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp4.getChoices()[2].first->time() == tok2.start()); - CPPUNIT_ASSERT(dp4.getChoices()[2].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp4.getChoices()[3].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp4.getChoices()[3].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp4.getChoices()[4].first->time() == tok3.start()); - CPPUNIT_ASSERT(dp4.getChoices()[4].second->time() == tok2.start()); - - std::string bothFilter = ""; - TiXmlElement* bothFilterXml = initXml(bothFilter); - ResourceThreatDecisionPoint dp5(client, flawedInstants[0], *bothFilterXml); - dp5.initialize(); - CPPUNIT_ASSERT(dp5.getChoices().size() == 3); - CPPUNIT_ASSERT(dp5.getChoices()[0].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp5.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp5.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp5.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp5.getChoices()[2].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp5.getChoices()[2].second->time() == tok3.start()); - - //the combination of ascendingKeyPredecessor and ascendingKeySuccessor have already been tested by now - - std::string earliestPred = ""; - TiXmlElement* earliestPredXml = initXml(earliestPred); - ResourceThreatDecisionPoint dp6(client, flawedInstants[0], *earliestPredXml); - dp6.initialize(); - CPPUNIT_ASSERT(dp6.getChoices().size() == 3); - CPPUNIT_ASSERT(dp6.getChoices()[0].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp6.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp6.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp6.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp6.getChoices()[2].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp6.getChoices()[2].second->time() == tok3.start()); - - std::string latestPred = ""; - TiXmlElement* latestPredXml = initXml(latestPred); - ResourceThreatDecisionPoint dp7(client, flawedInstants[0], *latestPredXml); - dp7.initialize(); - CPPUNIT_ASSERT(dp7.getChoices().size() == 3); - CPPUNIT_ASSERT(dp7.getChoices()[0].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp7.getChoices()[0].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp7.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp7.getChoices()[1].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp7.getChoices()[2].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp7.getChoices()[2].second->time() == tok3.start()); - - - std::string longestPred = ""; - TiXmlElement* longestPredXml = initXml(longestPred); - ResourceThreatDecisionPoint dp8(client, flawedInstants[0], *longestPredXml); - dp8.initialize(); - CPPUNIT_ASSERT(dp8.getChoices().size() == 5); - CPPUNIT_ASSERT(dp8.getChoices()[0].first->time() == tok3.start()); - - - std::string shortestPred = ""; - TiXmlElement* shortestPredXml = initXml(shortestPred); - ResourceThreatDecisionPoint dp9(client, flawedInstants[0], *shortestPredXml); - dp9.initialize(); - CPPUNIT_ASSERT(dp9.getChoices().size() == 3); - CPPUNIT_ASSERT(dp9.getChoices()[0].first->time() == tok2.start() || - dp9.getChoices()[0].first->time() == tok1.end()); - - std::string descendingKeyPred = ""; - TiXmlElement* descendingKeyPredXml = initXml(descendingKeyPred); - ResourceThreatDecisionPoint dp10(client, flawedInstants[0], *descendingKeyPredXml); - dp10.initialize(); - CPPUNIT_ASSERT(dp10.getChoices().size() == 3); - CPPUNIT_ASSERT(dp10.getChoices()[0].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp10.getChoices()[1].first->time() == tok1.end()); - - - std::string earliestSucc = ""; - TiXmlElement* earliestSuccXml = initXml(earliestSucc); - ResourceThreatDecisionPoint dp11(client, flawedInstants[0], *earliestSuccXml); - dp11.initialize(); - CPPUNIT_ASSERT(dp11.getChoices().size() == 3); - CPPUNIT_ASSERT(dp11.getChoices()[0].second->time() == tok2.start() || - dp11.getChoices()[0].second->time() == tok3.start()); - - std::string latestSucc = ""; - TiXmlElement* latestSuccXml = initXml(latestSucc); - ResourceThreatDecisionPoint dp12(client, flawedInstants[0], *latestSuccXml); - dp12.initialize(); - CPPUNIT_ASSERT(dp12.getChoices().size() == 3); - CPPUNIT_ASSERT(dp12.getChoices()[0].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp12.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp12.getChoices()[2].second->time() == tok2.start()); - - - std::string longestSucc = ""; - TiXmlElement* longestSuccXml = initXml(longestSucc); - ResourceThreatDecisionPoint dp13(client, flawedInstants[0], *longestSuccXml); - dp13.initialize(); - CPPUNIT_ASSERT(dp13.getChoices().size() == 3); - CPPUNIT_ASSERT(dp13.getChoices()[0].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp13.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp13.getChoices()[2].second->time() == tok2.start()); - - std::string shortestSucc = ""; - TiXmlElement* shortestSuccXml = initXml(shortestSucc); - ResourceThreatDecisionPoint dp14(client, flawedInstants[0], *shortestSuccXml); - dp14.initialize(); - CPPUNIT_ASSERT(dp14.getChoices().size() == 3); - CPPUNIT_ASSERT(dp14.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp14.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp14.getChoices()[2].second->time() == tok3.start()); - - std::string descendingKeySucc = ""; - TiXmlElement* descendingKeySuccXml = initXml(descendingKeySucc); - ResourceThreatDecisionPoint dp15(client, flawedInstants[0], *descendingKeySuccXml); - dp15.initialize(); - CPPUNIT_ASSERT(dp15.getChoices().size() == 3); - CPPUNIT_ASSERT(dp15.getChoices()[0].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp15.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp15.getChoices()[2].second->time() == tok2.start()); - - - std::string ascendingKeySucc = ""; - TiXmlElement* ascendingKeySuccXml = initXml(ascendingKeySucc); - ResourceThreatDecisionPoint dp16(client, flawedInstants[0], *ascendingKeySuccXml); - dp16.initialize(); - CPPUNIT_ASSERT(dp16.getChoices().size() == 3); - CPPUNIT_ASSERT(dp16.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp16.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp16.getChoices()[2].second->time() == tok3.start()); - - - std::string leastImpact = ""; - TiXmlElement* leastImpactXml = initXml(leastImpact); - ResourceThreatDecisionPoint dp17(client, flawedInstants[0], *leastImpactXml); - dp17.initialize(); - CPPUNIT_ASSERT(dp17.getChoices().size() == 5); - CPPUNIT_ASSERT(dp17.getChoices()[0].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp17.getChoices()[0].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp17.getChoices()[1].first->time() == tok1.end()); - CPPUNIT_ASSERT(dp17.getChoices()[1].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp17.getChoices()[2].first->time() == tok2.start()); - CPPUNIT_ASSERT(dp17.getChoices()[2].second->time() == tok3.start()); - CPPUNIT_ASSERT(dp17.getChoices()[3].first->time() == tok3.start()); - CPPUNIT_ASSERT(dp17.getChoices()[3].second->time() == tok2.start()); - CPPUNIT_ASSERT(dp17.getChoices()[4].first->time() == tok2.end()); - CPPUNIT_ASSERT(dp17.getChoices()[4].second->time() == tok3.start()); - - std::string precedesOnly = ""; - TiXmlElement* precedesOnlyXml = initXml(precedesOnly); - ResourceThreatDecisionPoint dp18(client, flawedInstants[0], *precedesOnlyXml); - dp18.initialize(); - ConstraintNameListener* nameListener = new ConstraintNameListener(dp18.getChoices()[0].first->time()); - dp18.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); - dp18.undo(); - delete (ConstrainedVariableListener*) nameListener; - ce->propagate(); - nameListener = new ConstraintNameListener(dp18.getChoices()[1].first->time()); - dp18.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); - dp18.undo(); - ce->propagate(); - delete (ConstrainedVariableListener*) nameListener; - - std::string concurrentOnly = ""; - TiXmlElement* concurrentOnlyXml = initXml(concurrentOnly); - ResourceThreatDecisionPoint dp19(client, flawedInstants[0], *concurrentOnlyXml); - dp19.initialize(); - nameListener = new ConstraintNameListener(dp19.getChoices()[0].first->time()); - dp19.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); - dp19.undo(); - delete (ConstrainedVariableListener*) nameListener; - ce->propagate(); - nameListener = new ConstraintNameListener(dp19.getChoices()[1].first->time()); - dp19.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); - dp19.undo(); - ce->propagate(); - delete (ConstrainedVariableListener*) nameListener; - - //pair first has already been implicitly tested and constraint first is necessary to make this easy anyway, so it'll get tested as well. - - std::string precedesFirst = ""; - TiXmlElement* precedesFirstXml = initXml(precedesFirst); - ResourceThreatDecisionPoint dp20(client, flawedInstants[0], *precedesFirstXml); - dp20.initialize(); - nameListener = new ConstraintNameListener(dp20.getChoices()[0].first->time()); - dp20.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); - dp20.undo(); - ce->propagate(); - dp20.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); - dp20.undo(); - ce->propagate(); - delete (ConstrainedVariableListener*) nameListener; - //step once more to test creating a constraint on the next choice - nameListener = new ConstraintNameListener(dp20.getChoices()[1].first->time()); - dp20.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); - dp20.undo(); - ce->propagate(); - delete nameListener; - - std::string concurrentFirst = ""; - TiXmlElement* concurrentFirstXml = initXml(concurrentFirst); - ResourceThreatDecisionPoint dp21(client, flawedInstants[0], *concurrentFirstXml); - dp21.initialize(); - nameListener = new ConstraintNameListener(dp21.getChoices()[0].first->time()); - dp21.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); - dp21.undo(); - ce->propagate(); - dp21.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("precedes")); - dp21.undo(); - ce->propagate(); - delete (ConstrainedVariableListener*) nameListener; - //step once more to test creating a constraint on the next choice - nameListener = new ConstraintNameListener(dp21.getChoices()[1].first->time()); - dp21.execute(); - ce->propagate(); - CPPUNIT_ASSERT(nameListener->getName() == LabelStr("concurrent")); - dp21.undo(); - ce->propagate(); - delete nameListener; - - delete concurrentFirstXml; - delete precedesFirstXml; - delete concurrentOnlyXml; - delete precedesOnlyXml; - delete leastImpactXml; - delete ascendingKeySuccXml; - delete descendingKeySuccXml; - delete shortestSuccXml; - delete longestSuccXml; - delete latestSuccXml; - delete earliestSuccXml; - delete descendingKeyPredXml; - delete shortestPredXml; - delete longestPredXml; - delete latestPredXml; - delete earliestPredXml; - delete bothFilterXml; - delete sucFilterXml; - delete predFilterXml; - delete noFilterXml; - - return true; - } + return true; + } static bool testResourceThreatManager() { diff --git a/src/PLASMA/Utils/base/DebugMsg.cc b/src/PLASMA/Utils/base/DebugMsg.cc index 3ab43de53..39f0aa117 100755 --- a/src/PLASMA/Utils/base/DebugMsg.cc +++ b/src/PLASMA/Utils/base/DebugMsg.cc @@ -7,7 +7,7 @@ #ifndef NO_DEBUG_MESSAGE_SUPPORT -#include "europa-config.h" +// #include "europa-config.h" #include #include From 04a79864cd5c7f277da2e3e3fdf143c7b77d9f83 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 12 Sep 2014 20:01:27 +0000 Subject: [PATCH 017/149] This commit fixes issue 101 and a resource test failure. Profile.{cc,hh}: Added a getInstant function and fixed some whitespace BoostFlowProfileGraph.cc: Removed the bizarre computation of when a transaction begins contributing to address a ResourceThreatDecisionPoint test failure. FlowProfile.cc: Added a more correct (but possibly inefficient) computation of the earliest instants when a transaction begins contributing to a level to fix a ResourceThreatDecisionPoint filtering test failure. ResourceThreatDecisionPoint.cc: Whitespace changes rs-test-module.cc: Added a custom deleter for transactions and switched to using shared pointers to manage transactions in tests to avoid invalid memory accesses in tests due to the pointers in Profile objects outliving the Transaction objects they point to. Some revision of object lifetime in the Resource design is needed. FlawFilter.hh: Removed useless non-virtual overrides of get/setContext which were preventing subclasses from overriding it themselves. This was part of getting Contexts correctly distributed in addressing issue 101. FlawManager.cc: Debug messages for context setting. MatchingRule.{cc,hh}: Added get/setContext for addressing issue 101 Filters.{cc,hh}: Removed the static, mutable IntervalIntDomain used to refer to the horizon to address issue 101. The horizon is now available via the Context object, which can be modified in the base Solver to get the shifting horizons that IDEA used. PSSolversImpl.cc: Added setting of the horizon in the Context object. solvers-test-module.cc: Updated tests to use the Context object for setting horizons. EuropaEngine.cc: Added setting of the horizon in the Context object. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6747 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/Resource/base/Profile.cc | 23 +- src/PLASMA/Resource/base/Profile.hh | 2 + .../component/BoostFlowProfileGraph.cc | 17 +- src/PLASMA/Resource/component/FlowProfile.cc | 84 +++-- .../Solvers/ResourceThreatDecisionPoint.cc | 80 ++-- src/PLASMA/Resource/test/rs-test-module.cc | 352 ++++++++++-------- src/PLASMA/Solvers/base/FlawFilter.hh | 4 +- src/PLASMA/Solvers/base/FlawManager.cc | 2 + src/PLASMA/Solvers/base/MatchingRule.cc | 1 + src/PLASMA/Solvers/base/MatchingRule.hh | 4 +- src/PLASMA/Solvers/component/Filters.cc | 32 +- src/PLASMA/Solvers/component/Filters.hh | 7 +- src/PLASMA/Solvers/component/PSSolversImpl.cc | 9 +- .../Solvers/test/solvers-test-module.cc | 75 ++-- src/PLASMA/System/base/EuropaEngine.cc | 4 +- 15 files changed, 411 insertions(+), 285 deletions(-) diff --git a/src/PLASMA/Resource/base/Profile.cc b/src/PLASMA/Resource/base/Profile.cc index c0a92604c..45f041151 100644 --- a/src/PLASMA/Resource/base/Profile.cc +++ b/src/PLASMA/Resource/base/Profile.cc @@ -45,6 +45,11 @@ namespace EUROPA { m_id.remove(); } +InstantId Profile::getInstant(const eint time) const { + std::map::const_iterator it = m_instants.find(time); + return (it == m_instants.end() ? InstantId::noId() : it->second); +} + void Profile::addTransaction(const TransactionId t) { checkError(m_transactions.find(t) == m_transactions.end(), "Attempted to insert a transaction twice!"); checkError(m_variableListeners.find(t) == m_variableListeners.end(), "Already have time and/or quantity listeners for this transaction."); @@ -413,13 +418,17 @@ namespace EUROPA { /** * @brief Remove */ - void Profile::handleTransactionVariableDeletion(const TransactionId& t){ - std::map::iterator listIt = m_otherListeners.find(t); - checkError(listIt != m_otherListeners.end(), - "Attempted to remove variable listener for transaction at time " << t->time()->toString() << " with quantity " << t->quantity()->toString() << "."); - delete (ConstraintAdditionListener*) listIt->second; - m_otherListeners.erase(t); - } + +void Profile::handleTransactionVariableDeletion(const TransactionId& t){ + std::map::iterator listIt = + m_otherListeners.find(t); + checkError(listIt != m_otherListeners.end(), + "Attempted to remove variable listener for transaction at time " << + t->time()->toString() << " with quantity " << + t->quantity()->toString() << "."); + delete (ConstraintAdditionListener*) listIt->second; + m_otherListeners.erase(t); +} void Profile::getLevel(const eint time, IntervalDomain& dest) { if(needsRecompute()) diff --git a/src/PLASMA/Resource/base/Profile.hh b/src/PLASMA/Resource/base/Profile.hh index bf4d0573a..58ed1e50b 100644 --- a/src/PLASMA/Resource/base/Profile.hh +++ b/src/PLASMA/Resource/base/Profile.hh @@ -106,6 +106,8 @@ namespace EUROPA { std::map::iterator getLeastInstant(const eint time); const std::map& getInstants() {return m_instants;} + + InstantId getInstant(const eint time) const; private: friend class ProfilePropagator; diff --git a/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc index 492cbf0c3..88615e8e0 100644 --- a/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc +++ b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc @@ -149,21 +149,12 @@ void BoostFlowProfileGraph::enableTransaction(const TransactionId& t, const InstantId& inst, TransactionId2InstantId& contributions) { debugMsg("BoostFlowProfileGraph:enableTransaction", - (isLowerLevel() ? "" : "") << "Enabling " << t << " at " - << inst->getTime()); + (isLowerLevel() ? "" : "") << "Enabling " << + (t->isConsumer() ? "consumer " : "producer ") << t << "" << t->toString() << + " at " << inst->getTime()); - edouble edgeCapacity = 0.0; + // edouble edgeCapacity = 0.0; - if(isLowerLevel() == t->isConsumer()) { - edgeCapacity = t->quantity()->lastDomain().getUpperBound(); - } - else { - edgeCapacity = t->quantity()->lastDomain().getLowerBound(); - } - - if(0.0 == edgeCapacity) { - contributions[t] = inst; //? - } if(std::find(m_activeTransactions.begin(), m_activeTransactions.end(), t) == m_activeTransactions.end()) { m_activeTransactions.push_back(t); diff --git a/src/PLASMA/Resource/component/FlowProfile.cc b/src/PLASMA/Resource/component/FlowProfile.cc index 4042f4441..2bcbe4fc1 100644 --- a/src/PLASMA/Resource/component/FlowProfile.cc +++ b/src/PLASMA/Resource/component/FlowProfile.cc @@ -70,33 +70,73 @@ namespace EUROPA delete (Transaction*) m_dummySourceTransaction; } - bool FlowProfile::getEarliestLowerLevelInstant( const TransactionId& t, InstantId& i ) - { - check_error( t.isValid()); - - TransactionId2InstantId::iterator ite = m_lowerLevelContribution.find( t ); - - if( m_lowerLevelContribution.end() == ite ) - return false; +bool FlowProfile::getEarliestLowerLevelInstant(const TransactionId& t, InstantId& i) { + check_error( t.isValid()); - i = (*ite).second; - - return true; + if(t->isConsumer()) { + i = getInstant(t->time()->lastDomain().getLowerBound()); + return true; + } + else { + std::map::const_iterator end = + m_instants.upper_bound(t->time()->lastDomain().getUpperBound()); + for(std::map::const_iterator start = + m_instants.lower_bound(t->time()->lastDomain().getLowerBound()); + start != end; ++start) { + InstantId inst = start->second; + for(std::set::const_iterator it = + inst->getTransactions().begin(); + it != inst->getTransactions().end(); ++it) { + if((*it)->isConsumer()) { + switch(getOrdering(t, *it)) { + case BEFORE_OR_AT: + case STRICTLY_AT: + i = inst; + return true; + default: + break; + } + } + } } + i = getInstant(t->time()->lastDomain().getUpperBound()); + return true; + } +} - bool FlowProfile::getEarliestUpperLevelInstant( const TransactionId& t, InstantId& i ) - { - check_error( t.isValid()); - - TransactionId2InstantId::iterator ite = m_upperLevelContribution.find( t ); - - if( m_upperLevelContribution.end() == ite ) - return false; - - i = (*ite).second; +bool FlowProfile::getEarliestUpperLevelInstant(const TransactionId& t, InstantId& i) { + check_error( t.isValid()); - return true; + if(!t->isConsumer()) { + i = getInstant(t->time()->lastDomain().getLowerBound()); + return true; + } + else { + std::map::const_iterator end = + m_instants.upper_bound(t->time()->lastDomain().getUpperBound()); + for(std::map::const_iterator start = + m_instants.lower_bound(t->time()->lastDomain().getLowerBound()); + start != end; ++start) { + InstantId inst = start->second; + for(std::set::const_iterator it = + inst->getTransactions().begin(); + it != inst->getTransactions().end(); ++it) { + if(!(*it)->isConsumer()) { + switch(getOrdering(t, *it)) { + case BEFORE_OR_AT: + case STRICTLY_AT: + i = inst; + return true; + default: + break; + } + } + } } + i = getInstant(t->time()->lastDomain().getUpperBound()); + return true; + } +} void FlowProfile::initRecompute(InstantId inst) { diff --git a/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc b/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc index 608a1c9db..17911cfde 100644 --- a/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc +++ b/src/PLASMA/Resource/component/Solvers/ResourceThreatDecisionPoint.cc @@ -93,42 +93,54 @@ namespace EUROPA { bool m_treatAsLowerFlaw; }; - class PredecessorNotContributingChoiceFilter : public DefaultChoiceFilter { - public: - PredecessorNotContributingChoiceFilter(Profile* profile, const LabelStr& explanation, const InstantId& inst) - : DefaultChoiceFilter(profile, explanation, inst) { - // For this ChoiceFilter, we need the profile to be a subclass of FlowProfile: - FlowProfile * fProfile = dynamic_cast ((Profile*) profile); - check_runtime_error(fProfile != 0, - "Cannot create PredecessorNotContributingChoiceFilter for profile not derived from FlowProfile " \ - " (choice of ResourceThreatHandler filter in PlannerConfig.xml probably conflicts with choice of profileType in NDDL)"); +class PredecessorNotContributingChoiceFilter : public DefaultChoiceFilter { + public: + PredecessorNotContributingChoiceFilter(Profile* profile, const LabelStr& explanation, + const InstantId& inst) + : DefaultChoiceFilter(profile, explanation, inst) { + // For this ChoiceFilter, we need the profile to be a subclass of FlowProfile: + FlowProfile * fProfile = dynamic_cast ((Profile*) profile); + checkRuntimeError(fProfile != 0, + "Cannot create PredecessorNotContributingChoiceFilter for " << + "profile not derived from FlowProfile (choice of " << + "ResourceThreatHandler filter in PlannerConfig.xml probably " << + "conflicts with choice of profileType in NDDL)"); + } + + bool operator()(const std::pair& p) const { + InstantId inst = InstantId::noId(); + bool contributing = false; + + if(m_treatAsLowerFlaw) { + if(p.first->isConsumer()) { + debugMsg("ResourceThreatDecisionPoint:filter:predecessorNot", + "Rejecting choice because flaw is lower level and predecessor is " << + "a consumer."); + return false; } - - bool operator()(const std::pair& p) const { - InstantId inst = InstantId::noId(); - bool contributing = false; - - if(m_treatAsLowerFlaw) { - if(p.first->isConsumer()) { - debugMsg("ResourceThreatDecisionPoint:filter:predecessorNot", "Rejecting choice because flaw is lower level and predecessor is a consumer."); - return false; - } - contributing = ((FlowProfile*) m_profile)->getEarliestLowerLevelInstant(p.first, inst); - } - else { - if(!p.first->isConsumer()) { - debugMsg("ResourceThreatDecisionPoint:filter:predecesorNot", "Rejecting choice because flaw is upper level and predecessor is a producer."); - return false; - } - contributing = ((FlowProfile*) m_profile)->getEarliestUpperLevelInstant(p.first, inst); - } - checkError(contributing, "Should always have an instant for transaction " << p.first->toString()); - condDebugMsg(inst->getTime() <= m_inst->getTime(), "ResourceThreatDecisionPoint:filter:predecessorNot", - "Rejecting choice because predecessor is contributing at this instant."); - return inst->getTime() > m_inst->getTime(); + contributing = + ((FlowProfile*) m_profile)->getEarliestLowerLevelInstant(p.first, inst); + } + else { + if(!p.first->isConsumer()) { + debugMsg("ResourceThreatDecisionPoint:filter:predecesorNot", + "Rejecting choice because flaw is upper level and predecessor is " << + "a producer."); + return false; } - std::string toString() const {return "PredecessorNotContributingFilter";} - }; + contributing = + ((FlowProfile*) m_profile)->getEarliestUpperLevelInstant(p.first, inst); + } + checkError(contributing, + "Should always have an instant for transaction " << + p.first->toString()); + condDebugMsg(inst->getTime() <= m_inst->getTime(), + "ResourceThreatDecisionPoint:filter:predecessorNot", + "Rejecting choice because predecessor is contributing at this instant."); + return inst->getTime() > m_inst->getTime(); + } + std::string toString() const {return "PredecessorNotContributingFilter";} +}; class SuccessorContributingChoiceFilter : public DefaultChoiceFilter { public: diff --git a/src/PLASMA/Resource/test/rs-test-module.cc b/src/PLASMA/Resource/test/rs-test-module.cc index 91bc0c4d6..0abf8b80d 100644 --- a/src/PLASMA/Resource/test/rs-test-module.cc +++ b/src/PLASMA/Resource/test/rs-test-module.cc @@ -26,6 +26,7 @@ #include "Debug.hh" #include "ThreatDecisionPoint.hh" +#include "Context.hh" #include "Profile.hh" #include "FlowProfile.hh" #include "IncrementalFlowProfile.hh" @@ -51,6 +52,8 @@ #include #include +#include + using namespace EUROPA; class ResourceTestEngine : public EngineBase @@ -170,7 +173,6 @@ class DummyDetector : public FVDetector { virtual PSResourceProfile* getVDLevelProfile() { return NULL; } }; - class DummyResource : public Resource { public: DummyResource(const PlanDatabaseId& planDatabase, const LabelStr& type, const LabelStr& name, @@ -206,6 +208,28 @@ class DummyResource : public Resource { void notifyDeleted(const InstantId inst) {} void notifyNoLongerFlawed(const InstantId inst){} }; + +class BareTransactionDeleter { + public: + BareTransactionDeleter(Profile& profile) : m_profile(&profile), m_res(NULL) {} + BareTransactionDeleter(DummyResource& res) : m_profile(NULL), m_res(&res) {} + void operator()(Transaction* t) { + if(m_profile != NULL) { + std::cout << "Removing " << t->getId() << " from a profile" << std::endl; + m_profile->removeTransaction(t->getId()); + } + if(m_res != NULL) { + std::cout << "Removing " << t->getId() << " from a resource" << std::endl; + m_res->removeTransaction(t->getId()); + } + delete t; + } + private: + Profile* m_profile; + DummyResource* m_res; +}; + +typedef boost::shared_ptr TransactionPtr; /** add tests for getClosedTransactions and getPendingTransactions! */ @@ -293,6 +317,7 @@ class ProfileTest { RESOURCE_DEFAULT_SETUP(ce, db, true); DummyDetector detector(ResourceId::noId()); DummyProfile profile(db.getId(), detector.getId()); + BareTransactionDeleter deleter(profile); Variable t1(ce.getId(), IntervalIntDomain(0, 0)); Variable t2(ce.getId(), IntervalIntDomain(10, 10)); @@ -303,23 +328,23 @@ class ProfileTest { std::set times; - Transaction trans1(t1.getId(), quantity.getId(), false); - Transaction trans2(t2.getId(), quantity.getId(), false); //distinct cases - Transaction trans3(t3.getId(), quantity.getId(), false); //overlap on left side. both trans1 and trans2 should appear at time 0 - Transaction trans4(t4.getId(), quantity.getId(), false); //overlap in the middle. should have trans3 and trans4 at time 1 and only trans4 at time 4 - Transaction trans5(t5.getId(), quantity.getId(), false); //overlap on right side. both trans 4 and trans5 should appear at time 4 + TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false), deleter); //distinct cases + TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false), deleter); //overlap on left side. both trans1 and trans2 should appear at time 0 + TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false), deleter); //overlap in the middle. should have trans3 and trans4 at time 1 and only trans4 at time 4 + TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false), deleter); //overlap on right side. both trans 4 and trans5 should appear at time 4 - profile.addTransaction(trans1.getId()); + profile.addTransaction(trans1->getId()); times.insert(0); ProfileIterator prof1(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof1)); - profile.addTransaction(trans2.getId()); + profile.addTransaction(trans2->getId()); times.insert(10); ProfileIterator prof2(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof2)); - profile.addTransaction(trans3.getId()); + profile.addTransaction(trans3->getId()); times.insert(3); ProfileIterator prof3(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof3)); @@ -327,7 +352,7 @@ class ProfileTest { CPPUNIT_ASSERT(!oCheck1.done()); CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().size() == 2); - profile.addTransaction(trans4.getId()); + profile.addTransaction(trans4->getId()); times.insert(1); times.insert(4); ProfileIterator prof4(profile.getId()); @@ -336,7 +361,7 @@ class ProfileTest { CPPUNIT_ASSERT(!oCheck2.done()); CPPUNIT_ASSERT(oCheck2.getInstant()->getTransactions().size() == 2); - profile.addTransaction(trans5.getId()); + profile.addTransaction(trans5->getId()); times.insert(6); ProfileIterator prof5(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof5)); @@ -344,7 +369,7 @@ class ProfileTest { CPPUNIT_ASSERT(!oCheck3.done()); CPPUNIT_ASSERT(oCheck3.getInstant()->getTransactions().size() == 2); - profile.removeTransaction(trans4.getId()); + profile.removeTransaction(trans4->getId()); times.erase(1); ProfileIterator prof6(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof6)); @@ -353,16 +378,16 @@ class ProfileTest { ProfileIterator oCheck5(profile.getId(), 4, 4); CPPUNIT_ASSERT(oCheck5.getInstant()->getTransactions().size() == 1); - profile.removeTransaction(trans1.getId()); - profile.removeTransaction(trans2.getId()); + profile.removeTransaction(trans1->getId()); + profile.removeTransaction(trans2->getId()); times.erase(10); ProfileIterator prof7(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, prof7)); ProfileIterator oCheck6(profile.getId(), 0, 0); CPPUNIT_ASSERT(oCheck6.getInstant()->getTransactions().size() == 1); - profile.removeTransaction(trans3.getId()); - profile.removeTransaction(trans5.getId()); + profile.removeTransaction(trans3->getId()); + profile.removeTransaction(trans5->getId()); ProfileIterator prof8(profile.getId()); CPPUNIT_ASSERT(prof8.done()); @@ -374,6 +399,7 @@ class ProfileTest { RESOURCE_DEFAULT_SETUP(ce, db, true); DummyDetector detector(ResourceId::noId()); DummyProfile profile(db.getId(), detector.getId()); + BareTransactionDeleter deleter(profile); Variable t1(ce.getId(), IntervalIntDomain(0, 0)); Variable t2(ce.getId(), IntervalIntDomain(10, 10)); @@ -387,17 +413,17 @@ class ProfileTest { times.insert(3); times.insert(4); times.insert(6); times.insert(10); - Transaction trans1(t1.getId(), quantity.getId(), false); - Transaction trans2(t2.getId(), quantity.getId(), false); - Transaction trans3(t3.getId(), quantity.getId(), false); - Transaction trans4(t4.getId(), quantity.getId(), false); - Transaction trans5(t5.getId(), quantity.getId(), false); + TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false), deleter); - profile.addTransaction(trans1.getId()); - profile.addTransaction(trans2.getId()); - profile.addTransaction(trans3.getId()); - profile.addTransaction(trans4.getId()); - profile.addTransaction(trans5.getId()); + profile.addTransaction(trans1->getId()); + profile.addTransaction(trans2->getId()); + profile.addTransaction(trans3->getId()); + profile.addTransaction(trans4->getId()); + profile.addTransaction(trans5->getId()); ProfileIterator baseTest(profile.getId()); CPPUNIT_ASSERT(checkTimes(times, baseTest)); @@ -410,8 +436,8 @@ class ProfileTest { CPPUNIT_ASSERT(checkTimes(times, prof1)); ProfileIterator oCheck1(profile.getId(), 2, 2); CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().size() == 2); - CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().find(trans3.getId()) != oCheck1.getInstant()->getTransactions().end()); - CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().find(trans4.getId()) != oCheck1.getInstant()->getTransactions().end()); + CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().find(trans3->getId()) != oCheck1.getInstant()->getTransactions().end()); + CPPUNIT_ASSERT(oCheck1.getInstant()->getTransactions().find(trans4->getId()) != oCheck1.getInstant()->getTransactions().end()); ProfileIterator oCheck1_1(profile.getId(), 3, 3); CPPUNIT_ASSERT(oCheck1_1.done()); @@ -449,44 +475,45 @@ class ProfileTest { DummyDetector detector(ResourceId::noId()); TimetableProfile r(db.getId(), detector.getId()); + BareTransactionDeleter deleter(r); // Variable t0(ce.getId(), IntervalIntDomain(MINUS_INFINITY, MINUS_INFINITY)); // Variable q0(ce.getId(), IntervalDomain(0, 0)); -// Transaction trans0(t0.getId(), q0.getId(), false); -// r.addTransaction(trans0.getId()); +// TransactionPtr trans0(new Transaction(t0.getId(), q0.getId(), false), deleter); +// r.addTransaction(trans0->getId()); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 0); Variable t1(ce.getId(), IntervalIntDomain(0, HORIZON_END)); Variable q1(ce.getId(), IntervalDomain(45, 45)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 1000 * 45); Variable t2(ce.getId(), IntervalIntDomain(1, HORIZON_END)); Variable q2(ce.getId(), IntervalDomain(35, 35)); - Transaction trans2(t2.getId(), q2.getId(), false); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false), deleter); + r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*45 + 80*999)); Variable t3(ce.getId(), IntervalIntDomain(2, HORIZON_END)); Variable q3(ce.getId(), IntervalDomain(20, 20)); - Transaction trans3(t3.getId(), q3.getId(), false); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*3)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*45 + 1*80 + 998*100)); - trans2.time()->restrictBaseDomain(IntervalIntDomain(1, trans2.time()->lastDomain().getUpperBound())); + trans2->time()->restrictBaseDomain(IntervalIntDomain(1, trans2->time()->lastDomain().getUpperBound())); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*3)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*45 + 1*80 + 998*100)); - trans2.time()->restrictBaseDomain(IntervalIntDomain(2, trans2.time()->lastDomain().getUpperBound())); + trans2->time()->restrictBaseDomain(IntervalIntDomain(2, trans2->time()->lastDomain().getUpperBound())); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*3 + 3*3)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (2*45 + 998*100)); @@ -502,68 +529,69 @@ class ProfileTest { DummyDetector detector(ResourceId::noId()); TimetableProfile r(db.getId(), detector.getId()); + BareTransactionDeleter deleter(r); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == 0); Variable t1(ce.getId(), IntervalIntDomain(4, 6)); Variable q1(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*1)); Variable t2(ce.getId(), IntervalIntDomain(-4, 10)); Variable q2(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans2(t2.getId(), q2.getId(), false); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false), deleter); + r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*1)); Variable t3(ce.getId(), IntervalIntDomain(1, 3)); Variable q3(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans3(t3.getId(), q3.getId(), false); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 +3*2 + 4*2 + 5*2 + 6*1)); Variable t4(ce.getId(), IntervalIntDomain(1, 2)); Variable q4(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans4(t4.getId(), q4.getId(), false); - r.addTransaction(trans4.getId()); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); + r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*2 + 5*2 + 6*2 + 7*1)); Variable t5(ce.getId(), IntervalIntDomain(3, 7)); Variable q5(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans5(t5.getId(), q5.getId(), false); - r.addTransaction(trans5.getId()); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), false), deleter); + r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*3 + 6*3 + 7*2 + 8*1)); Variable t6(ce.getId(), IntervalIntDomain(4, 7)); Variable q6(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans6(t6.getId(), q6.getId(), false); - r.addTransaction(trans6.getId()); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false), deleter); + r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*4 + 6*4 + 7*3 + 8*1)); // Insert for a singleton value Variable t7(ce.getId(), IntervalIntDomain(5, 5)); Variable q7(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - Transaction trans7(t7.getId(), q7.getId(), false); - r.addTransaction(trans7.getId()); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), false), deleter); + r.addTransaction(trans7->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*4 + 6*5 + 7*4 + 8*3 + 9*1)); // Now free them and check the retractions are working correctly - r.removeTransaction(trans7.getId()); + r.removeTransaction(trans7->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*4 + 6*4 + 7*3 + 8*1)); - r.removeTransaction(trans6.getId()); + r.removeTransaction(trans6->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*3 + 6*3 + 7*2 + 8*1)); - r.removeTransaction(trans5.getId()); + r.removeTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*2 + 5*2 + 6*2 + 7*1)); - r.removeTransaction(trans4.getId()); + r.removeTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 +3*2 + 4*2 + 5*2 + 6*1)); - r.removeTransaction(trans3.getId()); + r.removeTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*1)); - r.removeTransaction(trans2.getId()); + r.removeTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*1)); - r.removeTransaction(trans1.getId()); + r.removeTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == 0); RESOURCE_DEFAULT_TEARDOWN(); @@ -576,59 +604,60 @@ class ProfileTest { DummyDetector detector(ResourceId::noId()); TimetableProfile r(db.getId(), detector.getId()); + BareTransactionDeleter deleter(r); Variable t1(ce.getId(), IntervalIntDomain(0, 1)); Variable q1(ce.getId(), IntervalDomain(1, 1)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 1); Variable t2(ce.getId(), IntervalIntDomain(1, 3)); Variable q2(ce.getId(), IntervalDomain(4, 4)); - Transaction trans2(t2.getId(), q2.getId(), true); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + r.addTransaction(trans2->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1 + 4*2)); Variable t3(ce.getId(), IntervalIntDomain(2, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - Transaction trans3(t3.getId(), q3.getId(), false); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + r.addTransaction(trans3->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*2 + 5*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*1 + 4*1 + 12*1 + 8*1)); Variable t4(ce.getId(), IntervalIntDomain(3, 6)); Variable q4(ce.getId(), IntervalDomain(2, 2)); - Transaction trans4(t4.getId(), q4.getId(), false); - r.addTransaction(trans4.getId()); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); + r.addTransaction(trans4->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*3 + 5*2 + 6*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*1 + 4*1 + 12*1 + 10*1 + 2*2)); Variable t5(ce.getId(), IntervalIntDomain(2, 10)); Variable q5(ce.getId(), IntervalDomain(6, 6)); - Transaction trans5(t5.getId(), q5.getId(), true); - r.addTransaction(trans5.getId()); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + r.addTransaction(trans5->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*2 + 7*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*1 + 4*1 + 18*1 + 16*1 + 8*2 + 6*4)); Variable t6(ce.getId(), IntervalIntDomain(6, 8)); Variable q6(ce.getId(), IntervalDomain(3, 3)); - Transaction trans6(t6.getId(), q6.getId(), false); - r.addTransaction(trans6.getId()); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false), deleter); + r.addTransaction(trans6->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*3 + 7*2 + 8*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*1 + 4*1 + 18*1 + 16*1 + 8*2 + 9*2 + 6*2)); Variable t7(ce.getId(), IntervalIntDomain(7, 8)); Variable q7(ce.getId(), IntervalDomain(4, 4)); - Transaction trans7(t7.getId(), q7.getId(), true); - r.addTransaction(trans7.getId()); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true), deleter); + r.addTransaction(trans7->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*3 + +7* 3 + 8*3 + 9*1)); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == (1*1 + 4*1 + 18*1 + 16*1 + 8*2 + 9*1 + 13*1 + 6*2)); @@ -643,21 +672,22 @@ class ProfileTest { DummyDetector detector(ResourceId::noId()); TimetableProfile r(db.getId(), detector.getId()); + BareTransactionDeleter deleter(r); Variable t1(ce.getId(), IntervalIntDomain(0, 10)); Variable q1(ce.getId(), IntervalDomain(10, 10)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*10); - trans1.time()->restrictBaseDomain(IntervalIntDomain(1, trans1.time()->lastDomain().getUpperBound())); + trans1->time()->restrictBaseDomain(IntervalIntDomain(1, trans1->time()->lastDomain().getUpperBound())); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*9); - trans1.time()->restrictBaseDomain(IntervalIntDomain(trans1.time()->lastDomain().getLowerBound(), eint(8))); + trans1->time()->restrictBaseDomain(IntervalIntDomain(trans1->time()->lastDomain().getLowerBound(), eint(8))); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*7); - trans1.time()->restrictBaseDomain(IntervalIntDomain(trans1.time()->lastDomain().getLowerBound(), eint(6))); + trans1->time()->restrictBaseDomain(IntervalIntDomain(trans1->time()->lastDomain().getLowerBound(), eint(6))); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*5); RESOURCE_DEFAULT_TEARDOWN(); @@ -670,21 +700,21 @@ class ProfileTest { DummyDetector detector(ResourceId::noId()); TimetableProfile r(db.getId(), detector.getId()); - + BareTransactionDeleter deleter(r); // Test producer Variable t1(ce.getId(), IntervalIntDomain(0, 10)); Variable q1(ce.getId(), IntervalDomain(5, 10)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*10); // Test consumer Variable t3(ce.getId(), IntervalIntDomain(1, 5)); Variable q3(ce.getId(), IntervalDomain(1, 4)); - Transaction trans3(t3.getId(), q3.getId(), true); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + r.addTransaction(trans3->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*1 + 14*4 + 13*5);//+ 14*3 + 21*1 + 20*3 + 20*2); @@ -698,58 +728,59 @@ class ProfileTest { DummyResource r(db.getId(), LabelStr("Resource"), LabelStr("r1"), initialCapacity, initialCapacity, limitMin, limitMax, productionRateMax, -(consumptionRateMax), productionMax, -(consumptionMax)); + BareTransactionDeleter deleter(r); db.close(); Variable t1(ce.getId(), IntervalIntDomain(0, 1)); Variable q1(ce.getId(), IntervalDomain(productionRateMax, productionRateMax + 1)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); ce.propagate(); Variable t3(ce.getId(), IntervalIntDomain(0, 1)); Variable q3(ce.getId(), IntervalDomain(1, 1)); - Transaction trans3(t3.getId(), q3.getId(), false); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + r.addTransaction(trans3->getId()); // no violation because of temporal flexibility CPPUNIT_ASSERT(ce.propagate()); - trans1.time()->restrictBaseDomain(IntervalIntDomain(1, trans1.time()->lastDomain().getUpperBound())); - trans3.time()->restrictBaseDomain(IntervalIntDomain(1, trans3.time()->lastDomain().getUpperBound())); + trans1->time()->restrictBaseDomain(IntervalIntDomain(1, trans1->time()->lastDomain().getUpperBound())); + trans3->time()->restrictBaseDomain(IntervalIntDomain(1, trans3->time()->lastDomain().getUpperBound())); CPPUNIT_ASSERT(!ce.propagate()); //r->getResourceViolations(violations); //CPPUNIT_ASSERT(violations.size() == 1); //CPPUNIT_ASSERT(violations.front()->getType() == ResourceViolation::ProductionRateExceeded); - r.removeTransaction(trans3.getId()); - r.removeTransaction(trans1.getId()); + r.removeTransaction(trans3->getId()); + r.removeTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t2(ce.getId(), IntervalIntDomain(0, 1)); Variable q2(ce.getId(), IntervalDomain(-(consumptionRateMax), -(consumptionRateMax - 1))); - Transaction trans2(t2.getId(), q2.getId(), true); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + r.addTransaction(trans2->getId()); ce.propagate(); Variable t4(ce.getId(), IntervalIntDomain(0, 1)); Variable q4(ce.getId(), IntervalDomain(1, 1)); - Transaction trans4(t4.getId(), q4.getId(), true); - r.addTransaction(trans4.getId()); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + r.addTransaction(trans4->getId()); // no violation because of temporal flexibility CPPUNIT_ASSERT(ce.propagate()); - trans2.time()->restrictBaseDomain(IntervalIntDomain(1, trans2.time()->lastDomain().getUpperBound())); - trans4.time()->restrictBaseDomain(IntervalIntDomain(1, trans4.time()->lastDomain().getUpperBound())); + trans2->time()->restrictBaseDomain(IntervalIntDomain(1, trans2->time()->lastDomain().getUpperBound())); + trans4->time()->restrictBaseDomain(IntervalIntDomain(1, trans4->time()->lastDomain().getUpperBound())); CPPUNIT_ASSERT(!ce.propagate()); //violations.clear(); //r->getResourceViolations(violations); //CPPUNIT_ASSERT(violations.size() == 1); //CPPUNIT_ASSERT(violations.front()->getType() == ResourceViolation::ConsumptionRateExceeded); - r.removeTransaction(trans4.getId()); - r.removeTransaction(trans2.getId()); + r.removeTransaction(trans4->getId()); + r.removeTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); RESOURCE_DEFAULT_TEARDOWN(); @@ -764,45 +795,46 @@ class ProfileTest { DummyResource r(db.getId(), LabelStr("Resource"), LabelStr("r1"), initialCapacity, initialCapacity, limitMin, limitMax, productionRateMax, -(consumptionRateMax), productionMax, -(consumptionMax)); + BareTransactionDeleter deleter(r); db.close(); // Test that a violation is detected when the excess in the level cannot be overcome by remaining // production Variable t1(ce.getId(), IntervalIntDomain(2, 2)); Variable q1(ce.getId(), IntervalDomain(8, 8)); - Transaction trans1(t1.getId(), q1.getId(), true); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true), deleter); + r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t2(ce.getId(), IntervalIntDomain(3, 3)); Variable q2(ce.getId(), IntervalDomain(8, 8)); - Transaction trans2(t2.getId(), q2.getId(), true); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t3(ce.getId(), IntervalIntDomain(4, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - Transaction trans3(t3.getId(), q3.getId(), true); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t4(ce.getId(), IntervalIntDomain(5, 5)); Variable q4(ce.getId(), IntervalDomain(8, 8)); - Transaction trans4(t4.getId(), q4.getId(), true); - r.addTransaction(trans4.getId()); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t5(ce.getId(), IntervalIntDomain(6, 6)); Variable q5(ce.getId(), IntervalDomain(8, 8)); - Transaction trans5(t5.getId(), q5.getId(), true); - r.addTransaction(trans5.getId()); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate()); // This will push it over the edge Variable t6(ce.getId(), IntervalIntDomain(10, 10)); Variable q6(ce.getId(), IntervalDomain(8, 8)); - Transaction trans6(t6.getId(), q6.getId(), true); - r.addTransaction(trans6.getId()); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true), deleter); + r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(!ce.propagate()); CPPUNIT_ASSERT(checkLevelArea(r.getProfile()) == 0); @@ -821,51 +853,52 @@ class ProfileTest { DummyResource r(db.getId(), LabelStr("Resource"), LabelStr("r1"), initialCapacity, initialCapacity, limitMin, limitMax, PLUS_INFINITY, -(consumptionMax), PLUS_INFINITY, -(consumptionMax)); + BareTransactionDeleter deleter(r); db.close(); // Test that a violation is detected when the excess in the level cannot be overcome by remaining // production Variable t1(ce.getId(), IntervalIntDomain(2, 2)); Variable q1(ce.getId(), IntervalDomain(8, 8)); - Transaction trans1(t1.getId(), q1.getId(), true); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true), deleter); + r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t2(ce.getId(), IntervalIntDomain(3, 3)); Variable q2(ce.getId(), IntervalDomain(8, 8)); - Transaction trans2(t2.getId(), q2.getId(), true); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t3(ce.getId(), IntervalIntDomain(4, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - Transaction trans3(t3.getId(), q3.getId(), true); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t4(ce.getId(), IntervalIntDomain(5, 5)); Variable q4(ce.getId(), IntervalDomain(8, 8)); - Transaction trans4(t4.getId(), q4.getId(), true); - r.addTransaction(trans4.getId()); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t5(ce.getId(), IntervalIntDomain(6, 6)); Variable q5(ce.getId(), IntervalDomain(8, 8)); - Transaction trans5(t5.getId(), q5.getId(), true); - r.addTransaction(trans5.getId()); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t6(ce.getId(), IntervalIntDomain(8, 8)); Variable q6(ce.getId(), IntervalDomain(8, 8)); - Transaction trans6(t6.getId(), q6.getId(), true); - r.addTransaction(trans6.getId()); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true), deleter); + r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(ce.propagate()); // This will push it over the edge Variable t7(ce.getId(), IntervalIntDomain(10, 10)); Variable q7(ce.getId(), IntervalDomain(8, 8)); - Transaction trans7(t7.getId(), q7.getId(), true); - r.addTransaction(trans7.getId()); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true), deleter); + r.addTransaction(trans7->getId()); CPPUNIT_ASSERT(!ce.propagate()); CPPUNIT_ASSERT(checkLevelArea(r.getProfile()) == 0); @@ -914,8 +947,10 @@ class ProfileTest { // CPPUNIT_ASSERT(violations.size() == 1); // CPPUNIT_ASSERT(violations.front()->getType() == ResourceViolation::LevelTooHigh); - for(std::list::iterator it = transactions.begin(); it != transactions.end(); ++it) + for(std::list::iterator it = transactions.begin(); it != transactions.end(); ++it) { + r.removeTransaction(*it); delete (Transaction*) (*it); + } for(std::list::iterator it = vars.begin(); it != vars.end(); ++it) delete (ConstrainedVariable*) (*it); @@ -964,8 +999,10 @@ class ProfileTest { // r->getResourceViolations(violations); // CPPUNIT_ASSERT(violations.size() > 0); - for(std::list::iterator it = transactions.begin(); it != transactions.end(); ++it) + for(std::list::iterator it = transactions.begin(); it != transactions.end(); ++it) { + r.removeTransaction(*it); delete (Transaction*) (*it); + } for(std::list::iterator it = variables.begin(); it != variables.end(); ++it) delete (ConstrainedVariable*) (*it); RESOURCE_DEFAULT_TEARDOWN(); @@ -990,6 +1027,7 @@ class ProfileTest { DummyResource r(db.getId(), LabelStr("Resource"), LabelStr("r1"), initialCapacity, initialCapacity, limitMin, limitMax, productionRateMax, -(consumptionRateMax), 5, -(consumptionMax)); + BareTransactionDeleter deleter(r); db.close(); IntervalDomain result; @@ -1000,8 +1038,8 @@ class ProfileTest { // Test that a flaw is signalled when there is a possibility to violate limits Variable t1(ce.getId(), IntervalIntDomain(5, 5)); Variable q1(ce.getId(), IntervalDomain(5, 5)); - Transaction trans1(t1.getId(), q1.getId(), false); - r.addTransaction(trans1.getId()); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + r.addTransaction(trans1->getId()); // Have a single transaction, test before, at and after. getLevel(r, 0, result); @@ -1013,13 +1051,13 @@ class ProfileTest { Variable t2(ce.getId(), IntervalIntDomain(0, 7)); Variable q2(ce.getId(), IntervalDomain(5, 5)); - Transaction trans2(t2.getId(), q2.getId(), true); - r.addTransaction(trans2.getId()); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + r.addTransaction(trans2->getId()); Variable t3(ce.getId(), IntervalIntDomain(2, 10)); Variable q3(ce.getId(), IntervalDomain(5, 5)); - Transaction trans3(t3.getId(), q3.getId(), true); - r.addTransaction(trans3.getId()); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + r.addTransaction(trans3->getId()); // Confirm that we can query in the middle getLevel(r, 6, result); @@ -1040,6 +1078,7 @@ class ProfileTest { RESOURCE_DEFAULT_SETUP(ce, db, false); DummyDetector detector(ResourceId::noId()); DummyProfile profile(db.getId(), detector.getId()); + BareTransactionDeleter deleter(profile); Variable t1(ce.getId(), IntervalIntDomain(0, 10), true, "t1"); Variable t2(ce.getId(), IntervalIntDomain(10, 15), true, "t2"); @@ -1050,15 +1089,15 @@ class ProfileTest { Variable q3(ce.getId(), IntervalDomain(1, 1), true, "q3"); Variable q4(ce.getId(), IntervalDomain(1, 1), true, "q4"); - Transaction trans1(t1.getId(), q1.getId(), false); - Transaction trans2(t2.getId(), q2.getId(), true); - Transaction trans3(t3.getId(), q3.getId(), true); - Transaction trans4(t4.getId(), q4.getId(), false); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); - profile.addTransaction(trans1.getId()); - profile.addTransaction(trans2.getId()); - profile.addTransaction(trans3.getId()); - profile.addTransaction(trans4.getId()); + profile.addTransaction(trans1->getId()); + profile.addTransaction(trans2->getId()); + profile.addTransaction(trans3->getId()); + profile.addTransaction(trans4->getId()); InstantId inst = profile.getInstant(0); @@ -1067,14 +1106,14 @@ class ProfileTest { for(std::set::const_iterator it = inst->getTransactions().begin(); it != inst->getTransactions().end(); ++it) { CPPUNIT_ASSERT((*it).isValid()); - CPPUNIT_ASSERT((*it) == trans1.getId()); + CPPUNIT_ASSERT((*it) == trans1->getId()); } //for time 5 std::set trans; - trans.insert(trans1.getId()); - trans.insert(trans3.getId()); - trans.insert(trans4.getId()); + trans.insert(trans1->getId()); + trans.insert(trans3->getId()); + trans.insert(trans4->getId()); inst = profile.getInstant(5); CPPUNIT_ASSERT(inst.isValid()); @@ -1088,10 +1127,10 @@ class ProfileTest { CPPUNIT_ASSERT(trans.empty()); //for time 10 - trans.insert(trans1.getId()); - trans.insert(trans2.getId()); - trans.insert(trans3.getId()); - trans.insert(trans4.getId()); + trans.insert(trans1->getId()); + trans.insert(trans2->getId()); + trans.insert(trans3->getId()); + trans.insert(trans4->getId()); inst = profile.getInstant(10); CPPUNIT_ASSERT(inst.isValid()); @@ -1105,9 +1144,9 @@ class ProfileTest { CPPUNIT_ASSERT(trans.empty()); //for time 15 - trans.insert(trans2.getId()); - trans.insert(trans3.getId()); - trans.insert(trans4.getId()); + trans.insert(trans2->getId()); + trans.insert(trans3->getId()); + trans.insert(trans4->getId()); inst = profile.getInstant(15); CPPUNIT_ASSERT(inst.isValid()); @@ -1838,7 +1877,8 @@ class ResourceSolverTest { std::string earliest = ""; TiXmlElement* earliestXml = initXml(earliest); ResourceThreatManager earliestManager(*earliestXml); - earliestManager.initialize(*earliestXml, db, SOLVERS::ContextId::noId(), SOLVERS::FlawManagerId::noId()); + SOLVERS::Context ctx("foo"); + earliestManager.initialize(*earliestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); CPPUNIT_ASSERT(earliestManager.betterThan(instants[0], instants[1], explanation)); //these are identical except for the time CPPUNIT_ASSERT(earliestManager.betterThan(instants[1], instants[2], explanation)); //these have different levels CPPUNIT_ASSERT(!earliestManager.betterThan(instants[0], instants[0], explanation)); @@ -1846,7 +1886,7 @@ class ResourceSolverTest { std::string latest = ""; TiXmlElement* latestXml = initXml(latest); ResourceThreatManager latestManager(*latestXml); - latestManager.initialize(*latestXml, db, SOLVERS::ContextId::noId(), SOLVERS::FlawManagerId::noId()); + latestManager.initialize(*latestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); CPPUNIT_ASSERT(latestManager.betterThan(instants[3], instants[2], explanation)); CPPUNIT_ASSERT(latestManager.betterThan(instants[2], instants[1], explanation)); CPPUNIT_ASSERT(!latestManager.betterThan(instants[0], instants[0], explanation)); @@ -1854,7 +1894,7 @@ class ResourceSolverTest { std::string most = ""; TiXmlElement* mostXml = initXml(most); ResourceThreatManager mostManager(*mostXml); - mostManager.initialize(*mostXml, db, SOLVERS::ContextId::noId(), SOLVERS::FlawManagerId::noId()); + mostManager.initialize(*mostXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); CPPUNIT_ASSERT(mostManager.betterThan(instants[0], instants[1], explanation)); CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[0], explanation)); CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[2], explanation)); @@ -1863,7 +1903,7 @@ class ResourceSolverTest { std::string least = ""; TiXmlElement* leastXml = initXml(least); ResourceThreatManager leastManager(*leastXml); - leastManager.initialize(*leastXml, db, SOLVERS::ContextId::noId(), SOLVERS::FlawManagerId::noId()); + leastManager.initialize(*leastXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); CPPUNIT_ASSERT(!leastManager.betterThan(instants[0], instants[1], explanation)); CPPUNIT_ASSERT(leastManager.betterThan(instants[1], instants[0], explanation)); CPPUNIT_ASSERT(!leastManager.betterThan(instants[3], instants[4], explanation)); diff --git a/src/PLASMA/Solvers/base/FlawFilter.hh b/src/PLASMA/Solvers/base/FlawFilter.hh index ec6513157..5fb080042 100644 --- a/src/PLASMA/Solvers/base/FlawFilter.hh +++ b/src/PLASMA/Solvers/base/FlawFilter.hh @@ -21,8 +21,8 @@ namespace EUROPA { virtual bool test(const EntityId& entity); - ContextId getContext() const {return m_context;} - void setContext(ContextId& ctx) {m_context = ctx;} + // ContextId getContext() const {return m_context;} + // void setContext(ContextId& ctx) {m_context = ctx;} private: const bool m_isDynamic; diff --git a/src/PLASMA/Solvers/base/FlawManager.cc b/src/PLASMA/Solvers/base/FlawManager.cc index 618943ebc..c34cd7a5b 100644 --- a/src/PLASMA/Solvers/base/FlawManager.cc +++ b/src/PLASMA/Solvers/base/FlawManager.cc @@ -101,11 +101,13 @@ namespace EUROPA { for(std::set::const_iterator it = m_flawFilters->getRules().begin(); it != m_flawFilters->getRules().end(); ++it) { MatchingRuleId rule = *it; check_error(rule.isValid()); + debugMsg("FlawManager:initialize", "Setting context on " << rule); rule->setContext(m_context); } for(std::set::const_iterator it = m_flawHandlers->getRules().begin(); it != m_flawHandlers->getRules().end(); ++it) { MatchingRuleId rule = *it; check_error(rule.isValid()); + debugMsg("FlawManager:initialize", "Setting context on " << rule); rule->setContext(m_context); } handleInitialize(); diff --git a/src/PLASMA/Solvers/base/MatchingRule.cc b/src/PLASMA/Solvers/base/MatchingRule.cc index f72933319..35143c8cb 100644 --- a/src/PLASMA/Solvers/base/MatchingRule.cc +++ b/src/PLASMA/Solvers/base/MatchingRule.cc @@ -16,6 +16,7 @@ namespace EUROPA { MatchingRule::MatchingRule(const TiXmlElement& configData) : Component(configData), + m_context(), m_objectType(WILD_CARD()), m_predicate(WILD_CARD()), m_variable(WILD_CARD()), m_masterObjectType(WILD_CARD()), m_masterPredicate(WILD_CARD()), m_masterRelation(WILD_CARD()), m_tokenName(WILD_CARD()), diff --git a/src/PLASMA/Solvers/base/MatchingRule.hh b/src/PLASMA/Solvers/base/MatchingRule.hh index 110249527..767636686 100644 --- a/src/PLASMA/Solvers/base/MatchingRule.hh +++ b/src/PLASMA/Solvers/base/MatchingRule.hh @@ -68,8 +68,8 @@ namespace EUROPA { const LabelStr& tokenNameFilter() const; - ContextId getContext() {return m_context;} - void setContext(ContextId ctx) {m_context = ctx;} + ContextId getContext() const {return m_context;} + virtual void setContext(ContextId ctx) {check_error(ctx != ContextId::noId()); m_context = ctx;} protected: void setExpression(const std::string& expression); ContextId m_context; diff --git a/src/PLASMA/Solvers/component/Filters.cc b/src/PLASMA/Solvers/component/Filters.cc index b4122ec04..ccdc20afa 100644 --- a/src/PLASMA/Solvers/component/Filters.cc +++ b/src/PLASMA/Solvers/component/Filters.cc @@ -5,6 +5,7 @@ #include "RuleVariableListener.hh" #include "TokenVariable.hh" #include "RuleInstance.hh" +#include "Context.hh" #include @@ -155,11 +156,6 @@ namespace EUROPA { return !tok->master()->isAssigned(); } - /** HORIZON FILTERING **/ - IntervalIntDomain& HorizonFilter::getHorizon() { - static IntervalIntDomain sl_instance; - return sl_instance; - } HorizonFilter::HorizonFilter(const TiXmlElement& configData) : FlawFilter(configData, true) { @@ -194,13 +190,17 @@ namespace EUROPA { else token = entity; - const IntervalIntDomain& horizon = getHorizon(); + checkRuntimeError(getContext() != ContextId::noId(), + "HorizonFilter::test called without a valid context on " << + MatchingRule::getId()); + const IntervalIntDomain horizon = IntervalIntDomain(getContext()->get("horizonStart"), + getContext()->get("horizonEnd")); checkError(horizon.isFinite(), "Infinite Horizon not permitted." << horizon.toString()); const IntervalIntDomain& startTime = token->start()->lastDomain(); const IntervalIntDomain& endTime = token->end()->lastDomain(); bool withinHorizon = false; - + debugMsg("HorizonFilter:test", "Evaluating: " << token->toString() << " Start=" << startTime.toString() << ", End=" << endTime.toString() << @@ -223,9 +223,16 @@ namespace EUROPA { std::string HorizonFilter::toString() const { - const IntervalIntDomain& horizon = getHorizon(); - std::string expr = FlawFilter::toString(); - expr = expr + " Policy='" + m_policy.toString() + "' Horizon=" + horizon.toString(); + std::string expr = + FlawFilter::toString() + " Policy='" + m_policy.toString() + "' Horizon="; + if(getContext().isValid()) { + const IntervalIntDomain horizon = IntervalIntDomain(getContext()->get("horizonStart"), + getContext()->get("horizonEnd")); + expr = expr + horizon.toString(); + } + else { + expr = expr + "Undetermined"; + } return expr; } @@ -234,6 +241,11 @@ namespace EUROPA { setExpression(toString() + ":variable"); } + void HorizonVariableFilter::setContext(ContextId ctx) { + MatchingRule::setContext(ctx); + m_horizonFilter.setContext(ctx); + } + bool HorizonVariableFilter::test(const EntityId& entity) { if(!ConstrainedVariableId::convertable(entity)) return false; diff --git a/src/PLASMA/Solvers/component/Filters.hh b/src/PLASMA/Solvers/component/Filters.hh index 66c7f8124..f03f7a7e8 100644 --- a/src/PLASMA/Solvers/component/Filters.hh +++ b/src/PLASMA/Solvers/component/Filters.hh @@ -110,11 +110,6 @@ namespace EUROPA { return sl_policies; } - /** - * @brief uses a singleton horizon that is regularly adjusted. - */ - static IntervalIntDomain& getHorizon(); - private: LabelStr m_policy; @@ -129,7 +124,7 @@ namespace EUROPA { HorizonVariableFilter(const TiXmlElement& configData); bool test(const EntityId& entity); std::string toString() const; - + void setContext(ContextId ctx); private: HorizonFilter m_horizonFilter; }; diff --git a/src/PLASMA/Solvers/component/PSSolversImpl.cc b/src/PLASMA/Solvers/component/PSSolversImpl.cc index daa722a19..f36adf947 100644 --- a/src/PLASMA/Solvers/component/PSSolversImpl.cc +++ b/src/PLASMA/Solvers/component/PSSolversImpl.cc @@ -2,6 +2,7 @@ #include "PSSolversImpl.hh" #include "Filters.hh" #include "Solver.hh" +#include "Context.hh" namespace EUROPA { @@ -122,17 +123,17 @@ namespace EUROPA const std::string& PSSolverImpl::getConfigFilename() {return m_configFile;} eint::basis_type PSSolverImpl::getHorizonStart() { - return cast_int(SOLVERS::HorizonFilter::getHorizon().getLowerBound()); + return m_solver->getContext()->get("horizonStart"); } eint::basis_type PSSolverImpl::getHorizonEnd() { - return cast_int(SOLVERS::HorizonFilter::getHorizon().getUpperBound()); + return m_solver->getContext()->get("horizonEnd"); } void PSSolverImpl::configure(eint::basis_type horizonStart, eint::basis_type horizonEnd) { check_runtime_error(horizonStart <= horizonEnd); - SOLVERS::HorizonFilter::getHorizon().reset(IntervalIntDomain()); - SOLVERS::HorizonFilter::getHorizon().intersect(horizonStart, horizonEnd); + m_solver->getContext()->put("horizonStart", horizonStart); + m_solver->getContext()->put("horizonEnd", horizonEnd); } } diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index 7164939cf..d1d34807b 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -405,12 +405,14 @@ class FilterTests { UnboundVariableManager fm(*root); CPPUNIT_ASSERT(testEngine.playTransactions( (getTestLoadLibraryPath() + "/UnboundVariableFiltering.nddl").c_str() )); + // Set the horizon + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); + // Initialize after filling the database since we are not connected to an event source - fm.initialize(*root,testEngine.getPlanDatabase()); + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); - // Set the horizon - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); // Simple filter on a variable ConstrainedVariableSet variables = testEngine.getConstraintEngine()->getVariables(); @@ -458,12 +460,13 @@ class FilterTests { TestEngine testEngine; OpenConditionManager fm(*root); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/OpenConditionFiltering.nddl").c_str() )); + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); // Initialize with data in the database - fm.initialize(*root,testEngine.getPlanDatabase()); + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); TokenSet tokens = testEngine.getPlanDatabase()->getTokens(); for(TokenSet::const_iterator it = tokens.begin(); it != tokens.end(); ++it){ @@ -485,12 +488,13 @@ class FilterTests { TestEngine testEngine; ThreatManager fm(*root); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); CPPUNIT_ASSERT(testEngine.playTransactions(( getTestLoadLibraryPath() + "/ThreatFiltering.nddl").c_str())); // Initialize with data in the database - fm.initialize(*root,testEngine.getPlanDatabase()); + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); TokenSet tokens = testEngine.getPlanDatabase()->getTokens(); for(TokenSet::const_iterator it = tokens.begin(); it != tokens.end(); ++it){ @@ -1657,10 +1661,12 @@ class SolverTests { TiXmlElement* root = initXml((getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), "SimpleActivationSolver"); TiXmlElement* child = root->FirstChildElement(); { - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/SimpleActivation.nddl").c_str())); Solver solver(testEngine.getPlanDatabase(), *child); + ContextId ctx = solver.getContext(); + ctx->put("horizonStart", 0); + ctx->put("horizonEnd", 1000); + CPPUNIT_ASSERT(solver.solve()); } @@ -1672,12 +1678,15 @@ class SolverTests { TiXmlElement* root = initXml((getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), "SimpleRejectionSolver"); TiXmlElement* child = root->FirstChildElement(); { - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); + CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/SimpleRejection.nddl").c_str())); Solver solver(testEngine.getPlanDatabase(), *child); + ContextId ctx = solver.getContext(); + ctx->put("horizonStart", 0); + ctx->put("horizonEnd", 1000); + CPPUNIT_ASSERT(solver.solve(100, 100)); CPPUNIT_ASSERT_MESSAGE(toString(testEngine.getPlanDatabase()->getTokens().size()), testEngine.getPlanDatabase()->getTokens().size() == 1); } @@ -1858,8 +1867,10 @@ class SolverTests { // iterate over the possibilties with commiting and deleting with four tokens for(int i=1;i<255;i++) { - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 40); + ContextId ctx = solver.getContext(); + ctx->put("horizonStart", 0); + ctx->put("horizonEnd", 40); + TokenId first = db->getClient()->createToken("CommitTest.chaina", "first", false); first->start()->specify(0); solver.solve(100,100); @@ -1893,7 +1904,10 @@ class SolverTests { CPPUNIT_ASSERT_MESSAGE("Solver must be valid after discards.", solver.isValid()); - horizon = IntervalIntDomain(0, 40); + + ctx = solver.getContext(); + ctx->put("horizonStart", 0); + ctx->put("horizonEnd", 40); solver.solve(100,100); // TODO: this is failing, why? re-enable after understanding causes //CPPUNIT_ASSERT_MESSAGE("Solver must be valid after continuing solving after discards.", solver.isValid()); @@ -1928,11 +1942,12 @@ class FlawIteratorTests { TestEngine testEngine; UnboundVariableManager fm(*root); - fm.initialize(*root,testEngine.getPlanDatabase()); + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/UnboundVariableFiltering.nddl").c_str())); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); ConstrainedVariableSet variables = testEngine.getConstraintEngine()->getVariables(); IteratorId flawIterator = fm.createIterator(); @@ -1960,9 +1975,11 @@ class FlawIteratorTests { TestEngine testEngine; OpenConditionManager fm(*root); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); - fm.initialize(*root,testEngine.getPlanDatabase()); + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); + + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/OpenConditionFiltering.nddl").c_str())); TokenSet tokens = testEngine.getPlanDatabase()->getTokens(); @@ -1993,9 +2010,10 @@ class FlawIteratorTests { TestEngine testEngine; ThreatManager fm(*root); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); - fm.initialize(*root,testEngine.getPlanDatabase()); + Context ctx(""); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 1000); + fm.initialize(*root,testEngine.getPlanDatabase(), ctx.getId()); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/ThreatFiltering.nddl").c_str())); TokenSet tokens = testEngine.getPlanDatabase()->getTokens(); @@ -2028,8 +2046,9 @@ class FlawIteratorTests { UnboundVariableManager uvm(*(root->FirstChildElement("UnboundVariableManager"))); Solver solver(testEngine.getPlanDatabase(), *root); - IntervalIntDomain& horizon = HorizonFilter::getHorizon(); - horizon = IntervalIntDomain(0, 1000); + ContextId ctx = solver.getContext(); + ctx->put("horizonStart", 0); + ctx->put("horizonEnd", 1000); CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/ThreatFiltering.nddl").c_str())); diff --git a/src/PLASMA/System/base/EuropaEngine.cc b/src/PLASMA/System/base/EuropaEngine.cc index 3c8c4c34a..af59adeec 100644 --- a/src/PLASMA/System/base/EuropaEngine.cc +++ b/src/PLASMA/System/base/EuropaEngine.cc @@ -17,6 +17,7 @@ // Solver Support #include "Solver.hh" +#include "Context.hh" #include "Filters.hh" #include "PlanDatabaseWriter.hh" @@ -130,7 +131,8 @@ namespace EUROPA { eint start = horizonStart->baseDomain().getSingletonValue(); eint end = horizonEnd->baseDomain().getSingletonValue(); - SOLVERS::HorizonFilter::getHorizon() = IntervalDomain(start, end); + solver->getContext()->put("horizonStart", cast_double(start)); + solver->getContext()->put("horizonEnd", cast_double(end)); // Now get planner step max int steps = cast_int(plannerSteps->baseDomain().getSingletonValue()); From 7a291453042cdcd3b04b1af708e119acaeea7ee5 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 13 Sep 2014 19:54:06 +0000 Subject: [PATCH 018/149] -Small syntactic fixes for OS X -Added object variable filtering to DefaultPlannerConfig git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6748 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/Resource/CMakeLists.txt | 2 +- .../component/BoostFlowProfileGraph.cc | 26 +++++++++---------- .../component/BoostFlowProfileGraph.hh | 4 +-- src/PLASMA/Resource/component/FlowProfile.cc | 2 +- src/PLASMA/Resource/component/FlowProfile.hh | 16 +----------- .../Resource/component/FlowProfileGraph.hh | 9 +++---- src/PLASMA/Resource/component/Types.hh | 14 ++++++++++ .../Resource/test/rs-flow-test-module.cc | 1 + .../System/test/DefaultPlannerConfig.xml | 1 + 9 files changed, 38 insertions(+), 37 deletions(-) diff --git a/src/PLASMA/Resource/CMakeLists.txt b/src/PLASMA/Resource/CMakeLists.txt index 278d7ea8c..b87d0c606 100644 --- a/src/PLASMA/Resource/CMakeLists.txt +++ b/src/PLASMA/Resource/CMakeLists.txt @@ -3,7 +3,7 @@ set(internal_dependencies NDDL Solvers TemporalNetwork PlanDatabase) set(internal_components Solvers NDDL) set(root_sources ModuleResource.cc) set(base_sources FVDetector.cc Instant.cc PSResource.cc Profile.cc ProfilePropagator.cc Resource.cc ResourceTokenRelation.cc Transaction.cc) -set(component_sources ClosedWorldFVDetector.cc DurativeTokens.cc Edge.cc FlowProfile.cc GenericFVDetector.cc Graph.cc GroundedFVDetector.cc GroundedProfile.cc IncrementalFlowProfile.cc InstantTokens.cc MaxFlow.cc Node.cc OpenWorldFVDetector.cc Reservoir.cc Reusable.cc TimetableProfile.cc Types.cc NDDL/InterpreterResources.cc NDDL/NddlResource.cc Solvers/ResourceMatching.cc Solvers/ResourceThreatDecisionPoint.cc Solvers/ResourceThreatManager.cc) +set(component_sources BoostFlowProfileGraph.cc ClosedWorldFVDetector.cc DurativeTokens.cc Edge.cc FlowProfile.cc FlowProfileGraph.cc GenericFVDetector.cc Graph.cc GroundedFVDetector.cc GroundedProfile.cc IncrementalFlowProfile.cc InstantTokens.cc MaxFlow.cc Node.cc OpenWorldFVDetector.cc Reservoir.cc Reusable.cc TimetableProfile.cc Types.cc NDDL/InterpreterResources.cc NDDL/NddlResource.cc Solvers/ResourceMatching.cc Solvers/ResourceThreatDecisionPoint.cc Solvers/ResourceThreatManager.cc) set(test_sources module-tests.cc rs-flow-test-module.cc rs-test-module.cc) common_module_prepends("${base_sources}" "${component_sources}" "${test_sources}" base_sources component_sources test_sources) diff --git a/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc index 88615e8e0..169fe154a 100644 --- a/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc +++ b/src/PLASMA/Resource/component/BoostFlowProfileGraph.cc @@ -162,38 +162,38 @@ void BoostFlowProfileGraph::enableTransaction(const TransactionId& t, m_recalculate = true; } -edouble BoostFlowProfileGraph::getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, - const FlowProfile::TransactionIdTransactionIdPair2Order& other) { +edouble BoostFlowProfileGraph::getResidualFromSource(const TransactionIdTransactionIdPair2Order& at, + const TransactionIdTransactionIdPair2Order& other) { using namespace boost; reset(); for(std::vector::const_iterator it = m_activeTransactions.begin(); it != m_activeTransactions.end(); ++it) { addTransactionToGraph(*it); } - for(FlowProfile::TransactionIdTransactionIdPair2Order::const_iterator it = at.begin(); + for(TransactionIdTransactionIdPair2Order::const_iterator it = at.begin(); it != at.end(); ++it) { enableAt(it->first.first, it->first.second); } - for(FlowProfile::TransactionIdTransactionIdPair2Order::const_iterator it = other.begin(); + for(TransactionIdTransactionIdPair2Order::const_iterator it = other.begin(); it != other.end(); ++it) { debugMsg("BoostFlowProfileGraph:getResidualFromSource", it->first.first << - (it->second == FlowProfile::AFTER_OR_AT ? " after-or-at " : - (it->second == FlowProfile::BEFORE_OR_AT ? " before-or-at " : - (it->second == FlowProfile::NOT_ORDERED ? " unordered " : - (it->second == FlowProfile::STRICTLY_AT ? " at " : " unknown ")))) << + (it->second == AFTER_OR_AT ? " after-or-at " : + (it->second == BEFORE_OR_AT ? " before-or-at " : + (it->second == NOT_ORDERED ? " unordered " : + (it->second == STRICTLY_AT ? " at " : " unknown ")))) << it->first.second); switch(it->second) { - case FlowProfile::AFTER_OR_AT: + case AFTER_OR_AT: enableAtOrBefore(it->first.second, it->first.first); break; - case FlowProfile::BEFORE_OR_AT: + case BEFORE_OR_AT: enableAtOrBefore(it->first.first, it->first.second); - case FlowProfile::NOT_ORDERED: + case NOT_ORDERED: break; - case FlowProfile::STRICTLY_AT: + case STRICTLY_AT: enableAt(it->first.first, it->first.second); - case FlowProfile::UNKNOWN: + case UNKNOWN: break; default: break; diff --git a/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh b/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh index 7dff17f7a..fb3b16113 100644 --- a/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh +++ b/src/PLASMA/Resource/component/BoostFlowProfileGraph.hh @@ -81,8 +81,8 @@ class BoostFlowProfileGraph : public FlowProfileGraph { * edge. Might trigger a maximum flow (re) calculation if required. */ edouble getResidualFromSource(); - edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, - const FlowProfile::TransactionIdTransactionIdPair2Order& other); + edouble getResidualFromSource(const TransactionIdTransactionIdPair2Order& at, + const TransactionIdTransactionIdPair2Order& other); /** * @brief Disables every node reachable from the source in the residual network. Returns the sum diff --git a/src/PLASMA/Resource/component/FlowProfile.cc b/src/PLASMA/Resource/component/FlowProfile.cc index 2bcbe4fc1..726e44cc2 100644 --- a/src/PLASMA/Resource/component/FlowProfile.cc +++ b/src/PLASMA/Resource/component/FlowProfile.cc @@ -310,7 +310,7 @@ void FlowProfile::recomputeLevels(InstantId prev, InstantId inst) { 0, 0, 0, 0 ); } - FlowProfile::Order FlowProfile::getOrdering( const TransactionId t1, const TransactionId t2 ) +Order FlowProfile::getOrdering( const TransactionId t1, const TransactionId t2 ) { // in case constraint added and already constrained to be before or after we no longer have to // recalculate diff --git a/src/PLASMA/Resource/component/FlowProfile.hh b/src/PLASMA/Resource/component/FlowProfile.hh index eed724edd..0d5afba40 100644 --- a/src/PLASMA/Resource/component/FlowProfile.hh +++ b/src/PLASMA/Resource/component/FlowProfile.hh @@ -15,6 +15,7 @@ #include "ResourceDefs.hh" #include "Types.hh" #include "TemporalPropagator.hh" +#include "FlowProfileGraph.hh" #ifdef _MSC_VER # include #endif @@ -24,8 +25,6 @@ namespace EUROPA class Graph; class MaximumFlowAlgorithm; class Node; -class FlowProfileGraph; - /** * @brief Calculates the lower and upper level envelope of a resource. @@ -69,19 +68,6 @@ class FlowProfileGraph; public Profile { public: - /** - * @brief Indicates the ordering between two time variables associated with a transaction - */ - enum Order { - AFTER_OR_AT = 0, /*!< Indicates one transaction is strictly after or at the same time with another transaction. */ - BEFORE_OR_AT,/*!< Indicates one transaction is strictly before or at the same time with another transaction. */ - NOT_ORDERED,/*!< Indicates one transaction is not ordered with another transaction. */ - STRICTLY_AT,/*!< Indicates one transaction is strictly at the same time with another transaction. */ - UNKNOWN - }; - typedef std::pair TransactionIdTransactionIdPair; - typedef std::map< TransactionIdTransactionIdPair, Order > TransactionIdTransactionIdPair2Order; - /** * @brief Constructor */ diff --git a/src/PLASMA/Resource/component/FlowProfileGraph.hh b/src/PLASMA/Resource/component/FlowProfileGraph.hh index b5663785e..5eb83f5bc 100644 --- a/src/PLASMA/Resource/component/FlowProfileGraph.hh +++ b/src/PLASMA/Resource/component/FlowProfileGraph.hh @@ -3,7 +3,6 @@ #include "Types.hh" -#include "FlowProfile.hh" namespace EUROPA { @@ -84,8 +83,8 @@ class FlowProfileGraph * edge. Might trigger a maximum flow (re) calculation if required. */ virtual edouble getResidualFromSource() = 0; - virtual edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, - const FlowProfile::TransactionIdTransactionIdPair2Order& other) = 0; + virtual edouble getResidualFromSource(const TransactionIdTransactionIdPair2Order& at, + const TransactionIdTransactionIdPair2Order& other) = 0; /** * @brief Disables every node reachable from the source in the residual network. Returns the sum * of the contribution of each disabled node. The contribution is determined as following: @@ -151,8 +150,8 @@ class FlowProfileGraphImpl : public FlowProfileGraph { void disable(const TransactionId& transaction); void pushFlow( const TransactionId& transaction ); edouble getResidualFromSource(); - edouble getResidualFromSource(const FlowProfile::TransactionIdTransactionIdPair2Order& at, - const FlowProfile::TransactionIdTransactionIdPair2Order& other) { + edouble getResidualFromSource(const TransactionIdTransactionIdPair2Order& at, + const TransactionIdTransactionIdPair2Order& other) { return getResidualFromSource(); } diff --git a/src/PLASMA/Resource/component/Types.hh b/src/PLASMA/Resource/component/Types.hh index 000f07a45..1848f6548 100644 --- a/src/PLASMA/Resource/component/Types.hh +++ b/src/PLASMA/Resource/component/Types.hh @@ -124,6 +124,20 @@ typedef boost::unordered_map< Node*, edouble, NodeHash > Node2Double; typedef boost::unordered_map< Edge*, edouble, EdgeHash > Edge2DoubleMap; typedef boost::unordered_map< TransactionId, InstantId, TransactionIdHash > TransactionId2InstantId; #endif +/** + * @brief Indicates the ordering between two time variables associated with a transaction + */ +enum Order { + AFTER_OR_AT = 0, /*!< Indicates one transaction is strictly after or at the same time with another transaction. */ + BEFORE_OR_AT,/*!< Indicates one transaction is strictly before or at the same time with another transaction. */ + NOT_ORDERED,/*!< Indicates one transaction is not ordered with another transaction. */ + STRICTLY_AT,/*!< Indicates one transaction is strictly at the same time with another transaction. */ + UNKNOWN +}; +typedef std::pair TransactionIdTransactionIdPair; +typedef std::map< TransactionIdTransactionIdPair, Order > TransactionIdTransactionIdPair2Order; + + std::ostream& operator<<( std::ostream& os, const EdgeIdentity& fei ) ; diff --git a/src/PLASMA/Resource/test/rs-flow-test-module.cc b/src/PLASMA/Resource/test/rs-flow-test-module.cc index 6b11164cb..bf4c7376e 100644 --- a/src/PLASMA/Resource/test/rs-flow-test-module.cc +++ b/src/PLASMA/Resource/test/rs-flow-test-module.cc @@ -165,6 +165,7 @@ class FlowProfileTest testScenario13< EUROPA::IncrementalFlowProfile>(); testScenario14< EUROPA::IncrementalFlowProfile>(); //testPaulBug(); + return true; } static bool test(){ diff --git a/src/PLASMA/System/test/DefaultPlannerConfig.xml b/src/PLASMA/System/test/DefaultPlannerConfig.xml index 4a75e61f2..e7463b547 100644 --- a/src/PLASMA/System/test/DefaultPlannerConfig.xml +++ b/src/PLASMA/System/test/DefaultPlannerConfig.xml @@ -15,6 +15,7 @@ + From 06ce84ef268d6df92b07619f53e7e67b9f76f0ff Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 19 Sep 2014 22:34:45 +0000 Subject: [PATCH 019/149] -Adding direct finding of the Boost libraries git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6749 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/CMakeLists.txt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/PLASMA/CMakeLists.txt b/src/PLASMA/CMakeLists.txt index 189f3b629..5fa44bad3 100644 --- a/src/PLASMA/CMakeLists.txt +++ b/src/PLASMA/CMakeLists.txt @@ -23,6 +23,19 @@ else() set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -m32") endif(SIXTYFOUR) +if(BOOST_INCLUDE_PATH) + include_directories(${BOOST_INCLUDE_PATH}) +else() + find_package(Boost) + if(Boost_FOUND) + include_directories(${Boost_INCLUDE_DIRS}) + else() + error("Failed to find boost libraries") + endif() +else() + error("Failed to find boost libraries") +endif() + add_subdirectory(TinyXml) add_subdirectory(Utils) add_subdirectory(ConstraintEngine) From 5265f1c1e7cb356312872c33a7ac4df2215ce4d6 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 22 Sep 2014 16:49:41 +0000 Subject: [PATCH 020/149] Addresses issue 26 -Profile.{cc,hh}: Added explicit call to FactoryObj constructor -Resource.cc: Resource destructor will destroy un-owned or self-owned Transactions -Transaction.hh: Made the owner parameter to the Transaction constructor mandatory to catch instantiation errors. -FlowProfile.cc:Added noId owner parameter to default dummy source/sink transactions -Reservoir.cc:Added self owner parameter to transaction instantiation -Reusable.cc:Added self owner parameter to transaction instantiation -rs-flow-test-module.cc: added updated Transaction constructor calls -rs-test-module.cc: added updated Transaction constructor calls git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6750 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/Resource/base/Profile.cc | 4 +- src/PLASMA/Resource/base/Profile.hh | 2 +- src/PLASMA/Resource/base/Resource.cc | 25 ++-- src/PLASMA/Resource/base/Transaction.hh | 3 +- src/PLASMA/Resource/component/FlowProfile.cc | 6 +- src/PLASMA/Resource/component/Reservoir.cc | 3 +- src/PLASMA/Resource/component/Reusable.cc | 4 +- .../Resource/test/rs-flow-test-module.cc | 102 +++++++-------- src/PLASMA/Resource/test/rs-test-module.cc | 116 +++++++++--------- 9 files changed, 135 insertions(+), 130 deletions(-) diff --git a/src/PLASMA/Resource/base/Profile.cc b/src/PLASMA/Resource/base/Profile.cc index 45f041151..628b359e2 100644 --- a/src/PLASMA/Resource/base/Profile.cc +++ b/src/PLASMA/Resource/base/Profile.cc @@ -14,7 +14,9 @@ namespace EUROPA { Profile::Profile(const PlanDatabaseId db, const FVDetectorId flawDetector) - : m_id(this) + : + FactoryObj(), + m_id(this) , m_changeCount(0) , m_needsRecompute(false) , m_planDatabase(db) diff --git a/src/PLASMA/Resource/base/Profile.hh b/src/PLASMA/Resource/base/Profile.hh index 58ed1e50b..988faca32 100644 --- a/src/PLASMA/Resource/base/Profile.hh +++ b/src/PLASMA/Resource/base/Profile.hh @@ -38,7 +38,7 @@ namespace EUROPA { * for causing subclasses to recalculate the profile. * When should we recalculate? */ - class Profile : public FactoryObj { +class Profile : public FactoryObj { public: /** diff --git a/src/PLASMA/Resource/base/Resource.cc b/src/PLASMA/Resource/base/Resource.cc index aa43d254a..ae5fcc880 100644 --- a/src/PLASMA/Resource/base/Resource.cc +++ b/src/PLASMA/Resource/base/Resource.cc @@ -60,19 +60,18 @@ namespace EUROPA { { } - Resource::~Resource() - { - for(std::map::const_iterator it = m_transactionsToTokens.begin(); it != m_transactionsToTokens.end(); - ++it) { - if ((it->first->getOwner()).isNoId()) - delete (Transaction*) it->first; - } - - delete (Profile*) m_profile; - delete (ExplicitProfile*) m_limitProfile; - delete (ExplicitProfile*) m_capacityProfile; - delete (FVDetector*) m_detector; - } +Resource::~Resource() { + for(std::map::const_iterator it = m_transactionsToTokens.begin(); + it != m_transactionsToTokens.end(); ++it) { + if ((it->first->getOwner()).isNoId() || (it->first->getOwner() == getId())) + delete (Transaction*) it->first; + } + + delete (Profile*) m_profile; + delete (ExplicitProfile*) m_limitProfile; + delete (ExplicitProfile*) m_capacityProfile; + delete (FVDetector*) m_detector; +} void Resource::init(const edouble initCapacityLb, const edouble initCapacityUb, const edouble lowerLimit, const edouble upperLimit, diff --git a/src/PLASMA/Resource/base/Transaction.hh b/src/PLASMA/Resource/base/Transaction.hh index c1eb4612e..84bcb1e36 100644 --- a/src/PLASMA/Resource/base/Transaction.hh +++ b/src/PLASMA/Resource/base/Transaction.hh @@ -29,7 +29,8 @@ namespace EUROPA { * @param isConsumer Because all transactions have positive quantities, it is necessary to indicate that a transaction is * consuming the resource in some way other than a negative quantity. This flag is what indicates it. */ - Transaction(ConstrainedVariableId time, ConstrainedVariableId quantity, bool isConsumer, EntityId owner=EntityId::noId()); + Transaction(ConstrainedVariableId time, ConstrainedVariableId quantity, + bool isConsumer, EntityId owner); ~Transaction(); /** diff --git a/src/PLASMA/Resource/component/FlowProfile.cc b/src/PLASMA/Resource/component/FlowProfile.cc index 726e44cc2..f74b966c1 100644 --- a/src/PLASMA/Resource/component/FlowProfile.cc +++ b/src/PLASMA/Resource/component/FlowProfile.cc @@ -52,8 +52,10 @@ namespace EUROPA Variable * dummy4 = new Variable( db->getConstraintEngine(), IntervalIntDomain(0, 0)); - m_dummySourceTransaction = ( new Transaction(dummy1->getId(), dummy2->getId(), false ) )->getId(); - m_dummySinkTransaction = ( new Transaction(dummy3->getId(), dummy4->getId(), false) )->getId(); + m_dummySourceTransaction = + (new Transaction(dummy1->getId(), dummy2->getId(), false, EntityId::noId()))->getId(); + m_dummySinkTransaction = + (new Transaction(dummy3->getId(), dummy4->getId(), false, EntityId::noId()))->getId(); initializeGraphs(); } diff --git a/src/PLASMA/Resource/component/Reservoir.cc b/src/PLASMA/Resource/component/Reservoir.cc index 82b716091..b93eb6389 100644 --- a/src/PLASMA/Resource/component/Reservoir.cc +++ b/src/PLASMA/Resource/component/Reservoir.cc @@ -33,7 +33,8 @@ namespace EUROPA { debugMsg("Reservoir:createTransactions", "Creating transactions for " << (t->isConsumer() ? "consumer " : "producer ") << "token " << tok->getPredicateName().toString() << "(" << tok->getKey() << ")"); - TransactionId trans = (new Transaction(t->getTime(), t->getQuantity(), t->isConsumer()))->getId(); + TransactionId trans = + (new Transaction(t->getTime(), t->getQuantity(), t->isConsumer(), getId()))->getId(); m_transactionsToTokens.insert(std::pair(trans, tok)); m_tokensToTransactions.insert(std::pair(tok, trans)); } diff --git a/src/PLASMA/Resource/component/Reusable.cc b/src/PLASMA/Resource/component/Reusable.cc index 1887da7dd..5207c903d 100644 --- a/src/PLASMA/Resource/component/Reusable.cc +++ b/src/PLASMA/Resource/component/Reusable.cc @@ -60,8 +60,8 @@ namespace EUROPA { toString() << " Creating transactions for " << tok->getPredicateName().toString() << "(" << tok->getKey() << ")"); //here's the major difference between Reusable and Reservoir: always consume the quantity at the start //and produce it again at the end - TransactionId t1 = (new Transaction(t->start(), t->getQuantity(), true))->getId(); - TransactionId t2 = (new Transaction(t->end(), t->getQuantity(), false))->getId(); + TransactionId t1 = (new Transaction(t->start(), t->getQuantity(), true, getId()))->getId(); + TransactionId t2 = (new Transaction(t->end(), t->getQuantity(), false, getId()))->getId(); m_transactionsToTokens.insert(std::make_pair(t1, tok)); m_transactionsToTokens.insert(std::make_pair(t2, tok)); m_tokensToTransactions.insert(std::make_pair(tok, std::make_pair(t1, t2))); diff --git a/src/PLASMA/Resource/test/rs-flow-test-module.cc b/src/PLASMA/Resource/test/rs-flow-test-module.cc index bf4c7376e..935f64ecf 100644 --- a/src/PLASMA/Resource/test/rs-flow-test-module.cc +++ b/src/PLASMA/Resource/test/rs-flow-test-module.cc @@ -265,10 +265,10 @@ class FlowProfileTest ce.propagate(); - Transaction trans1(t1.getId(), q1.getId(), false); - Transaction trans2(t2.getId(), q2.getId(), true); - Transaction trans3(t3.getId(), q3.getId(), true); - Transaction trans4(t4.getId(), q4.getId(), false); + Transaction trans1(t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2(t2.getId(), q2.getId(), true, EntityId::noId()); + Transaction trans3(t3.getId(), q3.getId(), true, EntityId::noId()); + Transaction trans4(t4.getId(), q4.getId(), false, EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -309,10 +309,10 @@ class FlowProfileTest Variable q3( ce.getId(), IntervalDomain(1, 1), true, "q3" ); Variable q4( ce.getId(), IntervalDomain(1, 1), true, "q4" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); - Transaction trans3( t3.getId(), q3.getId(), true); - Transaction trans4( t4.getId(), q4.getId(), false); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), true, EntityId::noId()); + Transaction trans4( t4.getId(), q4.getId(), false, EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -334,8 +334,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(1, 1), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(1, 1), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -356,9 +356,9 @@ class FlowProfileTest Variable q2( ce.getId(), IntervalDomain(1, 2), true, "q2" ); Variable q3( ce.getId(), IntervalDomain(1, 2), true, "q3" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); - Transaction trans3( t3.getId(), q3.getId(), false ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), false , EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -380,9 +380,9 @@ class FlowProfileTest Variable q2( ce.getId(), IntervalDomain(1, 2), true, "q2" ); Variable q3( ce.getId(), IntervalDomain(1, 2), true, "q3" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); - Transaction trans3( t3.getId(), q3.getId(), false ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), false , EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -404,8 +404,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(1, 1), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(1, 1), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); EqualConstraint c0(LabelStr("concurrent"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); @@ -453,10 +453,10 @@ class FlowProfileTest Variable q3( ce.getId(), IntervalDomain(1, 2), true, "q3" ); Variable q4( ce.getId(), IntervalDomain(1, 2), true, "q4" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); - Transaction trans3( t3.getId(), q3.getId(), false); - Transaction trans4( t4.getId(), q4.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), false, EntityId::noId()); + Transaction trans4( t4.getId(), q4.getId(), true , EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -606,8 +606,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(2, 2), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(1, 2), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); EqualConstraint c0(LabelStr("concurrent"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); @@ -630,8 +630,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(1, 2), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(2, 2), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); EqualConstraint c0(LabelStr("concurrent"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); @@ -659,10 +659,10 @@ class FlowProfileTest Variable q3( ce.getId(), IntervalDomain(1, 1), true, "q3" ); Variable q4( ce.getId(), IntervalDomain(1, 1), true, "q4" ); - Transaction trans1( t1.getId(), q1.getId(), true); - Transaction trans2( t2.getId(), q2.getId(), false ); - Transaction trans3( t3.getId(), q3.getId(), true); - Transaction trans4( t4.getId(), q4.getId(), false ); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), false , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), true, EntityId::noId()); + Transaction trans4( t4.getId(), q4.getId(), false , EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); @@ -696,31 +696,31 @@ class FlowProfileTest Variable t1( ce.getId(), IntervalIntDomain(0,0), true, "t1" ); Variable q1( ce.getId(), IntervalDomain(3, 3), true, "q1" ); - Transaction trans1( t1.getId(), q1.getId(), true); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); Variable t2( ce.getId(), IntervalIntDomain(10, 10), true, "t2" ); Variable q2( ce.getId(), IntervalDomain(3, 3), true, "q2" ); - Transaction trans2( t2.getId(), q2.getId(), false ); + Transaction trans2( t2.getId(), q2.getId(), false , EntityId::noId()); LessThanEqualConstraint c0(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); Variable t3( ce.getId(), IntervalIntDomain(10, 10), true, "t3" ); Variable q3( ce.getId(), IntervalDomain(2, 2), true, "q3" ); - Transaction trans3( t3.getId(), q3.getId(), true); + Transaction trans3( t3.getId(), q3.getId(), true, EntityId::noId()); Variable t4( ce.getId(), IntervalIntDomain(100, 100), true, "t4" ); Variable q4( ce.getId(), IntervalDomain(2, 2), true, "q4" ); - Transaction trans4( t4.getId(), q4.getId(), false ); + Transaction trans4( t4.getId(), q4.getId(), false , EntityId::noId()); LessThanEqualConstraint c1(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t3.getId(), t4.getId())); Variable t5( ce.getId(), IntervalIntDomain(11, 100), true, "t5" ); Variable q5( ce.getId(), IntervalDomain(3, 3), true, "q5" ); - Transaction trans5( t5.getId(), q5.getId(), true); + Transaction trans5( t5.getId(), q5.getId(), true, EntityId::noId()); Variable t6( ce.getId(), IntervalIntDomain(12, 100), true, "t6" ); Variable q6( ce.getId(), IntervalDomain(3, 3), true, "q6" ); - Transaction trans6( t6.getId(), q6.getId(), false ); + Transaction trans6( t6.getId(), q6.getId(), false , EntityId::noId()); LessThanEqualConstraint c2(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t5.getId(), t6.getId())); @@ -763,8 +763,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(0, PLUS_INFINITY), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(0, PLUS_INFINITY), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), true); - Transaction trans2( t2.getId(), q2.getId(), false ); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), false , EntityId::noId()); LessThanEqualConstraint c1(LabelStr("precedes"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), t2.getId())); @@ -800,8 +800,8 @@ class FlowProfileTest Variable q1( ce.getId(), IntervalDomain(0, PLUS_INFINITY), true, "q1" ); Variable q2( ce.getId(), IntervalDomain(0, PLUS_INFINITY), true, "q2" ); - Transaction trans1( t1.getId(), q1.getId(), true); - Transaction trans2( t2.getId(), q2.getId(), false ); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), false , EntityId::noId()); Variable distance( ce.getId(), IntervalIntDomain( 1, PLUS_INFINITY ), true, "distance" ); @@ -873,9 +873,9 @@ class FlowProfileTest Variable q2( ce.getId(), IntervalDomain(3, 3), true, "q2" ); Variable q3( ce.getId(), IntervalDomain(3, 3), true, "q3" ); - Transaction trans1( t1.getId(), q1.getId(), true); - Transaction trans2( t2.getId(), q2.getId(), false ); - Transaction trans3( t3.getId(), q3.getId(), true ); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), false , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), true , EntityId::noId()); Variable distance( ce.getId(), IntervalIntDomain( 1, PLUS_INFINITY ), true, "distance" ); AddEqualConstraint c1(LabelStr("temporalDistance"), LabelStr("Temporal"), ce.getId() , makeScope(t1.getId(), distance.getId(), t2.getId())); @@ -907,7 +907,7 @@ class FlowProfileTest Variable t1( ce.getId(), IntervalIntDomain( 0, 10 ), true, "t1" ); Variable q1( ce.getId(), IntervalDomain(3, 3), true, "q1" ); - Transaction trans1( t1.getId(), q1.getId(), true); + Transaction trans1( t1.getId(), q1.getId(), true, EntityId::noId()); profile.addTransaction( trans1.getId() ); @@ -939,7 +939,7 @@ class FlowProfileTest Variable t2( ce.getId(), IntervalIntDomain( 5, 15 ), true, "t2" ); Variable q2( ce.getId(), IntervalDomain(3, 3), true, "q2" ); - Transaction trans2( t2.getId(), q2.getId(), true ); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); profile.addTransaction( trans2.getId() ); @@ -974,7 +974,7 @@ class FlowProfileTest Variable t3( ce.getId(), IntervalIntDomain( 20, 25 ), true, "t3" ); Variable q3( ce.getId(), IntervalDomain(3, 3), true, "q3" ); - Transaction trans3( t3.getId(), q3.getId(), true ); + Transaction trans3( t3.getId(), q3.getId(), true , EntityId::noId()); profile.addTransaction( trans3.getId() ); @@ -1009,7 +1009,7 @@ class FlowProfileTest Variable t4( ce.getId(), IntervalIntDomain(-10, 0 ), true, "t4" ); Variable q4( ce.getId(), IntervalDomain(3, 3), true, "q4" ); - Transaction trans4( t4.getId(), q4.getId(), true ); + Transaction trans4( t4.getId(), q4.getId(), true , EntityId::noId()); profile.addTransaction( trans4.getId() ); @@ -1061,10 +1061,10 @@ class FlowProfileTest Variable q3( ce.getId(), IntervalDomain(1, 1), true, "q3" ); Variable q4( ce.getId(), IntervalDomain(1, 1), true, "q4" ); - Transaction trans1( t1.getId(), q1.getId(), false); - Transaction trans2( t2.getId(), q2.getId(), true ); - Transaction trans3( t3.getId(), q3.getId(), true); - Transaction trans4( t4.getId(), q4.getId(), false); + Transaction trans1( t1.getId(), q1.getId(), false, EntityId::noId()); + Transaction trans2( t2.getId(), q2.getId(), true , EntityId::noId()); + Transaction trans3( t3.getId(), q3.getId(), true, EntityId::noId()); + Transaction trans4( t4.getId(), q4.getId(), false, EntityId::noId()); profile.addTransaction( trans1.getId() ); profile.addTransaction( trans2.getId() ); diff --git a/src/PLASMA/Resource/test/rs-test-module.cc b/src/PLASMA/Resource/test/rs-test-module.cc index 0abf8b80d..d0f932a92 100644 --- a/src/PLASMA/Resource/test/rs-test-module.cc +++ b/src/PLASMA/Resource/test/rs-test-module.cc @@ -328,11 +328,11 @@ class ProfileTest { std::set times; - TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false), deleter); - TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false), deleter); //distinct cases - TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false), deleter); //overlap on left side. both trans1 and trans2 should appear at time 0 - TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false), deleter); //overlap in the middle. should have trans3 and trans4 at time 1 and only trans4 at time 4 - TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false), deleter); //overlap on right side. both trans 4 and trans5 should appear at time 4 + TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false, EntityId::noId()), deleter); //distinct cases + TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false, EntityId::noId()), deleter); //overlap on left side. both trans1 and trans2 should appear at time 0 + TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false, EntityId::noId()), deleter); //overlap in the middle. should have trans3 and trans4 at time 1 and only trans4 at time 4 + TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false, EntityId::noId()), deleter); //overlap on right side. both trans 4 and trans5 should appear at time 4 profile.addTransaction(trans1->getId()); times.insert(0); @@ -413,11 +413,11 @@ class ProfileTest { times.insert(3); times.insert(4); times.insert(6); times.insert(10); - TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false), deleter); - TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false), deleter); - TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false), deleter); - TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false), deleter); - TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), quantity.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), quantity.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), quantity.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), quantity.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), quantity.getId(), false, EntityId::noId()), deleter); profile.addTransaction(trans1->getId()); profile.addTransaction(trans2->getId()); @@ -479,14 +479,14 @@ class ProfileTest { // Variable t0(ce.getId(), IntervalIntDomain(MINUS_INFINITY, MINUS_INFINITY)); // Variable q0(ce.getId(), IntervalDomain(0, 0)); -// TransactionPtr trans0(new Transaction(t0.getId(), q0.getId(), false), deleter); +// TransactionPtr trans0(new Transaction(t0.getId(), q0.getId(), false, EntityId::noId()), deleter); // r.addTransaction(trans0->getId()); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 0); Variable t1(ce.getId(), IntervalIntDomain(0, HORIZON_END)); Variable q1(ce.getId(), IntervalDomain(45, 45)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*1)); @@ -494,7 +494,7 @@ class ProfileTest { Variable t2(ce.getId(), IntervalIntDomain(1, HORIZON_END)); Variable q2(ce.getId(), IntervalDomain(35, 35)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2)); @@ -502,7 +502,7 @@ class ProfileTest { Variable t3(ce.getId(), IntervalIntDomain(2, HORIZON_END)); Variable q3(ce.getId(), IntervalDomain(20, 20)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*3)); @@ -535,44 +535,44 @@ class ProfileTest { Variable t1(ce.getId(), IntervalIntDomain(4, 6)); Variable q1(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*1)); Variable t2(ce.getId(), IntervalIntDomain(-4, 10)); Variable q2(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*1)); Variable t3(ce.getId(), IntervalIntDomain(1, 3)); Variable q3(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*2 +3*2 + 4*2 + 5*2 + 6*1)); Variable t4(ce.getId(), IntervalIntDomain(1, 2)); Variable q4(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*2 + 5*2 + 6*2 + 7*1)); Variable t5(ce.getId(), IntervalIntDomain(3, 7)); Variable q5(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), false), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*3 + 6*3 + 7*2 + 8*1)); Variable t6(ce.getId(), IntervalIntDomain(4, 7)); Variable q6(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false), deleter); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*4 + 6*4 + 7*3 + 8*1)); // Insert for a singleton value Variable t7(ce.getId(), IntervalIntDomain(5, 5)); Variable q7(ce.getId(), IntervalDomain(0, PLUS_INFINITY)); - TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), false), deleter); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans7->getId()); CPPUNIT_ASSERT(ce.propagate() && checkSum(r.getId()) == (1*1 + 2*3 + 3*3 + 4*3 + 5*4 + 6*5 + 7*4 + 8*3 + 9*1)); @@ -608,7 +608,7 @@ class ProfileTest { Variable t1(ce.getId(), IntervalIntDomain(0, 1)); Variable q1(ce.getId(), IntervalDomain(1, 1)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*1)); @@ -616,7 +616,7 @@ class ProfileTest { Variable t2(ce.getId(), IntervalIntDomain(1, 3)); Variable q2(ce.getId(), IntervalDomain(4, 4)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*1)); @@ -624,7 +624,7 @@ class ProfileTest { Variable t3(ce.getId(), IntervalIntDomain(2, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*2 + 5*1)); @@ -632,7 +632,7 @@ class ProfileTest { Variable t4(ce.getId(), IntervalIntDomain(3, 6)); Variable q4(ce.getId(), IntervalDomain(2, 2)); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans4->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*2 + 4*3 + 5*2 + 6*1)); @@ -640,7 +640,7 @@ class ProfileTest { Variable t5(ce.getId(), IntervalIntDomain(2, 10)); Variable q5(ce.getId(), IntervalDomain(6, 6)); - TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans5->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*2 + 7*1)); @@ -648,7 +648,7 @@ class ProfileTest { Variable t6(ce.getId(), IntervalIntDomain(6, 8)); Variable q6(ce.getId(), IntervalDomain(3, 3)); - TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false), deleter); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans6->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*3 + 7*2 + 8*1)); @@ -656,7 +656,7 @@ class ProfileTest { Variable t7(ce.getId(), IntervalIntDomain(7, 8)); Variable q7(ce.getId(), IntervalDomain(4, 4)); - TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true), deleter); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans7->getId()); ce.propagate(); CPPUNIT_ASSERT(checkSum(r.getId()) == (1*1 + 2*2 + 3*3 + 4*4 + 5*3 + 6*3 + +7* 3 + 8*3 + 9*1)); @@ -676,7 +676,7 @@ class ProfileTest { Variable t1(ce.getId(), IntervalIntDomain(0, 10)); Variable q1(ce.getId(), IntervalDomain(10, 10)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*10); @@ -705,7 +705,7 @@ class ProfileTest { // Test producer Variable t1(ce.getId(), IntervalIntDomain(0, 10)); Variable q1(ce.getId(), IntervalDomain(5, 10)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*10); @@ -713,7 +713,7 @@ class ProfileTest { // Test consumer Variable t3(ce.getId(), IntervalIntDomain(1, 5)); Variable q3(ce.getId(), IntervalDomain(1, 4)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); ce.propagate(); CPPUNIT_ASSERT(checkLevelArea(r.getId()) == 10*1 + 14*4 + 13*5);//+ 14*3 + 21*1 + 20*3 + 20*2); @@ -735,13 +735,13 @@ class ProfileTest { Variable t1(ce.getId(), IntervalIntDomain(0, 1)); Variable q1(ce.getId(), IntervalDomain(productionRateMax, productionRateMax + 1)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); ce.propagate(); Variable t3(ce.getId(), IntervalIntDomain(0, 1)); Variable q3(ce.getId(), IntervalDomain(1, 1)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); // no violation because of temporal flexibility @@ -761,13 +761,13 @@ class ProfileTest { Variable t2(ce.getId(), IntervalIntDomain(0, 1)); Variable q2(ce.getId(), IntervalDomain(-(consumptionRateMax), -(consumptionRateMax - 1))); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); ce.propagate(); Variable t4(ce.getId(), IntervalIntDomain(0, 1)); Variable q4(ce.getId(), IntervalDomain(1, 1)); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans4->getId()); // no violation because of temporal flexibility CPPUNIT_ASSERT(ce.propagate()); @@ -802,38 +802,38 @@ class ProfileTest { // production Variable t1(ce.getId(), IntervalIntDomain(2, 2)); Variable q1(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t2(ce.getId(), IntervalIntDomain(3, 3)); Variable q2(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t3(ce.getId(), IntervalIntDomain(4, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t4(ce.getId(), IntervalIntDomain(5, 5)); Variable q4(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t5(ce.getId(), IntervalIntDomain(6, 6)); Variable q5(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate()); // This will push it over the edge Variable t6(ce.getId(), IntervalIntDomain(10, 10)); Variable q6(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true), deleter); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(!ce.propagate()); @@ -860,44 +860,44 @@ class ProfileTest { // production Variable t1(ce.getId(), IntervalIntDomain(2, 2)); Variable q1(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t2(ce.getId(), IntervalIntDomain(3, 3)); Variable q2(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t3(ce.getId(), IntervalIntDomain(4, 4)); Variable q3(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t4(ce.getId(), IntervalIntDomain(5, 5)); Variable q4(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans4->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t5(ce.getId(), IntervalIntDomain(6, 6)); Variable q5(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true), deleter); + TransactionPtr trans5(new Transaction(t5.getId(), q5.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans5->getId()); CPPUNIT_ASSERT(ce.propagate()); Variable t6(ce.getId(), IntervalIntDomain(8, 8)); Variable q6(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true), deleter); + TransactionPtr trans6(new Transaction(t6.getId(), q6.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans6->getId()); CPPUNIT_ASSERT(ce.propagate()); // This will push it over the edge Variable t7(ce.getId(), IntervalIntDomain(10, 10)); Variable q7(ce.getId(), IntervalDomain(8, 8)); - TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true), deleter); + TransactionPtr trans7(new Transaction(t7.getId(), q7.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans7->getId()); CPPUNIT_ASSERT(!ce.propagate()); @@ -926,7 +926,7 @@ class ProfileTest { for (int i = 0; i < 11; i++){ ConstrainedVariableId time = (new Variable(ce.getId(), IntervalIntDomain(i, i)))->getId(); ConstrainedVariableId quantity = (new Variable(ce.getId(), IntervalDomain(productionRateMax, productionRateMax)))->getId(); - TransactionId t = (new Transaction(time, quantity, false))->getId(); + TransactionId t = (new Transaction(time, quantity, false, EntityId::noId()))->getId(); r.addTransaction(t); transactions.push_back(t); vars.push_back(quantity); @@ -973,7 +973,7 @@ class ProfileTest { for (int i = 0; i < 11; i++){ ConstrainedVariableId time = (new Variable(ce.getId(), IntervalIntDomain(i, i)))->getId(); ConstrainedVariableId quantity = (new Variable(ce.getId(), IntervalDomain(productionRateMax, productionRateMax)))->getId(); - TransactionId t = (new Transaction(time, quantity, false))->getId(); + TransactionId t = (new Transaction(time, quantity, false, EntityId::noId()))->getId(); r.addTransaction(t); //r->constrain(t); transactions.push_back(t); @@ -983,7 +983,7 @@ class ProfileTest { for (int i = 0; i < 11; i++){ ConstrainedVariableId time = (new Variable(ce.getId(), IntervalIntDomain(i, i)))->getId(); ConstrainedVariableId quantity = (new Variable(ce.getId(), IntervalDomain(productionRateMax, productionRateMax)))->getId(); - TransactionId t = (new Transaction(time, quantity, true))->getId(); + TransactionId t = (new Transaction(time, quantity, true, EntityId::noId()))->getId(); r.addTransaction(t); //r->constrain(t); transactions.push_back(t); @@ -1038,7 +1038,7 @@ class ProfileTest { // Test that a flaw is signalled when there is a possibility to violate limits Variable t1(ce.getId(), IntervalIntDomain(5, 5)); Variable q1(ce.getId(), IntervalDomain(5, 5)); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); r.addTransaction(trans1->getId()); // Have a single transaction, test before, at and after. @@ -1051,12 +1051,12 @@ class ProfileTest { Variable t2(ce.getId(), IntervalIntDomain(0, 7)); Variable q2(ce.getId(), IntervalDomain(5, 5)); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans2->getId()); Variable t3(ce.getId(), IntervalIntDomain(2, 10)); Variable q3(ce.getId(), IntervalDomain(5, 5)); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true, EntityId::noId()), deleter); r.addTransaction(trans3->getId()); // Confirm that we can query in the middle @@ -1089,10 +1089,10 @@ class ProfileTest { Variable q3(ce.getId(), IntervalDomain(1, 1), true, "q3"); Variable q4(ce.getId(), IntervalDomain(1, 1), true, "q4"); - TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false), deleter); - TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true), deleter); - TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true), deleter); - TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false), deleter); + TransactionPtr trans1(new Transaction(t1.getId(), q1.getId(), false, EntityId::noId()), deleter); + TransactionPtr trans2(new Transaction(t2.getId(), q2.getId(), true, EntityId::noId()), deleter); + TransactionPtr trans3(new Transaction(t3.getId(), q3.getId(), true, EntityId::noId()), deleter); + TransactionPtr trans4(new Transaction(t4.getId(), q4.getId(), false, EntityId::noId()), deleter); profile.addTransaction(trans1->getId()); profile.addTransaction(trans2->getId()); From 1e62e4a8a4e7fcef257989a4c29e940dd9bb3f26 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 22 Sep 2014 18:29:28 +0000 Subject: [PATCH 021/149] Addresses issue 4 -ResourceThreatManager.{cc,hh}: Provded implementation of noMoreFlaws -Types.hh: Reverting TRACE_GRAPH to 0, which shouldn't've gotten checked in as 1 -rs-test-module.cc: Added test for ResourceThreatManager::noMoreFFlaws -FlawManager.cc: Added a checkError to the base createIterator -FlawManager.hh: Added abstract FlawManager::noMoreFlaws. Should be const, but can't with the current implementation. -Solver.{cc,hh}:Implemented Solver::noMoreFlaws in terms of FlawManager::noMoreFlaws. -SolverDecisionPoint.hh: Made more of the interface public so it's testable. -OpenConditionManager.{cc,hh}: Added implementation of noMoreFlaws -ThreatManager.{cc,hh}: Added implementation of noMoreFlaws -UnboundVariableManager.{cc,hh}: Added implementation of noMoreFlaws -solvers-test-module.cc: Added tests for noMoreFlaws implementations git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6751 23e1bc29-d954-0410-9766-47de34158ba0 --- .../Solvers/ResourceThreatManager.cc | 75 +++--- .../Solvers/ResourceThreatManager.hh | 1 + src/PLASMA/Resource/component/Types.hh | 2 +- src/PLASMA/Resource/test/rs-test-module.cc | 248 ++++++++++-------- src/PLASMA/Solvers/base/FlawManager.cc | 5 +- src/PLASMA/Solvers/base/FlawManager.hh | 2 + src/PLASMA/Solvers/base/Solver.cc | 9 +- src/PLASMA/Solvers/base/Solver.hh | 3 +- .../Solvers/base/SolverDecisionPoint.hh | 5 +- .../Solvers/component/OpenConditionManager.cc | 5 + .../Solvers/component/OpenConditionManager.hh | 1 + src/PLASMA/Solvers/component/ThreatManager.cc | 76 +++--- src/PLASMA/Solvers/component/ThreatManager.hh | 2 + .../component/UnboundVariableManager.cc | 4 + .../component/UnboundVariableManager.hh | 2 +- .../Solvers/test/solvers-test-module.cc | 150 ++++++++++- 16 files changed, 413 insertions(+), 177 deletions(-) diff --git a/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.cc b/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.cc index 343d00137..99b11c100 100644 --- a/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.cc +++ b/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.cc @@ -30,6 +30,43 @@ namespace EUROPA { // } // }; +namespace { +class ThreatIterator : public FlawIterator { + public: + ThreatIterator(ResourceThreatManager& manager) : FlawIterator(manager) { + const ObjectSet& objs = manager.getPlanDatabase()->getObjects(); + for(ObjectSet::const_iterator it = objs.begin(); it != objs.end(); ++it) { + ObjectId obj(*it); + check_error(obj.isValid()); + debugMsg("ThreatIterator:ThreatIterator", "Checking to see if " << obj->toString() << " is a resource..."); + if(!ResourceId::convertable(obj)) + continue; + ResourceId res(obj); + std::vector temp; + debugMsg("ThreatIterator:ThreatIterator", "Resource! Getting flawed instants..."); + res->getFlawedInstants(temp); + m_flawedInstants.insert(m_flawedInstants.end(), temp.begin(), temp.end()); + } + debugMsg("ThreatIterator:ThreatIterator", "Got " << m_flawedInstants.size() << " total instants."); + m_it = m_flawedInstants.begin(); + advance(); + condDebugMsg(done(), "ThreatIterator:ThreatIterator", "Advanced to the end right away."); + } + protected: + private: + const EntityId nextCandidate() { + EntityId candidate; + if(m_it != m_flawedInstants.end()) { + candidate = *m_it; + ++m_it; + } + return candidate; + } + std::vector m_flawedInstants; + std::vector::iterator m_it; +}; +} + class InstantComparator { public: enum FlawDirection { @@ -284,40 +321,10 @@ namespace EUROPA { return os.str(); } - class ThreatIterator : public FlawIterator { - public: - ThreatIterator(ResourceThreatManager& manager) : FlawIterator(manager) { - const ObjectSet& objs = manager.getPlanDatabase()->getObjects(); - for(ObjectSet::const_iterator it = objs.begin(); it != objs.end(); ++it) { - ObjectId obj(*it); - check_error(obj.isValid()); - debugMsg("ThreatIterator:ThreatIterator", "Checking to see if " << obj->toString() << " is a resource..."); - if(!ResourceId::convertable(obj)) - continue; - ResourceId res(obj); - std::vector temp; - debugMsg("ThreatIterator:ThreatIterator", "Resource! Getting flawed instants..."); - res->getFlawedInstants(temp); - m_flawedInstants.insert(m_flawedInstants.end(), temp.begin(), temp.end()); - } - debugMsg("ThreatIterator:ThreatIterator", "Got " << m_flawedInstants.size() << " total instants."); - m_it = m_flawedInstants.begin(); - advance(); - condDebugMsg(done(), "ThreatIterator:ThreatIterator", "Advanced to the end right away."); - } - protected: - private: - const EntityId nextCandidate() { - EntityId candidate; - if(m_it != m_flawedInstants.end()) { - candidate = *m_it; - ++m_it; - } - return candidate; - } - std::vector m_flawedInstants; - std::vector::iterator m_it; - }; +bool ResourceThreatManager::noMoreFlaws() { + return ThreatIterator(*this).done(); +} + IteratorId ResourceThreatManager::createIterator() { return (new ThreatIterator(*this))->getId(); diff --git a/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.hh b/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.hh index 89c1ae81d..555424b11 100644 --- a/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.hh +++ b/src/PLASMA/Resource/component/Solvers/ResourceThreatManager.hh @@ -35,6 +35,7 @@ namespace EUROPA { virtual void notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType){} virtual void notifyAdded(const TokenId& token) {} virtual void notifyRemoved(const TokenId& token) {} + bool noMoreFlaws(); protected: private: diff --git a/src/PLASMA/Resource/component/Types.hh b/src/PLASMA/Resource/component/Types.hh index 1848f6548..0cddcbc78 100644 --- a/src/PLASMA/Resource/component/Types.hh +++ b/src/PLASMA/Resource/component/Types.hh @@ -30,7 +30,7 @@ #include "Instant.hh" #include "Transaction.hh" -#define TRACE_GRAPH 1 +#define TRACE_GRAPH 0 #ifdef TRACE_GRAPH diff --git a/src/PLASMA/Resource/test/rs-test-module.cc b/src/PLASMA/Resource/test/rs-test-module.cc index d0f932a92..1e84ddb90 100644 --- a/src/PLASMA/Resource/test/rs-test-module.cc +++ b/src/PLASMA/Resource/test/rs-test-module.cc @@ -215,11 +215,9 @@ class BareTransactionDeleter { BareTransactionDeleter(DummyResource& res) : m_profile(NULL), m_res(&res) {} void operator()(Transaction* t) { if(m_profile != NULL) { - std::cout << "Removing " << t->getId() << " from a profile" << std::endl; m_profile->removeTransaction(t->getId()); } if(m_res != NULL) { - std::cout << "Removing " << t->getId() << " from a resource" << std::endl; m_res->removeTransaction(t->getId()); } delete t; @@ -1476,52 +1474,53 @@ class ConstraintNameListener : public ConstrainedVariableListener { // Test that used to be in Solvers/test/solvers-test-module.cc class ResourceSolverTest { -public: - static bool test() { - EUROPA_runTest(testResourceDecisionPoint); - EUROPA_runTest(testResourceThreatDecisionPoint); - EUROPA_runTest(testResourceThreatManager); - return true; - } -private: + public: + static bool test() { + EUROPA_runTest(testResourceDecisionPoint); + EUROPA_runTest(testResourceThreatDecisionPoint); + EUROPA_runTest(testResourceThreatManager); + EUROPA_runTest(testResourceThreatManagerNoMoreFlaws); + return true; + } + private: - // TBS: This tested a previous version of ResourceThreatDecisionPoint (basically a glorified ThreatDecisionPoint, which we now test here), so - // there's not much value in this test anymore. - static bool testResourceDecisionPoint() { + // TBS: This tested a previous version of ResourceThreatDecisionPoint (basically a glorified ThreatDecisionPoint, which we now test here), so + // there's not much value in this test anymore. + static bool testResourceDecisionPoint() { - RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); + RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); - PlanDatabaseId db = dbObj.getId(); - ConstraintEngineId ce = ceObj.getId(); - DbClientId client = db->getClient(); + PlanDatabaseId db = dbObj.getId(); + ConstraintEngineId ce = ceObj.getId(); + DbClientId client = db->getClient(); - Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 2, 2, 0); + Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 2, 2, 0); - ReusableToken tok1(db, "Reusable.uses", IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); + ReusableToken tok1(db, "Reusable.uses", IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); - ReusableToken tok2(db, "Reusable.uses", IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); + ReusableToken tok2(db, "Reusable.uses", IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); - ReusableToken tok3(db, "Reusable.uses", IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); + ReusableToken tok3(db, "Reusable.uses", IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); - CPPUNIT_ASSERT(ce->propagate()); - CPPUNIT_ASSERT(reusable.hasTokensToOrder()); - TiXmlElement dummy(""); - SOLVERS::ThreatDecisionPoint dp1(client, tok1.getId(), dummy); + CPPUNIT_ASSERT(ce->propagate()); + CPPUNIT_ASSERT(reusable.hasTokensToOrder()); + TiXmlElement dummy(""); + SOLVERS::ThreatDecisionPoint dp1(client, tok1.getId(), dummy); - dp1.initialize(); + dp1.initialize(); - SOLVERS::ThreatDecisionPoint dp2(client, tok2.getId(), dummy); - dp2.initialize(); + SOLVERS::ThreatDecisionPoint dp2(client, tok2.getId(), dummy); + dp2.initialize(); - SOLVERS::ThreatDecisionPoint dp3(client, tok3.getId(), dummy); - dp3.initialize(); + SOLVERS::ThreatDecisionPoint dp3(client, tok3.getId(), dummy); + dp3.initialize(); - RESOURCE_DEFAULT_TEARDOWN(); - return true; - } + RESOURCE_DEFAULT_TEARDOWN(); + return true; + } static bool testResourceThreatDecisionPoint() { @@ -1849,73 +1848,116 @@ class ResourceSolverTest { } - static bool testResourceThreatManager() { - - RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); - - PlanDatabaseId db = dbObj.getId(); - ConstraintEngineId ce = ceObj.getId(); - DbClientId client = db->getClient(); - - Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 1, 1, 0); - - ReusableToken tok1(db, "Reusable.uses", IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); - - ReusableToken tok2(db, "Reusable.uses", IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); - - ReusableToken tok3(db, "Reusable.uses", IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), IntervalIntDomain(1, PLUS_INFINITY), - IntervalDomain(1.0, 1.0), "myReusable"); - - CPPUNIT_ASSERT(ce->propagate()); - - std::vector instants; - reusable.getFlawedInstants(instants); - - LabelStr explanation; - std::string earliest = ""; - TiXmlElement* earliestXml = initXml(earliest); - ResourceThreatManager earliestManager(*earliestXml); - SOLVERS::Context ctx("foo"); - earliestManager.initialize(*earliestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); - CPPUNIT_ASSERT(earliestManager.betterThan(instants[0], instants[1], explanation)); //these are identical except for the time - CPPUNIT_ASSERT(earliestManager.betterThan(instants[1], instants[2], explanation)); //these have different levels - CPPUNIT_ASSERT(!earliestManager.betterThan(instants[0], instants[0], explanation)); - - std::string latest = ""; - TiXmlElement* latestXml = initXml(latest); - ResourceThreatManager latestManager(*latestXml); - latestManager.initialize(*latestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); - CPPUNIT_ASSERT(latestManager.betterThan(instants[3], instants[2], explanation)); - CPPUNIT_ASSERT(latestManager.betterThan(instants[2], instants[1], explanation)); - CPPUNIT_ASSERT(!latestManager.betterThan(instants[0], instants[0], explanation)); - - std::string most = ""; - TiXmlElement* mostXml = initXml(most); - ResourceThreatManager mostManager(*mostXml); - mostManager.initialize(*mostXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); - CPPUNIT_ASSERT(mostManager.betterThan(instants[0], instants[1], explanation)); - CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[0], explanation)); - CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[2], explanation)); - CPPUNIT_ASSERT(!mostManager.betterThan(instants[3], instants[4], explanation)); - - std::string least = ""; - TiXmlElement* leastXml = initXml(least); - ResourceThreatManager leastManager(*leastXml); - leastManager.initialize(*leastXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); - CPPUNIT_ASSERT(!leastManager.betterThan(instants[0], instants[1], explanation)); - CPPUNIT_ASSERT(leastManager.betterThan(instants[1], instants[0], explanation)); - CPPUNIT_ASSERT(!leastManager.betterThan(instants[3], instants[4], explanation)); - CPPUNIT_ASSERT(!leastManager.betterThan(instants[4], instants[3], explanation)); - - //can't test upper/lower with reusables - delete leastXml; - delete mostXml; - delete latestXml; - delete earliestXml; - return true; - } + static bool testResourceThreatManager() { + + RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); + + PlanDatabaseId db = dbObj.getId(); + ConstraintEngineId ce = ceObj.getId(); + DbClientId client = db->getClient(); + + Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 1, 1, 0); + + ReusableToken tok1(db, "Reusable.uses", IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + ReusableToken tok2(db, "Reusable.uses", IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + ReusableToken tok3(db, "Reusable.uses", IntervalIntDomain(11, 16), IntervalIntDomain(18, 19), IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + CPPUNIT_ASSERT(ce->propagate()); + + std::vector instants; + reusable.getFlawedInstants(instants); + + LabelStr explanation; + std::string earliest = ""; + TiXmlElement* earliestXml = initXml(earliest); + ResourceThreatManager earliestManager(*earliestXml); + SOLVERS::Context ctx("foo"); + earliestManager.initialize(*earliestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); + CPPUNIT_ASSERT(earliestManager.betterThan(instants[0], instants[1], explanation)); //these are identical except for the time + CPPUNIT_ASSERT(earliestManager.betterThan(instants[1], instants[2], explanation)); //these have different levels + CPPUNIT_ASSERT(!earliestManager.betterThan(instants[0], instants[0], explanation)); + + std::string latest = ""; + TiXmlElement* latestXml = initXml(latest); + ResourceThreatManager latestManager(*latestXml); + latestManager.initialize(*latestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); + CPPUNIT_ASSERT(latestManager.betterThan(instants[3], instants[2], explanation)); + CPPUNIT_ASSERT(latestManager.betterThan(instants[2], instants[1], explanation)); + CPPUNIT_ASSERT(!latestManager.betterThan(instants[0], instants[0], explanation)); + + std::string most = ""; + TiXmlElement* mostXml = initXml(most); + ResourceThreatManager mostManager(*mostXml); + mostManager.initialize(*mostXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); + CPPUNIT_ASSERT(mostManager.betterThan(instants[0], instants[1], explanation)); + CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[0], explanation)); + CPPUNIT_ASSERT(!mostManager.betterThan(instants[1], instants[2], explanation)); + CPPUNIT_ASSERT(!mostManager.betterThan(instants[3], instants[4], explanation)); + + std::string least = ""; + TiXmlElement* leastXml = initXml(least); + ResourceThreatManager leastManager(*leastXml); + leastManager.initialize(*leastXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); + CPPUNIT_ASSERT(!leastManager.betterThan(instants[0], instants[1], explanation)); + CPPUNIT_ASSERT(leastManager.betterThan(instants[1], instants[0], explanation)); + CPPUNIT_ASSERT(!leastManager.betterThan(instants[3], instants[4], explanation)); + CPPUNIT_ASSERT(!leastManager.betterThan(instants[4], instants[3], explanation)); + + //can't test upper/lower with reusables + delete leastXml; + delete mostXml; + delete latestXml; + delete earliestXml; + return true; + } + + static bool testResourceThreatManagerNoMoreFlaws() { + RESOURCE_DEFAULT_SETUP(ceObj, dbObj, false); + + PlanDatabaseId db = dbObj.getId(); + ConstraintEngineId ce = ceObj.getId(); + DbClientId client = db->getClient(); + + Reusable reusable(db, "Reusable", "myReusable", "ClosedWorldFVDetector", "IncrementalFlowProfile", 1, 1, 0); + + ReusableToken tok1(db, "Reusable.uses", + IntervalIntDomain(1, 3), IntervalIntDomain(10, 12), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + + ReusableToken tok2(db, "Reusable.uses", + IntervalIntDomain(11, 13), IntervalIntDomain(15, 17), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + CPPUNIT_ASSERT(ce->propagate()); + + + std::string earliest = ""; + TiXmlElement* earliestXml = initXml(earliest); + ResourceThreatManager earliestManager(*earliestXml); + SOLVERS::Context ctx("foo"); + earliestManager.initialize(*earliestXml, db, ctx.getId(), SOLVERS::FlawManagerId::noId()); + + CPPUNIT_ASSERT(!earliestManager.noMoreFlaws()); + client->constrain(reusable.getId(), tok1.getId(), tok2.getId()); + CPPUNIT_ASSERT(ce->propagate()); + CPPUNIT_ASSERT(earliestManager.noMoreFlaws()); + + ReusableToken tok3(db, "Reusable.uses", + IntervalIntDomain(16, 18), IntervalIntDomain(20, 30), + IntervalIntDomain(1, PLUS_INFINITY), + IntervalDomain(1.0, 1.0), "myReusable"); + CPPUNIT_ASSERT(ce->propagate()); + + CPPUNIT_ASSERT(!earliestManager.noMoreFlaws()); + delete earliestXml; + return true; + } }; void ResourceModuleTests::cppSetup(void) diff --git a/src/PLASMA/Solvers/base/FlawManager.cc b/src/PLASMA/Solvers/base/FlawManager.cc index c34cd7a5b..3de0e1145 100644 --- a/src/PLASMA/Solvers/base/FlawManager.cc +++ b/src/PLASMA/Solvers/base/FlawManager.cc @@ -114,7 +114,10 @@ namespace EUROPA { condDebugMsg(!isValid(), "FlawManager:isValid", "Invalid datastructures in flaw manger."); } - IteratorId FlawManager::createIterator(){ return IteratorId::noId();} + IteratorId FlawManager::createIterator(){ + checkRuntimeError(ALWAYS_FAIL, "Should never get here."); + return IteratorId::noId(); + } void FlawManager::notifyRemoved(const ConstraintId& constraint) { // Check if it's the correct type (FlawHandler::VariableListener) diff --git a/src/PLASMA/Solvers/base/FlawManager.hh b/src/PLASMA/Solvers/base/FlawManager.hh index 604f97476..2b3fbcfdc 100644 --- a/src/PLASMA/Solvers/base/FlawManager.hh +++ b/src/PLASMA/Solvers/base/FlawManager.hh @@ -155,6 +155,8 @@ namespace EUROPA { ContextId getContext() const {return m_context;} + virtual bool noMoreFlaws() = 0; + protected: FlawManager(const TiXmlElement& configData); diff --git a/src/PLASMA/Solvers/base/Solver.cc b/src/PLASMA/Solvers/base/Solver.cc index c1812bb92..0a2811a2c 100644 --- a/src/PLASMA/Solvers/base/Solver.cc +++ b/src/PLASMA/Solvers/base/Solver.cc @@ -128,7 +128,14 @@ namespace EUROPA { std::string Solver::getLastExecutedDecision() const {return m_lastExecutedDecision;} - bool Solver::noMoreFlaws() const{return m_noFlawsFound;} + bool Solver::noMoreFlaws() { + for(FlawManagers::const_iterator it = m_flawManagers.begin(); + it != m_flawManagers.end(); ++it) { + if(!(*it)->noMoreFlaws()) + return false; + } + return true; + } const DecisionStack& Solver::getDecisionStack() const {return m_decisionStack;} diff --git a/src/PLASMA/Solvers/base/Solver.hh b/src/PLASMA/Solvers/base/Solver.hh index 435855c47..7176bc584 100644 --- a/src/PLASMA/Solvers/base/Solver.hh +++ b/src/PLASMA/Solvers/base/Solver.hh @@ -115,7 +115,7 @@ namespace EUROPA { /** * @brief Tests if we have concluded there are no more flaws. */ - bool noMoreFlaws() const; + bool noMoreFlaws(); /** * @brief Tests if the search space have been exhausted. @@ -238,6 +238,7 @@ namespace EUROPA { public: MasterFilter(const TiXmlElement& configData): FlawManager(configData){} IteratorId createIterator() {return IteratorId::noId();} + bool noMoreFlaws() {return true;} private: friend class Solver; void handleInitialize(){} diff --git a/src/PLASMA/Solvers/base/SolverDecisionPoint.hh b/src/PLASMA/Solvers/base/SolverDecisionPoint.hh index a5c687419..040a02da9 100644 --- a/src/PLASMA/Solvers/base/SolverDecisionPoint.hh +++ b/src/PLASMA/Solvers/base/SolverDecisionPoint.hh @@ -67,10 +67,11 @@ namespace EUROPA { void setCutoff(unsigned int maxChoices) {m_maxChoices = maxChoices;} const eint getFlawedEntityKey() {return m_entityKey;} - protected: + // protected: DecisionPoint(const DbClientId& client, eint entityKey, const LabelStr& explanation); - friend class Solver; /*!< grants special access to execute and undo methods */ + // friend class Solver; /*!< grants special access to execute and undo methods */ + // friend class ::FlawManagerTests; /** * @brief Tests if execute has been called more times than undo. diff --git a/src/PLASMA/Solvers/component/OpenConditionManager.cc b/src/PLASMA/Solvers/component/OpenConditionManager.cc index bbbdc9d50..0c9e210e5 100644 --- a/src/PLASMA/Solvers/component/OpenConditionManager.cc +++ b/src/PLASMA/Solvers/component/OpenConditionManager.cc @@ -25,6 +25,11 @@ namespace EUROPA { addFlaw(token); } } + + bool OpenConditionManager::noMoreFlaws() { + return m_flawCandidates.empty(); + } + /** * Filter out if not a token diff --git a/src/PLASMA/Solvers/component/OpenConditionManager.hh b/src/PLASMA/Solvers/component/OpenConditionManager.hh index d8e5e8cca..b3662030c 100644 --- a/src/PLASMA/Solvers/component/OpenConditionManager.hh +++ b/src/PLASMA/Solvers/component/OpenConditionManager.hh @@ -26,6 +26,7 @@ namespace EUROPA { virtual std::string toString(const EntityId& entity) const; + bool noMoreFlaws(); protected: virtual void addFlaw(const TokenId& token); virtual void removeFlaw(const TokenId& token); diff --git a/src/PLASMA/Solvers/component/ThreatManager.cc b/src/PLASMA/Solvers/component/ThreatManager.cc index 7ec035e15..7e319396d 100644 --- a/src/PLASMA/Solvers/component/ThreatManager.cc +++ b/src/PLASMA/Solvers/component/ThreatManager.cc @@ -11,10 +11,34 @@ * @date May, 2005 */ namespace EUROPA { - namespace SOLVERS { +namespace SOLVERS { +namespace { +class ThreatIterator : public FlawIterator { + public: + ThreatIterator(ThreatManager& manager) + : FlawIterator(manager), + m_it(manager.getPlanDatabase()->getTokensToOrder().begin()), + m_end(manager.getPlanDatabase()->getTokensToOrder().end()){ + advance(); + } + + private: + const EntityId nextCandidate() { + EntityId candidate; + if(m_it != m_end){ + candidate = m_it->second.first; + ++m_it; + } + return candidate; + } + + std::map >::const_iterator m_it; + std::map >::const_iterator m_end; +}; +} - ThreatManager::ThreatManager(const TiXmlElement& configData) - : FlawManager(configData){} +ThreatManager::ThreatManager(const TiXmlElement& configData) + : FlawManager(configData){} ThreatManager::~ThreatManager(){} @@ -35,6 +59,24 @@ namespace EUROPA { return staticMatch(entity) || FlawManager::dynamicMatch(entity); } +bool ThreatManager::noMoreFlaws() { + // const std::map >& flaws = + // getPlanDatabase()->getTokensToOrder(); + + // if(!flaws.empty()) { + // for(std::map >::const_iterator it = + // flaws.begin(); it != flaws.end(); ++it) { + // if(!dynamicMatch(it->second.first)) + // return false; + // } + // } + // return true; + return ThreatIterator(*this).done(); +} + +IteratorId ThreatManager::createIterator() { + return (new ThreatIterator(*this))->getId(); +} std::string ThreatManager::toString(const EntityId& entity) const { checkError(TokenId::convertable(entity), entity->toString()); TokenId token = entity; @@ -43,31 +85,5 @@ namespace EUROPA { return os.str(); } - class ThreatIterator : public FlawIterator { - public: - ThreatIterator(ThreatManager& manager) - : FlawIterator(manager), - m_it(manager.getPlanDatabase()->getTokensToOrder().begin()), - m_end(manager.getPlanDatabase()->getTokensToOrder().end()){ - advance(); - } - - private: - const EntityId nextCandidate() { - EntityId candidate; - if(m_it != m_end){ - candidate = m_it->second.first; - ++m_it; - } - return candidate; - } - - std::map >::const_iterator m_it; - std::map >::const_iterator m_end; - }; - - IteratorId ThreatManager::createIterator() { - return (new ThreatIterator(*this))->getId(); - } - } +} } diff --git a/src/PLASMA/Solvers/component/ThreatManager.hh b/src/PLASMA/Solvers/component/ThreatManager.hh index 2d6d4a961..c054f76a6 100644 --- a/src/PLASMA/Solvers/component/ThreatManager.hh +++ b/src/PLASMA/Solvers/component/ThreatManager.hh @@ -31,6 +31,8 @@ namespace EUROPA { std::string toString(const EntityId& entity) const; + bool noMoreFlaws(); + private: friend class ThreatIterator; void handleInitialize(); diff --git a/src/PLASMA/Solvers/component/UnboundVariableManager.cc b/src/PLASMA/Solvers/component/UnboundVariableManager.cc index 070f7bc25..cbb743769 100644 --- a/src/PLASMA/Solvers/component/UnboundVariableManager.cc +++ b/src/PLASMA/Solvers/component/UnboundVariableManager.cc @@ -198,6 +198,10 @@ namespace EUROPA { return os.str(); } + bool UnboundVariableManager::noMoreFlaws() { + return m_flawCandidates.empty(); + } + class UnboundVariableIterator : public FlawIterator { public: UnboundVariableIterator(UnboundVariableManager& manager) diff --git a/src/PLASMA/Solvers/component/UnboundVariableManager.hh b/src/PLASMA/Solvers/component/UnboundVariableManager.hh index f6d1b792a..9d2db553a 100644 --- a/src/PLASMA/Solvers/component/UnboundVariableManager.hh +++ b/src/PLASMA/Solvers/component/UnboundVariableManager.hh @@ -24,7 +24,7 @@ namespace EUROPA { IteratorId createIterator(); std::string toString(const EntityId& entity) const; - + bool noMoreFlaws(); private: friend class UnboundVariableIterator; diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index d1d34807b..6b6c900d9 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -193,14 +193,17 @@ class ComponentFactoryTests{ static bool testBasicAllocation(){ TestEngine testEngine(true); - TiXmlElement* configXml = initXml((getTestLoadLibraryPath() + "/ComponentFactoryTest.xml").c_str()); + TiXmlElement* configXml = + initXml((getTestLoadLibraryPath() + "/ComponentFactoryTest.xml").c_str()); for (TiXmlElement * child = configXml->FirstChildElement(); child != NULL; child = child->NextSiblingElement()) { - ComponentFactoryMgr* cfm = (ComponentFactoryMgr*)testEngine.getComponent("ComponentFactoryMgr"); - TestComponent * testComponent = static_cast(cfm->createInstance(*child)); + ComponentFactoryMgr* cfm = + (ComponentFactoryMgr*)testEngine.getComponent("ComponentFactoryMgr"); + TestComponent * testComponent = + static_cast(cfm->createInstance(*child)); delete testComponent; } @@ -1551,10 +1554,29 @@ class SolverTests { EUROPA_runTest(testDeletedFlaw); EUROPA_runTest(testDeleteAfterCommit); EUROPA_runTest(testSingleonGuardLoop); + EUROPA_runTest(testNoMoreFlawsAfterAddition); return true; } private: + static bool testNoMoreFlawsAfterAddition() { + TestEngine testEngine; + TiXmlElement* root = initXml( (getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), "SingletonLoop"); + TiXmlElement* child = root->FirstChildElement(); + + CPPUNIT_ASSERT(testEngine.playTransactions( (getTestLoadLibraryPath() + "/StaticCSP.nddl").c_str())); + Solver solver(testEngine.getPlanDatabase(), *child); + CPPUNIT_ASSERT(solver.solve()); + CPPUNIT_ASSERT(solver.noMoreFlaws()); + + testEngine.getPlanDatabase()->getClient()->createVariable("int", + IntervalIntDomain(0, 10), + "v5"); + CPPUNIT_ASSERT(!solver.noMoreFlaws()); + + return true; + } + /** * @brief Tests for an infinite loop when binding a singleton guard. @@ -2096,9 +2118,131 @@ class FlawIteratorTests { } }; + +class FlawManagerListener : public ConstraintEngineListener { + public: + FlawManagerListener(const ConstraintEngineId& ce, FlawManager& fm) + : ConstraintEngineListener(ce), m_fm(fm) {} + void notifyChanged(const ConstrainedVariableId& var, const DomainListener::ChangeType& change) { + m_fm.notifyChanged(var, change); + } + private: + FlawManager& m_fm; +}; + class FlawManagerTests { public: static bool test() { + EUROPA_runTest(testUnboundVariableNoMoreFlaws); + EUROPA_runTest(testThreatNoMoreFlaws); + EUROPA_runTest(testOpenConditionNoMoreFlaws); + return true; + } + static bool testUnboundVariableNoMoreFlaws() { + TestEngine testEngine; + TiXmlElement* root = initXml( (getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), "SingletonLoop"); + TiXmlElement* child = root->FirstChildElement()->FirstChildElement("UnboundVariableManager"); + Context ctx("foo"); + UnboundVariableManager m(*child); + + CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/StaticCSP.nddl").c_str())); + m.initialize(*child, testEngine.getPlanDatabase(), ctx.getId()); + FlawManagerListener listener(testEngine.getConstraintEngine(), m); + + CPPUNIT_ASSERT(!m.noMoreFlaws()); + Priority p = worstCasePriority() + 1; + std::list decisions; + for(DecisionPointId d = m.next(p); d.isValid(); d = m.next(p)) { + d->initialize(); + d->execute(); + CPPUNIT_ASSERT(testEngine.getConstraintEngine()->propagate()); + decisions.push_front(d); + p = worstCasePriority() + 1; + } + CPPUNIT_ASSERT(m.noMoreFlaws()); + + testEngine.getPlanDatabase()->getClient()->createVariable("int", + IntervalIntDomain(0, 10), + "v5"); + CPPUNIT_ASSERT(!m.noMoreFlaws()); + + for(std::list::iterator it = decisions.begin(); + it != decisions.end(); ++it) { + delete static_cast(*it); + } + delete root; + return true; + } + static bool testThreatNoMoreFlaws() { + TestEngine testEngine; + DbClientId client = testEngine.getPlanDatabase()->getClient(); + TiXmlElement* root = + initXml((getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), + "SimpleActivationSolver"); + TiXmlElement* child = + root->FirstChildElement()->FirstChildElement("ThreatManager"); + Context ctx("SimpleTokenSolverContext"); + ctx.put("horizonStart", 0); + ctx.put("horizonEnd", 100); + ThreatManager m(*child); + + CPPUNIT_ASSERT(testEngine.playTransactions((getTestLoadLibraryPath() + "/Model.nddl").c_str())); + ObjectId t = client->createObject("PredicateRoot", "foo"); + TokenId t0 = client->createToken("PredicateRoot.predicateD"); + TokenId t1 = client->createToken("PredicateRoot.predicateD"); + client->activate(t0); + client->activate(t1); + + m.initialize(*child, testEngine.getPlanDatabase(), ctx.getId()); + FlawManagerListener listener(testEngine.getConstraintEngine(), m); + + CPPUNIT_ASSERT(!m.noMoreFlaws()); + + client->constrain(t, t0, t1); + CPPUNIT_ASSERT(m.noMoreFlaws()); + + TokenId t2 = client->createToken("PredicateRoot.predicateD"); + client->activate(t2); + CPPUNIT_ASSERT(!m.noMoreFlaws()); + + delete root; + return true; + } + static bool testOpenConditionNoMoreFlaws() { + TestEngine testEngine; + TiXmlElement* root = initXml( (getTestLoadLibraryPath() + "/SolverTests.xml").c_str(), "GNATS_3196"); + TiXmlElement* child = root->FirstChildElement()->FirstChildElement("OpenConditionManager"); + Context ctx("foo"); + OpenConditionManager m(*child); + + CPPUNIT_ASSERT(testEngine.playTransactions( (getTestLoadLibraryPath() + "/OpenConditionFiltering.nddl").c_str())); + m.initialize(*child, testEngine.getPlanDatabase(), ctx.getId()); + FlawManagerListener listener(testEngine.getConstraintEngine(), m); + + + CPPUNIT_ASSERT(!m.noMoreFlaws()); + Priority p = worstCasePriority() + 1; + std::list decisions; + for(DecisionPointId d = m.next(p); d.isValid(); d = m.next(p)) { + d->initialize(); + d->execute(); + CPPUNIT_ASSERT(testEngine.getConstraintEngine()->propagate()); + decisions.push_front(d); + p = worstCasePriority() + 1; + } + CPPUNIT_ASSERT(m.noMoreFlaws()); + + testEngine.getPlanDatabase()->getClient()->createToken("HorizonFiltered.predicate1", + "testToken", + true, + false); + CPPUNIT_ASSERT(!m.noMoreFlaws()); + + for(std::list::iterator it = decisions.begin(); + it != decisions.end(); ++it) { + delete static_cast(*it); + } + delete root; return true; } }; From 71f6fad941ba8663963f70c7ac6c15e2d3b468ba Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 22 Sep 2014 21:17:50 +0000 Subject: [PATCH 022/149] Test for the GuardFilter/NotGuardFilter related to issue 69. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6752 23e1bc29-d954-0410-9766-47de34158ba0 --- .../Solvers/test/solvers-test-module.cc | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index 6b6c900d9..47b4570d4 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -36,6 +36,9 @@ #include +#include +#include + #ifdef near #undef near #endif @@ -53,6 +56,7 @@ using namespace EUROPA; using namespace EUROPA::SOLVERS; using namespace EUROPA::SOLVERS::HSTS; +using namespace boost; void registerTestElements(EngineId& engine); @@ -236,10 +240,56 @@ class FilterTests { EUROPA_runTest(testVariableFiltering); EUROPA_runTest(testTokenFiltering); EUROPA_runTest(testThreatFiltering); + EUROPA_runTest(testGuardFilter); return true; } private: + static bool testGuardFilter() { + TestEngine testEngine(true); + DbClientId client = testEngine.getPlanDatabase()->getClient(); + ObjectId obj = client->createObject("BacktrackTest", "filtered"); + TokenId tok = client->createToken("BacktrackTest.pred"); + client->activate(tok); + client->constrain(obj, tok, tok); + CPPUNIT_ASSERT_MESSAGE("Initially inconsistent", client->propagate()); + + const ConstrainedVariableSet& vars = + testEngine.getConstraintEngine()->getVariables(); + std::string filterStr(""); + scoped_ptr filterXml(initXml(filterStr)); + GuardFilter f(*filterXml); + NotGuardFilter g(*filterXml); + bool guardFound = false; + for(ConstrainedVariableSet::const_iterator it = vars.begin(); it != vars.end(); ++it) { + if((*it)->getName() == std::string("b")) { + CPPUNIT_ASSERT_MESSAGE(std::string("Should be a guard: ") + \ + (*it)->getName().toString(), + f.test(*it)); + CPPUNIT_ASSERT_MESSAGE(std::string("Should be a guard: ") + \ + (*it)->getName().toString(), + !g.test(*it)); + guardFound = true; + } + else if(starts_with((*it)->getName().toString(), "implicit") || + starts_with((*it)->getName().toString(), "ExprConstant_PSEUDO_VARIABLE")) { + //these *might* be guards, but might not. can't tell a priori, so skipping the + //test + } + else { + //everything else should be a guard + CPPUNIT_ASSERT_MESSAGE(std::string("Should not be a guard: ") + \ + (*it)->getName().toString(), + !f.test(*it)); + CPPUNIT_ASSERT_MESSAGE(std::string("Should not be a guard: ") + \ + (*it)->getName().toString(), + g.test(*it)); + } + } + CPPUNIT_ASSERT_MESSAGE("Failed to find any guards in the model.", guardFound); + return true; + } + static bool testRuleMatching() { TestEngine testEngine(true); From da85f6194bdc3fcda7df667345a498ce42185316 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 22 Sep 2014 21:50:52 +0000 Subject: [PATCH 023/149] Committed error check to "address" issue 134. More thought needs to be put into error handling with clients. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6753 23e1bc29-d954-0410-9766-47de34158ba0 --- src/PLASMA/PlanDatabase/base/Token.cc | 52 ++++++++++++++------------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/src/PLASMA/PlanDatabase/base/Token.cc b/src/PLASMA/PlanDatabase/base/Token.cc index 5e5cdd5ca..8cb89e306 100644 --- a/src/PLASMA/PlanDatabase/base/Token.cc +++ b/src/PLASMA/PlanDatabase/base/Token.cc @@ -314,30 +314,34 @@ namespace EUROPA{ check_error(ALWAYS_FAILS); } - void Token::doMerge(const TokenId& activeToken){ - check_error(isValid()); - check_error(isInactive()); - check_error(activeToken.isValid()); - check_error(activeToken->isActive()); - checkError(m_state->lastDomain().isMember(MERGED), "Not permitted to merge." << toString()); - check_error(getPlanDatabase()->getSchema()->isA(activeToken->getPredicateName(), m_predicateName), - "Cannot merge tokens with different predicates: " + - m_predicateName.toString() + ", " + activeToken->getPredicateName().toString()); - - m_state->setSpecified(MERGED); - m_unifyMemento = UnifyMementoId(new UnifyMemento(m_id, activeToken)); - m_activeToken = activeToken; - m_activeToken->addMergedToken(m_id); - - /** Send a message to all objects that it has been rejected **/ - const std::set& objects = getObject()->getBaseDomain().getValues(); - for(std::set::const_iterator it = objects.begin(); it!= objects.end(); ++it){ - ObjectId object = Entity::getTypedEntity(*it); - object->notifyMerged(m_id); - } - - m_planDatabase->notifyMerged(m_id); - } +void Token::doMerge(const TokenId& activeToken){ + check_error(isValid()); + check_error(isInactive()); + check_error(activeToken.isValid()); + check_error(activeToken->isActive()); + checkError(m_state->lastDomain().isMember(MERGED), + "Not permitted to merge." << toString()); + check_error(getPlanDatabase()->getSchema()->isA(activeToken->getPredicateName(), m_predicateName), + "Cannot merge tokens with different predicates: " + + m_predicateName.toString() + ", " + activeToken->getPredicateName().toString()); + checkError((isFact() && activeToken->isFact()) || true, + "Cannot merge fact " << toString() << " onto non-fact " << + activeToken->toString()); + + m_state->setSpecified(MERGED); + m_unifyMemento = UnifyMementoId(new UnifyMemento(m_id, activeToken)); + m_activeToken = activeToken; + m_activeToken->addMergedToken(m_id); + + /** Send a message to all objects that it has been rejected **/ + const std::set& objects = getObject()->getBaseDomain().getValues(); + for(std::set::const_iterator it = objects.begin(); it!= objects.end(); ++it){ + ObjectId object = Entity::getTypedEntity(*it); + object->notifyMerged(m_id); + } + + m_planDatabase->notifyMerged(m_id); +} void Token::split(){ check_error(isValid()); From b59aae475708cdde4382a41f5482fc2199b84c06 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 23 Sep 2014 20:05:09 +0000 Subject: [PATCH 024/149] src/Java/JavaUI/CMakeLists.txt: Comment cleanup, revised call to unjar src/PLASMA/System/CMakeLists.txt: Removed a superfluous message src/PLASMA/cmake/EuropaModule.cmake: Fixes to get Java building working on rivka. Factored out listing the contents of a jar file and greatly simplified the process. git-svn-id: https://europa-pso.googlecode.com/svn/PLASMA/trunk@6754 23e1bc29-d954-0410-9766-47de34158ba0 --- src/Java/JavaUI/CMakeLists.txt | 34 ++++++------- src/PLASMA/System/CMakeLists.txt | 1 - src/PLASMA/cmake/EuropaModule.cmake | 75 ++++++++++++++--------------- 3 files changed, 50 insertions(+), 60 deletions(-) diff --git a/src/Java/JavaUI/CMakeLists.txt b/src/Java/JavaUI/CMakeLists.txt index 44ed89f23..de410eed2 100644 --- a/src/Java/JavaUI/CMakeLists.txt +++ b/src/Java/JavaUI/CMakeLists.txt @@ -16,9 +16,10 @@ set(libjars lib/bsh-2.0b4.jar foreach(jar ${libjars}) set(classes "") - unjar(${jar}_unjarred ${CMAKE_CURRENT_SOURCE_DIR}/${jar} temp classes) -# message(STATUS ${classes}) - list(APPEND jarclasses ${classes}) + get_filename_component(jarname ${jar} NAME) + unjar(${jarname}_unjarred ${CMAKE_CURRENT_SOURCE_DIR}/${jar} temp contents) + # message(STATUS ${classes}) + list(APPEND jarcontents ${contents}) endforeach(jar) add_jar(PSUISwing @@ -110,26 +111,20 @@ add_jar(PSUISwing MANIFEST ${CMAKE_CURRENT_SOURCE_DIR}/META-INF/MANIFEST.SWING ) -# add_dependencies(PSUISwing ${jarclasses}) +foreach(f ${libjars}) + get_filename_component(jarname ${f} NAME) + add_dependencies(PSUISwing ${jarname}_unjarred) +endforeach(f) # foreach(f ${jarclasses}) -# add_custom_command(TARGET PSUISwing -# POST_BUILD #? -# COMMAND -# ${Java_JAR_EXECUTABLE} -uf PSUISwing.jar -C ${CMAKE_CURRENT_BINARY_DIR}/temp ${f} -# #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp -# ) +# add_dependencies(PSUISwing ${CMAKE_CURRENT_BINARY_DIR}/temp/${f}) # endforeach(f) -# add_custom_command(TARGET PSUISwing -# POST_BUILD #? -# COMMAND -# ${Java_JAR_EXECUTABLE} -uf PSUISwing.jar -C ${CMAKE_CURRENT_BINARY_DIR}/temp ${jarclasses} -# #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp -# ) -#string(REPLACE ";" "\n" classes_with_newlines ${jarclasses}) -foreach(f ${jarclasses}) +# add_dependencies(PSUISwing ${jarclasses}) + +file(REMOVE PSEngineAdditionalClasses) +foreach(f ${jarcontents}) file(APPEND PSEngineAdditionalClasses "${f}\n") endforeach(f) -#file(WRITE PSEngineAdditionalClasses ${jarclasses}) + add_custom_command(TARGET PSUISwing POST_BUILD #? COMMAND @@ -137,4 +132,5 @@ add_custom_command(TARGET PSUISwing #WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/temp ) + install_jar(PSUISwing ${EUROPA_ROOT}/dist/europa) \ No newline at end of file diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 9769df95a..49798bc75 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -80,7 +80,6 @@ add_jar(PSEngineGenerated include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) swig_add_module(PSEngine java base/PSEngine.i) -message(STATUS "!! ${System_FULL_DEPENDENCIES}") foreach(dep ${internal_dependencies}) add_common_module_include_dep(PSEngine ${dep}) target_link_libraries(PSEngine "${dep}${EUROPA_SUFFIX}") diff --git a/src/PLASMA/cmake/EuropaModule.cmake b/src/PLASMA/cmake/EuropaModule.cmake index 813caf3b9..290630caa 100644 --- a/src/PLASMA/cmake/EuropaModule.cmake +++ b/src/PLASMA/cmake/EuropaModule.cmake @@ -275,51 +275,46 @@ macro(declare_module name root_srcs base_srcs component_srcs test_srcs module_de FILES_MATCHING PATTERN "*.hh" PATTERN "*.h") endmacro(declare_module) -function(unjar target jar dest_dir classes) +function(list_jar jar contents) + set(jar_files "") + set(jar_files_ndir "") + set(jar_files_str "") + # message(STATUS ${Java_JAR_EXECUTABLE} tf ${jar}) execute_process( COMMAND ${Java_JAR_EXECUTABLE} tf ${jar} OUTPUT_VARIABLE jar_files_str RESULT_VARIABLE rv) string(REPLACE "\n" ";" jar_files_ndir ${jar_files_str}) - - set(jar_files "") - set(class_files "") - foreach(f ${jar_files_ndir}) - # set(fname "${dest_dir}/${f}") - set(fname "${f}") - list(APPEND jar_files ${fname}) - string(REGEX MATCH ".class$" classfile ${fname}) - #message(STATUS "File ${fname}") - if(classfile) - #message(STATUS "Class!") - string(REPLACE "\$" "\$\$" fname ${fname}) - list(APPEND class_files ${fname}) - endif(classfile) - endforeach(f) - set(classes ${class_files} PARENT_SCOPE) - #message(STATUS "Classes: ${classes}") - list(LENGTH class_files class_count) - if(class_count GREATER 0) - add_custom_command(OUTPUT ${class_files} - COMMAND ${Java_JAR_EXECUTABLE} - xf ${jar}; - #touch ${target} - WORKING_DIRECTORY ${dest_dir} - ) - else() - add_custom_command(OUTPUT ${jar_files} - COMMAND ${Java_JAR_EXECUTABLE} - xf ${jar}; - touch ${target} - WORKING_DIRECTORY ${dest_dir} - ) - endif(class_count GREATER 0) + foreach(fname ${jar_files_ndir}) + get_filename_component(n ${fname} NAME) + # message(STATUS ${n}) + if(NOT "${n}" STREQUAL "") + # message(STATUS ${n}) + list(APPEND jar_files ${fname}) + endif(NOT "${n}" STREQUAL "") + endforeach(fname) + list(REMOVE_ITEM jar_files "META-INF/MANIFEST.MF") + set(${contents} ${jar_files} PARENT_SCOPE) + + # list(REMOVE_ITEM jar_files_ndir "META-INF/") + # list(REMOVE_ITEM jar_files_ndir "META-INF/MANIFEST.MF") + # set(${contents} ${jar_files_ndir} PARENT_SCOPE) +endfunction(list_jar) + +function(unjar target jar dest_dir contents) + set(jar_contents "") + + list_jar(${jar} jar_contents) + + # message(STATUS ${jar_contents}) + set(${contents} ${jar_contents} PARENT_SCOPE) + add_custom_target(${target}) + add_custom_command( + TARGET ${target} + COMMAND ${Java_JAR_EXECUTABLE} + xf ${jar} + WORKING_DIRECTORY ${dest_dir} + ) - # set(all_classes "") - # foreach(f ${class_files}) - # string(REPLACE "\$" "\$\$" g ${f}) - #list(APPEND all_classes ${g}) - #endforeach(f) - #set(classes ${all_classes} PARENT_SCOPE) endfunction(unjar) \ No newline at end of file From ef5fa3446ca57e4fb5c2548e6d5fd572140a6ede Mon Sep 17 00:00:00 2001 From: Michael Vetter Date: Sat, 1 Nov 2014 10:58:30 +0100 Subject: [PATCH 025/149] Remove trailing whitespaces and tabs When reading your code for learning purposes I came across those not needed whitespaces. --- .../java/BlocksWorld/BlockHistoryEntry.java | 4 +- .../java/BlocksWorld/BlockWorld.java | 50 ++--- .../BlocksWorld/BlockWorldHistoryPanel.java | 46 ++--- .../BlocksWorld/BlockWorldSolverListener.java | 50 ++--- .../BlocksWorld/BlockWorldTableModel.java | 4 +- .../BlocksWorld/java/BlocksWorld/Main.java | 26 +-- examples/Light/java/Light/Main.java | 28 +-- examples/NQueens/java/NQueens/Main.java | 28 +-- .../NQueens/java/NQueens/NQueensPanel.java | 50 ++--- .../NQueens/java/NQueens/TSNQueensSolver.java | 106 +++++------ examples/Rover/java/Rover/Main.java | 28 +-- examples/Shopping/java/Shopping/Main.java | 28 +-- examples/UBO/java/UBO/ExhaustiveSolver.java | 106 +++++------ examples/UBO/java/UBO/HybridSolver.java | 30 +-- examples/UBO/java/UBO/IFlatIRelaxSolver.java | 166 ++++++++--------- examples/UBO/java/UBO/Main.java | 68 +++---- examples/UBO/java/UBO/PSResourceWrapper.java | 18 +- examples/UBO/java/UBO/PlanHistoryEntry.java | 10 +- examples/UBO/java/UBO/Precedence.java | 10 +- examples/UBO/java/UBO/RCPSPResource.java | 22 +-- examples/UBO/java/UBO/RCPSPSolver.java | 10 +- examples/UBO/java/UBO/RCPSPSolverBase.java | 78 ++++---- examples/UBO/java/UBO/RCPSPUtil.java | 42 ++--- examples/UBO/java/UBO/ResourceBase.java | 12 +- examples/UBO/java/UBO/ResourceProfile.java | 46 ++--- .../UBO/java/UBO/ResourceViolationInfo.java | 4 +- .../UBO/java/UBO/SolDistExhaustiveSolver.java | 172 +++++++++--------- examples/UBO/java/UBO/UBOSolverListener.java | 44 ++--- .../ops/ui/beanshell/swing/BeanShellView.java | 4 +- .../org/ops/ui/editor/model/OutlineNode.java | 2 +- .../ops/ui/editor/swing/ash/AshConsole.java | 6 +- .../ui/editor/swing/ash/ConsolePainter.java | 2 +- .../org/ops/ui/editor/swing/ash/Token.java | 2 +- .../ops/ui/editor/swing/ash/TokenMarker.java | 4 +- .../editor/swing/nddl/NddlAshInterpreter.java | 14 +- .../org/ops/ui/editor/swt/NddlEditor.java | 8 +- .../org/ops/ui/editor/swt/NddlScanner.java | 2 +- .../editor/swt/NddlToggleCommentHandler.java | 2 +- .../swt/NonRuleBasedDamagerRepairer.java | 8 +- .../org/ops/ui/filemanager/model/AstNode.java | 4 +- .../ui/filemanager/model/AstNodeTypes.java | 4 +- .../ops/ui/filemanager/model/ErrorRecord.java | 2 +- .../ops/ui/filemanager/model/FileModel.java | 2 +- .../model/unittesting/FileModelTest.java | 4 +- .../ui/gantt/model/EuropaGanttActivity.java | 14 +- .../ui/gantt/model/EuropaGanttResource.java | 12 +- .../ops/ui/gantt/model/IGanttActivity.java | 4 +- .../org/ops/ui/gantt/model/IGanttModel.java | 6 +- .../ops/ui/gantt/model/IGanttResource.java | 4 +- .../ops/ui/gantt/model/PSGanttActivity.java | 2 +- .../ui/gantt/model/PSGanttActivityImpl.java | 12 +- .../org/ops/ui/gantt/model/PSGanttModel.java | 6 +- .../ops/ui/gantt/model/PSGanttPSEModel.java | 44 ++--- .../org/ops/ui/gantt/swing/GanttView.java | 6 +- .../org/ops/ui/gantt/swing/LinePanel.java | 2 +- .../org/ops/ui/gantt/swing/PSEGantt.java | 148 +++++++-------- .../org/ops/ui/gantt/swing/PSGantt.java | 6 +- .../ui/gantt/swing/PSGanttColorProvider.java | 2 +- .../org/ops/ui/gantt/swing/ResourcePanel.java | 2 +- .../org/ops/ui/gantt/swing/TimelinePanel.java | 4 +- .../org/ops/ui/gantt/swing/TokenColor.java | 2 +- .../org/ops/ui/gantt/swing/TokenWidget.java | 2 +- .../org/ops/ui/gantt/swt/ActivityWidget.java | 14 +- .../org/ops/ui/gantt/swt/DetailsView.java | 62 +++---- .../org/ops/ui/gantt/swt/GanttView.java | 2 +- .../ops/ui/gantt/swt/GenericGanttView.java | 16 +- .../swt/ParameterTableContentProvider.java | 8 +- .../swt/ParameterTableLabelProvider.java | 10 +- .../org/ops/ui/gantt/swt/ResourcePanel.java | 2 +- .../org/ops/ui/gantt/swt/TimelinePanel.java | 4 +- .../org/ops/ui/gantt/swt/TokenColor.java | 2 +- .../org/ops/ui/gantt/swt/TokenSelection.java | 6 +- .../ui/main/swing/EuropaInternalFrame.java | 4 +- .../main/swing/FileNameExtensionFilter.java | 16 +- .../org/ops/ui/main/swing/PSComponent.java | 2 +- .../ops/ui/main/swing/PSComponentBase.java | 18 +- .../org/ops/ui/main/swing/PSDesktop.java | 88 ++++----- .../ops/ui/main/swing/PSMouseListener.java | 2 +- .../ui/main/swt/NddlConfigurationFields.java | 2 +- .../ops/ui/main/swt/NddlLaunchShortcut.java | 2 +- .../org/ops/ui/main/swt/NddlModelTab.java | 4 +- .../ops/ui/main/swt/NddlRunPerspective.java | 2 +- .../ui/mouse/swing/ActionDetailsPanel.java | 24 +-- .../ui/mouse/swing/ActionViolationsPanel.java | 20 +- .../ui/mouse/swing/MouseListenerPanel.java | 10 +- .../ui/rchart/model/PSResourceChartModel.java | 2 +- .../rchart/model/PSResourceChartPSEModel.java | 20 +- .../ui/rchart/swing/PSJFreeResourceChart.java | 70 +++---- .../ops/ui/rchart/swing/PSResourceChart.java | 4 +- .../ui/schemabrowser/model/SchemaModel.java | 4 +- .../schemabrowser/model/SchemaModelImpl.java | 44 ++--- .../ui/schemabrowser/model/SchemaNode.java | 12 +- .../model/SchemaSolverModel.java | 24 +-- .../schemabrowser/swing/SchemaTreeModel.java | 2 +- .../ui/schemabrowser/swing/SchemaView.java | 6 +- .../swt/SchemaContentProvider.java | 4 +- .../swt/SchemaLabelProvider.java | 2 +- .../ops/ui/schemabrowser/swt/SchemaView.java | 2 +- .../ops/ui/solver/model/SolverAdapter.java | 2 +- .../ops/ui/solver/model/SolverListener.java | 8 +- .../org/ops/ui/solver/model/SolverModel.java | 18 +- .../ui/solver/model/StepStatisticsRecord.java | 4 +- .../ops/ui/solver/model/TimeFormatHelper.java | 2 +- .../org/ops/ui/solver/swing/ConsoleView.java | 2 +- .../ui/solver/swing/OpenDecisionsPanel.java | 84 ++++----- .../ui/solver/swing/OpenDecisionsView.java | 2 +- .../ops/ui/solver/swing/PSSolverDialog.java | 140 +++++++------- .../solver/swing/PSSolverDialogListener.java | 2 +- .../org/ops/ui/solver/swing/PSSolverView.java | 6 +- .../org/ops/ui/solver/swt/DecisionsView.java | 6 +- .../org/ops/ui/solver/swt/SolverModelSWT.java | 2 +- .../ops/ui/solver/swt/SolverModelView.java | 2 +- .../ui/solver/swt/SolverModelViewImpl.java | 4 +- .../org/ops/ui/solver/swt/SolverView.java | 12 +- .../ui/solver/swt/StatisticsChartsView.java | 2 +- .../source/org/ops/ui/utils/Utilities.java | 18 +- .../source/org/ops/ui/utils/swing/Util.java | 54 +++--- src/Java/PSEngine/src/psengine/PSUtil.java | 28 +-- src/PLASMA/System/test/Java/RunGcov.java | 80 ++++---- 119 files changed, 1314 insertions(+), 1314 deletions(-) diff --git a/examples/BlocksWorld/java/BlocksWorld/BlockHistoryEntry.java b/examples/BlocksWorld/java/BlocksWorld/BlockHistoryEntry.java index d69c06da7..5da521636 100644 --- a/examples/BlocksWorld/java/BlocksWorld/BlockHistoryEntry.java +++ b/examples/BlocksWorld/java/BlocksWorld/BlockHistoryEntry.java @@ -6,7 +6,7 @@ public class BlockHistoryEntry protected Integer step_; protected String towers_; protected String opHistory_; - + public BlockHistoryEntry(Integer idx,Integer step,String towers,String opHistory) { idx_ = idx; @@ -14,7 +14,7 @@ public BlockHistoryEntry(Integer idx,Integer step,String towers,String opHistory towers_ = towers; opHistory_ = opHistory; } - + public Integer getIndex() { return idx_; } public Integer getStepNumber() { return step_; } public String getTowers() { return towers_; } diff --git a/examples/BlocksWorld/java/BlocksWorld/BlockWorld.java b/examples/BlocksWorld/java/BlocksWorld/BlockWorld.java index 3eff102ed..95b677404 100644 --- a/examples/BlocksWorld/java/BlocksWorld/BlockWorld.java +++ b/examples/BlocksWorld/java/BlocksWorld/BlockWorld.java @@ -10,22 +10,22 @@ public class BlockWorld { protected List> towers_; protected Map> blockToTower_; - + public BlockWorld() { towers_ = new Vector(); blockToTower_ = new HashMap(); } - + public List> getTowers() { return towers_; } - + public void addBlock(String name,String state,String bottomBlock, PSToken a) { //System.out.println("BlockWorld.add("+name+","+state+","+bottomBlock+")"); List tower = blockToTower_.get(name); if (tower == null) { - tower = new Vector(); + tower = new Vector(); towers_.add(tower); blockToTower_.put(name, tower); } @@ -35,16 +35,16 @@ public void addBlock(String name,String state,String bottomBlock, PSToken a) buf.append(name).append("=").append(state).append(bottomBlock != null ? "-"+bottomBlock : "") .append("(").append(getBounds(a)).append(")"); String towerValue = buf.toString(); - + if (state.equals("OnTable")) { - if (idx == -1) + if (idx == -1) tower.add(0,towerValue); else tower.set(idx,towerValue); } - + if (state.equals("On")) { - + // Add Bottom if we need to int bottomIdx = -1; for (int i=0;i tower : towers_) { buf.append("{"); for (int i=0;i 0) buf.append(","); - buf.append(tower.get(i)); + buf.append(tower.get(i)); } buf.append("} "); } - + return buf.toString(); } @@ -92,32 +92,32 @@ public static Object safeBound(int bound) return "-INF"; if (bound > INF) return "INF"; - + return bound; } public static String valueToString(PSVarValue v) { String type = v.getType().toString(); - + if ("STRING".equals(type)) return v.asString(); if ("INTEGER".equals(type)) - return new Integer(v.asInt()).toString(); + return new Integer(v.asInt()).toString(); if ("DOUBLE".equals(type)) return new Double(v.asDouble()).toString(); if ("BOOLEAN".equals(type)) return new Boolean(v.asBoolean()).toString(); if ("OBJECT".equals(type)) return v.asObject().getEntityName(); - + return "ERROR!!! UNKNOWN TYPE :" + type; } public static String varValueToString(PSVariable var) - { - if (var.isSingleton()) - return valueToString(var.getSingletonValue()); + { + if (var.isSingleton()) + return valueToString(var.getSingletonValue()); else if (var.isInterval()) { StringBuffer buf = new StringBuffer(); buf.append("[").append(var.getLowerBound()).append(",") @@ -136,20 +136,20 @@ else if (var.isEnumerated()) { buf.append("]"); return buf.toString(); } - + throw new RuntimeException("Unexpected ERROR: variable "+var.getEntityName()+" is not one of {Singleton, Interval, Enumeration}"); } public static String getBounds(PSToken t) { StringBuffer buf = new StringBuffer(); - + buf.append("[") .append(varValueToString(t.getStart())) .append(",") .append(varValueToString(t.getEnd())) .append("]"); - + return buf.toString(); - } + } } diff --git a/examples/BlocksWorld/java/BlocksWorld/BlockWorldHistoryPanel.java b/examples/BlocksWorld/java/BlocksWorld/BlockWorldHistoryPanel.java index dd9688d71..d75d94251 100644 --- a/examples/BlocksWorld/java/BlocksWorld/BlockWorldHistoryPanel.java +++ b/examples/BlocksWorld/java/BlocksWorld/BlockWorldHistoryPanel.java @@ -24,15 +24,15 @@ public class BlockWorldHistoryPanel protected int currentIdx_; protected JTextField gotoIdx_; protected JLabel status_; - + public BlockWorldHistoryPanel() { history_ = new Vector(); blockWorldHistory_ = new Vector(); - + historyTable_ = new JTable(); currentIdx_ = -1; - + JPanel buttonPanel = new JPanel(new FlowLayout()); JButton b; b = new JButton("<<"); b.addActionListener(this);b.setActionCommand("prev"); buttonPanel.add(b); @@ -40,29 +40,29 @@ public BlockWorldHistoryPanel() b = new JButton("Go To Step"); b.addActionListener(this);b.setActionCommand("goto"); buttonPanel.add(b); gotoIdx_ = new JTextField(6); buttonPanel.add(gotoIdx_); - + status_ = new JLabel(""); JPanel statusPanel = new JPanel(new FlowLayout()); statusPanel.add(status_); - + setLayout(new BorderLayout()); add(BorderLayout.NORTH,buttonPanel); - add(BorderLayout.CENTER,new JScrollPane(historyTable_)); + add(BorderLayout.CENTER,new JScrollPane(historyTable_)); add(BorderLayout.SOUTH,statusPanel); - + updateStatus(); } public List getHistory() { return history_; } public List getBlockWorldHistory() { return blockWorldHistory_; } - - protected void updateStatus() - { - status_.setText("Currently showing step "+(currentIdx_+1)+" out of "+blockWorldHistory_.size()+" available"); + + protected void updateStatus() + { + status_.setText("Currently showing step "+(currentIdx_+1)+" out of "+blockWorldHistory_.size()+" available"); } - - public void showStep(int step) - { + + public void showStep(int step) + { if (step>=0 && step rowIndex) diff --git a/examples/BlocksWorld/java/BlocksWorld/Main.java b/examples/BlocksWorld/java/BlocksWorld/Main.java index 98265df96..426a3d1de 100644 --- a/examples/BlocksWorld/java/BlocksWorld/Main.java +++ b/examples/BlocksWorld/java/BlocksWorld/Main.java @@ -6,14 +6,14 @@ import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; -class Main +class Main { protected static PSEngine psEngine_; - - public static void main(String args[]) + + public static void main(String args[]) { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); @@ -29,7 +29,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { @@ -42,28 +42,28 @@ protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "BlocksWorld_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } + } } diff --git a/examples/Light/java/Light/Main.java b/examples/Light/java/Light/Main.java index ec303c835..f4731a0db 100644 --- a/examples/Light/java/Light/Main.java +++ b/examples/Light/java/Light/Main.java @@ -6,20 +6,20 @@ import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; -class Main +class Main { protected static PSEngine psEngine_; - - public static void main(String args[]) + + public static void main(String args[]) { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); - + if(args.length > 2 && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); @@ -29,7 +29,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { @@ -42,28 +42,28 @@ protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "Light_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } + } } diff --git a/examples/NQueens/java/NQueens/Main.java b/examples/NQueens/java/NQueens/Main.java index f83ad6a2c..6d356f606 100644 --- a/examples/NQueens/java/NQueens/Main.java +++ b/examples/NQueens/java/NQueens/Main.java @@ -6,20 +6,20 @@ import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; -class Main +class Main { protected static PSEngine psEngine_; - - public static void main(String args[]) + + public static void main(String args[]) { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); - + if(args.length > 2 && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); @@ -29,7 +29,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { @@ -42,28 +42,28 @@ protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "NQueens_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } + } } diff --git a/examples/NQueens/java/NQueens/NQueensPanel.java b/examples/NQueens/java/NQueens/NQueensPanel.java index 5ff1af285..c727aa95e 100644 --- a/examples/NQueens/java/NQueens/NQueensPanel.java +++ b/examples/NQueens/java/NQueens/NQueensPanel.java @@ -11,7 +11,7 @@ import psengine.*; -public class NQueensPanel +public class NQueensPanel extends MouseAdapter implements TSNQueensSolver.SolverObserver { @@ -25,9 +25,9 @@ public class NQueensPanel protected List solutions_; protected int curSolution_; protected JButton nextBtn_,prevBtn_; - + public NQueensPanel(PSEngine psengine, - int queenCnt, + int queenCnt, JTextArea mouseInfo) { createUIPanel(psengine,queenCnt,mouseInfo); @@ -36,9 +36,9 @@ public NQueensPanel(PSEngine psengine, solutions_ = new Vector(); curSolution_ = -1; } - + public JPanel getUIPanel() { return uiPanel_; } - + public void createUIPanel(PSEngine psengine,int queenCnt, JTextArea mouseInfo) { uiPanel_ = new JPanel(new BorderLayout()); @@ -65,24 +65,24 @@ public void createUIPanel(PSEngine psengine,int queenCnt, JTextArea mouseInfo) prevBtn_.setEnabled(false); bottomPanel.add(prevBtn_); bottomPanel.add(nextBtn_); - + solverPanel.add(BorderLayout.NORTH,topPanel); solverPanel.add(BorderLayout.CENTER,solverBoard_); solverPanel.add(BorderLayout.SOUTH,bottomPanel); - + tabbedPane_ = new JTabbedPane(); tabbedPane_.addTab("Current State",new NQueensBoard(psengine,queenCnt,mouseInfo,false)); tabbedPane_.addTab("Solver",solverPanel); - uiPanel_.add(tabbedPane_); + uiPanel_.add(tabbedPane_); } - + public void mouseClicked(MouseEvent e) { try { - if (e.getSource()==solveBtn_) { + if (e.getSource()==solveBtn_) { SolverRunner handler = new SolverRunner(); - handler.start(); + handler.start(); } if (e.getSource()==nextBtn_) { setCurrentSolution(curSolution_+1); @@ -94,12 +94,12 @@ public void mouseClicked(MouseEvent e) catch (Exception ex) { throw new RuntimeException(ex); } - } - + } + class SolverRunner extends Thread { - public void run() + public void run() { solveBtn_.setEnabled(false); tabbedPane_.setEnabledAt(0,false); @@ -107,15 +107,15 @@ public void run() solver_.solve(maxIter); tabbedPane_.setEnabledAt(0,true); solveBtn_.setEnabled(true); - } + } } - public void iterationCompleted(int iteration) + public void iterationCompleted(int iteration) { SwingUtilities.invokeLater(new Updater1(iteration)); } - public void newSolutionFound(int iteration, List queenPositions, List queenViolations) + public void newSolutionFound(int iteration, List queenPositions, List queenViolations) { solutions_.add(new Object[]{new Integer(iteration),queenPositions,queenViolations}); SwingUtilities.invokeLater(new Updater2()); @@ -125,7 +125,7 @@ protected void setCurrentSolution(int i) { if (i >= solutions_.size() || i < 0) return; - + curSolution_=i; if (curSolution_==solutions_.size()-1) @@ -140,22 +140,22 @@ protected void setCurrentSolution(int i) solverBoard_.setSolution((Object[])solutions_.get(curSolution_)); } - + class Updater1 implements Runnable { int iteration_; - + public Updater1(int i) { iteration_ = i; } - + public void run() { - iterationCount_.setText("Iteration : "+iteration_); - } + iterationCount_.setText("Iteration : "+iteration_); + } } - + class Updater2 implements Runnable { public void run() { setCurrentSolution(solutions_.size()-1); - } + } } } diff --git a/examples/NQueens/java/NQueens/TSNQueensSolver.java b/examples/NQueens/java/NQueens/TSNQueensSolver.java index b6a14906f..f48dba2c1 100644 --- a/examples/NQueens/java/NQueens/TSNQueensSolver.java +++ b/examples/NQueens/java/NQueens/TSNQueensSolver.java @@ -21,16 +21,16 @@ public class TSNQueensSolver protected List observers_; protected int bestIter_; protected double bestCost_; - + public interface SolverObserver { public void iterationCompleted(int iteration); public void newSolutionFound(int iteration,List queenPositions,List queenViolations); } - + public TSNQueensSolver(int n,PSEngine engine) { - psengine_ = engine; + psengine_ = engine; tabuList_ = new HashMap(); queenCnt_ = n; observers_ = new Vector(); @@ -38,22 +38,22 @@ public TSNQueensSolver(int n,PSEngine engine) public void addObserver(SolverObserver o) { observers_.add(o); } public void removeObserver(SolverObserver o) { observers_.remove(o); } - + void notifyIterationCompleted(int iteration) { - dbgout(iteration+":"+queensToString()); + dbgout(iteration+":"+queensToString()); for (int i=0;i queenValues = new Vector(); List queenViolations = new Vector(); - - PSVariableList l = psengine_.getGlobalVariables(); - + + PSVariableList l = psengine_.getGlobalVariables(); + for (int i=0;i maxViolation) { maxVar = i; maxViolation = v.getViolation(); } - } - + } + return l.get(maxVar); } @@ -116,13 +116,13 @@ static class Move { public int slot_; public double violation_; - + public Move(int slot,double violation) { slot_ = slot; violation_ = violation; } - public int compareTo(Object obj) + public int compareTo(Object obj) { Move rhs = (Move)obj; @@ -130,15 +130,15 @@ public int compareTo(Object obj) return -1; else if (violation_ > rhs.violation_) return 1; - else + else return 0; - } + } } - + SortedSet getMoves(PSVariable queen,int curPos) { SortedSet moves = new TreeSet(); - + for (int i=0;i getMoves(PSVariable queen,int curPos) moves.add(new Move(i,v)); } } - + return moves; } public void solve(int maxIter) { init(); - + for (int i=0;psengine_.getViolation() > 0 && i < maxIter;i++) { PSVariable queenToMove = getQueenWithMaxViolation(); int curPos = queenToMove.getSingletonValue().asInt(); - + boolean moved = false; - SortedSet moves = getMoves(queenToMove,curPos); + SortedSet moves = getMoves(queenToMove,curPos); for (Move m : moves) { moved = makeMove(queenToMove,curPos,m,false); if (moved) break; } - - if (!moved) + + if (!moved) makeMove(queenToMove,curPos,moves.first(),true); - - checkSolution(); // See if we have a new best solution + + checkSolution(); // See if we have a new best solution notifyIterationCompleted(curIteration_++); - - if (curIteration_-bestIter_ > 50) + + if (curIteration_-bestIter_ > 50) restart(); } } - + protected void checkSolution() { double cost = psengine_.getViolation(); @@ -185,25 +185,25 @@ protected void checkSolution() bestCost_ = cost; bestIter_ = curIteration_; notifyNewSolutionFound(curIteration_); - } + } } - + void addToTabuList(PSVariable queenToMove,int orig,int dest) { String key = queenToMove.getEntityName() + "_" +orig+"_"+dest; - tabuList_.put(key,curIteration_+tabuTenure_); + tabuList_.put(key,curIteration_+tabuTenure_); } - + boolean isTabu(PSVariable queenToMove,int orig,int dest) { String key = queenToMove.getEntityName() + "_" +orig+"_"+dest; Integer iteration = (Integer)tabuList_.get(key); if (iteration == null) return false; - + return (iteration.intValue() > curIteration_); } - + boolean makeMove(PSVariable queenToMove,int curPos,Move m,boolean force) { if (force) @@ -212,18 +212,18 @@ boolean makeMove(PSVariable queenToMove,int curPos,Move m,boolean force) if (force || !isTabu(queenToMove,curPos,m.slot_)) { PSVarValue value = PSVarValue.getInstance(m.slot_); queenToMove.specifyValue(value); - dbgout("Moved queen "+queenToMove.getEntityName()+" from "+curPos+" to "+m.slot_); + dbgout("Moved queen "+queenToMove.getEntityName()+" from "+curPos+" to "+m.slot_); addToTabuList(queenToMove,curPos,m.slot_); return true; } - + return false; } - + String queensToString() { StringBuffer buf = new StringBuffer(); - + buf.append("{"); for (int i=0; i0) @@ -232,8 +232,8 @@ String queensToString() } buf.append("}"); buf.append(" violation:").append(psengine_.getViolation()); - + return buf.toString(); - } + } } diff --git a/examples/Rover/java/Rover/Main.java b/examples/Rover/java/Rover/Main.java index 31f6bc415..dc60f5303 100644 --- a/examples/Rover/java/Rover/Main.java +++ b/examples/Rover/java/Rover/Main.java @@ -6,20 +6,20 @@ import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; -class Main +class Main { protected static PSEngine psEngine_; - - public static void main(String args[]) + + public static void main(String args[]) { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); - + if(args.length > 2 && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); @@ -29,7 +29,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { @@ -42,28 +42,28 @@ protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "Rover_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } + } } diff --git a/examples/Shopping/java/Shopping/Main.java b/examples/Shopping/java/Shopping/Main.java index 44d471293..7f2e6dac0 100644 --- a/examples/Shopping/java/Shopping/Main.java +++ b/examples/Shopping/java/Shopping/Main.java @@ -6,20 +6,20 @@ import org.ops.ui.main.swing.PSDesktop; import bsh.Interpreter; -class Main +class Main { protected static PSEngine psEngine_; - - public static void main(String args[]) + + public static void main(String args[]) { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); - + if(args.length > 2 && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); @@ -29,7 +29,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { @@ -42,28 +42,28 @@ protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "Shopping_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } + } } diff --git a/examples/UBO/java/UBO/ExhaustiveSolver.java b/examples/UBO/java/UBO/ExhaustiveSolver.java index 41d857f7d..dd7b895e6 100644 --- a/examples/UBO/java/UBO/ExhaustiveSolver.java +++ b/examples/UBO/java/UBO/ExhaustiveSolver.java @@ -5,7 +5,7 @@ * This is an exhaustive solver used by the Hybrid solver, it uses : * - The incoming precedenceOracle to guide precedence selection at each decision point * - the incoming upper bound to prune the search tree faster. - * TODO: this was a very quick implementation to try the hybrid idea, it doesn't scale very well. + * TODO: this was a very quick implementation to try the hybrid idea, it doesn't scale very well. * use ideas from best performing B&B solvers for this problem, combined with the oracle and strengthened bound, it should kick ass. */ import java.util.List; @@ -19,27 +19,27 @@ import psengine.util.SimpleTimer; public class ExhaustiveSolver - extends RCPSPSolverBase + extends RCPSPSolverBase { List decisionStack_ = new Vector(); int lowerBound_; int upperBound_; SortedSet precedenceOracle_; DecisionPoint curDP_; - + public ExhaustiveSolver() - { + { } - + public void solve( - PSEngine psengine, - long timeout, + PSEngine psengine, + long timeout, int bound, - boolean usePSResources) + boolean usePSResources) { // TODO: get this to work solve(psengine,timeout,bound,Integer.MAX_VALUE,null,null,null); - } + } public void solve( PSEngine psengine, @@ -54,7 +54,7 @@ public void solve( init(psengine,timeout,lowerBound,upperBound,activities,resources,precedenceOracle); doSolve(); } - + protected void doSolve() { for (;;) { @@ -78,29 +78,29 @@ protected void doSolve() bestSolution_.clear(); bestSolution_.addAll(precedences_); timeToBest_ = timer_.getElapsed(); - RCPSPUtil.dbgout("ExhaustiveSolver found new best makespan "+bestMakespan_+" "+getSolutionAsString()); - } + RCPSPUtil.dbgout("ExhaustiveSolver found new best makespan "+bestMakespan_+" "+getSolutionAsString()); + } // if upper and lower bound cross, we're done if (upperBound_ <= lowerBound_) { doSolveFinished("Bounds crossed"); break; - } + } if (decisionStack_.isEmpty()) { doSolveFinished("exhausted"); break; } - else + else doBacktrack("Backtracking after finding solution"); } else { if (curDP_.hasNext()) { executeDecision(curDP_); - if (psengine_.getViolation() > 0) + if (psengine_.getViolation() > 0) doBacktrack("Backtracking because of violation"); - else if (getMakespan() > upperBound_) + else if (getMakespan() > upperBound_) doBacktrack("Backtracking because of upper bound "+getMakespan()+" vs. "+upperBound_); } else if (decisionStack_.isEmpty()) { @@ -111,9 +111,9 @@ else if (decisionStack_.isEmpty()) { doBacktrack("Backtracking because decision point exhausted choices"); } } - } + } } - + protected void doSolveFinished(String msg) { timer_.stop(); @@ -124,7 +124,7 @@ protected void doSolveFinished(String msg) restoreBestSolution(); resetState(); } - + public void init( PSEngine psengine, long timeout, @@ -135,7 +135,7 @@ public void init( List precedenceOracle) { timer_ = new SimpleTimer(); - timer_.start(); + timer_.start(); psengine_ = psengine; timeout_ = timeout; @@ -143,44 +143,44 @@ public void init( resources_ = resources; lowerBound_ = lowerBound; upperBound_ = upperBound; - + precedenceOracle_ = new TreeSet(); for (Precedence p : precedenceOracle) precedenceOracle_.add(p.toString()); - + resetSolution(); resetState(); } - + void resetState() { - curDP_ = null; + curDP_ = null; } - + int lastIdx_ = 0; - + protected DecisionPoint getNextDecisionPoint() { double lowestLevel = Double.MAX_VALUE; Resource maxViolatedResource = null; int maxViolatedTime = Integer.MIN_VALUE; - + int start = lastIdx_; for (int i=lastIdx_;;) { Resource r = resources_.get(i); ResourceViolationInfo rvi = r.getMaxViolation(); - + if ((rvi.level < lowestLevel) && (rvi.level < 0)) { lowestLevel = rvi.level; maxViolatedResource = r; maxViolatedTime = rvi.time; } - + i = (i+1) % resources_.size(); if (i == start) break; - } - + } + if (maxViolatedResource == null) { //RCPSPUtil.dbgout("No violations found!"); return null; @@ -188,27 +188,27 @@ protected DecisionPoint getNextDecisionPoint() else return new DecisionPoint(maxViolatedResource,maxViolatedTime); } - + protected void executeDecision(DecisionPoint dp) { decisionStack_.add(dp); - dp.execute(); + dp.execute(); curDP_ = null; } - + protected void doBacktrack(String reason) { curDP_ = decisionStack_.remove(decisionStack_.size()-1); - curDP_.undo(); + curDP_.undo(); //RCPSPUtil.dbgout(reason+" new stack size:"+decisionStack_.size()); } - + protected class DecisionPoint { TreeSet choices_; SortedSet executedChoices_; Precedence lastExecutedChoice_; - + public DecisionPoint(Resource r, int t) { choices_ = new TreeSet(); @@ -216,55 +216,55 @@ public DecisionPoint(Resource r, int t) if (conflictSet.size() < 2) RCPSPUtil.dbgout("ERROR!!: conflictSet size is :"+conflictSet.size()); - + for (int i=0;i oracle = new Vector(); oracle.addAll(ifirSolver_.getBestSolution()); - ifirSolver_.undoSolve(); - + ifirSolver_.undoSolve(); + exhSolver_ = new ExhaustiveSolver(); exhSolver_.solve( psengine, @@ -63,7 +63,7 @@ public void solve(PSEngine psengine, ifirSolver_.getActivityMap(), ifirSolver_.getResources(), oracle - ); + ); timer_.stop(); if (exhSolver_.getBestMakespan() < Integer.MAX_VALUE) lastSolver_ = exhSolver_; diff --git a/examples/UBO/java/UBO/IFlatIRelaxSolver.java b/examples/UBO/java/UBO/IFlatIRelaxSolver.java index 2fc692cfb..45d9636e7 100644 --- a/examples/UBO/java/UBO/IFlatIRelaxSolver.java +++ b/examples/UBO/java/UBO/IFlatIRelaxSolver.java @@ -13,47 +13,47 @@ import psengine.util.SimpleTimer; /* - * This is a solver based on the Iterative flattening and relaxation algorithm. + * This is a solver based on the Iterative flattening and relaxation algorithm. * It has been enhanced to be able to deal with general min/max precedence constraints */ -public class IFlatIRelaxSolver - extends RCPSPSolverBase +public class IFlatIRelaxSolver + extends RCPSPSolverBase { int curIteration_ = 0; - int nbStable_ = 0; + int nbStable_ = 0; int maxStable_ = 10000; int makespanBound_; - + boolean usePSResources_; Set criticalPath_; Map noGoods_; boolean hasViolations_; - + public void solve(PSEngine psengine, long timeout, // in msecs - int bound, + int bound, boolean usePSResources) { init(psengine,timeout,bound,usePSResources); - + for (int i=0; true ; i++) { flatten(); updateSolution(i); updateCriticalPrecedences(); - + if ((nbStable_ > maxStable_) || (bestMakespan_ <= makespanBound_)) break; - + if (timer_.getElapsed() > timeout) { timedOut_ = true; break; } - + relax(); curIteration_++; - } + } restoreBestSolution(); timer_.stop(); @@ -62,7 +62,7 @@ public void solve(PSEngine psengine, } public boolean timedOut() { return timedOut_; } - + protected Resource makeResource(PSResource r,int capacity) { if (usePSResources_) @@ -70,23 +70,23 @@ protected Resource makeResource(PSResource r,int capacity) else return new RCPSPResource(psengine_,r,capacity); } - + protected void init(PSEngine psengine,long timeout,int bound, boolean usePSResources) { timer_ = new SimpleTimer(); timer_.start(); - + timeout_ = timeout; timedOut_ = false; timeToBest_=timeout; - + psengine_ = psengine; makespanBound_ = bound; usePSResources_ = usePSResources; - + List res = PSUtil.toResourceList(psengine.getObjectsByType("CapacityResource")); resources_ = new Vector(); - + for (PSResource r : res) { PSResourceProfile prof = r.getCapacity(); int t = prof.getTimes().get(0); @@ -94,7 +94,7 @@ protected void init(PSEngine psengine,long timeout,int bound, boolean usePSResou resources_.add(makeResource(r,capacity)); //RCPSPUtil.dbgout("capacity for resource "+r.getName()+" is "+capacity); } - + PSTokenList tokens = psengine.getTokens(); activities_ = new TreeMap(); for (int i=0;i(); noGoods_ = new HashMap(); - + curIteration_ = 0; nbStable_ = 0; - + resetSolution(); // Completely relax finish time PSVariable v = psengine_.getVariableByName("maxDuration"); - v.specifyValue(PSVarValue.getInstance(100000)); + v.specifyValue(PSVarValue.getInstance(100000)); } public void flatten() { hasViolations_ = true; boolean addedConstraint = true; - + while (hasViolations_) { hasViolations_ = false; addedConstraint = false; for (Resource r : resources_) { //RCPSPUtil.dbgout("Before flatten() step : "+r.toString()); - + ResourceViolationInfo rvi = r.getMaxViolation(); int t = rvi.time; - if (t >= 0) { + if (t >= 0) { hasViolations_ = true; - if (addPrecedenceConstraint(r,t)) + if (addPrecedenceConstraint(r,t)) addedConstraint = true; } - //RCPSPUtil.dbgout("After flatten() step : "+r.toString()); + //RCPSPUtil.dbgout("After flatten() step : "+r.toString()); } - + if (!addedConstraint) break; - + if (timer_.getElapsed() > timeout_) { timedOut_ = true; break; - } + } } - + //if (hasViolations_) - // RCPSPUtil.dbgout("WARNING:unable to remove all violations"); + // RCPSPUtil.dbgout("WARNING:unable to remove all violations"); //RCPSPUtil.dbgout("flatten() finished "+timer_.getElapsedString()); } - + public void relax() { - double probOfDeletion = 0.3; + double probOfDeletion = 0.3; int before = precedences_.size(); - + boolean removed = false; psengine_.setAutoPropagation(false); @@ -165,52 +165,52 @@ public void relax() List precs = new Vector(); precs.addAll(precedences_); for (Precedence p : precs) { - if (p.isCritical && (Math.random() < probOfDeletion)) { - removePrecedence(p); + if (p.isCritical && (Math.random() < probOfDeletion)) { + removePrecedence(p); removed = true; } - + if (timer_.getElapsed() > timeout_) { timedOut_ = true; break; - } + } } - + // make sure we remove at least one precedence if (!removed) { for (Precedence p : precs) { if (p.isCritical) { - removePrecedence(p); - break; + removePrecedence(p); + break; } } } - psengine_.setAutoPropagation(true); - + psengine_.setAutoPropagation(true); + //RCPSPUtil.dbgout("Removed "+(before-precedences_.size())+" out of "+before+" precedences"); //RCPSPUtil.dbgout("after relax. makespan (current,best)=("+getMakespan()+","+bestMakespan_+")"); //RCPSPUtil.dbgout("relax() finished "+timer_.getElapsedString()); } - + /* * Try to fix capacity violation on resource r at time t by adding a precedence constraint */ protected boolean addPrecedenceConstraint(Resource r,int t) - { + { List conflictSet = r.getConflictSet(t); - + if (conflictSet.size() < 2) { RCPSPUtil.dbgout(r.getName()+": conflict set has less than 2 elements, bailing out without adding precedence constraint"); return false; } - + TreeSet candidates = new TreeSet(); - + // look for the pair of tokens with max(succ.LatestStart-pred.EarliestFinish) for (int i=0;i 0) { - removePrecedence(p); - addNoGood(p.pred,p.succ); // this can happen because of the max distance constraints, add a no-good - } + removePrecedence(p); + addNoGood(p.pred,p.succ); // this can happen because of the max distance constraints, add a no-good + } else return true; } - + //RCPSPUtil.dbgout("WARNING!: for "+r.getName()+" could not find activity pair with positive slack, bailing out without adding precedence constraint"); return false; } - + String getNoGoodKey(PSToken pred,PSToken succ) { int actPred = RCPSPUtil.getActivity(pred); int actSucc = RCPSPUtil.getActivity(succ); - return actPred + "<" + actSucc; + return actPred + "<" + actSucc; } - + int tabuTenure_ = 1; - + void addNoGood(PSToken pred,PSToken succ) { String key = getNoGoodKey(pred,succ); - noGoods_.put(key,curIteration_+tabuTenure_); + noGoods_.put(key,curIteration_+tabuTenure_); //RCPSPUtil.dbgout(curIteration_+" added noGood:{"+key+"}"); } - + boolean isNoGood(PSToken pred,PSToken succ) { String key = getNoGoodKey(pred,succ); Integer iteration = noGoods_.get(key); - + if (iteration == null) return false; - + return (iteration.intValue() > curIteration_); } - + protected void addPrecedence(Precedence p) { //RCPSPUtil.dbgout("adding {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); @@ -275,15 +275,15 @@ protected void removePrecedence(Precedence p) //RCPSPUtil.dbgout("removing {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); p.res.removePrecedence(p.pred,p.succ); precedences_.remove(p); - //RCPSPUtil.dbgout("removed {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); + //RCPSPUtil.dbgout("removed {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); } - + protected void updateSolution(int iteration) - { + { int newMakespan = getMakespan(); String violationMsg = (hasViolations_ ? " with violations" : ""); //RCPSPUtil.dbgout("Iteration "+iteration+": found makespan "+newMakespan+violationMsg); - + if (newMakespan < bestMakespan_ && !hasViolations_) { bestMakespan_ = newMakespan; bestSolution_.clear(); @@ -296,36 +296,36 @@ protected void updateSolution(int iteration) nbStable_++; } } - - public SortedMap getActivityMap() { return activities_; } + + public SortedMap getActivityMap() { return activities_; } /* (non-Javadoc) * @see UBO.RCPSPSolver#getActivities() */ - + protected void updateCriticalPrecedences() { // TODO: this only works if we're working with a solution that doesn't have any temporal violations /* int savedUb = RCPSPUtil.getUb(getProjectFinish()); - + // TODO: mark activities on the critical path - for (Precedence p : precs) { + for (Precedence p : precs) { if (criticalPath_.contains(pred.getKey) || criticalPath_.contains(pred.getKey)) p.isCritical = true; else p.isCritical = false; - } - */ + } + */ } - + public String printResources() { StringBuffer buf = new StringBuffer(); - + for (Resource r : resources_) { buf.append(r.toString()).append("\n"); } - - return buf.toString(); - } + + return buf.toString(); + } } diff --git a/examples/UBO/java/UBO/Main.java b/examples/UBO/java/UBO/Main.java index 4fa9fe9b4..facc56e64 100644 --- a/examples/UBO/java/UBO/Main.java +++ b/examples/UBO/java/UBO/Main.java @@ -13,7 +13,7 @@ class Main { protected static PSEngine psEngine_; - + public static void main(String args[]) { if ((args.length >= 4) && !(args[3].equals(""))) { @@ -21,13 +21,13 @@ public static void main(String args[]) } else { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); psEngine_ = PSEngine.makeInstance(); psEngine_.start(); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); loadCustomCode(debugMode); - + if((args.length >= 3) && args[2].equals("nogui")) { Interpreter bshInterpreter_ = new bsh.Interpreter(); try { @@ -36,7 +36,7 @@ public static void main(String args[]) } catch (Exception e) { throw new RuntimeException(e); - } + } } else { PSDesktop d = PSDesktop.makeInstance(psEngine_,args); @@ -44,50 +44,50 @@ public static void main(String args[]) } } } - + protected static void loadCustomCode(String debugMode) { //Load module with any custom code if it exists: String libName = "UBO_" + debugMode; - String fullLibName = LibraryLoader.getResolvedName(libName); + String fullLibName = LibraryLoader.getResolvedName(libName); if(fullLibName == null) { // Run 'make' to compile the library if you need it: - System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); + System.out.println("INFO: Custom library " + libName + " wasn't found and won't be loaded."); } else { // WARNING: Shared library loaded twice (see ticket #164) System.load(fullLibName); psEngine_.loadModule(fullLibName); - } + } } - - - static class ShutdownHook extends Thread + + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { psEngine_.shutdown(); } - } - - + } + + public static void runBatchTest(String args[]) { try { String debugMode = args[0]; String test = args[3]; Integer bound = new Integer(args[4]); - long timeoutMsecs = (new Integer(args[5])).intValue() * 1000; + long timeoutMsecs = (new Integer(args[5])).intValue() * 1000; String solver = args[6]; System.out.println("Running batch test: "+debugMode+" "+test+" "+bound+" "+timeoutMsecs+" "+solver); - LibraryLoader.loadLibrary("System_"+debugMode); + LibraryLoader.loadLibrary("System_"+debugMode); PSEngine engine = PSEngine.makeInstance(); engine.start(); String nddlModel = "UBO-gen-initial-state.nddl"; @@ -102,21 +102,21 @@ else if ("Hybrid".equals(solver)) else throw new RuntimeException("Unknown solver:"+solver); - //engine.shutdown(); TODO: this is causing problems + //engine.shutdown(); TODO: this is causing problems } catch (Exception e) { - throw new RuntimeException(e); + throw new RuntimeException(e); } - } - + } + public static void runBuiltInSolver(PSEngine engine,String solverName, String test,Integer bound, long timeoutMsecs) { PSVariable v = engine.getVariableByName("maxDuration"); v.specifyValue(PSVarValue.getInstance(bound)); PSSolver solver = engine.createSolver("PlannerConfig.xml"/*config*/); - solver.configure(0/*horizonStart*/,1000/*horizonEnd*/); - + solver.configure(0/*horizonStart*/,1000/*horizonEnd*/); + SimpleTimer timer = new SimpleTimer(); timer.start(); boolean timedOut = false; @@ -128,7 +128,7 @@ public static void runBuiltInSolver(PSEngine engine,String solverName, String te } } timer.stop(); - + // Save results // test-name bound best-makespan time-in-msecs solution stepCount int makespan = ((timedOut || solver.isExhausted()) ? 0 : bound); // TODO: this could be lower, ground solution and find out @@ -141,17 +141,17 @@ public static void runBuiltInSolver(PSEngine engine,String solverName, String te //.append(s.getSolutionAsString()) // TODO: extract solution .append(solver.getStepCount()).append(separator) .append("\n"); - - writeToFile("Solver-"+solverName+"-"+timeoutMsecs+".txt",buf.toString()); + + writeToFile("Solver-"+solverName+"-"+timeoutMsecs+".txt",buf.toString()); } public static void runRCPSPSolver(PSEngine engine,RCPSPSolver s, String test,Integer bound, long timeoutMsecs) - { + { // TODO: since this is randomized, run several times an get avg boolean usePSResources = false; // TODO: eventually switch to true s.solve(engine,timeoutMsecs,bound,usePSResources); //RCPSPUtil.ground(s.getActivities()); - + // Save results // test-name bound best-makespan time-in-msecs solution int makespan = (s.getBestMakespan() != Integer.MAX_VALUE ? s.getBestMakespan() : 0); @@ -164,20 +164,20 @@ public static void runRCPSPSolver(PSEngine engine,RCPSPSolver s, String test,Int .append(s.getTimeToBest()).append(separator) .append(s.getSolutionAsString()) .append("\n"); - + String filename = "Solver-"+s.getName()+"-"+(s.getActivities().size()-2)+".txt"; writeToFile(filename,buf.toString()); - } - + } + protected static void writeToFile(String filename,String str) { try { BufferedWriter out = new BufferedWriter(new FileWriter(filename,true/*append*/)); out.write(str); out.close(); - } + } catch (Exception e) { throw new RuntimeException(e); - } + } } } diff --git a/examples/UBO/java/UBO/PSResourceWrapper.java b/examples/UBO/java/UBO/PSResourceWrapper.java index 2dd64344b..1a4e4cd11 100644 --- a/examples/UBO/java/UBO/PSResourceWrapper.java +++ b/examples/UBO/java/UBO/PSResourceWrapper.java @@ -8,13 +8,13 @@ /* * This is a thin wrapper around PSResource */ -public class PSResourceWrapper extends ResourceBase +public class PSResourceWrapper extends ResourceBase { public PSResourceWrapper(PSEngine pse,PSResource r, int capacity) { super(pse,r,capacity); } - + public List getConflictSet(int t) { List retval = new Vector(); @@ -24,15 +24,15 @@ public List getConflictSet(int t) PSToken tok = psengine_.getTokenByKey(tokKeys.get(i)); retval.add(tok); } - + return retval; } - + public ResourceViolationInfo getMaxViolation() { int t = -1; double lowestLevel = Double.MAX_VALUE; - + PSResourceProfile prof = res_.getVDLevels(); PSTimePointList times = prof.getTimes(); for (int i=0; i=0) RCPSPUtil.dbgout("MaxViolation for "+res_.getEntityName()+" "+lowestLevel+" at time "+t); - - return new ResourceViolationInfo(t,lowestLevel); - } + + return new ResourceViolationInfo(t,lowestLevel); + } } diff --git a/examples/UBO/java/UBO/PlanHistoryEntry.java b/examples/UBO/java/UBO/PlanHistoryEntry.java index 34e1d652d..8fab6db55 100644 --- a/examples/UBO/java/UBO/PlanHistoryEntry.java +++ b/examples/UBO/java/UBO/PlanHistoryEntry.java @@ -6,7 +6,7 @@ public class PlanHistoryEntry Long remainingTreeSize_; String currentTree_; String currentPlan_; - + public PlanHistoryEntry( Integer step, Long remainingTreeSize, @@ -18,19 +18,19 @@ public PlanHistoryEntry( currentTree_ = currentTree; currentPlan_ = currentPlan; } - + public Integer getStepNumber() { return step_; } public Long getRemainingTreeSize() { return remainingTreeSize_; } public String getCurrentTree() { return currentTree_; } - public String getCurrentPlan() { return currentPlan_; } - + public String getCurrentPlan() { return currentPlan_; } + public String toString() { StringBuffer buf = new StringBuffer(); buf.append(step_).append(": ") .append("(").append(remainingTreeSize_).append(")") .append(currentTree_) - .append(currentPlan_); + .append(currentPlan_); return buf.toString(); } } diff --git a/examples/UBO/java/UBO/Precedence.java b/examples/UBO/java/UBO/Precedence.java index 647ec0574..2e1769fd3 100644 --- a/examples/UBO/java/UBO/Precedence.java +++ b/examples/UBO/java/UBO/Precedence.java @@ -17,28 +17,28 @@ public Precedence(PSResource r,PSToken p,PSToken s) this(r,p,s,0); int succStart = RCPSPUtil.getUb(succ.getStart()); int predFinish = RCPSPUtil.getLb(pred.getEnd()); - buffer = succStart-predFinish; + buffer = succStart-predFinish; } public Precedence(PSResource r,PSToken p,PSToken s, int b) { res = r; pred = p; - succ = s; + succ = s; isCritical = true; buffer = b; - } + } public int compareTo(Object o) { Precedence rhs = (Precedence)o; return rhs.buffer - buffer; } - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append(RCPSPUtil.getActivity(pred)).append("<").append(RCPSPUtil.getActivity(succ)); return buf.toString(); } -} +} diff --git a/examples/UBO/java/UBO/RCPSPResource.java b/examples/UBO/java/UBO/RCPSPResource.java index a76ac443e..c328fc5e9 100644 --- a/examples/UBO/java/UBO/RCPSPResource.java +++ b/examples/UBO/java/UBO/RCPSPResource.java @@ -9,13 +9,13 @@ /* * This is a version of Resource that performs much more computation outside EUROPA than PSResourceWrapper */ -public class RCPSPResource extends ResourceBase -{ +public class RCPSPResource extends ResourceBase +{ public RCPSPResource(PSEngine pse,PSResource r, int capacity) { super(pse,r,capacity); } - + public List getConflictSet(int t) { List conflictSet = new Vector(); @@ -23,7 +23,7 @@ public List getConflictSet(int t) PSTokenList toks = res_.getTokens(); for (int i=0;i getConflictSet(int t) // Don't try to order tokens that can't be ordered int predEndLb = RCPSPUtil.getLb(pred.getEnd()); int succStartUb = RCPSPUtil.getUb(pred.getStart()); - + if ((pred != succ) && (predEndLb <= succStartUb)) { retval.add(pred); retval.add(succ); } } } - + return retval; } - + public ResourceViolationInfo getMaxViolation() { int lowestTime = -1; double lowestLevel = Double.MAX_VALUE; - + ResourceProfile prof = getLevels(); Iterator times = prof.getTimes().iterator(); while (times.hasNext()) { @@ -60,10 +60,10 @@ public ResourceViolationInfo getMaxViolation() lowestTime = t; } } - + //if (lowestTime>=0) // RCPSPUtil.dbgout("MaxViolation for "+res_.getName()+" "+lowestLevel+" at time "+lowestTime); - - return new ResourceViolationInfo(lowestTime,lowestLevel); + + return new ResourceViolationInfo(lowestTime,lowestLevel); } } diff --git a/examples/UBO/java/UBO/RCPSPSolver.java b/examples/UBO/java/UBO/RCPSPSolver.java index 1a94a2589..f1c426307 100644 --- a/examples/UBO/java/UBO/RCPSPSolver.java +++ b/examples/UBO/java/UBO/RCPSPSolver.java @@ -5,13 +5,13 @@ import psengine.PSEngine; import psengine.PSToken; -public interface RCPSPSolver +public interface RCPSPSolver { public String getName(); - - public void solve(PSEngine psengine, + + public void solve(PSEngine psengine, long timeout, // in msecs - int bound, + int bound, boolean usePSResources); public long getElapsedMsecs(); @@ -28,4 +28,4 @@ public void solve(PSEngine psengine, public String getSolutionAsString(); -} \ No newline at end of file +} diff --git a/examples/UBO/java/UBO/RCPSPSolverBase.java b/examples/UBO/java/UBO/RCPSPSolverBase.java index d484bbd16..46b3a77b4 100644 --- a/examples/UBO/java/UBO/RCPSPSolverBase.java +++ b/examples/UBO/java/UBO/RCPSPSolverBase.java @@ -13,8 +13,8 @@ import psengine.PSVariable; import psengine.util.SimpleTimer; -public abstract class RCPSPSolverBase - implements RCPSPSolver +public abstract class RCPSPSolverBase + implements RCPSPSolver { protected SimpleTimer timer_; protected boolean timedOut_; @@ -23,15 +23,15 @@ public abstract class RCPSPSolverBase protected int bestMakespan_; protected PSEngine psengine_; - protected List resources_; + protected List resources_; protected SortedMap activities_; protected SortedSet precedences_; - - protected SortedSet bestSolution_; - + + protected SortedSet bestSolution_; + public String getName() { return getClass().getSimpleName(); } - - public Collection getActivities() { return activities_.values(); } + + public Collection getActivities() { return activities_.values(); } public List getResources() { return resources_; } public SortedSet getPrecedences() { return precedences_; } @@ -39,51 +39,51 @@ public abstract class RCPSPSolverBase public int getBestMakespan() { return bestMakespan_; } public long getTimeToBest() { return timeToBest_; } public SortedSet getBestSolution() { return bestSolution_; } - + public void undoSolve() { psengine_.setAutoPropagation(false); for (Precedence p : bestSolution_) p.res.removePrecedence(p.pred,p.succ); - - psengine_.setAutoPropagation(true); + + psengine_.setAutoPropagation(true); } - + public void restoreBestSolution() { psengine_.setAutoPropagation(false); - + for (Precedence p : precedences_) p.res.removePrecedence(p.pred,p.succ); precedences_.clear(); - + for (Precedence p : bestSolution_) - p.res.addPrecedence(p.pred,p.succ); + p.res.addPrecedence(p.pred,p.succ); - psengine_.setAutoPropagation(true); + psengine_.setAutoPropagation(true); } - + public String getSolutionAsString() { StringBuffer buf = new StringBuffer(); - - for (Precedence p : bestSolution_) + + for (Precedence p : bestSolution_) buf.append("{").append(RCPSPUtil.getActivity(p.pred)).append("<").append(RCPSPUtil.getActivity(p.succ)).append("}"); - + return buf.toString(); - } - + } + public int getMakespan() { return RCPSPUtil.getLb(getProjectFinish()); } - + public PSVariable getProjectFinish() { return activities_.get(activities_.lastKey()).getStart(); - } - + } + protected void addPrecedence(Precedence p) { //RCPSPUtil.dbgout("adding {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); @@ -97,42 +97,42 @@ protected void removePrecedence(Precedence p) //RCPSPUtil.dbgout("removing {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); p.res.removePrecedence(p.pred,p.succ); precedences_.remove(p); - //RCPSPUtil.dbgout("removed {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); - } + //RCPSPUtil.dbgout("removed {"+RCPSPUtil.getActivity(p.pred)+"<"+RCPSPUtil.getActivity(p.succ)+"} because of "+p.res.getName()); + } // TODO: do this faster with a key boolean isPrecedence(PSToken pred,PSToken succ) { int actPred = RCPSPUtil.getActivity(pred); int actSucc = RCPSPUtil.getActivity(succ); - + for (Precedence p : precedences_) { - if ((RCPSPUtil.getActivity(p.pred)==actPred) && (RCPSPUtil.getActivity(p.succ)==actSucc)) - return true; + if ((RCPSPUtil.getActivity(p.pred)==actPred) && (RCPSPUtil.getActivity(p.succ)==actSucc)) + return true; } - + return false; - } + } + - protected void resetSolution() { bestMakespan_ = Integer.MAX_VALUE; - bestSolution_ = new TreeSet(new PrecedenceComparator()); + bestSolution_ = new TreeSet(new PrecedenceComparator()); precedences_ = new TreeSet(new PrecedenceComparator()); } - + static class PrecedenceComparator implements Comparator { - public int compare(Precedence o1, Precedence o2) + public int compare(Precedence o1, Precedence o2) { int diff = RCPSPUtil.getActivity(o1.pred) - RCPSPUtil.getActivity(o2.pred); - if (diff != 0) + if (diff != 0) return diff; - else + else return RCPSPUtil.getActivity(o1.succ) - RCPSPUtil.getActivity(o2.succ); } - } + } } diff --git a/examples/UBO/java/UBO/RCPSPUtil.java b/examples/UBO/java/UBO/RCPSPUtil.java index 788ed50fc..9d51a21b1 100644 --- a/examples/UBO/java/UBO/RCPSPUtil.java +++ b/examples/UBO/java/UBO/RCPSPUtil.java @@ -6,63 +6,63 @@ import psengine.PSVarValue; import psengine.PSVariable; -public class RCPSPUtil +public class RCPSPUtil { public static int getActivity(PSToken tok) { return tok.getMaster().getParameter("m_identifier").getSingletonValue().asInt(); } - + public static int getLb(PSVariable v) { if (v.isSingleton()) return (new Double(valueToString(v.getSingletonValue()))).intValue(); else if (v.isInterval()) return (int)v.getLowerBound(); - + throw new RuntimeException("Can only get lb for singleton or interval vars"); } - + public static int getUb(PSVariable v) { if (v.isSingleton()) return (new Double(valueToString(v.getSingletonValue()))).intValue(); else if (v.isInterval()) return (int)v.getUpperBound(); - + throw new RuntimeException("Can only get ub for singleton or interval vars"); } - + public static boolean overlaps(PSToken tok, int t) { int lb = getLb(tok.getStart()); int ub = getLb(tok.getEnd()); - + return ((lb <= t) && (t <= ub)); - } + } public static String valueToString(PSVarValue v) { String type = v.getType().toString(); - + if ("STRING".equals(type)) return v.asString(); if ("INTEGER".equals(type)) - return new Integer(v.asInt()).toString(); + return new Integer(v.asInt()).toString(); if ("DOUBLE".equals(type)) return new Double(v.asDouble()).toString(); if ("BOOLEAN".equals(type)) return new Boolean(v.asBoolean()).toString(); if ("OBJECT".equals(type)) return v.asObject().getEntityName(); - + return "ERROR!!! UNKNOWN TYPE :" + type; } public static String varValueToString(PSVariable var) - { - if (var.isSingleton()) - return valueToString(var.getSingletonValue()); + { + if (var.isSingleton()) + return valueToString(var.getSingletonValue()); else if (var.isInterval()) { StringBuffer buf = new StringBuffer(); buf.append("[").append(var.getLowerBound()).append(",") @@ -81,9 +81,9 @@ else if (var.isEnumerated()) { buf.append("]"); return buf.toString(); } - + throw new RuntimeException("Unexpected ERROR: variable "+var.getEntityName()+" is not one of {Singleton, Interval, Enumeration}"); - } + } public static void ground(Collection tokens) { @@ -92,12 +92,12 @@ public static void ground(Collection tokens) ground(t.getEnd()); } } - + public static void ground(PSVariable v) { int value = RCPSPUtil.getLb(v); v.specifyValue(PSVarValue.getInstance(value)); - } + } public static void undoGround(Collection tokens) { @@ -110,11 +110,11 @@ public static void undoGround(PSVariable v) { int value = RCPSPUtil.getLb(v); v.reset(); - } + } + - public static void dbgout(String msg) { System.out.println(msg); - } + } } diff --git a/examples/UBO/java/UBO/ResourceBase.java b/examples/UBO/java/UBO/ResourceBase.java index 144381d23..79ac71eaa 100644 --- a/examples/UBO/java/UBO/ResourceBase.java +++ b/examples/UBO/java/UBO/ResourceBase.java @@ -2,32 +2,32 @@ import psengine.*; -public abstract class ResourceBase implements Resource +public abstract class ResourceBase implements Resource { protected PSEngine psengine_; protected PSResource res_; protected int capacity_; - + public ResourceBase(PSEngine pse,PSResource r, int capacity) { psengine_ = pse; capacity_ = capacity; res_ = r; } - + public int getCapacity() { return capacity_; } public PSResource getPSResource() { return res_; } public String getName() { return res_.getEntityName(); } - + public ResourceProfile getLevels() { return new ResourceProfile(this); } - + public String toString() { StringBuffer buf = new StringBuffer(); buf.append(res_.getEntityName()).append(" ").append(getLevels().toString()); return buf.toString(); - } + } } diff --git a/examples/UBO/java/UBO/ResourceProfile.java b/examples/UBO/java/UBO/ResourceProfile.java index 5f0e5f84d..8c0bb7609 100644 --- a/examples/UBO/java/UBO/ResourceProfile.java +++ b/examples/UBO/java/UBO/ResourceProfile.java @@ -8,40 +8,40 @@ import psengine.*; -public class ResourceProfile -{ +public class ResourceProfile +{ protected Resource res_; protected SortedMap levels_; - + public ResourceProfile(Resource r) { res_ = r; init(); } - + protected void init() { levels_ = new TreeMap(); levels_.put(0,res_.getCapacity()); - + PSTokenList acts = res_.getPSResource().getTokens(); for (int i=0;i> it = levels_.entrySet().iterator(); + if (levelAtStart == null) { + Iterator> it = levels_.entrySet().iterator(); while(it.hasNext()) { Entry entry = it.next(); if (entry.getKey() < start) @@ -51,27 +51,27 @@ protected void update(int start,int end,int qty) } levels_.put(start, levelAtStart); } - + Integer lastValue=levelAtStart; SortedMap submap = levels_.subMap(start, end); // this doesn't include end - Iterator> it = submap.entrySet().iterator(); + Iterator> it = submap.entrySet().iterator(); while(it.hasNext()) { Entry entry = it.next(); lastValue = entry.getValue()-qty; - entry.setValue(lastValue); + entry.setValue(lastValue); } - + Integer levelAtEnd=levels_.get(end); if (levelAtEnd == null) levels_.put(end, lastValue+qty); - - } - + + } + public Set getTimes() { return levels_.keySet(); } - + // TODO: make this more sophisticated public Integer getLevel(Integer time) { return levels_.get(time); } - + public String toString() { StringBuffer buf = new StringBuffer(); @@ -81,7 +81,7 @@ public String toString() Integer t = times.next(); buf.append("{").append(t).append("=").append(getLevel(t)).append("}"); } - + return buf.toString(); } } diff --git a/examples/UBO/java/UBO/ResourceViolationInfo.java b/examples/UBO/java/UBO/ResourceViolationInfo.java index 7cfe969db..7a4417f5f 100644 --- a/examples/UBO/java/UBO/ResourceViolationInfo.java +++ b/examples/UBO/java/UBO/ResourceViolationInfo.java @@ -1,10 +1,10 @@ package UBO; -public class ResourceViolationInfo +public class ResourceViolationInfo { public int time; public double level; - + public ResourceViolationInfo(int t,double l) { time = t; diff --git a/examples/UBO/java/UBO/SolDistExhaustiveSolver.java b/examples/UBO/java/UBO/SolDistExhaustiveSolver.java index f52bea868..77e1b0db7 100644 --- a/examples/UBO/java/UBO/SolDistExhaustiveSolver.java +++ b/examples/UBO/java/UBO/SolDistExhaustiveSolver.java @@ -12,36 +12,36 @@ /* * this is a different version of the Exhaustive solver that didn't turn out to be an improvement - * instead of starting from scratch, it removes 1, then 2, then 3 ... precedences from the incoming oracle and then + * instead of starting from scratch, it removes 1, then 2, then 3 ... precedences from the incoming oracle and then * performs and exhaustive search. * Leaving the code around for now, in case this idea can be reused in some form later. * For now it looks like it'll be much better to improve the Exhaustive solver by using ideas from existing B&B solvers */ public class SolDistExhaustiveSolver - extends RCPSPSolverBase + extends RCPSPSolverBase { List decisionStack_ = new Vector(); int lowerBound_; int upperBound_; SortedSet precedenceOracle_; DecisionPoint curDP_; - + public SolDistExhaustiveSolver() - { + { } - + public void solve( - PSEngine psengine, - long timeout, + PSEngine psengine, + long timeout, int bound, - boolean usePSResources) + boolean usePSResources) { // TODO: get this to work solve(psengine,timeout,bound,Integer.MAX_VALUE,null,null,null); - } + } Precedence noGood_ = null; - + public void solve( PSEngine psengine, long timeout, @@ -57,20 +57,20 @@ public void solve( if (precedenceOracle.size() > 0) { for (int i=0;i exclusions = it.next(); + List exclusions = it.next(); removePrecedences(exclusions); doSolve(); if (upperBound_ <= lowerBound_ || timedOut_) { solveFinished(precedenceOracle); - return; + return; } - + undoSolve(); - addPrecedences(exclusions); + addPrecedences(exclusions); } } } @@ -80,13 +80,13 @@ public void solve( solveFinished(precedenceOracle); } - + protected void solveFinished(List precedenceOracle) { bestSolution_.addAll(precedenceOracle); - timer_.stop(); + timer_.stop(); } - + protected void doSolve() { for (;;) { @@ -110,29 +110,29 @@ protected void doSolve() bestSolution_.clear(); bestSolution_.addAll(precedences_); timeToBest_ = timer_.getElapsed(); - RCPSPUtil.dbgout("ExhaustiveSolver found new best makespan "+bestMakespan_+" "+getSolutionAsString()); - } + RCPSPUtil.dbgout("ExhaustiveSolver found new best makespan "+bestMakespan_+" "+getSolutionAsString()); + } // if upper and lower bound cross, we're done if (upperBound_ <= lowerBound_) { doSolveFinished("Bounds crossed"); break; - } + } if (decisionStack_.isEmpty()) { doSolveFinished("exhausted"); break; } - else + else doBacktrack("Backtracking after finding solution"); } else { if (curDP_.hasNext()) { executeDecision(curDP_); - if (psengine_.getViolation() > 0) + if (psengine_.getViolation() > 0) doBacktrack("Backtracking because of violation"); - else if (getMakespan() > upperBound_) + else if (getMakespan() > upperBound_) doBacktrack("Backtracking because of upper bound "+getMakespan()+" vs. "+upperBound_); } else if (decisionStack_.isEmpty()) { @@ -143,9 +143,9 @@ else if (decisionStack_.isEmpty()) { doBacktrack("Backtracking because decision point exhausted choices"); } } - } + } } - + protected void doSolveFinished(String msg) { // TODO: timer_.stop(); @@ -156,7 +156,7 @@ protected void doSolveFinished(String msg) restoreBestSolution(); resetState(); } - + public void init( PSEngine psengine, long timeout, @@ -167,7 +167,7 @@ public void init( List precedenceOracle) { timer_ = new SimpleTimer(); - timer_.start(); + timer_.start(); psengine_ = psengine; timeout_ = timeout; @@ -175,44 +175,44 @@ public void init( resources_ = resources; lowerBound_ = lowerBound; upperBound_ = upperBound; - + precedenceOracle_ = new TreeSet(); for (Precedence p : precedenceOracle) precedenceOracle_.add(p.toString()); - + resetSolution(); resetState(); } - + void resetState() { - curDP_ = null; + curDP_ = null; } - + int lastIdx_ = 0; - + protected DecisionPoint getNextDecisionPoint() { double lowestLevel = Double.MAX_VALUE; Resource maxViolatedResource = null; int maxViolatedTime = Integer.MIN_VALUE; - + int start = lastIdx_; for (int i=lastIdx_;;) { Resource r = resources_.get(i); ResourceViolationInfo rvi = r.getMaxViolation(); - + if ((rvi.level < lowestLevel) && (rvi.level < 0)) { lowestLevel = rvi.level; maxViolatedResource = r; maxViolatedTime = rvi.time; } - + i = (i+1) % resources_.size(); if (i == start) break; - } - + } + if (maxViolatedResource == null) { //RCPSPUtil.dbgout("No violations found!"); return null; @@ -220,38 +220,38 @@ protected DecisionPoint getNextDecisionPoint() else return new DecisionPoint(maxViolatedResource,maxViolatedTime); } - + protected void executeDecision(DecisionPoint dp) { decisionStack_.add(dp); - dp.execute(); + dp.execute(); curDP_ = null; } - + protected void doBacktrack(String reason) { curDP_ = decisionStack_.remove(decisionStack_.size()-1); - curDP_.undo(); + curDP_.undo(); //RCPSPUtil.dbgout(reason+" new stack size:"+decisionStack_.size()); } - + boolean isNoGood(PSToken pred,PSToken succ) { return false; - /* + /* if (noGood_ == null) return false; - + return ((noGood_.pred.getKey()==pred.getKey()) && (noGood_.succ.getKey() == succ.getKey())); */ } - + protected class DecisionPoint { TreeSet choices_; SortedSet executedChoices_; Precedence lastExecutedChoice_; - + public DecisionPoint(Resource r, int t) { choices_ = new TreeSet(); @@ -259,78 +259,78 @@ public DecisionPoint(Resource r, int t) if (conflictSet.size() < 2) RCPSPUtil.dbgout("ERROR!!: conflictSet size is :"+conflictSet.size()); - + for (int i=0;i l) { psengine_.setAutoPropagation(false); - + for (Precedence p : l) p.res.addPrecedence(p.pred,p.succ); - - psengine_.setAutoPropagation(true); + + psengine_.setAutoPropagation(true); } - + void removePrecedences(List l) { psengine_.setAutoPropagation(false); - + for (Precedence p : l) p.res.removePrecedence(p.pred,p.succ); - - psengine_.setAutoPropagation(true); + + psengine_.setAutoPropagation(true); } - + class OracleIterator { int setSize_; @@ -338,7 +338,7 @@ class OracleIterator List counter_; int counterRow_; int max_; - + public OracleIterator(List source,int setSize) { setSize_ = setSize; @@ -346,54 +346,54 @@ public OracleIterator(List source,int setSize) counter_ = new Vector(); for (int i=0;i= 0; + return counterRow_ >= 0; } - + void incCounter() { int newValue = counter_.get(counterRow_)+1; while ((newValue + (counter_.size()-counterRow_) > max_) && counterRow_>=0) { counterRow_--; if (counterRow_ >= 0) - newValue = counter_.get(counterRow_)+1; + newValue = counter_.get(counterRow_)+1; } - + if (counterRow_ >=0) { for (int i=0;(counterRow_+i) next() { List retval = new Vector(); - + for (Integer i : counter_) retval.add(source_.get(i)); - + incCounter(); //printExcluded(retval); - + return retval; } - + void printExcluded(List retval) { StringBuffer buf = new StringBuffer(); buf.append("Excluded:"); for (Precedence p: retval) buf.append(p.toString()).append(","); - RCPSPUtil.dbgout(buf.toString()); + RCPSPUtil.dbgout(buf.toString()); } } - + } diff --git a/examples/UBO/java/UBO/UBOSolverListener.java b/examples/UBO/java/UBO/UBOSolverListener.java index 40f0d1233..9c505dde7 100644 --- a/examples/UBO/java/UBO/UBOSolverListener.java +++ b/examples/UBO/java/UBO/UBOSolverListener.java @@ -16,7 +16,7 @@ public class UBOSolverListener Vector planHistory_; Vector treeSize_; Vector currentTree_; - + public UBOSolverListener() { lastDepth_ = 0; @@ -26,16 +26,16 @@ public UBOSolverListener() treeSize_ = new Vector(); currentTree_ = new Vector(); } - + PSEngine getPSEngine() { - return PSDesktop.getInstance().getPSEngine(); + return PSDesktop.getInstance().getPSEngine(); // return PSDesktop.desktop.getPSEngine(); } - + public Vector getDecisionHistory() { return decisionHistory_; } public Vector getPlanHistory() { return planHistory_; } - + protected PlanHistoryEntry makePlanHistoryEntry(PSSolver s) { // Compute remaining nodes to explore @@ -43,25 +43,25 @@ protected PlanHistoryEntry makePlanHistoryEntry(PSSolver s) for (Integer i : treeSize_) { if (i != null) size *= i; - } - + } + PlanHistoryEntry entry = new PlanHistoryEntry(s.getStepCount(),size,currentTree_.toString(),plan_.toString()); return entry; } - + protected void decreasePlanSize(int delta) { int newSize = Math.max(0,plan_.size()-delta); - + plan_.setSize(newSize); treeSize_.setSize(newSize); currentTree_.setSize(newSize); } - + public void stepCompleted(PSSolver s) { - String lastDecision = s.getLastExecutedDecision(); + String lastDecision = s.getLastExecutedDecision(); if (lastDecision.startsWith("INSTANT") && (lastDepth_ <= s.getDepth())) { Pattern p = Pattern.compile("token=[0-9]+"); Matcher m = p.matcher(lastDecision); @@ -70,7 +70,7 @@ public void stepCompleted(PSSolver s) m.find(); Integer succId = new Integer(lastDecision.substring(m.start()+6,m.end())); String tokenDecision = " tokens:{" + predId + "} < {" + succId +"}"; - + PSObject resource = getPSEngine().getTokenByKey(predId).getOwner(); PSToken pred = getPSEngine().getTokenByKey(predId).getMaster(); PSToken succ = getPSEngine().getTokenByKey(succId).getMaster(); @@ -91,29 +91,29 @@ public void stepCompleted(PSSolver s) String decision = decisionBuf.toString(); String decisionMsg = s.getStepCount() + ": "+ decision + " because of " + resource.getEntityName() + tokenDecision; decisionHistory_.add(decisionMsg); - //System.out.println(decisionMsg); + //System.out.println(decisionMsg); plan_.add(decision); treeSize_.add((remaining > 0) ? remaining : new Integer(1)); currentTree_.add("("+choiceIdx+","+choiceCnt+")"); PlanHistoryEntry entry = makePlanHistoryEntry(s); - planHistory_.add(entry); - //System.out.println(entry); - } - + planHistory_.add(entry); + //System.out.println(entry); + } + if (lastDepth_ >= s.getDepth()) { String btMsg = s.getStepCount() + ": Backtracked! from "+plan_.size()+" to "+s.getDepth(); decisionHistory_.add(btMsg); - //System.out.println(btMsg); + //System.out.println(btMsg); decreasePlanSize(lastDepth_ - s.getDepth()); PlanHistoryEntry entry = makePlanHistoryEntry(s); - planHistory_.add(entry); - //System.out.println(entry); + planHistory_.add(entry); + //System.out.println(entry); } - lastDepth_ = s.getDepth(); + lastDepth_ = s.getDepth(); //System.out.println(s.getStepCount()+" set last depth to:"+lastDepth_); } -} +} diff --git a/src/Java/JavaUI/source/org/ops/ui/beanshell/swing/BeanShellView.java b/src/Java/JavaUI/source/org/ops/ui/beanshell/swing/BeanShellView.java index 4ef51f4f9..29daa8c6c 100644 --- a/src/Java/JavaUI/source/org/ops/ui/beanshell/swing/BeanShellView.java +++ b/src/Java/JavaUI/source/org/ops/ui/beanshell/swing/BeanShellView.java @@ -23,8 +23,8 @@ public BeanShellView(SolverModel solverModel, PSDesktop psDesktop) { console = new JConsole(); this.setContentPane(console); - this.interpreter = new Interpreter(console); - + this.interpreter = new Interpreter(console); + // Register variables try { interpreter.set("desktop", psDesktop); diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/model/OutlineNode.java b/src/Java/JavaUI/source/org/ops/ui/editor/model/OutlineNode.java index 8fadaa229..7e675d32e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/model/OutlineNode.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/model/OutlineNode.java @@ -8,7 +8,7 @@ /** * Outline node. Outline tree is computed from AST tree. This class also * contains a bunch of static methods for the actual AST to Outline conversion. - * + * * @author Tatiana Kichkaylo */ public class OutlineNode { diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/AshConsole.java b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/AshConsole.java index 573f49d9c..4eb1fde87 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/AshConsole.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/AshConsole.java @@ -1636,7 +1636,7 @@ public Dimension minimumLayoutSize(Container parent) { dim.height = insets.top + insets.bottom; Dimension centerPref = center.getMinimumSize(); - dim.width += centerPref.width; + dim.width += centerPref.width; dim.height += centerPref.height; Dimension rightPref = right.getMinimumSize(); dim.width += rightPref.width; @@ -1750,7 +1750,7 @@ public void insertUpdate(DocumentEvent evt) { int newStart; int newEnd; - if(selectionStart > offset || (selectionStart + if(selectionStart > offset || (selectionStart == selectionEnd && selectionStart == offset)) newStart = selectionStart + length; else @@ -1885,7 +1885,7 @@ public void mousePressed(MouseEvent evt) { } } - private void doSingleClick(MouseEvent evt, int line, + private void doSingleClick(MouseEvent evt, int line, int offset, int dot) { if((evt.getModifiers() & InputEvent.SHIFT_MASK) != 0) { rectSelect = (evt.getModifiers() & InputEvent.CTRL_MASK) != 0; diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/ConsolePainter.java b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/ConsolePainter.java index 06c3cd36e..6e3e0b058 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/ConsolePainter.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/ConsolePainter.java @@ -568,7 +568,7 @@ protected void paintBracketHighlight(Graphics gfx, int line, int y) { protected void paintCaret(Graphics gfx, int line, int y) { if(console.isCaretVisible()) { - int offset = console.getCaretPosition() + int offset = console.getCaretPosition() - console.getLineStartOffset(line); int caretX = console._offsetToX(line,offset); int caretWidth = ((blockCaret || console.isOverwriteEnabled()) ? fm.charWidth('w') : 1); diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/Token.java b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/Token.java index 9863f9020..827fbc09b 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/Token.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/Token.java @@ -51,7 +51,7 @@ public class Token { /** * Literal 3 token id. This can be used to mark a numeric - * literal + * literal */ public static final byte LITERAL3 = 5; diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/TokenMarker.java b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/TokenMarker.java index dc84509e7..2351f44b3 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/TokenMarker.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swing/ash/TokenMarker.java @@ -109,7 +109,7 @@ public Token markTokens(Segment line, int lineIndex) { * add syntax tokens to the token list. Then, it should return * the initial token type for the next line.

* - * For example if the current line contains the start of a + * For example if the current line contains the start of a * multiline comment that doesn't end on that line, this method * should return the comment token type so that it continues on * the next line. @@ -141,7 +141,7 @@ public boolean supportsMultilineTokens() { * the document. This inserts a gap in the lineInfo * array. * @param index The first line number - * @param lines The number of lines + * @param lines The number of lines */ public void insertLines(int index, int lines) { if(lines <= 0) diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swing/nddl/NddlAshInterpreter.java b/src/Java/JavaUI/source/org/ops/ui/editor/swing/nddl/NddlAshInterpreter.java index 28fc5b13d..fd7bc95ee 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swing/nddl/NddlAshInterpreter.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swing/nddl/NddlAshInterpreter.java @@ -10,31 +10,31 @@ //import psengine.NddlInterpreter; import psengine.PSEngine; -public class NddlAshInterpreter extends AshInterpreter +public class NddlAshInterpreter extends AshInterpreter { PrintStream consoleErr_ = System.err; //NddlInterpreter interpreter_ = null; - public NddlAshInterpreter(PSEngine pse) + public NddlAshInterpreter(PSEngine pse) { super("Nddl"); //interpreter_ = pse.getNddlInterpreter(); } - public void setConsole(AshConsole console) + public void setConsole(AshConsole console) { consoleErr_ = new PrintStream(new BufferedOutputStream(new DocumentOutputStream(console.getDocument(), "!!")), true); //interpreter_.setErrorStream(consoleErr_); } - public void source(String filename) + public void source(String filename) { - //interpreter_.source(filename); + //interpreter_.source(filename); } - public boolean eval(String toEval) + public boolean eval(String toEval) { return false; - //return interpreter_.eval(toEval); + //return interpreter_.eval(toEval); } } diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlEditor.java b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlEditor.java index 62bb1db46..254d1373b 100755 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlEditor.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlEditor.java @@ -9,7 +9,7 @@ /** * NDDL editor with syntax highlighting. - * + * * @author Tatiana */ public class NddlEditor extends TextEditor { @@ -29,7 +29,7 @@ public NddlEditor() { /** * Create the part control. - * + * * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override @@ -45,7 +45,7 @@ public void dispose() { /** * Used by platform to get the OutlinePage and ProjectionSupport adapter. - * + * * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ @SuppressWarnings("unchecked") @@ -60,7 +60,7 @@ public Object getAdapter(Class required) { } return super.getAdapter(required); } - + public NddlContentProvider getNddlContentProvider() { return provider; } diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlScanner.java b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlScanner.java index 5a196f1c3..8f20a0129 100755 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlScanner.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlScanner.java @@ -95,7 +95,7 @@ private static final class CharacterRule implements IRule { /** * Creates a new operator rule. - * + * * @param token * Token to use for this rule */ diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlToggleCommentHandler.java b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlToggleCommentHandler.java index 2a23fa627..8b6ea3652 100644 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlToggleCommentHandler.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NddlToggleCommentHandler.java @@ -16,7 +16,7 @@ /** * Trigger comment // for the current selection of the currently active editor. - * + * * @author Tatiana, Tristan */ public class NddlToggleCommentHandler extends AbstractHandler { diff --git a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NonRuleBasedDamagerRepairer.java b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NonRuleBasedDamagerRepairer.java index 6b770e7b0..537aef1f5 100755 --- a/src/Java/JavaUI/source/org/ops/ui/editor/swt/NonRuleBasedDamagerRepairer.java +++ b/src/Java/JavaUI/source/org/ops/ui/editor/swt/NonRuleBasedDamagerRepairer.java @@ -19,7 +19,7 @@ public class NonRuleBasedDamagerRepairer implements IPresentationDamager, /** The document this object works on */ protected IDocument fDocument; - + /** * The default text attribute if non is returned as data by the current * token @@ -43,7 +43,7 @@ public void setDocument(IDocument document) { * Returns the end offset of the line that contains the specified offset or * if the offset is inside a line delimiter, the end offset of the next * line. - * + * * @param offset * the offset whose line end offset must be computed * @return the line end offset for the given offset @@ -112,7 +112,7 @@ public void createPresentation(TextPresentation presentation, /** * Adds style information to the given text presentation. - * + * * @param presentation * the text presentation to be extended * @param offset @@ -128,4 +128,4 @@ protected void addRange(TextPresentation presentation, int offset, presentation.addStyleRange(new StyleRange(offset, length, attr .getForeground(), attr.getBackground(), attr.getStyle())); } -} \ No newline at end of file +} diff --git a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNode.java b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNode.java index 4f13dbae4..a6b4f0544 100644 --- a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNode.java +++ b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNode.java @@ -5,7 +5,7 @@ /** * Java version of Antlr3 AST node as passed through verbose string - * + * * @author Tatiana Kichkaylo */ public class AstNode { @@ -27,7 +27,7 @@ public class AstNode { /** * Read from the string/offset. Expect to see * "text":token-type:"file":line:offset-in-line or "text":token-type - * + * * @return offset past this node */ public int readNodeFrom(String astString, int offset) { diff --git a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNodeTypes.java b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNodeTypes.java index d23eb6b87..5c3fcd121 100644 --- a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNodeTypes.java +++ b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/AstNodeTypes.java @@ -1,7 +1,7 @@ package org.ops.ui.filemanager.model; /** - * Type constants. The numbers in this file should match those in + * Type constants. The numbers in this file should match those in * /Europa/src/PLASMA/NDDL/base/NDDL3.tokens */ public interface AstNodeTypes { @@ -20,6 +20,6 @@ public interface AstNodeTypes { public static final int FACT_KEYWORD = 59; // instantiation of predicate public static final int PREDICATE_INSTANCE = 9; - public static final int CONSTRAINT_INSTANCE = 4; + public static final int CONSTRAINT_INSTANCE = 4; public static final int ENUM_KEYWORD = 32; } diff --git a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/ErrorRecord.java b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/ErrorRecord.java index 33ca651a9..12e09de29 100644 --- a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/ErrorRecord.java +++ b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/ErrorRecord.java @@ -3,7 +3,7 @@ /** * Record for representing error messages accompanying AST. All fields are read * only. - * + * * @author Tatiana Kichkaylo */ public class ErrorRecord { diff --git a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/FileModel.java b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/FileModel.java index 96716f1ee..b69fd806e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/FileModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/FileModel.java @@ -9,7 +9,7 @@ * File model gets AST from a file. To do so, it creates a brand new copy of * engine, and deletes it when it is done. Loading of models into an engine for * running is done in SolverModel. - * + * * @author Tatiana Kichkaylo */ public class FileModel { diff --git a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/unittesting/FileModelTest.java b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/unittesting/FileModelTest.java index 164abc59e..c1af1a7a0 100644 --- a/src/Java/JavaUI/source/org/ops/ui/filemanager/model/unittesting/FileModelTest.java +++ b/src/Java/JavaUI/source/org/ops/ui/filemanager/model/unittesting/FileModelTest.java @@ -19,10 +19,10 @@ * Often changes to the NDDL grammar cause these constants to shift, in which * case AstNodeTypes.java needs to be updated. For now this update is manual, * which is bad. - * + * * At the very least we need some unittests to verify that constants still * match. - * + * * @author Tatiana Kichkaylo */ public class FileModelTest extends TestCase { diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttActivity.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttActivity.java index 86d276075..baf4dea94 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttActivity.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttActivity.java @@ -37,7 +37,7 @@ public boolean hasViolation() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getStartMin() */ @Override @@ -47,7 +47,7 @@ public int getStartMin() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getStartMax() */ @Override @@ -57,7 +57,7 @@ public int getStartMax() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getEndMin() */ @Override @@ -67,7 +67,7 @@ public int getEndMin() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getEndMax() */ @Override @@ -77,7 +77,7 @@ public int getEndMax() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getDurMin() */ @Override @@ -87,7 +87,7 @@ public int getDurMin() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getDurMax() */ @Override @@ -101,7 +101,7 @@ public int getKey() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttActivity#getText() */ @Override diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttResource.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttResource.java index 4e43a1ccf..ab2b336e4 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttResource.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/EuropaGanttResource.java @@ -6,7 +6,7 @@ /** * Implementation of IGanttResource around Europa PSResource - * + * * @author tatiana */ public class EuropaGanttResource implements IGanttResource { @@ -52,7 +52,7 @@ public String toString() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttResource#getName() */ @Override @@ -62,7 +62,7 @@ public String getName() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttResource#getActualMin() */ @Override @@ -72,7 +72,7 @@ public double getActualMin() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttResource#getActualMax() */ @Override @@ -82,7 +82,7 @@ public double getActualMax() { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttResource#getLow(int) */ @Override @@ -92,7 +92,7 @@ public double getLow(int time) { /* * (non-Javadoc) - * + * * @see org.ops.ui.gantt.model.IGanttResource#getHigh(int) */ @Override diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttActivity.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttActivity.java index 500dfd41f..b777811a6 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttActivity.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttActivity.java @@ -2,7 +2,7 @@ /** * Interface for the data structure representing an activity in Gantt chart - * + * * @author Tatiana */ public interface IGanttActivity { @@ -32,4 +32,4 @@ public interface IGanttActivity { * underlying data */ public Object getData(); -} \ No newline at end of file +} diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttModel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttModel.java index 9daaa5178..78b376d89 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttModel.java @@ -3,11 +3,11 @@ import java.util.List; /** Generic model providing access to activities and resource profiles. - * + * * @author Tatiana */ public interface IGanttModel { - + public int getResourceCount(); public List getActivities(int resource); @@ -20,4 +20,4 @@ public interface IGanttModel { public String getResourceName(int index); -} \ No newline at end of file +} diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttResource.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttResource.java index 231df30ee..51eeefcb9 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttResource.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/IGanttResource.java @@ -2,7 +2,7 @@ /** * Interface for a resource profile to be used with Gantt chart. - * + * * @author tatiana */ public interface IGanttResource { @@ -21,4 +21,4 @@ public interface IGanttResource { /** @return the upper bound value for the given time step */ public double getHigh(int time); -} \ No newline at end of file +} diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivity.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivity.java index cdd8afeb2..9ba85a8e3 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivity.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivity.java @@ -2,7 +2,7 @@ import java.util.Calendar; -public interface PSGanttActivity +public interface PSGanttActivity { public Object getKey(); public Calendar getStart(); diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivityImpl.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivityImpl.java index 14f4a55cd..a7dbdacb4 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivityImpl.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttActivityImpl.java @@ -2,16 +2,16 @@ import java.util.Calendar; -public class PSGanttActivityImpl - implements PSGanttActivity +public class PSGanttActivityImpl + implements PSGanttActivity { protected Object key_; protected Calendar start_; protected Calendar finish_; protected double violation_; - - public PSGanttActivityImpl(Object key, - Calendar start, + + public PSGanttActivityImpl(Object key, + Calendar start, Calendar finish, double violation) { @@ -24,5 +24,5 @@ public PSGanttActivityImpl(Object key, public Calendar getFinish() { return finish_; } public Object getKey() { return key_; } public Calendar getStart() { return start_; } - public double getViolation() { return violation_; } + public double getViolation() { return violation_; } } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttModel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttModel.java index d39f430d8..585bd9342 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttModel.java @@ -3,13 +3,13 @@ import java.util.Calendar; import java.util.Iterator; -public interface PSGanttModel +public interface PSGanttModel { public String[] getResourceColumnNames(); public String getResourceColumn(int resource, int column); - + public int getResourceCount(); public Iterator getActivities(int resource); public void setActivityStart(Object key, Calendar start); - public void setActivityFinish(Object key, Calendar finish); + public void setActivityFinish(Object key, Calendar finish); } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttPSEModel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttPSEModel.java index 1b6637f26..aea997b81 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttPSEModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/model/PSGanttPSEModel.java @@ -15,39 +15,39 @@ import psengine.PSTokenList; import psengine.PSObjectList; -public class PSGanttPSEModel - implements PSGanttModel +public class PSGanttPSEModel + implements PSGanttModel { Calendar startHorizon_; String objectsType_; PSObjectList resources_; int timeUnit_; - + public PSGanttPSEModel(PSEngine pse, Calendar startHorizon, String objectsType) { - this(pse,startHorizon,objectsType,Calendar.MINUTE); + this(pse,startHorizon,objectsType,Calendar.MINUTE); } - + public PSGanttPSEModel(PSEngine pse, Calendar startHorizon, String objectsType, int timeUnit) { startHorizon_ = startHorizon; objectsType_ = objectsType; resources_ = pse.getObjectsByType(objectsType_); timeUnit_=timeUnit; - + } - public Iterator getActivities(int resource) + public Iterator getActivities(int resource) { assert (resource >=0 && resource < getResourceCount()); - + // TODO: cache activities? List acts = new ArrayList(); - + PSTokenList tokens = resources_.get(resource).getTokens(); for (int i=0;i getActivities(int resource) { start = 0; } - + acts.add(new PSGanttActivityImpl(token.getEntityKey(), instantToCalendar(start), instantToCalendar(end), @@ -64,10 +64,10 @@ public Iterator getActivities(int resource) ) ); } - + return acts.iterator(); } - + protected Calendar instantToCalendar(double i) { Calendar retval = (Calendar)startHorizon_.clone(); @@ -76,32 +76,32 @@ protected Calendar instantToCalendar(double i) return retval; } - public String getResourceColumn(int resource, int column) + public String getResourceColumn(int resource, int column) { if (column == 0 && resource < getResourceCount()) return resources_.get(resource).getEntityName(); - + return ""; } static String resourceColumnNames_[] = { "Name" }; - public String[] getResourceColumnNames() + public String[] getResourceColumnNames() { return resourceColumnNames_; } - public int getResourceCount() + public int getResourceCount() { return resources_.size(); } - public void setActivityStart(Object key, Calendar start) + public void setActivityStart(Object key, Calendar start) { // TODO Auto-generated method stub notifyChange(key,"StartChanged",start); } - public void setActivityFinish(Object key, Calendar finish) + public void setActivityFinish(Object key, Calendar finish) { // TODO Auto-generated method stub notifyChange(key,"FinishChanged",finish); @@ -111,16 +111,16 @@ public void setActivityFinish(Object key, Calendar finish) protected void notifyChange(Object key, String type, Object value) { Object newValue=value; - + if (value instanceof Calendar) { SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en","US")); newValue = formatter.format(((Calendar)value).getTime()); } - + System.out.println(++notificationCnt_ + " - Object changed - {"+ "id:"+key+" "+ "type:"+type+" "+ "newValue:"+newValue+ "}" - ); + ); } } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/GanttView.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/GanttView.java index 1e8f62944..64104d321 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/GanttView.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/GanttView.java @@ -50,7 +50,7 @@ public class GanttView extends EuropaInternalFrame { /** Make this thing configurable? Issue 117 */ private boolean skipEmptyObjects = false; - + /** Odd and even background colors */ protected static final Color oddBg = new Color(250, 255, 250), evenBg = new Color(250, 250, 150), boldGrid = Color.gray, @@ -133,7 +133,7 @@ protected void updateView() { LinePanel line; if (r != null) { // Can resource timeline also have tokens? - line = new ResourcePanel(r); + line = new ResourcePanel(r); // . TODO } else { TimelinePanel tline = new TimelinePanel(model.getResourceName(i)); @@ -154,7 +154,7 @@ protected void updateView() { tokenPanel.add(line); labelPanel.add(line.getLabel()); } - + Point p = new Point(0,0); timeHeader.setViewPosition(p); labelVPort.setViewPosition(p); diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/LinePanel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/LinePanel.java index 37030d41e..95c77828a 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/LinePanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/LinePanel.java @@ -7,7 +7,7 @@ /** * Parent class for TimelinePanel and ResourcePanel. - * + * * @author Tatiana Kichkaylo */ public abstract class LinePanel extends JPanel { diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSEGantt.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSEGantt.java index e26841a1c..367f06632 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSEGantt.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSEGantt.java @@ -50,43 +50,43 @@ /* * PSGantt implementation that uses egantt */ -public class PSEGantt +public class PSEGantt extends PSGantt implements MouseMotionListener, DrawingPartListener { /** - * + * */ private static final long serialVersionUID = -7727371579397987014L; - + GanttTable gantt_; Map actEntries_; JButton refreshBtn_; Calendar start_; Calendar end_; PSGanttColorProvider colorProvider_; - + public PSEGantt(PSGanttModel model, - Calendar start, + Calendar start, Calendar end) { super(model); start_ = start; end_ = end; colorProvider_ = new DefaultColorProvider(); - + makeGantt(); - + refreshBtn_ = new JButton("Refresh"); setLayout(new BorderLayout()); //add(BorderLayout.NORTH,refreshBtn_); add(BorderLayout.CENTER,gantt_); - add(new GanttToolBar(gantt_.getViewManager(GanttTable.TIME_AXIS)), BorderLayout.SOUTH); + add(new GanttToolBar(gantt_.getViewManager(GanttTable.TIME_AXIS)), BorderLayout.SOUTH); } - + public PSGanttColorProvider getColorProvider() { return colorProvider_; } public void setColorProvider(PSGanttColorProvider cp) { colorProvider_ = cp; } - + protected void makeGantt() { gantt_ = new GanttTable(makeTableModel(model_)); @@ -94,11 +94,11 @@ protected void makeGantt() //System.out.println("model rows:"+model.getTableModel().getRowCount()); TableColumnModel columnModel = gantt_.getColumnModel(1); TableColumn column = columnModel.getColumn(0); - + // Enable drag and drop TableCellEditor editor = gantt_.getDefaultEditor(1, AbstractDrawingState.class); column.setCellEditor(editor); - + gantt_.getDrawingContext().put( ContextConstants.EDITING_AXIS, ContextResources.OTHER_PROPERTY, @@ -106,12 +106,12 @@ protected void makeGantt() gantt_.getDrawingContext().put( ContextConstants.EDITING_MODE, - ContextResources.OTHER_PROPERTY, - EditorDrawingModule.MOVE_RESIZE_EDITOR); + ContextResources.OTHER_PROPERTY, + EditorDrawingModule.MOVE_RESIZE_EDITOR); // Display timeline at the top column.setHeaderValue(GanttEntryHelper.createCalendar()); - gantt_.setTimeRange(start_.getTime(),end_.getTime()); + gantt_.setTimeRange(start_.getTime(),end_.getTime()); gantt_.addMouseMotionListener(this); /* TODO: Disable row selection? @@ -119,16 +119,16 @@ protected void makeGantt() activityTable.setRowSelectionAllowed(false); activityTable.setColumnSelectionAllowed(false); activityTable.setCellSelectionEnabled(false); - */ + */ } - + public void refresh() { remove(gantt_); makeGantt(); - add(BorderLayout.CENTER,gantt_); + add(BorderLayout.CENTER,gantt_); } - + protected TableModel makeTableModel(PSGanttModel model) { String[][] columnNames = { @@ -147,14 +147,14 @@ protected TableModel makeTableModel(PSGanttModel model) while (resActivities.hasNext()) { PSGanttActivity act = resActivities.next(); String context = mapColor(colorProvider_.getColor(act)); - + MutableDrawingPart entry = GanttDrawingPartHelper.createActivityEntry( - act.getKey(), + act.getKey(), act.getStart().getTime(), - act.getFinish().getTime(), - context, + act.getFinish().getTime(), + context, actList - ); + ); actEntries_.put(act.getKey(), entry); //System.out.println("ID:"+key+" Start:"+start.getTime()+" Finish:"+finish.getTime()); } @@ -166,31 +166,31 @@ protected TableModel makeTableModel(PSGanttModel model) data[i][1] = activities; } - return JTableHelper.createTableModel(data, columnNames); + return JTableHelper.createTableModel(data, columnNames); } - + // DrawingPartListener methods - public void stateChanged(DrawingPartEvent event) + public void stateChanged(DrawingPartEvent event) { String colors[] = { GradientColorModule.GREEN_GRADIENT_CONTEXT, - GradientColorModule.RED_GRADIENT_CONTEXT, + GradientColorModule.RED_GRADIENT_CONTEXT, }; - + Object key = event.getSource(); MutableDrawingPart entry = actEntries_.get(key); - //LongInterval li = (LongInterval)entry.getInterval()[0]; + //LongInterval li = (LongInterval)entry.getInterval()[0]; //int idx = (int)(Math.round(Math.random())); //System.out.println("range:"+li.getRangeValue()+" idx:"+idx); //entry.setContext(key, colors[idx]); - + List changes = (List)(event.changes().next()); - + int changeType = ((Integer)changes.get(0)).intValue(); Long newValue = (Long)changes.get(1); Calendar calValue = new GregorianCalendar(); calValue.setTime(new java.util.Date(newValue.longValue())); - + switch (changeType) { case MutableIntervalListener.START_CHANGED : model_.setActivityStart(key,calValue); @@ -201,17 +201,17 @@ public void stateChanged(DrawingPartEvent event) default: System.err.println("ERROR:Unknow MutableIntervalListener change:"+changeType); } - } - - // MouseMotionListenerMethods - public void mouseDragged(MouseEvent e) + } + + // MouseMotionListenerMethods + public void mouseDragged(MouseEvent e) { if (e.isPopupTrigger()) return; } - public void mouseMoved(MouseEvent e) - { + public void mouseMoved(MouseEvent e) + { if (e.isPopupTrigger()) return; @@ -222,49 +222,49 @@ public void mouseMoved(MouseEvent e) DrawingState state = getDrawingState((JTable) e.getComponent(), e.getPoint()); if (state == null) return; - + MouseEvent evt = getTranslatedMouseEvent(e, cellRect); MutableInterval interval = (MutableInterval) getInterval( evt.getPoint(), - 3, - state, + 3, + state, GanttTable.TIME_AXIS); - + Object key = (interval == null ? null : interval.getKey()); notifyMouseMoved(key); } public MutableInterval getInterval( - Point point, - int buffer, - DrawingState drawing, - Object axisKey) + Point point, + int buffer, + DrawingState drawing, + Object axisKey) { Object key = drawing.getValueAt(point, buffer, buffer); return (MutableInterval) getInterval(key, drawing, axisKey); } - - protected AxisInterval getInterval(Object key, DrawingState drawing, Object axisKey) + + protected AxisInterval getInterval(Object key, DrawingState drawing, Object axisKey) { for (Iterator iter = drawing.parts(); iter.hasNext();) { DrawingPart part = (DrawingPart) iter.next(); if (part.isSummaryPart()) continue; - + AxisInterval[] interval = part.getInterval(key, new AxisInterval[] {}); int index = part.keys().indexOf(axisKey); if (index < 0) continue; - + if (interval != null && index < interval.length && interval[index] != null) return interval[index]; } return null; } - protected Rectangle getCellRect(JTable table, Point location) + protected Rectangle getCellRect(JTable table, Point location) { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); @@ -273,55 +273,55 @@ protected Rectangle getCellRect(JTable table, Point location) return null; return table.getCellRect(row, column, true); - } - - protected MouseEvent getTranslatedMouseEvent(MouseEvent evt, Rectangle cellRect) - { + } + + protected MouseEvent getTranslatedMouseEvent(MouseEvent evt, Rectangle cellRect) + { Point location = new Point(evt.getPoint()); location.translate(-cellRect.x, -cellRect.y); - - - Component component = SwingUtilities.getAncestorOfClass(GanttTable.class, evt.getComponent()) != null + + + Component component = SwingUtilities.getAncestorOfClass(GanttTable.class, evt.getComponent()) != null ? SwingUtilities.getAncestorOfClass(GanttTable.class, evt.getComponent()) : evt.getComponent(); - return location != null ? + return location != null ? new MouseEvent(component, evt.getID(), evt.getWhen(), evt.getModifiers(), location.x, location.y, evt.getClickCount(), evt.isPopupTrigger(), evt.getButton()) : null; - } - - protected DrawingState getDrawingState(JTable table, Point location) + } + + protected DrawingState getDrawingState(JTable table, Point location) { int row = table.rowAtPoint(location); int column = table.columnAtPoint(location); - + if (row < 0 || column < 0) return null; - + Object value = table.getValueAt(row, column); return value instanceof DrawingState ? (DrawingState) value : null; - } - + } + protected static class DefaultColorProvider implements PSGanttColorProvider { - public Color getColor(PSGanttActivity activity) + public Color getColor(PSGanttActivity activity) { return (activity.getViolation() == 0 ? Color.GREEN : Color.RED); } } - + static Map colorMap_; - + static String mapColor(Color c) { String retval = colorMap_.get(c); - + if (retval == null) retval = GradientColorModule.WHITE_GRADIENT_CONTEXT; - + return retval; } - - static + + static { colorMap_ = new HashMap(); colorMap_.put(Color.BLACK, GradientColorModule.BLACK_GRADIENT_CONTEXT); diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGantt.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGantt.java index e0e098fa6..6e94e9d58 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGantt.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGantt.java @@ -3,13 +3,13 @@ import org.ops.ui.main.swing.PSComponentBase; import org.ops.ui.gantt.model.PSGanttModel; -public abstract class PSGantt +public abstract class PSGantt extends PSComponentBase { private static final long serialVersionUID = 1L; - + protected PSGanttModel model_; - + public PSGantt(PSGanttModel model) { model_ = model; diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGanttColorProvider.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGanttColorProvider.java index 68787403b..ad9a3b51b 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGanttColorProvider.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/PSGanttColorProvider.java @@ -3,7 +3,7 @@ import java.awt.Color; import org.ops.ui.gantt.model.PSGanttActivity; -public interface PSGanttColorProvider +public interface PSGanttColorProvider { public Color getColor(PSGanttActivity activity); } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/ResourcePanel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/ResourcePanel.java index 09de2c3b4..f1cc6ca79 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/ResourcePanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/ResourcePanel.java @@ -9,7 +9,7 @@ /** * Single resource profile panel, includes upper and lower lines. - * + * * @author Tatiana Kichkaylo */ public class ResourcePanel extends LinePanel { diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/TimelinePanel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/TimelinePanel.java index 2d7d541ee..ed32da85f 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swing/TimelinePanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swing/TimelinePanel.java @@ -5,7 +5,7 @@ /** * Single resource time line, may include multiple rows of tokens. Rows are * ordered by the earliest token start, ties are broken by the order of arrival. - * + * * @author Tatiana Kichkaylo */ public class TimelinePanel extends LinePanel { @@ -53,7 +53,7 @@ public void addToken(TokenWidget token) { if (index >= lines.size()) { line = new ArrayList(); - + // Insert so that the earliest token starts are sorted int mine = token.getActivity().getStartMin(); for (index=0; index 0 ? token.getViolationExpl() : "--"); parameterViewer.setInput(token); } } - + private void clear() { token = null; refresh(); } - + // Ie no token selected protected void hideViewContents() { noData.heightHint = -1; yesData.heightHint = 0; - + noData.exclude = false; yesData.exclude = true; - + noLabel.setVisible(true); yesComposite.setVisible(false); redraw(); } - + // Ie a token is selected protected void showViewContents() { noData.heightHint = 0; yesData.heightHint = -1; - + noData.exclude = true; yesData.exclude = false; @@ -219,16 +219,16 @@ protected void showViewContents() { yesComposite.setVisible(true); redraw(); } - + private void redraw() { parent.layout(true, true); yesComposite.layout(true, true); - + noLabel.redraw(); yesComposite.redraw(); } - + //********************************************************************* // SolverListener Interface // @@ -252,7 +252,7 @@ private void redraw() { @Override public void afterStepping() { clear(); } - + //********************************************************************* // SolverModelView Interface // @@ -265,7 +265,7 @@ public void setModel() { super.setModel(); clear(); } - + //********************************************************************* // ISelectionListener Interface //********************************************************************* diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GanttView.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GanttView.java index 8711fc2aa..a0637f44c 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GanttView.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GanttView.java @@ -11,7 +11,7 @@ /** * Gantt chart view - SWT version for the Eclipse plugin - * + * * @author Tatiana Kichkaylo, Tristan Smith */ public class GanttView extends GenericGanttView implements SolverListener, diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GenericGanttView.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GenericGanttView.java index 3eacd0f0d..e68113434 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GenericGanttView.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/GenericGanttView.java @@ -36,7 +36,7 @@ /** * Gantt chart view - SWT version for the Eclipse plugin - * + * * @author Tatiana Kichkaylo, Tristan Smith */ public abstract class GenericGanttView extends ViewPart implements ISelectionProvider { @@ -58,7 +58,7 @@ public abstract class GenericGanttView extends ViewPart implements ISelectionPro /** Odd and even background colors */ protected static Color oddBg, evenBg, smallGrid, boldGrid = ColorConstants.gray; - + /** Make this thing configurable? Issue 117 */ private boolean skipEmptyObjects = false; @@ -70,7 +70,7 @@ public abstract class GenericGanttView extends ViewPart implements ISelectionPro @Override public void createPartControl(final Composite parent) { initializeColors(); - + final Sash sash = new Sash(parent, SWT.VERTICAL); labelCanvas = new FigureCanvas(parent, SWT.H_SCROLL); @@ -193,18 +193,18 @@ public void setBounds(org.eclipse.draw2d.geometry.Rectangle rect) { // Register so we can report when user selects tokens: getSite().setSelectionProvider(this); } - + @Override public void setFocus() { } - + protected abstract IGanttModel getGanttModel(); private void doUpdate() { contents.removeAll(); lines.clear(); labelContents.removeAll(); - + IGanttModel gmodel = getGanttModel(); if (gmodel == null) { stepCount = 0; @@ -329,8 +329,8 @@ public void removeSelectionChangedListener( public void setSelection(ISelection selection) { for (ISelectionChangedListener listener : selectionChangedListeners ) { listener.selectionChanged(new SelectionChangedEvent( - this, selection/*getSelection()*/)); + this, selection/*getSelection()*/)); } } - + } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableContentProvider.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableContentProvider.java index 75a3e9fb4..8bfa98b12 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableContentProvider.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableContentProvider.java @@ -8,11 +8,11 @@ import psengine.PSVariableList; /** - * Content provider for token parameters (ie variables), + * Content provider for token parameters (ie variables), * simply returns all variables as an array. - * + * * @author Tristan Smith - * + * */ public class ParameterTableContentProvider implements @@ -29,7 +29,7 @@ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { @Override public Object[] getElements(Object inputElement) { PSToken token = (PSToken) inputElement; - + if(token == null) { return null; } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableLabelProvider.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableLabelProvider.java index 3b05fca4d..de77bfc7a 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableLabelProvider.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ParameterTableLabelProvider.java @@ -8,17 +8,17 @@ import psengine.PSVariable; /** - * Label provider for token parameters (ie variables), assumes you + * Label provider for token parameters (ie variables), assumes you * want the variable name in first column and user-friendly value * in second. - * + * * @author Tristan Smith - * + * */ public class ParameterTableLabelProvider extends ColumnLabelProvider { - + public void update(ViewerCell cell) { Object element = cell.getElement(); cell.setText(getColumnText(element, cell.getColumnIndex())); @@ -32,7 +32,7 @@ public void update(ViewerCell cell) { // @Override public String getColumnText(Object element, int index) { PSVariable variable = (PSVariable) element; - + if(variable == null) { return "--"; } diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ResourcePanel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ResourcePanel.java index 1274bf896..ebb13c449 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ResourcePanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/ResourcePanel.java @@ -9,7 +9,7 @@ /** * Single resource profile panel, includes upper and lower lines. - * + * * @author Tatiana Kichkaylo */ public class ResourcePanel extends LinePanel { diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TimelinePanel.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TimelinePanel.java index f08fe6c06..3e9287a30 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TimelinePanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TimelinePanel.java @@ -7,7 +7,7 @@ /** * Single resource time line, may include multiple rows of tokens. Rows are * ordered by the earliest token start, ties are broken by the order of arrival. - * + * * @author Tatiana Kichkaylo */ public class TimelinePanel extends LinePanel { @@ -25,7 +25,7 @@ public class TimelinePanel extends LinePanel { * (6 + (showDurationLine ? 1 : 0)); private ArrayList> lines = new ArrayList>(); - + public TimelinePanel(String resourceName) { super(resourceName); this.setLayoutManager(null); diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenColor.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenColor.java index 15af5debf..6b0479bfc 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenColor.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenColor.java @@ -5,7 +5,7 @@ /** * Color structure for painting a token - * + * * @author Tatiana */ public class TokenColor { diff --git a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenSelection.java b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenSelection.java index 8d664f04f..565592a1e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenSelection.java +++ b/src/Java/JavaUI/source/org/ops/ui/gantt/swt/TokenSelection.java @@ -6,13 +6,13 @@ public class TokenSelection implements ISelection { private IGanttActivity token; - + TokenSelection(IGanttActivity activity) { this.token = activity; } - + public IGanttActivity getToken() { return token; } - + @Override public boolean isEmpty() { return token == null; diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/EuropaInternalFrame.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/EuropaInternalFrame.java index a77ea3d1d..25b056f77 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/EuropaInternalFrame.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/EuropaInternalFrame.java @@ -13,7 +13,7 @@ /** * Base class for internal frames of Swing version of GUI. This class takes care * of various open/close behavior and supplies check box menu item - * + * * @author Tatiana Kichkaylo */ public class EuropaInternalFrame extends JInternalFrame { @@ -36,7 +36,7 @@ public void internalFrameClosing(InternalFrameEvent e) { } }); } - + /** Minimum/initial size. Made into a method for overriding */ public Dimension getFavoriteSize() { return new Dimension(100, 100); diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/FileNameExtensionFilter.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/FileNameExtensionFilter.java index f2684b203..3e476f12e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/FileNameExtensionFilter.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/FileNameExtensionFilter.java @@ -21,18 +21,18 @@ *

* The following example creates a {@code FileNameExtensionFilter} that will * show {@code jpg} files: - * + * *

  * FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
  * JFileChooser fileChooser = ...;
  * fileChooser.addChoosableFileFilter(filter);
  * 
- * + * * @see FileFilter * @see javax.swing.JFileChooser#setFileFilter * @see javax.swing.JFileChooser#addChoosableFileFilter * @see javax.swing.JFileChooser#getFileFilter - * + * * @version 1.1 02/02/06 * @since 1.6 */ @@ -51,7 +51,7 @@ public final class FileNameExtensionFilter extends FileFilter { * and file name extensions. The returned {@code FileNameExtensionFilter} * will accept all directories and any file with a file name extension * contained in {@code extensions}. - * + * * @param description * textual description for the filter, may be {@code null} * @param extensions @@ -83,7 +83,7 @@ public FileNameExtensionFilter(String description, String... extensions) { * Tests the specified file, returning true if the file is accepted, false * otherwise. True is returned if the extension matches one of the file name * extensions of this {@code FileFilter}, or the file is a directory. - * + * * @param f * the {@code File} to test * @return true if the file is to be accepted, false otherwise @@ -116,7 +116,7 @@ public boolean accept(File f) { /** * The description of this filter. For example: "JPG and GIF Images." - * + * * @return the description of this filter */ @Override @@ -126,7 +126,7 @@ public String getDescription() { /** * Returns the set of file name extensions files are tested against. - * + * * @return the set of file name extensions files are tested against */ public String[] getExtensions() { @@ -140,7 +140,7 @@ public String[] getExtensions() { * This method is intended to be used for debugging purposes, and the * content and format of the returned string may vary between * implementations. - * + * * @return a string representation of this {@code FileNameExtensionFilter} */ @Override diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponent.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponent.java index 4ed5f2b98..ca888efd7 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponent.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponent.java @@ -1,6 +1,6 @@ package org.ops.ui.main.swing; -public interface PSComponent +public interface PSComponent { public void addMouseListener(PSMouseListener l); public void removeMouseListener(PSMouseListener l); diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponentBase.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponentBase.java index b5c843bf7..a14b3a811 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponentBase.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSComponentBase.java @@ -4,32 +4,32 @@ import java.util.ArrayList; import javax.swing.JPanel; -public abstract class PSComponentBase - extends JPanel - implements PSComponent +public abstract class PSComponentBase + extends JPanel + implements PSComponent { private static final long serialVersionUID = 1L; - + List mouseListeners_; - + public PSComponentBase() { mouseListeners_ = new ArrayList(); } - public void addMouseListener(PSMouseListener l) + public void addMouseListener(PSMouseListener l) { mouseListeners_.add(l); } - public void removeMouseListener(PSMouseListener l) + public void removeMouseListener(PSMouseListener l) { mouseListeners_.remove(l); } - + protected void notifyMouseMoved(Object key) { if (key != null) System.out.println("MouseMovedOver{"+key+"}"); - + for (PSMouseListener l : mouseListeners_) { l.mouseMoved(key); } diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSDesktop.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSDesktop.java index 792d045c9..5386f60eb 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSDesktop.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSDesktop.java @@ -53,15 +53,15 @@ public class PSDesktop // protected NddlAshInterpreter nddlInterpreter_; protected JConsole bshConsole_; protected Interpreter bshInterpreter_; - + protected static String debugMode_="g"; protected static String bshFile_=null; public static void main(String[] args) - { + { try { String debugMode = args[0]; - PSUtil.loadLibraries(debugMode); + PSUtil.loadLibraries(debugMode); PSEngine engine = PSEngine.makeInstance(); engine.start(); @@ -72,39 +72,39 @@ public static void main(String[] args) } catch (Exception e) { e.printStackTrace(); - Runtime.getRuntime().exit(-1); + Runtime.getRuntime().exit(-1); } } - - static class ShutdownHook extends Thread + + static class ShutdownHook extends Thread { public ShutdownHook() { super("ShutdownHook"); } - - public void run() + + public void run() { PSDesktop.getInstance().getPSEngine().shutdown(); } - } + } public String getLibsMode() { return debugMode_; } - + public static PSDesktop getInstance() { if (instance_ == null) instance_ = makeInstance(PSEngine.makeInstance(),new String[]{"g",null}); - + return instance_; } - + public static Map parseArgs(String args[]) { Map retval = new HashMap(); String debugMode = "g"; - String bshFile = null; - + String bshFile = null; + if (args.length > 0) debugMode = args[0]; if ((args.length > 1) && (args[1].length()>0)) @@ -112,41 +112,41 @@ public static Map parseArgs(String args[]) retval.put("debugMode", debugMode); retval.put("bshFile",bshFile); - + return retval; } - + public static PSDesktop makeInstance(PSEngine pse,String args[]) { - if (instance_ != null) + if (instance_ != null) throw new RuntimeException("PSDesktop is a singleton"); init(args); instance_ = new PSDesktop(pse); - + return instance_; } public static void init(String[] args) - { - init(parseArgs(args)); + { + init(parseArgs(args)); } - + public static void init(Map args) { debugMode_ = args.get("debugMode"); - bshFile_ = args.get("bshFile"); + bshFile_ = args.get("bshFile"); } - + protected PSDesktop(PSEngine pse) { assert (pse != null); psEngine_ = pse; // nddlInterpreter_ = new NddlAshInterpreter(psEngine_); bshConsole_ = new JConsole(); - bshInterpreter_ = new Interpreter(bshConsole_); + bshInterpreter_ = new Interpreter(bshConsole_); } - + public PSEngine getPSEngine() { return psEngine_; } public void runUI() @@ -236,7 +236,7 @@ public void addBshVariable(String name,Object obj) throw new RuntimeException(e); } } - + protected void registerBshVariables() { addBshVariable("desktop",this); @@ -247,10 +247,10 @@ public PSSolver makeSolver(String config,int horizonStart,int horizonEnd) { PSSolver solver = getPSEngine().createSolver(config); solver.configure(horizonStart,horizonEnd); - + return solver; } - + public PSSolverDialog makeSolverDialog(PSSolver solver) { try { @@ -259,7 +259,7 @@ public PSSolverDialog makeSolverDialog(PSSolver solver) PSSolverDialog d = new PSSolverDialog(this,solver); frame.getContentPane().add(new JScrollPane(d)); frame.setSize(675,375); - + return d; } catch (Exception e) @@ -284,7 +284,7 @@ public void showTokens(PSObject o) } public void showTokens(String title,PSTokenList l) - { + { List columnNames = new ArrayList(); List data = new ArrayList(); columnNames.add("Key"); @@ -308,12 +308,12 @@ public void showTokens(String title,PSTokenList l) } data.add(row); } - + JInternalFrame frame = makeNewFrame(title); JTable table = new JTable(new Util.MatrixTableModel(data,columnNames)); JScrollPane scrollpane = new JScrollPane(table); - frame.getContentPane().add(scrollpane); + frame.getContentPane().add(scrollpane); frame.setSize(frame.getSize()); // Force repaint } @@ -326,7 +326,7 @@ public JInternalFrame makeSchemaBrowserFrame() return frame; } - + public JInternalFrame makeViolationsFrame() { ActionViolationsPanel vp = new ActionViolationsPanel(getPSEngine()); @@ -347,7 +347,7 @@ public JInternalFrame makeDetailsFrame() frame.setSize(300,200); return frame; - } + } public PSResourceChart makeResourceChart(PSResource r,Calendar start) { @@ -361,7 +361,7 @@ public JInternalFrame makeResourcesFrame(String type,Calendar start) { JTabbedPane resourceTabs = new JTabbedPane(); List resources = PSUtil.toResourceList(getPSEngine().getObjectsByType(type)); - for (PSResource r : resources) + for (PSResource r : resources) resourceTabs.add(r.getEntityName(),makeResourceChart(r,start)); JInternalFrame frame = makeNewFrame("Resources"); @@ -370,7 +370,7 @@ public JInternalFrame makeResourcesFrame(String type,Calendar start) return frame; } - + public JInternalFrame makeResourceGanttFrame( String objectsType, Calendar start, @@ -378,7 +378,7 @@ public JInternalFrame makeResourceGanttFrame( { return makeResourceGanttFrame(objectsType,start,end,Calendar.MINUTE); } - + public JInternalFrame makeResourceGanttFrame( String objectsType, Calendar start, @@ -393,8 +393,8 @@ public JInternalFrame makeResourceGanttFrame( return frame; } - -/* + +/* // Creates a table on the results of a JoSQL query public void makeTableFrame(String title,List l,String josqlQry) { @@ -406,12 +406,12 @@ public void makeTableFrame(String title,List l,String josqlQry) model.parse(josqlQry); model.execute(l); - + //Query qry = new Query(); //qry.parse(josqlQry); //List data = qry.execute(l).getResults(); //TableModel model = Util.makeTableModel(data, new String[]{"toString"}); - + JTable table = new JTable(model); JScrollPane scrollpane = new JScrollPane(table); @@ -422,14 +422,14 @@ public void makeTableFrame(String title,List l,String josqlQry) throw new RuntimeException(e); } } - + public void makeNddlConsole() { JInternalFrame nddlInterpFrame = makeNewFrame("Nddl Console"); AshConsole console = new AshConsole(nddlInterpreter_); nddlInterpreter_.setConsole(console); console.setTokenMarker(new NddlTokenMarker()); - nddlInterpFrame.setContentPane(console); + nddlInterpFrame.setContentPane(console); } public void makeAnmlConsole() @@ -440,7 +440,7 @@ public void makeAnmlConsole() anmlInterpreter.setConsole(console); console.setTokenMarker(new AnmlTokenMarker()); anmlInterpFrame.setContentPane(console); - } + } */ } diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSMouseListener.java b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSMouseListener.java index d14e99a7a..154feca1d 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swing/PSMouseListener.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swing/PSMouseListener.java @@ -1,6 +1,6 @@ package org.ops.ui.main.swing; -public interface PSMouseListener +public interface PSMouseListener { public void mouseMoved(Object key); } diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlConfigurationFields.java b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlConfigurationFields.java index 5d2d3b734..f26bc4ebe 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlConfigurationFields.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlConfigurationFields.java @@ -2,7 +2,7 @@ /** * Attribute names in a launch configuration for NDDL models - * + * * @author Tatiana Kichkaylo */ public interface NddlConfigurationFields { diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlLaunchShortcut.java b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlLaunchShortcut.java index 6be867342..b5e6abb22 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlLaunchShortcut.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlLaunchShortcut.java @@ -17,7 +17,7 @@ /** * Launch shortcut to appear in "Run as" menus - * + * * @author Tatiana Kichkaylo */ public class NddlLaunchShortcut implements ILaunchShortcut, diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlModelTab.java b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlModelTab.java index 7d96297b9..c083b2314 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlModelTab.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlModelTab.java @@ -80,11 +80,11 @@ public void widgetSelected(SelectionEvent evt) { fHorizonEnd = createSingleText(comp, 2); fHorizonEnd.addModifyListener(this); } - + public void modifyText(ModifyEvent e) { this.updateLaunchConfigurationDialog(); } - + private Text createSingleText(Composite parent, int hspan) { Text t = new Text(parent, SWT.SINGLE | SWT.BORDER); t.setFont(parent.getFont()); diff --git a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlRunPerspective.java b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlRunPerspective.java index 2c832e814..7dcc2c988 100644 --- a/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlRunPerspective.java +++ b/src/Java/JavaUI/source/org/ops/ui/main/swt/NddlRunPerspective.java @@ -55,7 +55,7 @@ private void addViews() { IPageLayout.RIGHT, 0.3f, factory.getEditorArea()); bottomRight.addView(DetailsView.VIEW_ID); bottomRight.addView(IPageLayout.ID_RES_NAV); - + // Little buttons at the bottom. Left from the template factory.addFastView("org.eclipse.team.ccvs.ui.RepositoriesView", 0.50f); // NON-NLS-1 factory.addFastView("org.eclipse.team.sync.views.SynchronizeView", diff --git a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionDetailsPanel.java b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionDetailsPanel.java index 1a56107de..0947c260e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionDetailsPanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionDetailsPanel.java @@ -6,32 +6,32 @@ import psengine.PSVariable; import psengine.PSVariableList; -public class ActionDetailsPanel - extends MouseListenerPanel +public class ActionDetailsPanel + extends MouseListenerPanel { private static final long serialVersionUID = 7779941401503562818L; protected PSEngine psengine_ = null; - + public ActionDetailsPanel(PSEngine pse) { psengine_ = pse; } - + @Override - public void mouseMoved(Object key) + public void mouseMoved(Object key) { - if (key == null) + if (key == null) text_.setText(""); - else + else text_.setText(getDetails((Integer)key)); } - + protected String getDetails(Integer key) { return tokenDetails(psengine_.getTokenByKey(key)); } - + protected String tokenDetails(PSToken t) { StringBuffer buf = new StringBuffer(); @@ -40,7 +40,7 @@ protected String tokenDetails(PSToken t) .append("Name : ").append(t.getEntityName()).append("\n") .append("isFact : ").append(t.isFact()).append("\n") ; - + if (t.getParameters().size() > 0) { buf.append("Parameters:").append("\n"); PSVariableList parameters = t.getParameters(); @@ -49,7 +49,7 @@ protected String tokenDetails(PSToken t) buf.append(p.getEntityName()).append(" : ").append(p.toString()).append("\n"); } } - + return buf.toString(); - } + } } diff --git a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionViolationsPanel.java b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionViolationsPanel.java index 744d444e9..af861a2a0 100644 --- a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionViolationsPanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/ActionViolationsPanel.java @@ -3,34 +3,34 @@ import psengine.PSEngine; import psengine.PSToken; -public class ActionViolationsPanel - extends MouseListenerPanel +public class ActionViolationsPanel + extends MouseListenerPanel { private static final long serialVersionUID = 7462693069863073725L; protected PSEngine psengine_ = null; - + public ActionViolationsPanel(PSEngine pse) { psengine_ = pse; } - + @Override - public void mouseMoved(Object key) + public void mouseMoved(Object key) { - if (key == null) + if (key == null) text_.setText(""); - else + else text_.setText(getViolations((Integer)key)); } - + protected String getViolations(Integer key) { return tokenViolations(psengine_.getTokenByKey(key)); } - + protected String tokenViolations(PSToken t) { return t.getViolationExpl(); - } + } } diff --git a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/MouseListenerPanel.java b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/MouseListenerPanel.java index 9f0911f16..4fc5b8175 100644 --- a/src/Java/JavaUI/source/org/ops/ui/mouse/swing/MouseListenerPanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/mouse/swing/MouseListenerPanel.java @@ -6,17 +6,17 @@ public abstract class MouseListenerPanel extends JPanel - implements PSMouseListener + implements PSMouseListener { private static final long serialVersionUID = 1L; - + protected JTextArea text_; - + public MouseListenerPanel() { text_ = new JTextArea(""); - add(text_); + add(text_); } - + public abstract void mouseMoved(Object key); } diff --git a/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartModel.java b/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartModel.java index 25d7b8a5d..a7a7d84e8 100644 --- a/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartModel.java @@ -5,7 +5,7 @@ import psengine.PSResourceProfile; -public interface PSResourceChartModel +public interface PSResourceChartModel { public PSResourceProfile getCapacity(); public PSResourceProfile getUsage(); diff --git a/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartPSEModel.java b/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartPSEModel.java index 598c1d00d..ee12d09af 100644 --- a/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartPSEModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/rchart/model/PSResourceChartPSEModel.java @@ -3,37 +3,37 @@ import psengine.PSResource; import psengine.PSResourceProfile; -public class PSResourceChartPSEModel - implements PSResourceChartModel +public class PSResourceChartPSEModel + implements PSResourceChartModel { protected PSResource resource_; - + public PSResourceChartPSEModel(PSResource resource) { resource_ = resource; } - public PSResourceProfile getCapacity() + public PSResourceProfile getCapacity() { return resource_.getCapacity(); } - public PSResourceProfile getUsage() + public PSResourceProfile getUsage() { return resource_.getUsage(); - } + } - public PSResourceProfile getLimit() + public PSResourceProfile getLimit() { return resource_.getLimits(); } - public PSResourceProfile getFDLevel() + public PSResourceProfile getFDLevel() { return resource_.getFDLevels(); } - - public PSResourceProfile getVDLevel() + + public PSResourceProfile getVDLevel() { return resource_.getVDLevels(); } diff --git a/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSJFreeResourceChart.java b/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSJFreeResourceChart.java index 1ed118bb7..3d37fdb5e 100644 --- a/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSJFreeResourceChart.java +++ b/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSJFreeResourceChart.java @@ -27,31 +27,31 @@ import psengine.PSTimePointList; import org.ops.ui.rchart.model.PSResourceChartModel; -public class PSJFreeResourceChart - extends PSResourceChart +public class PSJFreeResourceChart + extends PSResourceChart { /** - * + * */ private static final long serialVersionUID = 9008639833839752404L; - + JFreeChart chart_; Calendar start_; - + public PSJFreeResourceChart(String resourceName, PSResourceChartModel model, Calendar start) { super(model,resourceName); - + start_ = start; chart_ = createChart(); JPanel chartPanel = makeResourcePanel(chart_); setLayout(new BorderLayout()); add(new JScrollPane(chartPanel)); } - - protected JFreeChart createChart() + + protected JFreeChart createChart() { XYDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createTimeSeriesChart( @@ -73,42 +73,42 @@ protected JFreeChart createChart() plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); - + XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); } - + DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yy")); - + return chart; - } - + } + protected JPanel makeResourcePanel(JFreeChart chart) { ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(500, 270)); chartPanel.setMouseZoomable(true, false); - + return chartPanel; - } + } - protected XYDataset createDataset() - { + protected XYDataset createDataset() + { TimeSeriesCollection dataset = new TimeSeriesCollection(); int seriesCnt = 5; TimeSeries ts[] = new TimeSeries[seriesCnt]; - + ts[0] = resourceProfileToTimeSeries("FD Level Lower Bound", model_.getFDLevel(),false); ts[1] = resourceProfileToTimeSeries("FD Level Upper Bound", model_.getFDLevel(),true); ts[2] = resourceProfileToTimeSeries("Limit Lower Bound", model_.getLimit(),false); ts[3] = resourceProfileToTimeSeries("Limit Upper Bound", model_.getLimit(),true); ts[4] = resourceProfileToTimeSeries("Capacity", model_.getCapacity(),true); - + RegularTimePeriod maxX = new Minute(((Calendar)start_.clone()).getTime()); for (int i=0;i= einfinity) continue; - + // Display a step function if ((lastTime >=0) && (lastValue != value) && (i-lastTime > 1)) { time.add(Calendar.MINUTE, -1); @@ -176,11 +176,11 @@ protected TimeSeries resourceProfileToTimeSeries(String name,PSResourceProfile r ts.addOrUpdate(t1,lastValue); } - ts.addOrUpdate(t,value); + ts.addOrUpdate(t,value); lastTime = i; lastValue = value; } - - return ts; + + return ts; } } diff --git a/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSResourceChart.java b/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSResourceChart.java index 174424a99..bd0ef66b6 100644 --- a/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSResourceChart.java +++ b/src/Java/JavaUI/source/org/ops/ui/rchart/swing/PSResourceChart.java @@ -5,12 +5,12 @@ // TODO: do we really need a specialized ResourceChart, or just a generic time series chart will suffice? -public abstract class PSResourceChart +public abstract class PSResourceChart extends PSComponentBase { protected PSResourceChartModel model_; protected String resourceName_; - + public PSResourceChart(PSResourceChartModel model, String resourceName) { model_ = model; diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModel.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModel.java index 5f68065b5..264f25041 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModel.java @@ -1,7 +1,7 @@ package org.ops.ui.schemabrowser.model; -public interface SchemaModel +public interface SchemaModel { public boolean isInitialized(); public SchemaNode getObjectTypesNode(); -} \ No newline at end of file +} diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModelImpl.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModelImpl.java index e10d7cc13..121aab177 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModelImpl.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaModelImpl.java @@ -19,79 +19,79 @@ /** * Accessor class for EUROPA schema. Uses PSEngine to get actual data - * + * */ -public class SchemaModelImpl implements SchemaModel +public class SchemaModelImpl implements SchemaModel { /** Solver model pointing to loaded files and PSEngine to do all the work */ protected PSEngine engine_; - - public SchemaModelImpl(PSEngine e) + + public SchemaModelImpl(PSEngine e) { engine_ = e; } /** Make a node for object types */ - public SchemaNode getObjectTypesNode() + public SchemaNode getObjectTypesNode() { if (!isInitialized()) return null; SchemaNode rootNode = new SchemaNode(Type.CATEGORY, "Object types"); PSObjectTypeList types = engine_.getPSSchema().getAllPSObjectTypes(); - for (int i = 0; i < types.size(); i++) + for (int i = 0; i < types.size(); i++) rootNode.add(makeObjectTypeNode(types.get(i))); return rootNode; } - + protected SchemaNode makeObjectTypeNode(PSObjectType type) { SchemaNode typeNode = new SchemaNode( - Type.OBJECT_TYPE, - type.getNameString(), + Type.OBJECT_TYPE, + type.getNameString(), type.getParentName()); - + PSStringList members = type.getMemberNames(); - for (int j = 0; j < members.size(); j++) + for (int j = 0; j < members.size(); j++) typeNode.add(makeObjectMemberNode(type,members.get(j))); PSTokenTypeList preds = type.getPredicates(); - for (int j = 0; j < preds.size(); j++) + for (int j = 0; j < preds.size(); j++) typeNode.add(makeTokenTypeNode(preds.get(j))); - + return typeNode; } - + protected SchemaNode makeObjectMemberNode(PSObjectType type,String memberName) { - PSDataType mtype = type.getMemberTypeRef(memberName); + PSDataType mtype = type.getMemberTypeRef(memberName); return new SchemaNode( - Type.OBJECT_TYPE_MEMBER, + Type.OBJECT_TYPE_MEMBER, memberName, mtype); } - + protected SchemaNode makeTokenTypeNode(PSTokenType ttype) { SchemaNode pnode = new SchemaNode( - Type.TOKEN_TYPE, + Type.TOKEN_TYPE, ttype.getName()); - + PSStringList argNames = ttype.getParameterNames(); for (int k = 0; k < argNames.size(); k++) { PSDataType atype = ttype.getParameterType(k); pnode.add(new SchemaNode( Type.TOKEN_TYPE_PARAMETER, - argNames.get(k), + argNames.get(k), atype)); } return pnode; } - - public boolean isInitialized() + + public boolean isInitialized() { return engine_ != null; } diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaNode.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaNode.java index f2b33ef59..4d8fa15d9 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaNode.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaNode.java @@ -7,10 +7,10 @@ /** * Node of the schema tree. - * + * * @author Tatiana Kichkaylo */ -public class SchemaNode +public class SchemaNode { /** Seed for conversion to array */ private final static SchemaNode[] seedArray = {}; @@ -123,22 +123,22 @@ public void clear() { children.clear(); } - public void setFileLocation(FileLocation fl) + public void setFileLocation(FileLocation fl) { this.fileLocation = fl; } - public FileLocation getFileLocation() + public FileLocation getFileLocation() { return fileLocation; } - + public static class FileLocation { public String filename; public int startLine; public int endLine; - + public FileLocation(String fn, int sl, int el) { filename = fn; diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaSolverModel.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaSolverModel.java index 41f11476d..ec9918f4d 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaSolverModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/model/SchemaSolverModel.java @@ -11,26 +11,26 @@ /** * Accessor class for EUROPA schema. Uses PSEngine to get actual data - * + * * TODO JRB: this class shouldn't be needed, the PSSchema API should be extended to provide file location info * which is the only thing this class adds - * + * */ -public class SchemaSolverModel extends SchemaModelImpl +public class SchemaSolverModel extends SchemaModelImpl { /** Solver model pointing to loaded files and PSEngine to do all the work */ protected SolverModel model; protected HashMap astMap = null; - - public SchemaSolverModel(SolverModel model) + + public SchemaSolverModel(SolverModel model) { super(model != null ? model.getEngine() : null); this.model = model; } /** Make a node for object types */ - public SchemaNode getObjectTypesNode() + public SchemaNode getObjectTypesNode() { if (!isInitialized()) return null; @@ -42,22 +42,22 @@ public SchemaNode getObjectTypesNode() return super.getObjectTypesNode(); } - + protected SchemaNode makeObjectTypeNode(PSObjectType type) { SchemaNode typeNode = super.makeObjectTypeNode(type); - + AstNode ast = astMap.get(typeNode.getName()); if (ast != null) typeNode.setFileLocation(new SchemaNode.FileLocation( ast.getFileName(), ast.getLine(), ast.getEndLine())); - + return typeNode; } - - private void collectClasses(AstNode ast, HashMap map) + + private void collectClasses(AstNode ast, HashMap map) { if (ast.getType() == AstNodeTypes.CLASS_DEF) { map.put(ast.getChildren().get(0).getText(), ast); @@ -67,7 +67,7 @@ private void collectClasses(AstNode ast, HashMap map) } } - public boolean isInitialized() + public boolean isInitialized() { return super.isInitialized() && (model != null) && !model.isTerminated(); } diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaTreeModel.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaTreeModel.java index cb4455571..b374759c8 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaTreeModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaTreeModel.java @@ -12,7 +12,7 @@ /** * Convert schema nodes into Swing tree model - * + * * @author Tatiana Kichkaylo */ public class SchemaTreeModel implements TreeModel { diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaView.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaView.java index 4efb9fdd4..b3feb4b96 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaView.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swing/SchemaView.java @@ -12,10 +12,10 @@ public class SchemaView extends JPanel { /** - * + * */ private static final long serialVersionUID = 1L; - + private JTree tree; private SchemaTreeModel treeModel; @@ -24,7 +24,7 @@ public SchemaView(SchemaModel model) { this.treeModel = new SchemaTreeModel(model); setLayout(new BorderLayout()); - + // Widgets this.tree = new JTree(treeModel); this.add(new JScrollPane(tree)); diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaContentProvider.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaContentProvider.java index d2cb41fd0..cf7b8f60f 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaContentProvider.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaContentProvider.java @@ -7,7 +7,7 @@ /** * Wrapping SchemaSource as a SWT content provider - * + * * @author Tatiana Kichkaylo */ public class SchemaContentProvider implements ITreeContentProvider { @@ -26,7 +26,7 @@ public SchemaContentProvider(SchemaModel model) { public void setModel(SchemaModel model) { this.model = model; } - + public void dispose() { } diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaLabelProvider.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaLabelProvider.java index fe43ba6c5..23c8aba02 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaLabelProvider.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaLabelProvider.java @@ -13,7 +13,7 @@ /** * Label and icon provider for the SWT version of schema browser - * + * * @author Tatiana Kichkaylo */ public class SchemaLabelProvider extends LabelProvider implements diff --git a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaView.java b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaView.java index 97272c7e0..55b81ff73 100644 --- a/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaView.java +++ b/src/Java/JavaUI/source/org/ops/ui/schemabrowser/swt/SchemaView.java @@ -22,7 +22,7 @@ /** * Europa schema browser - SWT version - * + * * @author Tatiana Kichkaylo */ public class SchemaView extends SolverModelViewImpl { diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverAdapter.java b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverAdapter.java index 0f469521e..7cfbbaaf3 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverAdapter.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverAdapter.java @@ -3,7 +3,7 @@ /** * Convenience class: empty implementation of SolverListener. The class is made * abstract to force clients to provide at least some methods. - * + * * @author Tatiana Kichkaylo */ public abstract class SolverAdapter implements SolverListener { diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverListener.java b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverListener.java index 36086c556..790de256f 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverListener.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverListener.java @@ -2,22 +2,22 @@ /** * Listener to Solver Model - * + * * @author Tatiana Kichkaylo */ public interface SolverListener { /** Solver started/restarted */ public void solverStarted(); - + /** Solver stopped */ public void solverStopped(); - + /** Called before the solver starts running */ public void beforeStepping(); /** * Called each time new statistics are available, even mid-run - * + * * @param time * stepping time in ms */ diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverModel.java b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverModel.java index 618a9d266..e9a0fcf68 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverModel.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/model/SolverModel.java @@ -11,8 +11,8 @@ /** * Solver model corresponds to a single engine, or "run". Each launch of an NDDL - * model creates a separate solver model. - * + * model creates a separate solver model. + * * @author tatiana */ @@ -25,10 +25,10 @@ public class SolverModel { /** Property name in the engine config: list of search paths for includes */ private final String INCLUDE_PATH = "nddl.includePath"; - + protected Logger log = Logger.getLogger(getClass().getName()); private PSEngine engine = null; - private PSSolver solver = null; + private PSSolver solver = null; private ArrayList listeners = new ArrayList(); private ArrayList stepStatistics = new ArrayList(); @@ -40,7 +40,7 @@ public class SolverModel { private int horizonStart, horizonEnd; /** Planner configuration file */ private File plannerConfig = null; - + public void configure(File modelFile, File plannerConfigFile, int horizonStart, int horizonEnd) { this.modelFile = modelFile; @@ -69,11 +69,11 @@ public void loadNddlFile(File file) { this.engine.getConfig().setProperty(INCLUDE_PATH, oldPath); } } - + public File getModelFile() { return this.modelFile; } - + public File getPlannerConfig() { return this.plannerConfig; } @@ -113,7 +113,7 @@ public void removeSolverListener(SolverListener lnr) { /** * Make one step (assuming we can) - * + * * @return time in ms */ public long stepOnce() { @@ -163,7 +163,7 @@ public StepStatisticsRecord getStepStatistics(int step) { public boolean isTerminated() { return solver == null; } - + /** Start and configure engine. Assume it is not already running */ public synchronized void start() { if (engine != null) diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/model/StepStatisticsRecord.java b/src/Java/JavaUI/source/org/ops/ui/solver/model/StepStatisticsRecord.java index 09f433b64..54484a1a1 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/model/StepStatisticsRecord.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/model/StepStatisticsRecord.java @@ -7,7 +7,7 @@ /** * A single record containing various aspects of step statistics - * + * * @author Tatiana Kichkaylo */ public class StepStatisticsRecord { @@ -29,7 +29,7 @@ public static StepStatisticsRecord getEmpty() { /** * Create a record for the current state of the solver. - * + * * @param solver * the solver to read data from * @param timeMs diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/model/TimeFormatHelper.java b/src/Java/JavaUI/source/org/ops/ui/solver/model/TimeFormatHelper.java index 15c8919f2..ec91c499f 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/model/TimeFormatHelper.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/model/TimeFormatHelper.java @@ -3,7 +3,7 @@ import java.text.NumberFormat; public abstract class TimeFormatHelper { - + private TimeFormatHelper() {} private final static NumberFormat decimal3 = NumberFormat diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/swing/ConsoleView.java b/src/Java/JavaUI/source/org/ops/ui/solver/swing/ConsoleView.java index e0245f64b..396ee0f5d 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/swing/ConsoleView.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/swing/ConsoleView.java @@ -8,7 +8,7 @@ /** * A read-only view to capture engine's error output. Used by PSSolverDialog. - * + * * @author Tatiana */ public class ConsoleView extends EuropaInternalFrame { diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsPanel.java b/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsPanel.java index ac074fa08..8d57b4aa8 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsPanel.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsPanel.java @@ -22,8 +22,8 @@ import org.ops.ui.utils.swing.Util; -public class OpenDecisionsPanel - extends JPanel +public class OpenDecisionsPanel + extends JPanel implements ActionListener { private static final long serialVersionUID = 2128067653391774807L; @@ -43,25 +43,25 @@ public class OpenDecisionsPanel // so need to keep track explicitly protected List snList_; // StepNumbers protected List ledList_; // LastExecutedDecisions - + public OpenDecisionsPanel() { odList_ = new Vector>(); snList_ = new Vector(); ledList_ = new Vector(); - + currentIdx_ = -1; - + labelTotal_ = new JLabel(makeLabelTotal(),SwingConstants.CENTER); labelCurrent_ = new JLabel(makeLabelCurrent(),SwingConstants.CENTER); JPanel btnPanel = new JPanel(new FlowLayout()); - + btnPrev_ = new JButton("<<"); btnPrev_.addActionListener(this);btnPrev_.setActionCommand("prev"); btnNext_ = new JButton(">>"); btnNext_.addActionListener(this);btnNext_.setActionCommand("next"); checkButtons(); JButton btn; btn = new JButton("Go To Step"); btn.addActionListener(this);btn.setActionCommand("goto"); - + gotoIdx_ = new JTextField(6); btnPanel.add(btnPrev_); btnPanel.add(btnNext_); @@ -70,53 +70,53 @@ public OpenDecisionsPanel() lastExecutedDecision_ = new JTextArea(5,10); lastExecutedDecision_.setLineWrap(true); - + JPanel topPanel = new JPanel(new BorderLayout()); JPanel p = new JPanel(new GridLayout(3,1)); p.add(labelTotal_); p.add(btnPanel); p.add(new JLabel("Last Executed Decision",SwingConstants.CENTER)); - + ledTable_ = new JTable(); ledTable_.setTableHeader(null); ledTable_.setPreferredScrollableViewportSize(new Dimension(500, 70)); - + JTabbedPane tp = new JTabbedPane(); tp.addTab("As Table", new JScrollPane(ledTable_)); tp.addTab("As Text", new JScrollPane(lastExecutedDecision_)); topPanel.add(BorderLayout.NORTH,p); - topPanel.add(BorderLayout.CENTER,tp); + topPanel.add(BorderLayout.CENTER,tp); odTable_ = new JTable(Util.makeTableModel(odList_,new String[]{"toString"})); odTable_.setTableHeader(null); odTable_.setPreferredScrollableViewportSize(new Dimension(500, 70)); - + setLayout(new BorderLayout()); add(BorderLayout.NORTH, topPanel); - + JPanel odPanel = new JPanel(new BorderLayout()); odPanel.add(BorderLayout.NORTH,labelCurrent_); - odPanel.add(BorderLayout.CENTER, new JScrollPane(odTable_)); - add(BorderLayout.CENTER, odPanel); + odPanel.add(BorderLayout.CENTER, new JScrollPane(odTable_)); + add(BorderLayout.CENTER, odPanel); } - + protected String makeLabelTotal() { String retval = "Open Decisions for "+odList_.size()+" steps are available"; - + return retval; } protected String makeLabelCurrent() { String retval=""; - + if (currentIdx_ >= 0) retval = "Currently looking at "+ odList_.get(currentIdx_).size() +" Open Decisions for step "+snList_.get(currentIdx_); - + return retval; } - + protected void checkButtons() { btnPrev_.setEnabled(currentIdx_ > 0); @@ -126,9 +126,9 @@ protected void checkButtons() protected void updateTable() { // TODO: put in Swing thread? - odTable_.setModel(Util.makeTableModel(odList_.get(currentIdx_),new String[]{"toString"})); + odTable_.setModel(Util.makeTableModel(odList_.get(currentIdx_),new String[]{"toString"})); } - + protected void updateStatus() { checkButtons(); @@ -137,37 +137,37 @@ protected void updateStatus() String led = ledList_.get(currentIdx_); lastExecutedDecision_.setText(led); lastExecutedDecision_.setCaretPosition(0); - + List details = new Vector(); StringTokenizer tok = new StringTokenizer(led,":"); - while (tok.hasMoreTokens()) + while (tok.hasMoreTokens()) details.add(tok.nextToken()); // TODO: put in Swing thread? - ledTable_.setModel(Util.makeTableModel(details,new String[]{"toString"})); + ledTable_.setModel(Util.makeTableModel(details,new String[]{"toString"})); } - + protected void showNext() { currentIdx_++; updateStatus(); } - + protected void showPrev() { currentIdx_--; updateStatus(); } - + protected void beep() { - java.awt.Toolkit.getDefaultToolkit().beep(); + java.awt.Toolkit.getDefaultToolkit().beep(); } - + protected void gotoStep() { int step; - + try { step = new Integer(gotoIdx_.getText()); } @@ -176,46 +176,46 @@ protected void gotoStep() beep(); return; } - + for (int i=0;i < snList_.size();i++) { if (snList_.get(i)==step) { currentIdx_=i; updateStatus(); } } - + // TODO: display error message beep(); } - + public void addEntry(int stepNumber,List od,String lastExecutedDecision) { snList_.add(stepNumber); odList_.add(od); ledList_.add(lastExecutedDecision); - + if (snList_.size() == 1) showNext(); - + checkButtons(); labelTotal_.setText(makeLabelTotal()); } - - public void actionPerformed(ActionEvent e) + + public void actionPerformed(ActionEvent e) { if ("next".equals(e.getActionCommand())) { showNext(); return; - } + } if ("prev".equals(e.getActionCommand())) { showPrev(); return; - } + } if ("goto".equals(e.getActionCommand())) { gotoStep(); return; - } - } + } + } } diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsView.java b/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsView.java index ff4d49a48..eeff9deea 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsView.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/swing/OpenDecisionsView.java @@ -28,7 +28,7 @@ /** * Panel for open decisions. This panel listens to SolverModel and gets all data * from it. - * + * * @author Tatiana Kichkaylo */ public class OpenDecisionsView extends EuropaInternalFrame { diff --git a/src/Java/JavaUI/source/org/ops/ui/solver/swing/PSSolverDialog.java b/src/Java/JavaUI/source/org/ops/ui/solver/swing/PSSolverDialog.java index 9a84f9660..23bbf50fb 100644 --- a/src/Java/JavaUI/source/org/ops/ui/solver/swing/PSSolverDialog.java +++ b/src/Java/JavaUI/source/org/ops/ui/solver/swing/PSSolverDialog.java @@ -40,19 +40,19 @@ import psengine.PSSolver; import psengine.PSStringList; -public class PSSolverDialog +public class PSSolverDialog extends JPanel implements ActionListener { private static final long serialVersionUID = -7130640151223933584L; - + protected JTextField horizonStart_ = new JTextField("0"); protected JTextField horizonEnd_ = new JTextField("5760"); protected JTextField maxSteps_ = new JTextField("2000"); protected JTextField maxDepth_ = new JTextField("100000"); protected JTextField configFile_ = new JTextField("../Crew1/PlannerConfig.xml"); protected JTextField incSteps_ = new JTextField("500",8); - + protected JButton btnConfigure_= new JButton("Configure"); protected JButton btnStep_= new JButton("Go"); protected JButton btnSolve_ = new JButton("Solve"); @@ -60,30 +60,30 @@ public class PSSolverDialog protected JLabel lblRunTime_ = new JLabel(format(startTime_)); protected JLabel lblStepCnt_ = new JLabel("0"); protected JLabel lblMaxStepCnt_ = new JLabel("0"); - + protected XYSeries solverDepthSeries_; protected XYSeries stepTimeSeries_; protected XYSeries stepAvgTimeSeries_; protected double totalTime_; protected XYSeries decisionCntSeries_; protected JPanel chartsPanel_; - + protected OpenDecisionsPanel openDecisions_; - + protected JSplitPane topSplitPane_; - + protected PSDesktop desktop_; protected PSSolver solver_; protected Integer maxStepsValue_=100; protected Integer maxDepthValue_=100; - + protected List listeners_ = new Vector(); - + public PSSolverDialog(PSDesktop desktop,PSSolver solver) { desktop_ = desktop; solver_ = solver; - + if (solver != null) { horizonStart_ = new JTextField(new Integer(solver_.getHorizonStart()).toString(),15); horizonEnd_ = new JTextField(new Integer(solver_.getHorizonEnd()).toString(),15); @@ -92,18 +92,18 @@ public PSSolverDialog(PSDesktop desktop,PSSolver solver) configFile_ = new JTextField(solver_.getConfigFilename()); incSteps_ = new JTextField(maxStepsValue_.toString(),8); } - + totalTime_ = 0; - + JPanel solverPanel = new JPanel(new BorderLayout()); JTabbedPane tp = new JTabbedPane(); tp.add("Run",makeRunPanel()); tp.add("Configure",makeConfigPanel()); solverPanel.add(tp); - - openDecisions_ = new OpenDecisionsPanel(); - setLayout(new BorderLayout()); + openDecisions_ = new OpenDecisionsPanel(); + + setLayout(new BorderLayout()); add(solverPanel); JInternalFrame frame = desktop_.makeNewFrame("Solver Open Decisions"); @@ -111,10 +111,10 @@ public PSSolverDialog(PSDesktop desktop,PSSolver solver) frame.setSize(400,400); frame.setLocation(700,20); } - + public void addListener(PSSolverDialogListener l) { listeners_.add(l); } public void removeListener(PSSolverDialogListener l) { listeners_.remove(l); } - + protected JPanel makeConfigPanel() { JPanel p = new JPanel(new FlowLayout()); @@ -129,24 +129,24 @@ protected JPanel makeConfigPanel() btnConfigure_.addActionListener(this);btnConfigure_.setActionCommand("configure"); - JPanel buttonPanel = new JPanel(new FlowLayout()); - buttonPanel.add(btnConfigure_); - + JPanel buttonPanel = new JPanel(new FlowLayout()); + buttonPanel.add(btnConfigure_); + JPanel p1 = new JPanel(new BorderLayout()); p1.add(BorderLayout.CENTER,configPanel); p1.add(BorderLayout.SOUTH,buttonPanel); p.add(p1); - + return p; } - + protected JPanel makeRunPanel() { JPanel p = new JPanel(new BorderLayout()); - + chartsPanel_ = new JPanel(new GridLayout(1,3)); - + stepTimeSeries_ = new XYSeries("Time (secs) per Step"); stepAvgTimeSeries_ = new XYSeries("Avg Time (secs) per Step"); chartsPanel_.add(makeChartPanel( @@ -156,7 +156,7 @@ protected JPanel makeRunPanel() new XYSeries[]{stepTimeSeries_,stepAvgTimeSeries_}, false // Create legend )); - + decisionCntSeries_ = new XYSeries("Open Decision Cnt"); chartsPanel_.add(makeChartPanel( "Open Decision Count", // title @@ -164,7 +164,7 @@ protected JPanel makeRunPanel() "Open Decision Count", // y-axis label new XYSeries[]{decisionCntSeries_}, false // Create legend - )); + )); solverDepthSeries_ = new XYSeries("Decisions in Plan"); chartsPanel_.add(makeChartPanel( @@ -173,7 +173,7 @@ protected JPanel makeRunPanel() "Decisions in Plan", // y-axis label new XYSeries[]{solverDepthSeries_}, false // Create legend - )); + )); btnStep_.addActionListener(this);btnStep_.setActionCommand("step"); btnSolve_.addActionListener(this);btnSolve_.setActionCommand("solve"); @@ -181,14 +181,14 @@ protected JPanel makeRunPanel() boolean enabled = solver_ != null; btnStep_.setEnabled(enabled); btnSolve_.setEnabled(enabled); - + JPanel buttonPanel = new JPanel(new GridLayout(1,4)); /* lblMaxStepCnt_.setText(solver_.getMaxSteps().toString()); buttonPanel.add(new JLabel("Max Step Count : ")); buttonPanel.add(lblMaxStepCnt_); */ - + buttonPanel.add(new JLabel("Run for")); buttonPanel.add(incSteps_); buttonPanel.add(new JLabel("steps")); @@ -200,12 +200,12 @@ protected JPanel makeRunPanel() JPanel totalsPanel = new JPanel(new GridLayout(1,4)); lblStepCnt_.setText(Integer.toString(solver_.getStepCount())); totalsPanel.add(new JLabel("Step Count : ")); - totalsPanel.add(lblStepCnt_); + totalsPanel.add(lblStepCnt_); totalsPanel.add(new JLabel("Run Time :")); totalsPanel.add(lblRunTime_); JPanel p2 = new JPanel(new FlowLayout()); p2.add(totalsPanel); - + JPanel p3 = new JPanel(new FlowLayout()); p3.add(chartsPanel_); p.add(BorderLayout.NORTH,p1); @@ -224,12 +224,12 @@ protected JPanel makeChartPanel( XYSeriesCollection dataset = new XYSeriesCollection(); for (XYSeries s : series) dataset.addSeries(s); - + JFreeChart chart = createChart(title,xAxisLabel,yAxisLabel,dataset,createLegend); return makeChartPanel(chart); } - + protected JPanel makeChartPanel(JFreeChart chart) { JPanel p = new JPanel(new BorderLayout()); @@ -237,37 +237,37 @@ protected JPanel makeChartPanel(JFreeChart chart) ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(200, 150)); chartPanel.setMouseZoomable(true, false); - + Border border = BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(1, 1, 1, 1), BorderFactory.createEtchedBorder() ); chartPanel.setBorder(border); - + p.add(new JScrollPane(chartPanel)); return p; } - + protected JFreeChart createChart( String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, - boolean createLegend) + boolean createLegend) { JFreeChart chart = ChartFactory.createXYLineChart( title, xAxisLabel, yAxisLabel, - dataset, + dataset, PlotOrientation.VERTICAL, createLegend, // create legend? true, // generate tooltips? false // generate URLs? ); - + chart.setBackgroundPaint(Color.white); - + XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); @@ -275,17 +275,17 @@ protected JFreeChart createChart( plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); - + XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); } - + return chart; - } - + } + public void configureSolver() { int horizonStart = getInteger(horizonStart_.getText()); @@ -294,36 +294,36 @@ public void configureSolver() solver_ = desktop_.getPSEngine().createSolver(config); solver_.configure(horizonStart,horizonEnd); } - + protected int getInteger(String text) { return new Integer(text.trim()); } - + public void stepSolver() { try { startTime_ = System.currentTimeMillis(); setButtons(false); - + int maxIter = getInteger(incSteps_.getText()); int stepCnt = solver_.getStepCount(); int max = stepCnt+maxIter; - - for (int i=1; solver_.hasFlaws() + + for (int i=1; solver_.hasFlaws() && !solver_.isExhausted() && !solver_.isTimedOut() - && stepCnt SWIGList(Object list) { try { List retval = new Vector(); - + Method m = list.getClass().getMethod("size", (Class[])null); int size = (Integer)m.invoke(list,(Object[])null); m = list.getClass().getMethod("get", new Class[]{int.class}); @@ -64,7 +64,7 @@ public static List SWIGList(Object list) args[0] = i; retval.add(m.invoke(list, args)); } - + return retval; } catch (Exception e) { diff --git a/src/Java/JavaUI/source/org/ops/ui/utils/swing/Util.java b/src/Java/JavaUI/source/org/ops/ui/utils/swing/Util.java index ca0917bc1..0254bfc6c 100644 --- a/src/Java/JavaUI/source/org/ops/ui/utils/swing/Util.java +++ b/src/Java/JavaUI/source/org/ops/ui/utils/swing/Util.java @@ -9,19 +9,19 @@ import javax.swing.table.TableModel; import javax.swing.table.AbstractTableModel; -public class Util +public class Util { public static JTable makeTable(List l,String fields[]) { JTable table = new JTable(Util.makeTableModel(l,fields)); return table; } - - public static TableModel makeTableModel(List l, String fields[]) + + public static TableModel makeTableModel(List l, String fields[]) { - return new ListTableModel(l,fields); + return new ListTableModel(l,fields); } - + protected static class ListTableModel extends AbstractTableModel { @@ -30,16 +30,16 @@ protected static class ListTableModel protected List data_; protected List columnNames_; protected List columnMethods_; - + public ListTableModel(List l,String fields[]) { data_ = new Vector(); columnNames_ = new Vector(); columnMethods_ = new Vector(); - if (l == null) + if (l == null) return; - + data_ = l; if (fields != null) { columnNames_ = Arrays.asList(fields); @@ -54,9 +54,9 @@ protected void mapFields(String fields[]) { if (data_.size() == 0) return; - + Class c = data_.get(0).getClass(); - + int i=0; try { for (String s : fields) { @@ -74,16 +74,16 @@ protected void mapFields(String fields[]) protected void mapFields() { columnNames_ = new Vector(); - + if (data_.size() == 0) return; - Class c = data_.get(0).getClass(); - + Class c = data_.get(0).getClass(); + try { - for (Method m : c.getMethods()) { + for (Method m : c.getMethods()) { Class paramTypes[] = m.getParameterTypes(); - if (m.getName().startsWith("get") && + if (m.getName().startsWith("get") && (paramTypes==null || paramTypes.length==0)) { columnMethods_.add(m); columnNames_.add(m.getName().substring(3)); @@ -95,47 +95,47 @@ protected void mapFields() System.err.println("Error mapping field : "+e.getMessage()); } } - + public int getColumnCount() { return columnNames_.size(); } public String getColumnName(int columnIndex) { return columnNames_.get(columnIndex); } - + public int getRowCount() { return data_.size(); } - public Object getValueAt(int rowIndex, int columnIndex) + public Object getValueAt(int rowIndex, int columnIndex) { try { Object o = data_.get(rowIndex); Method m = columnMethods_.get(columnIndex); - + return m.invoke(o, (Object[])null); } catch (Exception e) { - return e.getMessage(); + return e.getMessage(); } } } - + static public class MatrixTableModel extends AbstractTableModel { private static final long serialVersionUID = -8922640086581386437L; - + protected List data_; protected List columnNames_; - + public MatrixTableModel(List data,List columnNames) { data_ = data; columnNames_ = columnNames; } - public int getColumnCount() { return columnNames_.size(); } - public String getColumnName(int columnIndex) { return columnNames_.get(columnIndex).toString(); } + public int getColumnCount() { return columnNames_.size(); } + public String getColumnName(int columnIndex) { return columnNames_.get(columnIndex).toString(); } public int getRowCount() { return data_.size(); } @SuppressWarnings("unchecked") - public Object getValueAt(int rowIndex, int columnIndex) + public Object getValueAt(int rowIndex, int columnIndex) { // MD: Need to check for INDEX-OUT-OF-BOUND error if(rowIndex < data_.size()) { @@ -145,6 +145,6 @@ public Object getValueAt(int rowIndex, int columnIndex) return null; } else return null; - } + } } } diff --git a/src/Java/PSEngine/src/psengine/PSUtil.java b/src/Java/PSEngine/src/psengine/PSUtil.java index 3136d3805..500ee5a17 100644 --- a/src/Java/PSEngine/src/psengine/PSUtil.java +++ b/src/Java/PSEngine/src/psengine/PSUtil.java @@ -15,7 +15,7 @@ public static List toJavaList(Object psList) { try { List retval = new Vector(); - + Method m = psList.getClass().getMethod("size", (Class[])null); int size = (Integer)m.invoke(psList,(Object[])null); m = psList.getClass().getMethod("get", new Class[]{int.class}); @@ -24,33 +24,33 @@ public static List toJavaList(Object psList) args[0] = i; retval.add(m.invoke(psList, args)); } - + return retval; } catch (Exception e) { throw new RuntimeException(e); } - } - + } + // TODO: unify this one with the toJavaList by using generics public static List toResourceList(PSObjectList psList) { List retval = new Vector(); - - for (int i=0; i Date: Mon, 3 Nov 2014 15:06:05 -0800 Subject: [PATCH 026/149] Adding .travis.yml to start CI configuration --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..d70d81b0d --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +language: cpp +compiler: + - gcc + - clang +script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 018ffa740cd3f3287f89e62928bbadb270442822 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 3 Nov 2014 15:09:30 -0800 Subject: [PATCH 027/149] -Moving CMake requirement down one revision for Travis CI --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 54bfc03fb..ba565984b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8.8) +cmake_minimum_required(VERSION 2.8.7) if((CMAKE_MAJOR_VERSION GREATER 3) OR (CMAKE_MAJOR_VERSION EQUAL 3)) if(COMMAND cmake_policy) cmake_policy(SET CMP0003 NEW) From 1c8cf637b1aaee7989b923a5ac1c868177924846 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 3 Nov 2014 15:21:29 -0800 Subject: [PATCH 028/149] -Small fix to CMake files to report errors rather than produce errors --- src/PLASMA/CMakeLists.txt | 4 ++-- src/PLASMA/NDDL/CMakeLists.txt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/PLASMA/CMakeLists.txt b/src/PLASMA/CMakeLists.txt index 5fa44bad3..80c79f1d9 100644 --- a/src/PLASMA/CMakeLists.txt +++ b/src/PLASMA/CMakeLists.txt @@ -30,10 +30,10 @@ else() if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) else() - error("Failed to find boost libraries") + message(FATAL_ERROR "Failed to find boost libraries") endif() else() - error("Failed to find boost libraries") + message(FATAL_ERROR "Failed to find boost libraries") endif() add_subdirectory(TinyXml) diff --git a/src/PLASMA/NDDL/CMakeLists.txt b/src/PLASMA/NDDL/CMakeLists.txt index 010fd45c2..099db584d 100644 --- a/src/PLASMA/NDDL/CMakeLists.txt +++ b/src/PLASMA/NDDL/CMakeLists.txt @@ -2,7 +2,7 @@ include(EuropaModule) set(ANTLR_FIND_REQUIRED TRUE) include(FindANTLR) if(NOT ANTLR_FOUND) - message(ERROR "ANTLR not found!") + message(FATAL_ERROR "ANTLR not found!") endif(NOT ANTLR_FOUND) set(nddl_parser_sources NDDL3.tokens NDDL3Lexer.cpp NDDL3Lexer.h NDDL3Parser.cpp NDDL3Parser.h) From 6e4316527639c23d3a9657dda026f6455e8b7d45 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 3 Nov 2014 15:29:07 -0800 Subject: [PATCH 029/149] Trying to add installation of boost --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index d70d81b0d..ff3049913 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,4 +2,5 @@ language: cpp compiler: - gcc - clang +install: sudo apt-get boost script: mkdir build && cd build && cmake .. && make \ No newline at end of file From eca4448c8ec8b0694fb5460cf9bf7360fb6b6ccb Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 3 Nov 2014 15:34:59 -0800 Subject: [PATCH 030/149] Forgot to tell apt-get to install boost --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ff3049913..9d23b8552 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get boost +install: sudo apt-get install boost script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 55301c1e7429b93b538c6ae6ed38e095b162baed Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 3 Nov 2014 15:45:37 -0800 Subject: [PATCH 031/149] Temporarily having command list all available packages --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9d23b8552..a3da79436 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install boost +install: sudo apt-get update && sudo apt-cache search . script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 07707f412ac8018704b10f6aa98379c68fdfa428 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 09:45:32 -0800 Subject: [PATCH 032/149] Trying to add boost installation --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a3da79436..04ff0e80a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get update && sudo apt-cache search . +install: sudo apt-get update && sudo apt-get install libboost-dev . script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 7adcfff48ed510e6a00c96cf69c1e1eed57b4bde Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 10:00:49 -0800 Subject: [PATCH 033/149] More trying to install boost --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 04ff0e80a..930c05ffa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get update && sudo apt-get install libboost-dev . +install: sudo apt-get install libboost-dev . script: mkdir build && cd build && cmake .. && make \ No newline at end of file From cb091ceb1cdd184710c988a8f43b41305ce640da Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 10:13:02 -0800 Subject: [PATCH 034/149] Left a spurious . that I think is causing Travis to try to install all packages --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 930c05ffa..40de70626 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install libboost-dev . +install: sudo apt-get install libboost-dev script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 43932a443705d69ce77527f9fa22c1ceb3ca441c Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 10:20:39 -0800 Subject: [PATCH 035/149] Adding cppunit --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 40de70626..097c5c56d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install libboost-dev +install: sudo apt-get install libboost-dev libcppunit-dev script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 3d7a7480951221738f3796ef399360e6fa9de8bb Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 10:32:30 -0800 Subject: [PATCH 036/149] Adding installation of antlr and removing (currently) unused europa-config.h reference --- .travis.yml | 2 +- src/PLASMA/Utils/CMakeLists.txt | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 097c5c56d..b023ea3ac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install libboost-dev libcppunit-dev +install: sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr script: mkdir build && cd build && cmake .. && make \ No newline at end of file diff --git a/src/PLASMA/Utils/CMakeLists.txt b/src/PLASMA/Utils/CMakeLists.txt index a06c49099..c2d726d3d 100644 --- a/src/PLASMA/Utils/CMakeLists.txt +++ b/src/PLASMA/Utils/CMakeLists.txt @@ -1,8 +1,8 @@ include(CheckIncludeFileCXX) -check_include_file_cxx(tr1/functional HAVE_TR1_FUNCTIONAL) -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/europa-config.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/europa-config.h") -include_directories(${CMAKE_CURRENT_BINARY_DIR}) +# check_include_file_cxx(tr1/functional HAVE_TR1_FUNCTIONAL) +# configure_file("${CMAKE_CURRENT_SOURCE_DIR}/europa-config.h.in" +# "${CMAKE_CURRENT_BINARY_DIR}/europa-config.h") +# include_directories(${CMAKE_CURRENT_BINARY_DIR}) include(EuropaModule) set(internal_dependencies TinyXml) From 8978e17dd18baf1f4f6e6e26e8e237941db95e5f Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 10:42:59 -0800 Subject: [PATCH 037/149] Adding swig install --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b023ea3ac..abd91ddf1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr +install: sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr swig script: mkdir build && cd build && cmake .. && make \ No newline at end of file From 1407615b5a83da4b9b761fc1b3f5a323a74638c2 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 12:00:31 -0800 Subject: [PATCH 038/149] Adding verbosity while figuring out Travis builds --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index abd91ddf1..2d98f0790 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,4 @@ compiler: - gcc - clang install: sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr swig -script: mkdir build && cd build && cmake .. && make \ No newline at end of file +script: mkdir build && cd build && cmake .. && make VERBOSE=1 \ No newline at end of file From 18a4e538bd43db9efc9705971e1e3888472dda0b Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 15:27:12 -0800 Subject: [PATCH 039/149] Bumping CMake version back up, since there's a required feature; adding installation of newer CMake version to Travis --- .travis.yml | 2 +- CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2d98f0790..f12178743 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr swig +install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr swig cmake script: mkdir build && cd build && cmake .. && make VERBOSE=1 \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index ba565984b..54bfc03fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8.7) +cmake_minimum_required(VERSION 2.8.8) if((CMAKE_MAJOR_VERSION GREATER 3) OR (CMAKE_MAJOR_VERSION EQUAL 3)) if(COMMAND cmake_policy) cmake_policy(SET CMP0003 NEW) From e362bf31d32dba1eb5378cef43eb10c96550d654 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 15:30:55 -0800 Subject: [PATCH 040/149] Moving cmake up in priority to see if that'll do the job --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index f12178743..a0621c10e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get install libboost-dev libcppunit-dev libantlr3c-dev antlr swig cmake +install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get install cmake libboost-dev libcppunit-dev libantlr3c-dev antlr swig script: mkdir build && cd build && cmake .. && make VERBOSE=1 \ No newline at end of file From 2296b169f201f45c06592d0912e9f9ad436f9174 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 4 Nov 2014 15:35:44 -0800 Subject: [PATCH 041/149] Forgot to add the update --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a0621c10e..4cee837a0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,5 @@ language: cpp compiler: - gcc - clang -install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get install cmake libboost-dev libcppunit-dev libantlr3c-dev antlr swig +install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get update -qq && sudo apt-get install cmake libboost-dev libcppunit-dev libantlr3c-dev antlr swig script: mkdir build && cd build && cmake .. && make VERBOSE=1 \ No newline at end of file From 2ee64516cb28b545287cb3c66a40bb42d5a5055f Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 6 Nov 2014 19:08:06 -0800 Subject: [PATCH 042/149] More fixes for building on Travis. Hopefully Java will get generated and compiled correctly now. --- src/Java/PSEngine/CMakeLists.txt | 116 ++++++++++--------------------- src/PLASMA/System/CMakeLists.txt | 111 +++++++++++++++++------------ src/PLASMA/Utils/CMakeLists.txt | 8 +-- 3 files changed, 107 insertions(+), 128 deletions(-) diff --git a/src/Java/PSEngine/CMakeLists.txt b/src/Java/PSEngine/CMakeLists.txt index 952cc1e3e..178d8fb1b 100644 --- a/src/Java/PSEngine/CMakeLists.txt +++ b/src/Java/PSEngine/CMakeLists.txt @@ -4,47 +4,6 @@ if(NOT java_included) message(FATAL_ERROR "Failed to include UseJava") endif(NOT java_included) -# add_jar(PSEngineGenerated -# SOURCES -# generated/psengine/PSConstraint.java -# generated/psengine/PSConstraintEngineListener.java -# generated/psengine/PSConstraintList.java -# generated/psengine/PSDataType.java -# generated/psengine/PSDataTypeList.java -# generated/psengine/PSEngine.java -# generated/psengine/PSEngineInterface.java -# generated/psengine/PSEngineInterfaceJNI.java -# generated/psengine/PSEntity.java -# generated/psengine/PSException.java -# generated/psengine/PSIntList.java -# generated/psengine/PSLanguageException.java -# generated/psengine/PSLanguageExceptionList.java -# generated/psengine/PSObject.java -# generated/psengine/PSObjectList.java -# generated/psengine/PSObjectType.java -# generated/psengine/PSObjectTypeList.java -# generated/psengine/PSPlanDatabaseClient.java -# generated/psengine/PSPlanDatabaseListener.java -# generated/psengine/PSResource.java -# generated/psengine/PSResourceProfile.java -# generated/psengine/PSSchema.java -# generated/psengine/PSSolver.java -# generated/psengine/PSStringList.java -# generated/psengine/PSTimePointList.java -# generated/psengine/PSToken.java -# generated/psengine/PSTokenList.java -# generated/psengine/PSTokenState.java -# generated/psengine/PSTokenType.java -# generated/psengine/PSTokenTypeList.java -# generated/psengine/PSValueList.java -# generated/psengine/PSVarType.java -# generated/psengine/PSVarValue.java -# generated/psengine/PSVariable.java -# generated/psengine/PSVariableList.java -# generated/psengine/StringErrorStream.java -# generated/psengine/EngineConfig.java -# ) - #set(CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}) #list(APPEND CMAKE_JAVA_INCLUDE_PATH ${CMAKE_CURRENT_BINARY_DIR}/PSEngineGenerated.jar) add_jar(PSEngineJar @@ -52,46 +11,47 @@ add_jar(PSEngineJar src/psengine/PSUtil.java src/psengine/util/LibraryLoader.java src/psengine/util/SimpleTimer.java - generated/psengine/EngineConfig.java - generated/psengine/PSConstraint.java - generated/psengine/PSConstraintEngineListener.java - generated/psengine/PSConstraintList.java - generated/psengine/PSDataType.java - generated/psengine/PSDataTypeList.java - generated/psengine/PSEngine.java - generated/psengine/PSEngineInterface.java - generated/psengine/PSEngineInterfaceJNI.java - generated/psengine/PSEntity.java - generated/psengine/PSException.java - generated/psengine/PSIntList.java - generated/psengine/PSLanguageException.java - generated/psengine/PSLanguageExceptionList.java - generated/psengine/PSObject.java - generated/psengine/PSObjectList.java - generated/psengine/PSObjectType.java - generated/psengine/PSObjectTypeList.java - generated/psengine/PSPlanDatabaseClient.java - generated/psengine/PSPlanDatabaseListener.java - generated/psengine/PSResource.java - generated/psengine/PSResourceProfile.java - generated/psengine/PSSchema.java - generated/psengine/PSSolver.java - generated/psengine/PSStringList.java - generated/psengine/PSTimePointList.java - generated/psengine/PSToken.java - generated/psengine/PSTokenList.java - generated/psengine/PSTokenState.java - generated/psengine/PSTokenType.java - generated/psengine/PSTokenTypeList.java - generated/psengine/PSValueList.java - generated/psengine/PSVarType.java - generated/psengine/PSVarValue.java - generated/psengine/PSVariable.java - generated/psengine/PSVariableList.java - generated/psengine/StringErrorStream.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/EngineConfig.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSConstraint.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSConstraintEngineListener.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSConstraintList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSDataType.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSDataTypeList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSEngine.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSEngineInterface.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSEngineInterfaceJNI.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSEntity.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSException.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSIntList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSLanguageException.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSLanguageExceptionList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSObject.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSObjectList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSObjectType.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSObjectTypeList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSPlanDatabaseClient.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSPlanDatabaseListener.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSResource.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSResourceProfile.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSSchema.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSSolver.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSStringList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSTimePointList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSToken.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSTokenList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSTokenState.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSTokenType.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSTokenTypeList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSValueList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSVarType.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSVarValue.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSVariable.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/PSVariableList.java + ${CMAKE_BINARY_DIR}/src/PLASMA/System/psengine/StringErrorStream.java # INCLUDE_JARS # PSEngineGenerated.jar OUTPUT_NAME PSEngine) + add_dependencies(PSEngineJar PSEngineGenerated) install_jar(PSEngineJar ${EUROPA_ROOT}/dist/europa) \ No newline at end of file diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 49798bc75..ad7c7dc70 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -26,7 +26,7 @@ declare_module(System "${root_sources}" "${base_sources}" "${component_sources}" find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(CMAKE_SWIG_FLAGS "") -set(CMAKE_SWIG_OUTDIR "${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine") +set(CMAKE_SWIG_OUTDIR "${CMAKE_CURRENT_BINARY_DIR}/psengine") set_source_files_properties(base/PSEngine.i PROPERTIES CPLUSPLUS ON) set_source_files_properties(base/PSEngine.i PROPERTIES SWIG_FLAGS "-package;psengine;-includeall") @@ -36,56 +36,75 @@ if(NOT java_included) message(FATAL_ERROR "Failed to include UseJava") endif(NOT java_included) +if(NOT EUROPA_ROOT) +message(FATAL_ERROR "EUROPA_ROOT not set") +endif(NOT EUROPA_ROOT) +message(STATUS "EUROPA_ROOT: ${EUROPA_ROOT}") + +set(SWIG_GENERATED_JAVA + psengine/PSConstraint.java + psengine/PSConstraintEngineListener.java + psengine/PSConstraintList.java + psengine/PSDataType.java + psengine/PSDataTypeList.java + psengine/PSEngine.java + psengine/PSEngineInterface.java + psengine/PSEngineInterfaceJNI.java + psengine/PSEntity.java + psengine/PSException.java + psengine/PSIntList.java + psengine/PSLanguageException.java + psengine/PSLanguageExceptionList.java + psengine/PSObject.java + psengine/PSObjectList.java + psengine/PSObjectType.java + psengine/PSObjectTypeList.java + psengine/PSPlanDatabaseClient.java + psengine/PSPlanDatabaseListener.java + psengine/PSResource.java + psengine/PSResourceProfile.java + psengine/PSSchema.java + psengine/PSSolver.java + psengine/PSStringList.java + psengine/PSTimePointList.java + psengine/PSToken.java + psengine/PSTokenList.java + psengine/PSTokenState.java + psengine/PSTokenType.java + psengine/PSTokenTypeList.java + psengine/PSValueList.java + psengine/PSVarType.java + psengine/PSVarValue.java + psengine/PSVariable.java + psengine/PSVariableList.java + psengine/StringErrorStream.java + psengine/EngineConfig.java +) + +set(SWIG_GENERATED_JAVA_FULL_PATH "") +foreach(f ${SWIG_GENERATED_JAVA}) + list(APPEND SWIG_GENERATED_JAVA_FULL_PATH ${CMAKE_CURRENT_BINARY_DIR}/${f}) +endforeach(f) + add_jar(PSEngineGenerated - SOURCES - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraint.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintEngineListener.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSConstraintList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSDataType.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSDataTypeList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngine.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngineInterface.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEngineInterfaceJNI.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSEntity.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSException.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSIntList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSLanguageException.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSLanguageExceptionList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObject.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectType.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSObjectTypeList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSPlanDatabaseClient.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSPlanDatabaseListener.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSResource.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSResourceProfile.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSSchema.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSSolver.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSStringList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTimePointList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSToken.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenState.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenType.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSTokenTypeList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSValueList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVarType.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVarValue.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVariable.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/PSVariableList.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/StringErrorStream.java - ${CMAKE_SOURCE_DIR}/src/Java/PSEngine/generated/psengine/EngineConfig.java - OUTPUT_DIR ${CMAKE_SOURCE_DIR}/src/java/PSEngine) + SOURCES ${SWIG_GENERATED_JAVA_FULL_PATH} + OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) -swig_add_module(PSEngine java base/PSEngine.i) +set(PSEngine_target PSEngine${EUROPA_SUFFIX}) +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) +swig_add_module(${PSEngine_target} java base/PSEngine.i) +add_dependencies(${PSEngine_target} base) foreach(dep ${internal_dependencies}) - add_common_module_include_dep(PSEngine ${dep}) - target_link_libraries(PSEngine "${dep}${EUROPA_SUFFIX}") + add_common_module_include_dep(${PSEngine_target} ${dep}) + target_link_libraries(${PSEngine_target} "${dep}${EUROPA_SUFFIX}") endforeach(dep) -add_common_module_include_dep(PSEngine System) -target_link_libraries(PSEngine "System${EUROPA_SUFFIX}") -add_dependencies(PSEngineGenerated PSEngine) +add_common_module_include_dep(${PSEngine_target} System) +target_link_libraries(${PSEngine_target} "System${EUROPA_SUFFIX}") +add_dependencies(PSEngineGenerated ${PSEngine_target}) +install(TARGETS ${PSEngine_target} + EXPORT Europa2 + DESTINATION ${EUROPA_ROOT}/dist/europa) add_subdirectory(test) \ No newline at end of file diff --git a/src/PLASMA/Utils/CMakeLists.txt b/src/PLASMA/Utils/CMakeLists.txt index a06c49099..394156559 100644 --- a/src/PLASMA/Utils/CMakeLists.txt +++ b/src/PLASMA/Utils/CMakeLists.txt @@ -1,8 +1,8 @@ include(CheckIncludeFileCXX) -check_include_file_cxx(tr1/functional HAVE_TR1_FUNCTIONAL) -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/europa-config.h.in" - "${CMAKE_CURRENT_BINARY_DIR}/europa-config.h") -include_directories(${CMAKE_CURRENT_BINARY_DIR}) +#check_include_file_cxx(tr1/functional HAVE_TR1_FUNCTIONAL) +#configure_file("${CMAKE_CURRENT_SOURCE_DIR}/europa-config.h.in" +# "${CMAKE_CURRENT_BINARY_DIR}/europa-config.h") +#include_directories(${CMAKE_CURRENT_BINARY_DIR}) include(EuropaModule) set(internal_dependencies TinyXml) From 6769542916242d64879ad38cc03f84d04a87e8b9 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 11 Nov 2014 11:29:56 -0800 Subject: [PATCH 043/149] Fixing JNI include location on OS X (possibly this should be Java-versioned rather than OS X-versioned. --- src/PLASMA/System/CMakeLists.txt | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index ad7c7dc70..1d7bef55d 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -1,5 +1,18 @@ +#14 -> Yosemite +#13 -> Mavericks +#12 -> Mountain Lion +#11 -> Lion +#10 -> Snow Leopard if(${APPLE}) - set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) + exec_program(uname ARGS -r OUTPUT_VARIABLE DARWIN_VERSION) + + if(DARWIN_VERSION VERSION_EQUAL 14) + message(STATUS "Setting Yosemite include") + set(JNI_INCLUDE_DIRS /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/include) + else(DARWIN_VERSION) + message(STATUS "Setting pre-Yosemite include") + set(JNI_INCLUDE_DIRS /System/Library/Frameworks/JavaVM.framework/Versions/A/Headers) + endif(DARWIN_VERSION VERSION_EQUAL 14) else(${APPLE}) find_package(JNI REQUIRED) endif(${APPLE}) @@ -93,9 +106,9 @@ add_jar(PSEngineGenerated include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) set(PSEngine_target PSEngine${EUROPA_SUFFIX}) -file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) +#file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) swig_add_module(${PSEngine_target} java base/PSEngine.i) -add_dependencies(${PSEngine_target} base) +#add_dependencies(${PSEngine_target} base) foreach(dep ${internal_dependencies}) add_common_module_include_dep(${PSEngine_target} ${dep}) target_link_libraries(${PSEngine_target} "${dep}${EUROPA_SUFFIX}") From 6e97f1da1e8d2472c0d1bcf5af7330b9dfebf333 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Tue, 11 Nov 2014 13:13:05 -0800 Subject: [PATCH 044/149] Trying to fix SWIG output directory creation --- src/PLASMA/System/CMakeLists.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 1d7bef55d..4da8f2e5a 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -106,9 +106,12 @@ add_jar(PSEngineGenerated include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) set(PSEngine_target PSEngine${EUROPA_SUFFIX}) -#file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) +# file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) swig_add_module(${PSEngine_target} java base/PSEngine.i) -#add_dependencies(${PSEngine_target} base) +# add_dependencies(${PSEngine_target} ${CMAKE_CURRENT_BINARY_DIR}/base) +add_custom_command(TARGET ${PSEngine_target} PRE_BUILD + COMMAND mkdir -p ${CMAKE_CURRENT_BINARY_DIR}/base) + foreach(dep ${internal_dependencies}) add_common_module_include_dep(${PSEngine_target} ${dep}) target_link_libraries(${PSEngine_target} "${dep}${EUROPA_SUFFIX}") From e2a41cbe7a87f3b5c834f1ed7d1fd461a59e92d7 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 14 Nov 2014 15:22:35 -0800 Subject: [PATCH 045/149] Hopefully the last changes to get Europa building on Travis --- src/Java/JavaUI/CMakeLists.txt | 9 +++++---- src/PLASMA/System/CMakeLists.txt | 10 +++++----- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/Java/JavaUI/CMakeLists.txt b/src/Java/JavaUI/CMakeLists.txt index de410eed2..52f8f6ee0 100644 --- a/src/Java/JavaUI/CMakeLists.txt +++ b/src/Java/JavaUI/CMakeLists.txt @@ -20,12 +20,13 @@ foreach(jar ${libjars}) unjar(${jarname}_unjarred ${CMAKE_CURRENT_SOURCE_DIR}/${jar} temp contents) # message(STATUS ${classes}) list(APPEND jarcontents ${contents}) + set(CMAKE_JAVA_INCLUDE_PATH "${CMAKE_JAVA_INCLUDE_PATH}:${jar}") endforeach(jar) - + set(CMAKE_JAVA_INCLUDE_PATH "${CMAKE_JAVA_INCLUDE_PATH}:lib/PSEngine.jar") add_jar(PSUISwing - INCLUDE_JARS - ${libjars} - ${CMAKE_CURRENT_BINARY_DIR}/../PSEngine/PSEngine.jar + # INCLUDE_JARS + # ${libjars} + # ${CMAKE_CURRENT_BINARY_DIR}/../PSEngine/PSEngine.jar SOURCES #${jarclasses} source/org/ops/ui/beanshell/swing/BeanShellView.java diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index 4da8f2e5a..b9df98170 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -34,7 +34,7 @@ common_module_prepends("${base_sources}" "${component_sources}" "${test_sources} declare_module(System "${root_sources}" "${base_sources}" "${component_sources}" "${test_sources}" "${internal_dependencies}" "") - +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) #TODO: let the user configure which language or languages to build for find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) @@ -100,8 +100,8 @@ foreach(f ${SWIG_GENERATED_JAVA}) endforeach(f) add_jar(PSEngineGenerated - SOURCES ${SWIG_GENERATED_JAVA_FULL_PATH} - OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) + SOURCES ${SWIG_GENERATED_JAVA_FULL_PATH}) + #OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) include_directories(${ANTLR_INCLUDE_DIR}) include_directories(${JNI_INCLUDE_DIRS}) @@ -109,8 +109,8 @@ set(PSEngine_target PSEngine${EUROPA_SUFFIX}) # file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/base) swig_add_module(${PSEngine_target} java base/PSEngine.i) # add_dependencies(${PSEngine_target} ${CMAKE_CURRENT_BINARY_DIR}/base) -add_custom_command(TARGET ${PSEngine_target} PRE_BUILD - COMMAND mkdir -p ${CMAKE_CURRENT_BINARY_DIR}/base) +#add_custom_command(TARGET ${PSEngine_target} PRE_LINK +# COMMAND mkdir base) foreach(dep ${internal_dependencies}) add_common_module_include_dep(${PSEngine_target} ${dep}) From 33fb71d1b2c995a22153468979b9db018b7ddec6 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 14 Nov 2014 17:14:46 -0800 Subject: [PATCH 046/149] Removing verbosity and adding test running to the build --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 4cee837a0..7de995620 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,4 @@ compiler: - gcc - clang install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get update -qq && sudo apt-get install cmake libboost-dev libcppunit-dev libantlr3c-dev antlr swig -script: mkdir build && cd build && cmake .. && make VERBOSE=1 \ No newline at end of file +script: mkdir build && cd build && cmake .. && make && ctest \ No newline at end of file From 73c121450daf861899e9fa94d0b024560c51e4c4 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 15 Nov 2014 08:52:09 -0800 Subject: [PATCH 047/149] Bumping up the verbosity of testing to get more info on Travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7de995620..6e3ded414 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,4 @@ compiler: - gcc - clang install: sudo add-apt-repository --yes ppa:kalakris/cmake && sudo apt-get update -qq && sudo apt-get install cmake libboost-dev libcppunit-dev libantlr3c-dev antlr swig -script: mkdir build && cd build && cmake .. && make && ctest \ No newline at end of file +script: mkdir build && cd build && cmake .. && make -j2 && ctest -VV \ No newline at end of file From fc937fafb59eef726beff028c213276979446b40 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 15 Nov 2014 09:08:25 -0800 Subject: [PATCH 048/149] Add failure-on-exception to constraint engine tests --- src/PLASMA/ConstraintEngine/test/ce-test-module.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/PLASMA/ConstraintEngine/test/ce-test-module.cc b/src/PLASMA/ConstraintEngine/test/ce-test-module.cc index cea026d3a..f06e93e69 100644 --- a/src/PLASMA/ConstraintEngine/test/ce-test-module.cc +++ b/src/PLASMA/ConstraintEngine/test/ce-test-module.cc @@ -76,6 +76,7 @@ ConstraintEngineId DefaultEngineAccessor::s_instance; } \ catch(std::exception e) { \ std::cout << e.what() << std::endl; \ + CPPUNIT_FAIL(e.what()); \ } \ } From 65a4d2849b6abc415019d76511cf8b2b1e982192 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Dec 2014 09:08:37 -0800 Subject: [PATCH 049/149] Resolving small conflict in comments --- src/PLASMA/System/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/PLASMA/System/CMakeLists.txt b/src/PLASMA/System/CMakeLists.txt index b9df98170..7cc6f13ed 100644 --- a/src/PLASMA/System/CMakeLists.txt +++ b/src/PLASMA/System/CMakeLists.txt @@ -112,6 +112,8 @@ swig_add_module(${PSEngine_target} java base/PSEngine.i) #add_custom_command(TARGET ${PSEngine_target} PRE_LINK # COMMAND mkdir base) +#add_dependencies(${PSEngine_target} base) + foreach(dep ${internal_dependencies}) add_common_module_include_dep(${PSEngine_target} ${dep}) target_link_libraries(${PSEngine_target} "${dep}${EUROPA_SUFFIX}") From 9818781f1342b0795d100a9d94fa2aadd418da95 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Dec 2014 11:18:26 -0800 Subject: [PATCH 050/149] Changes to make CE tests pass. Closing a singleton base domain now marks the variable as specified. This seems inconsistent with a previous commit to distinguish specified variables from variables with singleton base domains, but that commit didn't touch Variable::handleRestrictBaseDomain, which does specify variables whose base domain gets restricted to a singleton. This should be clarified and made consistent. See issue #165. Made the beginning of the ConstraintEngine::ChangeType enumeration and the DomainListener::ChangeType enumeration into line. See issue #166 Added initializers to the EquivalenceClassCollection constructor, which caused some random test failures sometimes. --- src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc | 2 ++ src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh | 1 + .../ConstraintEngine/component/EquivalenceClassCollection.cc | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc index c8af52e75..5f1173c57 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc +++ b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc @@ -381,6 +381,8 @@ namespace EUROPA { if(getCurrentDomain().isEmpty()) return; + if(internal_baseDomain().isSingleton() && !isSpecified()) + internalSpecify(internal_baseDomain().getSingletonValue()); } void ConstrainedVariable::open() { diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh index dfa1ab93a..20a8d8b02 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh @@ -122,6 +122,7 @@ namespace EUROPA { enum Event { UPPER_BOUND_DECREASED = 0, /**< If the upper bound of an interval domain is reduced. */ LOWER_BOUND_INCREASED, /**< If the lower bound of an interval domain is increased. */ + REFTIME_CHANGED, /**< PHM Support for reftime calculations. */ BOUNDS_RESTRICTED, /**< Both upper and lower are decreased and increased respectively. */ VALUE_REMOVED, /**< A restriction to an enumerated domain. */ RESTRICT_TO_SINGLETON, /**< A restriction of the domain to a singleton value through inference. */ diff --git a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc index dea2a11f2..a404c95be 100644 --- a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc +++ b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc @@ -40,7 +40,7 @@ namespace EUROPA{ } EquivalenceClassCollection::EquivalenceClassCollection() - :m_requiresUpdate(false){} + : m_nodesByVar(), m_graphsByKey(), m_requiresUpdate(false), m_nextCycle(0), m_nextGraph(0) {} EquivalenceClassCollection::~EquivalenceClassCollection(){ for(std::map::iterator it = m_nodesByVar.begin(); it != m_nodesByVar.end(); ++it) From 69ba98b39e24614e5d57777dc88756f09959279b Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Dec 2014 14:32:22 -0800 Subject: [PATCH 051/149] Adding registration of "Random" variable handler. Fixes issue #161. --- src/PLASMA/Solvers/ModuleSolvers.cc | 1 + src/PLASMA/System/test/CMakeLists.txt | 4 +-- .../System/test/RandomPlannerConfig.xml | 27 +++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 src/PLASMA/System/test/RandomPlannerConfig.xml diff --git a/src/PLASMA/Solvers/ModuleSolvers.cc b/src/PLASMA/Solvers/ModuleSolvers.cc index aab642e8d..3a2bd0b85 100644 --- a/src/PLASMA/Solvers/ModuleSolvers.cc +++ b/src/PLASMA/Solvers/ModuleSolvers.cc @@ -59,6 +59,7 @@ namespace EUROPA { REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, StandardVariableHandler); REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, Min); REGISTER_FLAW_HANDLER(cfm,SOLVERS::MaxValue, Max); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::RandomValue, Random); REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::ValueEnum, ValEnum); REGISTER_FLAW_MANAGER(cfm,SOLVERS::OpenConditionManager, OpenConditionManager); diff --git a/src/PLASMA/System/test/CMakeLists.txt b/src/PLASMA/System/test/CMakeLists.txt index 7d5e68d6c..04d077530 100644 --- a/src/PLASMA/System/test/CMakeLists.txt +++ b/src/PLASMA/System/test/CMakeLists.txt @@ -37,7 +37,7 @@ function(run_planner_problem model configFile dep) set(model "${model}.nddl") endif(NOT is_nddl) - set(test_target run-nddl-interp-${model}) + set(test_target run-nddl-interp-${model}-${configFile}) add_test(NAME ${test_target} COMMAND ${exec_plan} ${model} ${configFile} nddl) #add_dependencies(${dep} ${test_target}) @@ -59,7 +59,7 @@ run_planner_problem(HTX.3 HTX.3.solverConfig.xml nddl) run_planner_problem(reusable-test-transaction ReusableTestConfig.xml nddl) run_planner_problem(unary-resource-test-transaction ReusableTestConfig.xml nddl) run_planner_problem(Mini-crew-init.nddl MiniCrewSolverConfig.xml nddl) - +run_planner_problem(basic-model-transaction RandomPlannerConfig.xml nddl) file(GLOB models *.nddl) file(COPY ${models} DESTINATION .) diff --git a/src/PLASMA/System/test/RandomPlannerConfig.xml b/src/PLASMA/System/test/RandomPlannerConfig.xml new file mode 100644 index 000000000..285da745c --- /dev/null +++ b/src/PLASMA/System/test/RandomPlannerConfig.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + From 560e15e5d0b5028156010f60512fed0a3b934b87 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Dec 2014 16:54:11 -0800 Subject: [PATCH 052/149] Added tests for Domain::lt, Domain::eq, and Domain:::leq, per the description of issue #153. They would be expected to fail, but aren't. --- .../ConstraintEngine/test/domain-tests.cc | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/src/PLASMA/ConstraintEngine/test/domain-tests.cc b/src/PLASMA/ConstraintEngine/test/domain-tests.cc index 4064b11a0..ca2b7cc32 100644 --- a/src/PLASMA/ConstraintEngine/test/domain-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/domain-tests.cc @@ -8,6 +8,109 @@ namespace EUROPA { +class DummyDT : public DataType { + public: + DummyDT(); + virtual ~DummyDT() {} + + bool isNumeric() const {return true;} + bool isBool() const {return false;} + bool isString() const {return false;} + + edouble createValue(const std::string& value) const {return 1.0;} + + static const std::string& NAME() { + static std::string sl_name("DummyDT"); + return sl_name; + } + static const DataTypeId& instance(); + +}; + +class DummyDomain : public Domain { + public: + DummyDomain(const DataTypeId& id = DummyDT::instance()) : Domain(id, false, true) {} + bool isEmpty() const {return false;} + bool isFinite() const {return true;} + bool isSingleton() const {return true;} + size_type getSize() const {return 1;} + edouble getUpperBound() const {return 1.0;} + edouble getLowerBound() const {return 1.0;} + bool getBounds(edouble& lb, edouble& ub) const {lb = getLowerBound(); ub = getUpperBound();} + void getValues(std::list& results) const {results.clear(); results.push_back(1.0);} + edouble getSingletonValue() const {return 1.0;} + void empty() {} + void set(edouble value) {} + void reset(const Domain& dom) {} + void relax(const Domain& dom) {} + void relax(edouble value) {} + void insert(edouble value) {} + void insert(const std::list& values) {} + void remove(edouble value) {} + bool intersect(const Domain& dom) {return false;} + bool intersect(const edouble lb, const edouble ub) {return false;} + bool difference(const Domain& dom) {return false;} + bool equate(Domain& dom) {return false;} + bool isMember(edouble value) const {return value == 1.0;} + bool isSubsetOf(const Domain& dom) const {return dom.isMember(1.0);} + bool intersects(const Domain& dom) const {return isSubsetOf(dom);} + Domain* copy() const; + bool convertToMemberValue(const std::string& strValue, edouble& dblValue) const { + return false; + } + void testPrecision(const edouble& value) const {} + private: +}; + +Domain* DummyDomain::copy() const {return new DummyDomain(DummyDT::instance());} + +const DataTypeId& DummyDT::instance() { + static DummyDT sl_instance; + return sl_instance.getId(); +} + +DummyDT::DummyDT() : DataType(DummyDT::NAME().c_str()) { + m_minDelta = 0.5; + m_baseDomain = new DummyDomain(getId()); +} + +class IntrinsicsTest { + public: + static bool test() { + DataTypeId dt = DummyDT::instance(); + EUROPA_runTest(lessThanTest); + EUROPA_runTest(equalTest); + EUROPA_runTest(lessThanOrEqualTest); + return true; + }; + static bool lessThanTest() { + DummyDomain dom; + CPPUNIT_ASSERT(dom.lt(0.0, 0.5)); + CPPUNIT_ASSERT(!dom.lt(0.0, 0.4)); + CPPUNIT_ASSERT(dom.lt(0.0, 0.6)); + CPPUNIT_ASSERT(!dom.lt(0.0, 0.0)); + return true; + } + + static bool equalTest() { + DummyDomain dom; + CPPUNIT_ASSERT(dom.eq(0.0, 0.0)); + CPPUNIT_ASSERT(!dom.eq(0.0, 0.5)); + CPPUNIT_ASSERT(dom.eq(0.0, 0.4)); + CPPUNIT_ASSERT(!dom.eq(0.0, 0.6)); + return true; + } + static bool lessThanOrEqualTest() { + DummyDomain dom; + CPPUNIT_ASSERT(dom.leq(0.0, 0.5)); + CPPUNIT_ASSERT(dom.leq(0.0, 0.4)); + CPPUNIT_ASSERT(dom.leq(0.0, 0.6)); + CPPUNIT_ASSERT(dom.leq(0.0, 0.0)); + CPPUNIT_ASSERT(!dom.leq(0.5, 0.0)); + return true; + } +}; + class ChangeListener : public DomainListener { public: ChangeListener() @@ -1813,6 +1916,7 @@ bool DomainTests::test() { /*runTestSuite(EUROPA::IntervalDomainTest::test); runTestSuite(EUROPA::EnumeratedDomainTest::test); runTestSuite(EUROPA::MixedTypeTest::test);*/ + EUROPA::IntrinsicsTest::test(); EUROPA::IntervalDomainTest::test(); EUROPA::EnumeratedDomainTest::test(); EUROPA::MixedTypeTest::test(); From b929d930d1dc0d8c7f0159a421ed583ee4dacfd7 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Thu, 4 Dec 2014 16:57:22 -0800 Subject: [PATCH 053/149] More tests which stubbornly refuse to fail. --- .../ConstraintEngine/test/domain-tests.cc | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/PLASMA/ConstraintEngine/test/domain-tests.cc b/src/PLASMA/ConstraintEngine/test/domain-tests.cc index ca2b7cc32..d10008ba3 100644 --- a/src/PLASMA/ConstraintEngine/test/domain-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/domain-tests.cc @@ -89,6 +89,12 @@ class IntrinsicsTest { CPPUNIT_ASSERT(!dom.lt(0.0, 0.4)); CPPUNIT_ASSERT(dom.lt(0.0, 0.6)); CPPUNIT_ASSERT(!dom.lt(0.0, 0.0)); + + CPPUNIT_ASSERT(dom.lt(1.0, 1.5)); + CPPUNIT_ASSERT(!dom.lt(1.0, 1.4)); + CPPUNIT_ASSERT(dom.lt(1.0, 1.6)); + CPPUNIT_ASSERT(!dom.lt(1.0, 1.0)); + return true; } @@ -98,6 +104,11 @@ class IntrinsicsTest { CPPUNIT_ASSERT(!dom.eq(0.0, 0.5)); CPPUNIT_ASSERT(dom.eq(0.0, 0.4)); CPPUNIT_ASSERT(!dom.eq(0.0, 0.6)); + + CPPUNIT_ASSERT(dom.eq(1.0, 1.0)); + CPPUNIT_ASSERT(!dom.eq(1.0, 1.5)); + CPPUNIT_ASSERT(dom.eq(1.0, 1.4)); + CPPUNIT_ASSERT(!dom.eq(1.0, 1.6)); return true; } static bool lessThanOrEqualTest() { @@ -107,6 +118,12 @@ class IntrinsicsTest { CPPUNIT_ASSERT(dom.leq(0.0, 0.6)); CPPUNIT_ASSERT(dom.leq(0.0, 0.0)); CPPUNIT_ASSERT(!dom.leq(0.5, 0.0)); + + CPPUNIT_ASSERT(dom.leq(1.0, 1.5)); + CPPUNIT_ASSERT(dom.leq(1.0, 1.4)); + CPPUNIT_ASSERT(dom.leq(1.0, 1.6)); + CPPUNIT_ASSERT(dom.leq(1.0, 1.0)); + CPPUNIT_ASSERT(!dom.leq(1.5, 1.0)); return true; } }; From 222d4d51e67e24c2633f8c3025effc8fcb064e60 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 5 Dec 2014 13:04:50 -0800 Subject: [PATCH 054/149] Adding the GitHub README, trying to fix some issues found by Coverity. --- README.md | 25 ++++++++++++ .../ConstraintEngine/test/domain-tests.cc | 1 + .../TemporalNetwork/base/DispatchGraph.cc | 9 +++-- .../TemporalNetwork/base/DistanceGraph.cc | 2 +- .../TemporalNetwork/base/TemporalNetwork.cc | 13 +++--- src/PLASMA/Utils/base/Error.cc | 3 +- src/PLASMA/Utils/base/Error.hh | 40 ++++++------------- 7 files changed, 52 insertions(+), 41 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..8d17287db --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# Main wiki page + +# EUROPA + +**EUROPA is available under [NASA's Open Source Agreement (NOSA) ](http://opensource.arc.nasa.gov/page/nosa-software-agreement)** + +Welcome! EUROPA is a framework to model and tackle problems in Planning, Scheduling and Constraint Programming. EUROPA is typically embedded in a host application. It is designed to be expressive, efficient, extendable and configurable. It includes: + +- **A Plan Database:** The technology cornerstone of EUROPA for storage and manipulation of plans as they are initialized and refined. The EUROPA Plan Database integrates a rich representation for actions, states, objects and constraints with powerful algorithms for automated reasoning, propagation, querying and manipulation. +- **A Problem Solver:** A core solver to automatically find and fix flaws in the plan database. It can be configured to plan, schedule or both. It can be easily customized to integrate specialized heuristics and resolution operations. +- **A Tool Box:** Europa includes a debugger for instrumentation and visualization of applications. It also includes a very high-level, declarative modeling language for describing problem domains and partial-plans. + +[Learn more...](What-Is-Europa.md) + +EUROPA was developed at NASA's Ames Research Center and is available under NASA's open source agreement [(NOSA)](http://opensource.arc.nasa.gov/page/nosa-software-agreement) + +|**Getting Started**|**Documentation**|**Development**| +|-------------------|-----------------|---------------| +|[Download](Europa-Download.md)|[Background/Overview](Europa-Background.md)|[Building EUROPA](Building-Europa.md)| +|[Installation](Europa-Installation.md)|[User Documentation](Europa-Docs.md)|[Automated Builds](Nightly-Builds.md)| +|[Quick Start](Quick-Start.md)|[Examples](Europa-Examples.md)|[Developer Notes](Misc-Development.md)| +||[Publications](Europa-Publications.md)|[Product Roadmap](Europa-Roadmap.md)| +|||[People](Europa-Team.md)| + +For questions, please use the [europa-users](http://groups.google.com/group/europa-users) google group. \ No newline at end of file diff --git a/src/PLASMA/ConstraintEngine/test/domain-tests.cc b/src/PLASMA/ConstraintEngine/test/domain-tests.cc index d10008ba3..7217cd383 100644 --- a/src/PLASMA/ConstraintEngine/test/domain-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/domain-tests.cc @@ -85,6 +85,7 @@ class IntrinsicsTest { }; static bool lessThanTest() { DummyDomain dom; + CPPUNIT_ASSERT(dom.minDelta() == 0.5); CPPUNIT_ASSERT(dom.lt(0.0, 0.5)); CPPUNIT_ASSERT(!dom.lt(0.0, 0.4)); CPPUNIT_ASSERT(dom.lt(0.0, 0.6)); diff --git a/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc b/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc index e00b62156..5d915be50 100644 --- a/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc +++ b/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc @@ -60,14 +60,15 @@ void DispatchGraph::createEdge(DispatchNode* from, DispatchNode* to, void DispatchGraph::filter( void (*keepEdge)(DispatchNode*, DispatchNode*, Time) ) { - if (bellmanFord() == false) - handle_error(bellmanFord() == false, + if (bellmanFord() == false) { + check_error(bellmanFord() == false, "Dispatchability analysis called on inconsistent graph", TempNetErr::DistanceGraphInconsistentError()); + } this->reversePostorder = new DispatchNode*[this->nodes.size()]; if (!this->reversePostorder) - handle_error(!this->reversePostorder, + check_error(!this->reversePostorder, "Could not allocate memory to process dispatchability", TempNetErr::TempNetMemoryError()); this->sccLeaders = std::vector(); @@ -108,7 +109,7 @@ void DispatchGraph::findSccs( void (*keepEdge)(DispatchNode*, DispatchNode*, Int nodeCount = this->nodes.size(); DispatchNode** scc = new DispatchNode*[nodeCount]; // Scratch list for SCCs. if (!scc) - handle_error(!scc, + check_error(!scc, "Could not allocate memory to process dispatchability", TempNetErr::TempNetMemoryError()); buildReversePostorder (this->nodes); diff --git a/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc b/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc index 90fe2f3d6..b736acb5f 100644 --- a/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc +++ b/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc @@ -126,7 +126,7 @@ Void attachEdge (DedgeId*& edgeArray, Int& size, Int& count, DedgeId edge) size = 2*size; DedgeId* newEdgeArray = new DedgeId[size]; if(!newEdgeArray) - handle_error(!newEdgeArray, + check_error(!newEdgeArray, "Memory allocation failed for TemporalNetwork edge-array", TempNetErr::TempNetMemoryError()); for (Int i=0; i result; - if(id.isInvalid()) - handle_error(is.isInvalid(), - "Cannot get scope of invalid constraint.", - TempNetErr::TempNetInvalidConstraintError()); + if(id.isInvalid()) { + check_error(id.isInvalid(), + "Cannot get scope of invalid constraint.", + TempNetErr::TempNetInvalidConstraintError()); + } Tspec* spec = id.operator->(); result.push_back(spec->head->getId()); @@ -378,7 +379,7 @@ namespace EUROPA { Time TemporalNetwork::getConstraintUpperBound(const TemporalConstraintId& id) { if(id.isInvalid()) - handle_error(id.isInvalid(), + check_error(id.isInvalid(), "Cannot get scope of invalid constraint.", TempNetErr::TempNetInvalidConstraintError()); @@ -390,7 +391,7 @@ namespace EUROPA { Time TemporalNetwork::getConstraintLowerBound(const TemporalConstraintId& id) { if(id.isInvalid()) - handle_error(id.isInvalid(), + check_error(id.isInvalid(), "Cannot get scope of invalid constraint.", TempNetErr::TempNetInvalidConstraintError()); Tspec* spec = id.operator->(); diff --git a/src/PLASMA/Utils/base/Error.cc b/src/PLASMA/Utils/base/Error.cc index 457fb15ef..7b46fd8ab 100644 --- a/src/PLASMA/Utils/base/Error.cc +++ b/src/PLASMA/Utils/base/Error.cc @@ -63,10 +63,9 @@ Error::Error(const std::string& condition, const std::string& msg, const std::st s_os = &(std::cerr); } +// coverity[+kill] void Error::handleAssert() { display(); - if (throwEnabled()) - throw *this; #ifndef __BEOS__ assert(false); // Need the stack to work backwards and look at state in the debugger #else diff --git a/src/PLASMA/Utils/base/Error.hh b/src/PLASMA/Utils/base/Error.hh index 1a7aa157e..a678b74b8 100644 --- a/src/PLASMA/Utils/base/Error.hh +++ b/src/PLASMA/Utils/base/Error.hh @@ -51,22 +51,6 @@ */ #define ALWAYS_FAIL (false) -/** - * @def handle_error - * Create an error instance for throwing, printing, etc., per class Error. - * @param cond Condition that failed (was false), implying an error has occurred. - * @param optarg Optional arguments passed on to the appropriate - * class Error constructor. - */ -#ifndef _MSC_VER -#define handle_error(cond, optarg...) { \ - new Error(#cond, ##optarg, __FILE__, __LINE__); \ -} -#else -#define handle_error(cond, ...) { \ - new Error(#cond, __VA_ARGS__, __FILE__, __LINE__); \ -} -#endif /** * @def DECLARE_ERROR * Declare an error as a function that returns a string naming itself. @@ -81,25 +65,25 @@ #ifndef _MSC_VER #define assertTrue(cond, optarg...) { \ if (!(cond)) { \ - (new Error(#cond, ##optarg, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #define assertFalse(cond, optarg...) { \ if (cond) { \ - (new Error(#cond, ##optarg, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #else #define assertTrue(cond, ...) { \ if (!(cond)) { \ - (new Error(#cond, __VA_ARGS__, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #define assertFalse(cond, ...) { \ if (cond) { \ - (new Error(#cond, __VA_ARGS__, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #endif @@ -178,13 +162,13 @@ #ifndef _MSC_VER #define check_error(cond, optarg...) { \ if (!(cond)) { \ - (new Error(#cond, ##optarg, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #else #define check_error(cond, ...) { \ if (!(cond)) { \ - (new Error(#cond, __VA_ARGS__, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #endif @@ -194,7 +178,7 @@ if (!(cond)) { \ std::stringstream sstr; \ sstr << msg; \ - (new Error(#cond, sstr.str(), ##optarg, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, sstr.str(), ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #else @@ -204,7 +188,7 @@ if (!(cond)) { \ std::stringstream sstr; \ sstr << msg; \ - (new Error(#cond, sstr.str(), __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, sstr.str(), __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } @@ -212,7 +196,7 @@ if (!(cond)) { \ std::stringstream sstr; \ sstr << msg; \ - (new Error(#cond, sstr.str(), __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, sstr.str(), __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #endif @@ -246,13 +230,13 @@ #ifndef _MSC_VER #define check_runtime_error(cond, optarg...) { \ if (!(cond)) { \ - (new Error(#cond, ##optarg, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #else #define check_runtime_error(cond, ...) { \ if (!(cond)) { \ - (new Error(#cond, __VA_ARGS__, __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } #endif @@ -260,7 +244,7 @@ if (!(cond)) { \ std::stringstream sstr; \ sstr << msg; \ - (new Error(#cond, sstr.str(), __FILE__, __LINE__))->handleAssert(); \ + Error __e__(#cond, sstr.str(), __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ } \ } From 21f7bf6c8997ee9eb9ee406aca3ca26f3869cc03 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 5 Dec 2014 13:06:53 -0800 Subject: [PATCH 055/149] Adding Travis CI autobuild badge --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 8d17287db..3311bdb36 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@ -# Main wiki page - -# EUROPA +# EUROPA [![Build Status](https://travis-ci.org/nasa/europa.svg?branch=master)](https://travis-ci.org/nasa/europa) **EUROPA is available under [NASA's Open Source Agreement (NOSA) ](http://opensource.arc.nasa.gov/page/nosa-software-agreement)** From bd07bb05c6c83e7fa183f09fef8f450fb3e90570 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 5 Dec 2014 13:08:53 -0800 Subject: [PATCH 056/149] Adding Coverity badge --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3311bdb36..063871980 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ -# EUROPA [![Build Status](https://travis-ci.org/nasa/europa.svg?branch=master)](https://travis-ci.org/nasa/europa) +# EUROPA [![Build Status](https://travis-ci.org/nasa/europa.svg?branch=master)](https://travis-ci.org/nasa/europa) + Coverity Scan Build Status + **EUROPA is available under [NASA's Open Source Agreement (NOSA) ](http://opensource.arc.nasa.gov/page/nosa-software-agreement)** From a4b22203711023ae119419d84c69ef3e5b7dce1c Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 5 Dec 2014 13:09:43 -0800 Subject: [PATCH 057/149] Moving the coverity badge --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 063871980..fd9c25a3a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# EUROPA [![Build Status](https://travis-ci.org/nasa/europa.svg?branch=master)](https://travis-ci.org/nasa/europa) +# EUROPA + +[![Build Status](https://travis-ci.org/nasa/europa.svg?branch=master)](https://travis-ci.org/nasa/europa) Coverity Scan Build Status From f99cdd1594d38347034bec558e00e1fa8379d00b Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 5 Dec 2014 15:48:25 -0800 Subject: [PATCH 058/149] Trying to fix links in README Fixing some problems found by Coverity: - Removed m_chars entirely - Added a missing return value --- README.md | 12 ++++++------ src/PLASMA/ConstraintEngine/test/domain-tests.cc | 2 +- src/PLASMA/Utils/base/LabelStr.cc | 13 ------------- src/PLASMA/Utils/base/LabelStr.hh | 4 ---- 4 files changed, 7 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index fd9c25a3a..5adc51037 100644 --- a/README.md +++ b/README.md @@ -13,16 +13,16 @@ Welcome! EUROPA is a framework to model and tackle problems in Planning, Schedu - **A Problem Solver:** A core solver to automatically find and fix flaws in the plan database. It can be configured to plan, schedule or both. It can be easily customized to integrate specialized heuristics and resolution operations. - **A Tool Box:** Europa includes a debugger for instrumentation and visualization of applications. It also includes a very high-level, declarative modeling language for describing problem domains and partial-plans. -[Learn more...](What-Is-Europa.md) +[Learn more...](What-Is-Europa) EUROPA was developed at NASA's Ames Research Center and is available under NASA's open source agreement [(NOSA)](http://opensource.arc.nasa.gov/page/nosa-software-agreement) |**Getting Started**|**Documentation**|**Development**| |-------------------|-----------------|---------------| -|[Download](Europa-Download.md)|[Background/Overview](Europa-Background.md)|[Building EUROPA](Building-Europa.md)| -|[Installation](Europa-Installation.md)|[User Documentation](Europa-Docs.md)|[Automated Builds](Nightly-Builds.md)| -|[Quick Start](Quick-Start.md)|[Examples](Europa-Examples.md)|[Developer Notes](Misc-Development.md)| -||[Publications](Europa-Publications.md)|[Product Roadmap](Europa-Roadmap.md)| -|||[People](Europa-Team.md)| +|[Download](Europa-Download)|[Background/Overview](Europa-Background)|[Building EUROPA](Building-Europa)| +|[Installation](Europa-Installation)|[User Documentation](Europa-Docs)|[Automated Builds](Nightly-Builds)| +|[Quick Start](Quick-Start)|[Examples](Europa-Examples)|[Developer Notes](Misc-Development)| +||[Publications](Europa-Publications)|[Product Roadmap](Europa-Roadmap)| +|||[People](Europa-Team)| For questions, please use the [europa-users](http://groups.google.com/group/europa-users) google group. \ No newline at end of file diff --git a/src/PLASMA/ConstraintEngine/test/domain-tests.cc b/src/PLASMA/ConstraintEngine/test/domain-tests.cc index 7217cd383..064020a9d 100644 --- a/src/PLASMA/ConstraintEngine/test/domain-tests.cc +++ b/src/PLASMA/ConstraintEngine/test/domain-tests.cc @@ -36,7 +36,7 @@ class DummyDomain : public Domain { size_type getSize() const {return 1;} edouble getUpperBound() const {return 1.0;} edouble getLowerBound() const {return 1.0;} - bool getBounds(edouble& lb, edouble& ub) const {lb = getLowerBound(); ub = getUpperBound();} + bool getBounds(edouble& lb, edouble& ub) const {lb = getLowerBound(); ub = getUpperBound(); return false;} void getValues(std::list& results) const {results.clear(); results.push_back(1.0);} edouble getSingletonValue() const {return 1.0;} void empty() {} diff --git a/src/PLASMA/Utils/base/LabelStr.cc b/src/PLASMA/Utils/base/LabelStr.cc index 2615965dc..e780691b5 100644 --- a/src/PLASMA/Utils/base/LabelStr.cc +++ b/src/PLASMA/Utils/base/LabelStr.cc @@ -33,9 +33,6 @@ namespace EUROPA { LabelStr::LabelStr() { std::string empty(""); m_key = getKey(empty); -#ifndef EUROPA_FAST - m_chars = empty.c_str(); -#endif } pthread_mutex_t& LabelStrMutex() @@ -53,27 +50,18 @@ namespace EUROPA { LabelStr::LabelStr(const std::string& label) { m_key = getKey(label); -#ifndef EUROPA_FAST - m_chars = label.c_str(); -#endif } LabelStr::LabelStr(const char* label) { std::string str(label); m_key = getKey(label); -#ifndef EUROPA_FAST - m_chars = label; -#endif } LabelStr::LabelStr(edouble key) : m_key(key) { check_error(isString(m_key), "Invalid key provided."); -#ifndef EUROPA_FAST - m_chars = toString().c_str(); -#endif } const std::string& LabelStr::toString() const { @@ -88,7 +76,6 @@ namespace EUROPA { LabelStr::LabelStr(const LabelStr& org) : m_key(org.m_key) { - m_chars = org.m_chars; } LabelStr::operator edouble () const { diff --git a/src/PLASMA/Utils/base/LabelStr.hh b/src/PLASMA/Utils/base/LabelStr.hh index fb77989c5..3a7502a32 100644 --- a/src/PLASMA/Utils/base/LabelStr.hh +++ b/src/PLASMA/Utils/base/LabelStr.hh @@ -202,10 +202,6 @@ namespace EUROPA { static std::map& keysFromString(); static std::map& stringFromKeys(); -#ifndef EUROPA_FAST - const char* m_chars; -#endif - }; } #endif From 9403121efa6e2853ebd06ed047e9e702f5d1c54a Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 6 Dec 2014 23:58:55 -0800 Subject: [PATCH 059/149] Fixing issues found by Coverity --- src/PLASMA/ANML/base/ANMLTranslator.cc | 27 ++-- src/PLASMA/NDDL/component/NddlInterpreter.cc | 27 ++-- src/PLASMA/PlanDatabase/base/DbClient.cc | 10 +- src/PLASMA/PlanDatabase/base/Object.cc | 2 +- src/PLASMA/PlanDatabase/base/Schema.cc | 4 +- src/PLASMA/PlanDatabase/base/UnifyMemento.cc | 5 +- src/PLASMA/Resource/base/Profile.cc | 1 + src/PLASMA/Resource/base/ProfilePropagator.cc | 1 + src/PLASMA/Resource/component/Edge.cc | 3 +- .../RulesEngine/base/ProxyVariableRelation.cc | 6 +- src/PLASMA/Solvers/base/FlawHandler.cc | 2 - src/PLASMA/Solvers/base/Solver.cc | 85 +++++----- .../Solvers/component/ThreatDecisionPoint.cc | 8 +- .../Solvers/test/solvers-test-module.cc | 6 +- src/PLASMA/System/base/EuropaEngine.cc | 9 +- src/PLASMA/System/base/PSEngineImpl.cc | 4 +- .../TemporalNetwork/base/DistanceGraph.hh | 2 +- .../TemporalNetwork/base/TemporalNetwork.cc | 4 +- src/PLASMA/Utils/Number.hh | 146 +++++++++--------- src/PLASMA/Utils/base/Engine.cc | 21 ++- src/PLASMA/Utils/base/IdTable.hh | 2 +- 21 files changed, 198 insertions(+), 177 deletions(-) diff --git a/src/PLASMA/ANML/base/ANMLTranslator.cc b/src/PLASMA/ANML/base/ANMLTranslator.cc index aca1f1ed9..74ea695b9 100644 --- a/src/PLASMA/ANML/base/ANMLTranslator.cc +++ b/src/PLASMA/ANML/base/ANMLTranslator.cc @@ -483,10 +483,11 @@ namespace ANML } Range::Range(const std::string& name,const Type& dataType,const std::string& lb,const std::string& ub) - : Type(name!="" ? name : autoIdentifier("Range")) - , m_dataType(dataType) - , m_lb(lb) - , m_ub(ub) + : Type(name!="" ? name : autoIdentifier("Range")), + m_isResourceType(false), + m_dataType(dataType), + m_lb(lb), + m_ub(ub) { // TODO: convert lb,ub to typed values } @@ -687,15 +688,18 @@ namespace ANML } Variable::Variable(const Type& dataType, const std::string& name) - : m_name(name) - , m_dataType(dataType) + : m_name(name), + m_objType(NULL), + m_dataType(dataType) + { } Variable::Variable(const Type& dataType, const std::string& name, const std::vector& args) - : m_name(name) - , m_dataType(dataType) - , m_args(args) + : m_name(name), + m_objType(NULL), + m_dataType(dataType), + m_args(args) { } @@ -1126,15 +1130,14 @@ namespace ANML } Proposition::Proposition(TemporalQualifier* tq,Fluent* f) - : m_temporalQualifier(tq) + : m_context(), m_temporalQualifier(tq), m_fluents(), m_parentAction(NULL) { m_fluents.push_back(f); commonInit(); } Proposition::Proposition(TemporalQualifier* tq,const std::vector& fluents) - : m_temporalQualifier(tq) - , m_fluents(fluents) + : m_context(), m_temporalQualifier(tq), m_fluents(fluents), m_parentAction(NULL) { commonInit(); } diff --git a/src/PLASMA/NDDL/component/NddlInterpreter.cc b/src/PLASMA/NDDL/component/NddlInterpreter.cc index 807a1d083..7a29cb304 100644 --- a/src/PLASMA/NDDL/component/NddlInterpreter.cc +++ b/src/PLASMA/NDDL/component/NddlInterpreter.cc @@ -28,19 +28,22 @@ NddlInterpreter::~NddlInterpreter() { } -pANTLR3_INPUT_STREAM getInputStream(std::istream& input, const std::string& source, std::string& strInput) -{ - if (source == "") { - // TODO: this is kind of a hack, see if it can be made more robust & efficient - std::istringstream* is = dynamic_cast(&input); - strInput = is->str(); // This makes a copy of the original string that could be avoided - - debugMsg("NddlInterpreter", "INPUT SCRIPT:" << std::endl << strInput); - return antlr3NewAsciiStringInPlaceStream((pANTLR3_UINT8)strInput.c_str(),(ANTLR3_UINT32)strInput.size(),(pANTLR3_UINT8)source.c_str()); - } - else { - return antlr3AsciiFileStreamNew((pANTLR3_UINT8)source.c_str()); +pANTLR3_INPUT_STREAM getInputStream(std::istream& input, const std::string& source, + std::string& strInput) { + if (source == "") { + // TODO: this is kind of a hack, see if it can be made more robust & efficient + std::istringstream* is = dynamic_cast(&input); + if(is != NULL) { + strInput = is->str(); // This makes a copy of the original string that could be avoided + + debugMsg("NddlInterpreter", "INPUT SCRIPT:" << std::endl << strInput); + return antlr3NewAsciiStringInPlaceStream((pANTLR3_UINT8)strInput.c_str(),(ANTLR3_UINT32)strInput.size(),(pANTLR3_UINT8)source.c_str()); } + } + else { + return antlr3AsciiFileStreamNew((pANTLR3_UINT8)source.c_str()); + } + return NULL; } bool isFile(const std::string& filename) diff --git a/src/PLASMA/PlanDatabase/base/DbClient.cc b/src/PLASMA/PlanDatabase/base/DbClient.cc index 602443f5a..3311e1cfc 100644 --- a/src/PLASMA/PlanDatabase/base/DbClient.cc +++ b/src/PLASMA/PlanDatabase/base/DbClient.cc @@ -4,6 +4,8 @@ #include #include +#include + #include "Debug.hh" #include "Entity.hh" #include "Utils.hh" @@ -566,21 +568,21 @@ namespace EUROPA { ConstrainedVariableId PSPlanDatabaseClientImpl::toId(PSVariable* v) { - return dynamic_cast(v)->getId(); + return boost::polymorphic_cast(v)->getId(); } ConstraintId PSPlanDatabaseClientImpl::toId(PSConstraint* c) { - return dynamic_cast(c)->getId(); + return boost::polymorphic_cast(c)->getId(); } ObjectId PSPlanDatabaseClientImpl::toId(PSObject* o) { - return dynamic_cast(o)->getId(); + return boost::polymorphic_cast(o)->getId(); } TokenId PSPlanDatabaseClientImpl::toId(PSToken* t) { - return dynamic_cast(t)->getId(); + return boost::polymorphic_cast(t)->getId(); } } diff --git a/src/PLASMA/PlanDatabase/base/Object.cc b/src/PLASMA/PlanDatabase/base/Object.cc index 6b8556ab7..dc0d2450b 100644 --- a/src/PLASMA/PlanDatabase/base/Object.cc +++ b/src/PLASMA/PlanDatabase/base/Object.cc @@ -384,7 +384,7 @@ namespace EUROPA { ConstrainedVariableId Object::getVariable(const std::vector& path) const { unsigned int index = path[0]; - checkError(index >= 0 && index < m_variables.size(), + checkError(index < m_variables.size(), "index of " << index << " out of bounds for " << getName().toString()); ConstrainedVariableId var = m_variables[index]; diff --git a/src/PLASMA/PlanDatabase/base/Schema.cc b/src/PLASMA/PlanDatabase/base/Schema.cc index d12e3ffb2..d49a0665e 100644 --- a/src/PLASMA/PlanDatabase/base/Schema.cc +++ b/src/PLASMA/PlanDatabase/base/Schema.cc @@ -459,7 +459,9 @@ namespace EUROPA { if(membershipRelation_it == membershipRelation.end() && hasParent(parentType)) return getNameFromIndex(getParent(parentType), index); - // Alternately, we have to have a hit + checkError(membershipRelation_it != membershipRelation.end(), + "Invalid membership relation: " << parentType); + // Alternately, we have to have a hit const NameValueVector& members = membershipRelation_it->second; unsigned int counter = 0; for(NameValueVector::const_iterator it = members.begin(); it != members.end(); ++it){ diff --git a/src/PLASMA/PlanDatabase/base/UnifyMemento.cc b/src/PLASMA/PlanDatabase/base/UnifyMemento.cc index 9411e2bc2..b946c06f3 100644 --- a/src/PLASMA/PlanDatabase/base/UnifyMemento.cc +++ b/src/PLASMA/PlanDatabase/base/UnifyMemento.cc @@ -11,9 +11,10 @@ namespace EUROPA { m_sm.release(); } - UnifyMemento::UnifyMemento() {} +UnifyMemento::UnifyMemento() : m_method(mergeMethod), m_mm(), m_sm() {} - UnifyMemento::UnifyMemento(const TokenId& inactiveToken, const TokenId& activeToken) { +UnifyMemento::UnifyMemento(const TokenId& inactiveToken, + const TokenId& activeToken) { static const char* TRUE_VALUE = "1"; const char *envStr = getenv("EUROPA_USE_STACK_METHOD"); diff --git a/src/PLASMA/Resource/base/Profile.cc b/src/PLASMA/Resource/base/Profile.cc index 628b359e2..0ae4db829 100644 --- a/src/PLASMA/Resource/base/Profile.cc +++ b/src/PLASMA/Resource/base/Profile.cc @@ -19,6 +19,7 @@ namespace EUROPA { m_id(this) , m_changeCount(0) , m_needsRecompute(false) + , m_constraintKeyLb(0) , m_planDatabase(db) , m_detector(flawDetector) { diff --git a/src/PLASMA/Resource/base/ProfilePropagator.cc b/src/PLASMA/Resource/base/ProfilePropagator.cc index 904b9daca..5ca65f1dd 100644 --- a/src/PLASMA/Resource/base/ProfilePropagator.cc +++ b/src/PLASMA/Resource/base/ProfilePropagator.cc @@ -12,6 +12,7 @@ namespace EUROPA { : DefaultPropagator(name, constraintEngine) , m_updateRequired(false) , m_inBatchMode(false) + , m_batchListener(NULL) { } diff --git a/src/PLASMA/Resource/component/Edge.cc b/src/PLASMA/Resource/component/Edge.cc index 4dbaef581..a43811ad7 100644 --- a/src/PLASMA/Resource/component/Edge.cc +++ b/src/PLASMA/Resource/component/Edge.cc @@ -72,8 +72,9 @@ namespace EUROPA std::ostream& operator<<( std::ostream& os, const Edge& fe ) { + std::ios::fmtflags f(os.flags()); os << fe.getIdentity() << " {" << fe.getCapacity() << "} (enabled: " << std::boolalpha << fe.isEnabled() << ")"; - + os.flags(f); return os; } } diff --git a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc index fc6fc55af..84b3fad3c 100644 --- a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc +++ b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc @@ -20,7 +20,11 @@ namespace EUROPA { const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables), m_objectDomain(static_cast(getCurrentDomain(variables[0]))), - m_proxyDomain(static_cast(getCurrentDomain(variables[1]))){ + m_proxyDomain(static_cast(getCurrentDomain(variables[1]))), + m_path(), + m_autoSpecified(false), + m_sourceConstraintKey(), + m_sourceConstraint() { checkError(getScope().size() == ARG_COUNT, toString()); } diff --git a/src/PLASMA/Solvers/base/FlawHandler.cc b/src/PLASMA/Solvers/base/FlawHandler.cc index eb99eda7b..8a1d45df7 100644 --- a/src/PLASMA/Solvers/base/FlawHandler.cc +++ b/src/PLASMA/Solvers/base/FlawHandler.cc @@ -37,8 +37,6 @@ namespace EUROPA { const char* maxChoicesStr = m_configData->Attribute("maxChoices"); m_maxChoices = static_cast(atof(maxChoicesStr)); - checkError(m_maxChoices >= 0, maxChoicesStr << " must be positive"); - // The base uses a number that exceeds the max absolute value priority allowed. // It also multiplies by a minimum of 1 to ensure that 0 guards are handled as low weights. // Note also that we make it 2 so that defaul t compatibility heuristics diff --git a/src/PLASMA/Solvers/base/Solver.cc b/src/PLASMA/Solvers/base/Solver.cc index 0a2811a2c..5e8ad7518 100644 --- a/src/PLASMA/Solvers/base/Solver.cc +++ b/src/PLASMA/Solvers/base/Solver.cc @@ -28,53 +28,54 @@ } namespace EUROPA { - namespace SOLVERS { +namespace SOLVERS { - Solver::Solver(const PlanDatabaseId& db, const TiXmlElement& configData) - : m_id(this), m_db(db), - m_stepCountFloor(0), m_depthFloor(0), m_stepCount(0), - m_noFlawsFound(false), m_exhausted(false), m_timedOut(false), +Solver::Solver(const PlanDatabaseId& db, const TiXmlElement& configData) + : m_baseConflictLevel(0.0), + m_id(this), m_db(db), + m_stepCountFloor(0), m_depthFloor(0), m_stepCount(0), + m_noFlawsFound(false), m_exhausted(false), m_timedOut(false), #ifdef _MSC_VER - m_maxSteps( UINT_MAX ), - m_maxDepth( UINT_MAX ), + m_maxSteps( UINT_MAX ), + m_maxDepth( UINT_MAX ), #else - m_maxSteps(std::numeric_limits::max()), - m_maxDepth(std::numeric_limits::max()), + m_maxSteps(std::numeric_limits::max()), + m_maxDepth(std::numeric_limits::max()), #endif //_MSC_VER - m_masterFlawFilter(configData), m_ceListener(db->getConstraintEngine(), *this), - m_dbListener(db, *this) { - checkError(strcmp(configData.Value(), "Solver") == 0, - "Configuration file error. Expected element but found " << configData.Value()); - - // Extract the name of the Solver - m_name = extractData(configData, "name"); - - m_context = ((new Context(m_name.toString() + "Context"))->getId()); - // Initialize the common filter - m_masterFlawFilter.initialize(configData, m_db, m_context); - - // Now load all the flaw managers - for (TiXmlElement * child = configData.FirstChildElement(); - child != NULL; - child = child->NextSiblingElement()) { - const char* component = child->Attribute("component"); - - if(strcmp(child->Value(), "FlawFilter") != 0){ - // If no component name is provided, register it with the tag name of configuration element - // thus obtaining the default. - if(component == NULL) - child->SetAttribute("component", child->Value()); - - // Now allocate the particular flaw manager using an abstract factory pattern. - EngineId& engine = db->getEngine(); - ComponentFactoryMgr* cfm = (ComponentFactoryMgr*)engine->getComponent("ComponentFactoryMgr"); - FlawManagerId flawManager = cfm->createInstance(*child); - debugMsg("Solver:Solver", "Created FlawManager with id " << flawManager); - flawManager->initialize(*child, m_db, m_context, m_masterFlawFilter.getId()); - m_flawManagers.push_back(flawManager); - } - } + m_masterFlawFilter(configData), m_ceListener(db->getConstraintEngine(), *this), + m_dbListener(db, *this) { + checkError(strcmp(configData.Value(), "Solver") == 0, + "Configuration file error. Expected element but found " << configData.Value()); + + // Extract the name of the Solver + m_name = extractData(configData, "name"); + + m_context = ((new Context(m_name.toString() + "Context"))->getId()); + // Initialize the common filter + m_masterFlawFilter.initialize(configData, m_db, m_context); + + // Now load all the flaw managers + for (TiXmlElement * child = configData.FirstChildElement(); + child != NULL; + child = child->NextSiblingElement()) { + const char* component = child->Attribute("component"); + + if(strcmp(child->Value(), "FlawFilter") != 0){ + // If no component name is provided, register it with the tag name of configuration element + // thus obtaining the default. + if(component == NULL) + child->SetAttribute("component", child->Value()); + + // Now allocate the particular flaw manager using an abstract factory pattern. + EngineId& engine = db->getEngine(); + ComponentFactoryMgr* cfm = (ComponentFactoryMgr*)engine->getComponent("ComponentFactoryMgr"); + FlawManagerId flawManager = cfm->createInstance(*child); + debugMsg("Solver:Solver", "Created FlawManager with id " << flawManager); + flawManager->initialize(*child, m_db, m_context, m_masterFlawFilter.getId()); + m_flawManagers.push_back(flawManager); } + } +} Solver::~Solver(){ cleanupDecisions(); diff --git a/src/PLASMA/Solvers/component/ThreatDecisionPoint.cc b/src/PLASMA/Solvers/component/ThreatDecisionPoint.cc index aa41debed..d5d2c8fc7 100644 --- a/src/PLASMA/Solvers/component/ThreatDecisionPoint.cc +++ b/src/PLASMA/Solvers/component/ThreatDecisionPoint.cc @@ -18,8 +18,12 @@ namespace EUROPA { return(TokenId::convertable(entity) || TokenId(entity)->isActive()); } - ThreatDecisionPoint::ThreatDecisionPoint(const DbClientId& client, const TokenId& tokenToOrder, const TiXmlElement& configData, const LabelStr& explanation) - : DecisionPoint(client, tokenToOrder->getKey(), explanation), m_tokenToOrder(tokenToOrder), m_index(0) { + ThreatDecisionPoint::ThreatDecisionPoint(const DbClientId& client, + const TokenId& tokenToOrder, + const TiXmlElement& configData, + const LabelStr& explanation) + : DecisionPoint(client, tokenToOrder->getKey(), explanation), + m_tokenToOrder(tokenToOrder), m_choiceCount(0), m_index(0) { // Here is where we would look for custom processing for configuration of the decision point } diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index 47b4570d4..2c2809d5a 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -442,8 +442,10 @@ class FilterTests { std::vector rules; me.getMatches(ConstrainedVariableId(E_predicateC->duration()), rules); CPPUNIT_ASSERT_MESSAGE(toString(rules.size()) + " for " + token->getPredicateName().toString(), rules.size() == 4); - for(int i=0;i>4; i++) - CPPUNIT_ASSERT_MESSAGE(rules[i]->toString(), expectedRules.find(LabelStr(rules[i]->toString())) != expectedRules.end()); + for(int i=0;i<4; i++) {//? { + CPPUNIT_ASSERT_MESSAGE(rules[i]->toString(), + expectedRules.find(LabelStr(rules[i]->toString())) != expectedRules.end()); + } nukeToken(db->getClient(),token); } diff --git a/src/PLASMA/System/base/EuropaEngine.cc b/src/PLASMA/System/base/EuropaEngine.cc index af59adeec..588a5ef97 100644 --- a/src/PLASMA/System/base/EuropaEngine.cc +++ b/src/PLASMA/System/base/EuropaEngine.cc @@ -27,11 +27,10 @@ namespace EUROPA { //Logger &EuropaEngine::LOGGER = Logger::getInstance( "EUROPA::System::EuropaEngine", Logger::DEBUG ); LOGGER_CLASS_INSTANCE_IMPL( EuropaEngine, "EUROPA::System::EuropaEngine", DEBUG ); - EuropaEngine::EuropaEngine() - { - Error::doThrowExceptions(); // throw exceptions! - Error::doDisplayErrors(); - } +EuropaEngine::EuropaEngine() : m_totalNodes(0), m_finalDepth(0) { + Error::doThrowExceptions(); // throw exceptions! + Error::doDisplayErrors(); +} EuropaEngine::~EuropaEngine() { diff --git a/src/PLASMA/System/base/PSEngineImpl.cc b/src/PLASMA/System/base/PSEngineImpl.cc index a0c892878..ac6cb9b58 100644 --- a/src/PLASMA/System/base/PSEngineImpl.cc +++ b/src/PLASMA/System/base/PSEngineImpl.cc @@ -24,9 +24,7 @@ namespace EUROPA { return new PSEngineImpl(); } - PSEngineImpl::PSEngineImpl() - { - } +PSEngineImpl::PSEngineImpl() : m_started(false) {} PSEngineImpl::~PSEngineImpl() { diff --git a/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh b/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh index c10a5e4bd..98a27e8f1 100644 --- a/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh +++ b/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh @@ -400,7 +400,7 @@ public: /** * @brief constructor */ - Dedge ():m_id(this){} + Dedge ():m_id(this), length(0) {} /** * @brief destructor */ diff --git a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc index da409fce3..ae9f4a6ea 100644 --- a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc +++ b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc @@ -1065,7 +1065,9 @@ namespace EUROPA { this->consistent = c; } - Tnode::Tnode(TemporalNetwork* t) : Dnode(), m_deletionMarker(true) , owner(t){ +Tnode::Tnode(TemporalNetwork* t) : + Dnode(), reftime(0), prev_reftime(0), ordinal(0), m_deletionMarker(true), index(0), + owner(t){ lowerBound = NEG_INFINITY; upperBound = POS_INFINITY; } diff --git a/src/PLASMA/Utils/Number.hh b/src/PLASMA/Utils/Number.hh index 41cc7b877..327aeed5e 100644 --- a/src/PLASMA/Utils/Number.hh +++ b/src/PLASMA/Utils/Number.hh @@ -206,97 +206,97 @@ namespace EUROPA { return std::numeric_limits::minus_infinity(); \ } -#define handle_inf_add(type, v1, v2) { \ - if(((type::basis_type) v1) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v2) > std::numeric_limits::minus_infinity()) \ - return std::numeric_limits::infinity(); \ - } \ - else if(((type::basis_type) v1) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v2) < std::numeric_limits::infinity()) \ - return std::numeric_limits::minus_infinity(); \ +#define handle_inf_add(type, v1, v2) { \ + if(static_cast(v1) >= std::numeric_limits::infinity()) { \ + if(static_cast(v2) > std::numeric_limits::minus_infinity()) \ + return std::numeric_limits::infinity(); \ + } \ + else if(static_cast(v1) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v2) < std::numeric_limits::infinity()) \ + return std::numeric_limits::minus_infinity(); \ } \ - if(((type::basis_type) v2) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v1) > std::numeric_limits::minus_infinity()) \ + if(static_cast(v2) >= std::numeric_limits::infinity()) { \ + if(static_cast(v1) > std::numeric_limits::minus_infinity()) \ return std::numeric_limits::infinity(); \ } \ - else if(((type::basis_type) v2) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v1) < std::numeric_limits::infinity()) \ + else if(static_cast(v2) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v1) < std::numeric_limits::infinity()) \ return std::numeric_limits::minus_infinity(); \ } \ } #define handle_inf_sub(type, v1, v2) { \ - if(((type::basis_type) v1) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v2) < std::numeric_limits::infinity()) \ + if(static_cast(v1) >= std::numeric_limits::infinity()) { \ + if(static_cast(v2) < std::numeric_limits::infinity()) \ return std::numeric_limits::infinity(); \ } \ - else if(((type::basis_type) v1) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v2) > std::numeric_limits::minus_infinity()) \ + else if(static_cast(v1) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v2) > std::numeric_limits::minus_infinity()) \ return std::numeric_limits::minus_infinity(); \ } \ - if(((type::basis_type) v2) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v1) < std::numeric_limits::infinity()) \ + if(static_cast(v2) >= std::numeric_limits::infinity()) { \ + if(static_cast(v1) < std::numeric_limits::infinity()) \ return std::numeric_limits::minus_infinity(); \ } \ - else if(((type::basis_type) v2) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v1) > std::numeric_limits::minus_infinity()) \ + else if(static_cast(v2) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v1) > std::numeric_limits::minus_infinity()) \ return std::numeric_limits::infinity(); \ } \ } #define handle_inf_mul(type, v1, v2) { \ - if(((type::basis_type) v1) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v2) > 0) \ + if(static_cast(v1) >= std::numeric_limits::infinity()) { \ + if(static_cast(v2) > 0) \ return std::numeric_limits::infinity(); \ - else if(((type::basis_type) v2) < 0) \ + else if(static_cast(v2) < 0) \ return std::numeric_limits::minus_infinity(); \ } \ - else if(((type::basis_type) v1) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v2) > 0) \ + else if(static_cast(v1) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v2) > 0) \ return std::numeric_limits::minus_infinity(); \ - else if(((type::basis_type) v2) < 0) \ + else if(static_cast(v2) < 0) \ return std::numeric_limits::infinity(); \ } \ - if(((type::basis_type) v2) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v1) > 0) \ + if(static_cast(v2) >= std::numeric_limits::infinity()) { \ + if(static_cast(v1) > 0) \ return std::numeric_limits::infinity(); \ - else if(((type::basis_type) v1) < 0) \ + else if(static_cast(v1) < 0) \ return std::numeric_limits::minus_infinity(); \ } \ - else if(((type::basis_type) v2) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v1) > 0) \ + else if(static_cast(v2) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v1) > 0) \ return std::numeric_limits::minus_infinity(); \ - else if(((type::basis_type) v1) < 0) \ + else if(static_cast(v1) < 0) \ return std::numeric_limits::infinity(); \ } \ } #define handle_inf_div(type, v1, v2) { \ - if(((type::basis_type) v1) >= std::numeric_limits::infinity()) { \ - if(((type::basis_type) v2) > 0 && ((type::basis_type) v2) < std::numeric_limits::infinity()) \ + if(static_cast(v1) >= std::numeric_limits::infinity()) { \ + if(static_cast(v2) > 0 && static_cast(v2) < std::numeric_limits::infinity()) \ return std::numeric_limits::infinity(); \ - else if(((type::basis_type) v2) < 0 && ((type::basis_type) v2) > std::numeric_limits::minus_infinity()) \ + else if(static_cast(v2) < 0 && static_cast(v2) > std::numeric_limits::minus_infinity()) \ return std::numeric_limits::minus_infinity(); \ } \ - else if(((type::basis_type) v1) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v2) > 0 && ((type::basis_type) v2) < std::numeric_limits::infinity()) \ + else if(static_cast(v1) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v2) > 0 && static_cast(v2) < std::numeric_limits::infinity()) \ return std::numeric_limits::minus_infinity(); \ - else if(((type::basis_type) v2) < 0 && ((type::basis_type) v2) > std::numeric_limits::minus_infinity()) \ + else if(static_cast(v2) < 0 && static_cast(v2) > std::numeric_limits::minus_infinity()) \ return std::numeric_limits::infinity(); \ } \ - else if(((type::basis_type) v2) >= std::numeric_limits::infinity() || ((type::basis_type) v2) <= std::numeric_limits::minus_infinity()) { \ - if(((type::basis_type) v1) < std::numeric_limits::infinity() && ((type::basis_type) v1) > std::numeric_limits::minus_infinity()) \ + else if(static_cast(v2) >= std::numeric_limits::infinity() || static_cast(v2) <= std::numeric_limits::minus_infinity()) { \ + if(static_cast(v1) < std::numeric_limits::infinity() && static_cast(v1) > std::numeric_limits::minus_infinity()) \ return type(0, true); \ } \ } #define handle_inf_mod(type, v1, v2) { \ - if(((type::basis_type) v1) >= std::numeric_limits::infinity() || ((type::basis_type) v1) <= std::numeric_limits::minus_infinity()) \ + if(static_cast(v1) >= std::numeric_limits::infinity() || static_cast(v1) <= std::numeric_limits::minus_infinity()) \ return type(0, true); \ - else if(((type::basis_type) v2) == std::numeric_limits::infinity()) \ - return type(((type::basis_type) v1), true); \ - else if(((type::basis_type) v2) == std::numeric_limits::minus_infinity()) \ - return type(-((type::basis_type) v1), true); \ + else if(static_cast(v2) == std::numeric_limits::infinity()) \ + return type(static_cast(v1), true); \ + else if(static_cast(v2) == std::numeric_limits::minus_infinity()) \ + return type(-static_cast(v1), true); \ } /** @@ -304,14 +304,14 @@ namespace EUROPA { */ #ifndef NO_OVERFLOW_CHECKING #define op(type, a, x, b) { \ - double temp = ((double)(a)) x (b); \ + double temp = static_cast(a) x (b); \ if(temp > std::numeric_limits::infinity()) { \ throw std::overflow_error("greater-than-infinity error"); \ } \ else if(temp < std::numeric_limits::minus_infinity()) { \ throw std::underflow_error("less-than-minus-infinity error"); \ } \ - return type((type::basis_type)temp, true); \ + return type(static_cast(temp), true); \ } #else #define op(type, a, x, b) return (a) x (b) @@ -394,7 +394,7 @@ namespace EUROPA { } } - eint(const unsigned int v) : m_v((long)v) { + eint(const unsigned int v) : m_v(static_cast(v)) { if(m_v > std::numeric_limits::infinity()) { assert(m_v <= std::numeric_limits::infinity()); m_v = cast_int(std::numeric_limits::infinity()); @@ -404,7 +404,7 @@ namespace EUROPA { m_v = cast_int(std::numeric_limits::minus_infinity()); } } - eint(const unsigned long v) : m_v((long)v) { + eint(const unsigned long v) : m_v(static_cast(v)) { if(m_v > std::numeric_limits::infinity()) { assert(m_v <= std::numeric_limits::infinity()); assert(m_v >= std::numeric_limits::minus_infinity()); @@ -538,7 +538,7 @@ namespace EUROPA { #ifdef _MSC_VER friend struct std::numeric_limits; #else - friend class std::numeric_limits; + friend struct std::numeric_limits; #endif //_MSC_VER /** @@ -547,7 +547,7 @@ namespace EUROPA { eint(const int v, bool) : m_v(v) {} eint(const unsigned int v, bool) : m_v(v) {} eint(const long v, bool) : m_v(v) {} - eint(const unsigned long v, bool) : m_v(v) {} + eint(const unsigned long v, bool) : m_v(static_cast(v)) {} friend eint operator+(const long o, const eint e); friend eint operator-(const long o, const eint e); @@ -601,7 +601,7 @@ namespace EUROPA { edouble() : m_v(0.0) {} inline edouble operator+() const {return edouble(+m_v, true);} inline edouble operator-() const {return edouble(-m_v, true);} - inline bool operator!() const {return !m_v;} + inline bool operator!() const {return m_v == 0.0;} inline edouble operator++() {handle_inf_unary(edouble, m_v); return edouble(++m_v, true);} inline edouble operator++(int) {handle_inf_unary(edouble, m_v); return edouble(m_v++, true);} inline edouble operator--() {handle_inf_unary(edouble, m_v); return edouble(--m_v, true);} @@ -629,7 +629,7 @@ namespace EUROPA { GEN_COMPARISONS(long long int); GEN_COMPARISONS(long double); - inline operator eint() const {return eint((long)m_v);} //is this a good idea? + inline operator eint() const {return eint(static_cast(m_v));} //is this a good idea? friend eint::basis_type cast_int(const edouble e); friend long cast_long(const edouble e); @@ -643,7 +643,7 @@ namespace EUROPA { #ifdef _MSC_VER friend struct std::numeric_limits; #else - friend class std::numeric_limits; + friend struct std::numeric_limits; #endif //_MSC_VER //private version that doesn't do infinity checking @@ -678,20 +678,20 @@ namespace EUROPA { double m_v; }; - edouble eint::operator+(const edouble o) const {handle_inf_add(edouble, m_v, o.m_v); op(edouble, (double)m_v, +, o.m_v);} - edouble eint::operator-(const edouble o) const {handle_inf_sub(edouble, m_v, o.m_v); op(edouble, (double)m_v, -, o.m_v);} - edouble eint::operator*(const edouble o) const {handle_inf_mul(edouble, m_v, o.m_v); op(edouble, (double)m_v, *, o.m_v);} - edouble eint::operator/(const edouble o) const {handle_inf_div(edouble, m_v, o.m_v); op(edouble, (double)m_v, /, o.m_v);} - edouble eint::operator+(const double o) const {handle_inf_add(edouble, m_v, o); op(edouble, (double)m_v, +, o);} - edouble eint::operator-(const double o) const {handle_inf_sub(edouble, m_v, o); op(edouble, (double)m_v, -, o);} - edouble eint::operator*(const double o) const {handle_inf_mul(edouble, m_v, o); op(edouble, (double)m_v, *, o);} - edouble eint::operator/(const double o) const {handle_inf_div(edouble, m_v, o); op(edouble, (double)m_v, /, o);} - bool eint::operator<(const edouble o) const {return m_v < o.m_v;} - bool eint::operator<=(const edouble o) const {return m_v <= o.m_v;} - bool eint::operator==(const edouble o) const {return m_v == o.m_v;} - bool eint::operator>=(const edouble o) const {return m_v >= o.m_v;} - bool eint::operator>(const edouble o) const {return m_v > o.m_v;} - bool eint::operator!=(const edouble o) const {return m_v != o.m_v;} +edouble eint::operator+(const edouble o) const {handle_inf_add(edouble, m_v, o.m_v); op(edouble, static_cast(m_v), +, o.m_v);} +edouble eint::operator-(const edouble o) const {handle_inf_sub(edouble, m_v, o.m_v); op(edouble, static_cast(m_v), -, o.m_v);} +edouble eint::operator*(const edouble o) const {handle_inf_mul(edouble, m_v, o.m_v); op(edouble, static_cast(m_v), *, o.m_v);} +edouble eint::operator/(const edouble o) const {handle_inf_div(edouble, m_v, o.m_v); op(edouble, static_cast(m_v), /, o.m_v);} +edouble eint::operator+(const double o) const {handle_inf_add(edouble, m_v, o); op(edouble, static_cast(m_v), +, o);} +edouble eint::operator-(const double o) const {handle_inf_sub(edouble, m_v, o); op(edouble, static_cast(m_v), -, o);} +edouble eint::operator*(const double o) const {handle_inf_mul(edouble, m_v, o); op(edouble, static_cast(m_v), *, o);} +edouble eint::operator/(const double o) const {handle_inf_div(edouble, m_v, o); op(edouble, static_cast(m_v), /, o);} +bool eint::operator<(const edouble o) const {return m_v < o.m_v;} +bool eint::operator<=(const edouble o) const {return m_v <= o.m_v;} +bool eint::operator==(const edouble o) const {return m_v == o.m_v;} +bool eint::operator>=(const edouble o) const {return m_v >= o.m_v;} +bool eint::operator>(const edouble o) const {return m_v > o.m_v;} +bool eint::operator!=(const edouble o) const {return m_v != o.m_v;} bool eint::operator<(const double o) const {return m_v < o;} bool eint::operator<=(const double o) const {return m_v <= o;} @@ -750,7 +750,7 @@ namespace std { {return EUROPA::eint(numeric_limits::max(), true);} #endif inline EUROPA::eint numeric_limits::minus_infinity() throw() {return -infinity();} - inline EUROPA::eint numeric_limits::max() throw() {return cast_basis(infinity()) - (long)1;} +inline EUROPA::eint numeric_limits::max() throw() {return cast_basis(infinity()) - 1L;} inline EUROPA::eint numeric_limits::min() throw() {return -max();} inline EUROPA::eint numeric_limits::epsilon() throw() {return 0;} inline EUROPA::eint numeric_limits::round_error() throw() {return 0;} @@ -788,7 +788,7 @@ namespace std { inline EUROPA::edouble abs(const EUROPA::edouble d) { return EUROPA::edouble(abs(d.m_v), true);} inline EUROPA::edouble sqrt(const EUROPA::edouble d) { handle_inf_unary(EUROPA::edouble, d); return EUROPA::edouble(sqrt(d.m_v), true);} - inline EUROPA::edouble pow(const EUROPA::edouble d, const EUROPA::eint i) {return EUROPA::edouble(std::pow(d.m_v, (int)i.m_v));} +inline EUROPA::edouble pow(const EUROPA::edouble d, const EUROPA::eint i) {return EUROPA::edouble(std::pow(d.m_v, static_cast(i.m_v)));} inline EUROPA::edouble sin(const EUROPA::edouble d) {return EUROPA::edouble(std::sin(d.m_v), true);} inline EUROPA::edouble ceil(const EUROPA::edouble d) {return EUROPA::edouble(std::ceil(d.m_v), true);} inline EUROPA::edouble floor(const EUROPA::edouble d) {return EUROPA::edouble(std::floor(d.m_v), true);} @@ -803,9 +803,9 @@ namespace std { namespace boost { //I'm not entirely sure this is safe, but it's worked so far. Maybe this should be changed to - //*((size_t*)&(__x.m_v)) - size_t hash::operator()(EUROPA::edouble __x) const {return (size_t) (__x.m_v);} - size_t hash::operator()(EUROPA::eint __x) const {return (size_t) (long) (__x.m_v);} +//*((size_t*)&(__x.m_v)) +size_t hash::operator()(EUROPA::edouble __x) const {return static_cast(__x.m_v);} +size_t hash::operator()(EUROPA::eint __x) const {return static_cast(static_cast(__x.m_v));} } // #define min MIN_COPY diff --git a/src/PLASMA/Utils/base/Engine.cc b/src/PLASMA/Utils/base/Engine.cc index 4fd7f140b..86d7790dd 100644 --- a/src/PLASMA/Utils/base/Engine.cc +++ b/src/PLASMA/Utils/base/Engine.cc @@ -437,17 +437,16 @@ namespace EUROPA return NULL; } - EngineComponent* EngineBase::removeComponent(const std::string& name) - { - EngineComponent* c = getComponent(name); - - if (c != NULL) - getComponents().erase(LabelStr(name)); - - static EngineId s_nullEngineId; - c->setEngine(s_nullEngineId); - return c; - } +EngineComponent* EngineBase::removeComponent(const std::string& name) { + static EngineId s_nullEngineId; + EngineComponent* c = getComponent(name); + + if (c != NULL) { + getComponents().erase(LabelStr(name)); + c->setEngine(s_nullEngineId); + } + return c; +} std::map& EngineBase::getComponents() { diff --git a/src/PLASMA/Utils/base/IdTable.hh b/src/PLASMA/Utils/base/IdTable.hh index 3dc1b84b4..7e2704ae8 100644 --- a/src/PLASMA/Utils/base/IdTable.hh +++ b/src/PLASMA/Utils/base/IdTable.hh @@ -62,7 +62,7 @@ namespace EUROPA { IdTable(); static IdTable& getInstance(); - std::map > m_collection; /* > m_collection; /**< Map from pointers to keys */ std::map m_typeCnts; }; } From 62fd39da8f6f4c050e4fdbe45dcb6e91166e6352 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 6 Dec 2014 23:59:15 -0800 Subject: [PATCH 060/149] Fixing issues found by clang's -Weverything --- src/PLASMA/TinyXml/base/tinyxml.cpp | 20 +- src/PLASMA/TinyXml/base/tinyxml.h | 21 +- src/PLASMA/TinyXml/base/tinyxmlparser.cpp | 1948 +++++++++++---------- src/PLASMA/TinyXml/test/xmltest.cpp | 233 ++- 4 files changed, 1116 insertions(+), 1106 deletions(-) diff --git a/src/PLASMA/TinyXml/base/tinyxml.cpp b/src/PLASMA/TinyXml/base/tinyxml.cpp index ce943030f..16ddcbb83 100644 --- a/src/PLASMA/TinyXml/base/tinyxml.cpp +++ b/src/PLASMA/TinyXml/base/tinyxml.cpp @@ -42,21 +42,21 @@ void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_OSTREAM* stream ) void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) { - int i=0; + TIXML_STRING::size_type i=0; - while( i<(int)str.length() ) + while( i < static_cast(str.length()) ) { int c = str[i]; if ( c == '&' - && i < ( (int)str.length() - 2 ) + && i < ( static_cast(str.length() - 2 )) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // © -- copyright symbol, for example. - while ( i<(int)str.length() ) + while ( i(str.length()) ) { outString->append( str.c_str() + i, 1 ); ++i; @@ -94,13 +94,13 @@ void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) // Easy pass at non-alpha/numeric/symbol // 127 is the delete key. Below 32 is symbolic. char buf[ 32 ]; - sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); + sprintf( buf, "&#x%02X;", static_cast ( c & 0xff ) ); outString->append( buf, strlen( buf ) ); ++i; } else { - char realc = (char) c; + char realc = static_cast( c); outString->append( &realc, 1 ); ++i; } @@ -726,7 +726,7 @@ bool TiXmlDocument::LoadFile( const char* filename ) fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. - if ( length == 0 ) + if ( length == 0 || length == -1) { fclose( file ); return false; @@ -735,7 +735,7 @@ bool TiXmlDocument::LoadFile( const char* filename ) // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; - data.reserve( length ); + data.reserve( static_cast(length) ); const int BUF_SIZE = 2048; char buf[BUF_SIZE]; @@ -896,12 +896,12 @@ void TiXmlAttribute::SetDoubleValue( double _value ) SetValue (buf); } -const int TiXmlAttribute::IntValue() const +int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } -const double TiXmlAttribute::DoubleValue() const +double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } diff --git a/src/PLASMA/TinyXml/base/tinyxml.h b/src/PLASMA/TinyXml/base/tinyxml.h index 8bc95a094..052fef2cc 100644 --- a/src/PLASMA/TinyXml/base/tinyxml.h +++ b/src/PLASMA/TinyXml/base/tinyxml.h @@ -36,6 +36,7 @@ distribution. #include #include #include +#include // Help out windows: #if defined( _DEBUG ) && !defined( DEBUG ) @@ -504,12 +505,12 @@ class TiXmlNode : public TiXmlBase /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } - TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. - TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. - TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. - TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. - TiXmlText* ToText() const { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. - TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? boost::polymorphic_cast(const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? boost::polymorphic_cast( const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? boost::polymorphic_cast( const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? boost::polymorphic_cast( const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlText* ToText() const { return ( this && type == TEXT ) ? boost::polymorphic_cast( const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. + TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? boost::polymorphic_cast( const_cast(this)) : 0; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlNode* Clone() const = 0; @@ -587,8 +588,8 @@ class TiXmlAttribute : public TiXmlBase const char* Name() const { return name.c_str (); } ///< Return the name of this attribute. const char* Value() const { return value.c_str (); } ///< Return the value of this attribute. - const int IntValue() const; ///< Return the value of this attribute, converted to an integer. - const double DoubleValue() const; ///< Return the value of this attribute, converted to a double. + int IntValue() const; ///< Return the value of this attribute, converted to an integer. + double DoubleValue() const; ///< Return the value of this attribute, converted to a double. /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. @@ -1050,7 +1051,7 @@ class TiXmlDocument : public TiXmlNode /** Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. */ - const int ErrorId() const { return errorId; } + int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable @@ -1205,7 +1206,7 @@ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - TiXmlHandle( TiXmlNode* node ) { this->node = node; } + TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } /// Copy constructor TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } diff --git a/src/PLASMA/TinyXml/base/tinyxmlparser.cpp b/src/PLASMA/TinyXml/base/tinyxmlparser.cpp index 085a25399..75b9e0d85 100644 --- a/src/PLASMA/TinyXml/base/tinyxmlparser.cpp +++ b/src/PLASMA/TinyXml/base/tinyxmlparser.cpp @@ -31,1130 +31,1140 @@ namespace EUROPA { // Note tha "PutString" hardcodes the same list. This // is less flexible than it appears. Changing the entries -// or order will break putstring. +// or order will break putstring. TiXmlBase::Entity TiXmlBase::entity[ NUM_ENTITY ] = { - { "&", 5, '&' }, - { "<", 4, '<' }, - { ">", 4, '>' }, - { """, 6, '\"' }, - { "'", 6, '\'' } + { "&", 5, '&' }, + { "<", 4, '<' }, + { ">", 4, '>' }, + { """, 6, '\"' }, + { "'", 6, '\'' } }; class TiXmlParsingData { - friend class TiXmlDocument; + friend class TiXmlDocument; public: - //TiXmlParsingData( const char* now, const TiXmlParsingData* prevData ); - void Stamp( const char* now ); + //TiXmlParsingData( const char* now, const TiXmlParsingData* prevData ); + void Stamp( const char* now ); - const TiXmlCursor& Cursor() { return cursor; } - //void Update( const char* now ); + const TiXmlCursor& Cursor() { return cursor; } + //void Update( const char* now ); private: - // Only used by the document! - TiXmlParsingData( const char* start, int _tabsize, int row, int col ) - { - assert( start ); - stamp = start; - tabsize = _tabsize; - cursor.row = row; - cursor.col = col; - } - - TiXmlCursor cursor; - const char* stamp; - int tabsize; + // Only used by the document! + TiXmlParsingData( const char* start, int _tabsize, int row, int col ) + { + assert( start ); + stamp = start; + tabsize = _tabsize; + cursor.row = row; + cursor.col = col; + } + + TiXmlCursor cursor; + const char* stamp; + int tabsize; }; void TiXmlParsingData::Stamp( const char* now ) { - assert( now ); - - // Do nothing if the tabsize is 0. - if ( tabsize < 1 ) - { - return; - } - - // Get the current row, column. - int row = cursor.row; - int col = cursor.col; - const char* p = stamp; - assert( p ); - - while ( p < now ) - { - // Code contributed by Fletcher Dunn: (modified by lee) - switch (*p) { - case 0: - // We *should* never get here, but in case we do, don't - // advance past the terminating null character, ever - return; - - case '\r': - // bump down to the next line - ++row; - col = 0; - // Eat the character - ++p; - - // Check for \r\n sequence, and treat this as a single character - if (*p == '\n') { - ++p; - } - break; - - case '\n': - // bump down to the next line - ++row; - col = 0; - - // Eat the character - ++p; - - // Check for \n\r sequence, and treat this as a single - // character. (Yes, this bizarre thing does occur still - // on some arcane platforms...) - if (*p == '\r') { - ++p; - } - break; - - case '\t': - // Eat the character - ++p; - - // Skip to next tab stop - col = (col / tabsize + 1) * tabsize; - break; - - default: - // Eat the character - ++p; - - // Normal char - just advance one column - ++col; - break; - } - } - cursor.row = row; - cursor.col = col; - assert( cursor.row >= -1 ); - assert( cursor.col >= -1 ); - stamp = p; - assert( stamp ); + assert( now ); + + // Do nothing if the tabsize is 0. + if ( tabsize < 1 ) + { + return; + } + + // Get the current row, column. + int row = cursor.row; + int col = cursor.col; + const char* p = stamp; + assert( p ); + + while ( p < now ) + { + // Code contributed by Fletcher Dunn: (modified by lee) + switch (*p) { + case 0: + // We *should* never get here, but in case we do, don't + // advance past the terminating null character, ever + return; + + case '\r': + // bump down to the next line + ++row; + col = 0; + // Eat the character + ++p; + + // Check for \r\n sequence, and treat this as a single character + if (*p == '\n') { + ++p; + } + break; + + case '\n': + // bump down to the next line + ++row; + col = 0; + + // Eat the character + ++p; + + // Check for \n\r sequence, and treat this as a single + // character. (Yes, this bizarre thing does occur still + // on some arcane platforms...) + if (*p == '\r') { + ++p; + } + break; + + case '\t': + // Eat the character + ++p; + + // Skip to next tab stop + col = (col / tabsize + 1) * tabsize; + break; + + default: + // Eat the character + ++p; + + // Normal char - just advance one column + ++col; + break; + } + } + cursor.row = row; + cursor.col = col; + assert( cursor.row >= -1 ); + assert( cursor.col >= -1 ); + stamp = p; + assert( stamp ); } const char* TiXmlBase::SkipWhiteSpace( const char* p ) { - if ( !p || !*p ) - { - return 0; - } - while ( p && *p ) - { - if ( isspace( *p ) || *p == '\n' || *p =='\r' ) // Still using old rules for white space. - ++p; - else - break; - } - - return p; + if ( !p || !*p ) + { + return 0; + } + while ( p && *p ) + { + if ( isspace( *p ) || *p == '\n' || *p =='\r' ) // Still using old rules for white space. + ++p; + else + break; + } + + return p; } #ifdef TIXML_USE_STL /*static*/ bool TiXmlBase::StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag ) { - for( ;; ) - { - if ( !in->good() ) return false; - - int c = in->peek(); - if ( !IsWhiteSpace( c ) ) - return true; - *tag += in->get(); - } + for( ;; ) + { + if ( !in->good() ) return false; + + int c = in->peek(); + if ( !IsWhiteSpace( c ) ) + return true; + char realc = '\0'; + in->get(realc); + *tag += realc; + } } /*static*/ bool TiXmlBase::StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->peek(); - if ( c == character ) - return true; - - in->get(); - *tag += c; - } - return false; + while ( in->good() ) + { + int c = in->peek(); + if ( c == character ) + return true; + + char realc = '\0'; + in->get(realc); + *tag += realc; + } + return false; } #endif const char* TiXmlBase::ReadName( const char* p, TIXML_STRING * name ) { - *name = ""; - assert( p ); - - // Names start with letters or underscores. - // After that, they can be letters, underscores, numbers, - // hyphens, or colons. (Colons are valid ony for namespaces, - // but tinyxml can't tell namespaces from names.) - if ( p && *p - && ( isalpha( (unsigned char) *p ) || *p == '_' ) ) - { - while( p && *p - && ( isalnum( (unsigned char ) *p ) - || *p == '_' - || *p == '-' - || *p == '.' - || *p == ':' ) ) - { - (*name) += *p; - ++p; - } - return p; - } - return 0; + *name = ""; + assert( p ); + + // Names start with letters or underscores. + // After that, they can be letters, underscores, numbers, + // hyphens, or colons. (Colons are valid ony for namespaces, + // but tinyxml can't tell namespaces from names.) + if ( p && *p + && ( isalpha( static_cast(*p) ) || *p == '_' ) ) + { + while( p && *p + && ( isalnum( static_cast(*p) ) + || *p == '_' + || *p == '-' + || *p == '.' + || *p == ':' ) ) + { + (*name) += *p; + ++p; + } + return p; + } + return 0; } const char* TiXmlBase::GetEntity( const char* p, char* value ) { - // Presume an entity, and pull it out. + // Presume an entity, and pull it out. TIXML_STRING ent; - int i; - - // Handle the &#x entities. - if ( strncmp( "&#x", p, 3 ) == 0 - && *(p+3) - && *(p+4) - && ( *(p+4) == ';' || *(p+5) == ';' ) - ) - { - *value = 0; - - if ( *(p+4) == ';' ) - { - // Short, one value entity. - if ( isalpha( *(p+3) ) ) *value += ( tolower( *(p+3) ) - 'a' + 10 ); - else *value += ( *(p+3) - '0' ); - - return p+5; - } - else - { - // two value entity - if ( isalpha( *(p+3) ) ) *value += ( tolower( *(p+3) ) - 'a' + 10 ) * 16; - else *value += ( *(p+3) - '0' ) * 16; - - if ( isalpha( *(p+4) ) ) *value += ( tolower( *(p+4) ) - 'a' + 10 ); - else *value += ( *(p+4) - '0' ); - - return p+6; - } - } - - // Now try to match it. - for( i=0; i" so the - // sub-tag can orient itself. - - if ( !StreamTo( in, '<', tag ) ) - { - SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0 ); - return; - } - - while ( in->good() ) - { - int tagIndex = tag->length(); - while ( in->good() && in->peek() != '>' ) - { - int c = in->get(); - (*tag) += (char) c; - } - - if ( in->good() ) - { - // We now have something we presume to be a node of - // some sort. Identify it, and call the node to - // continue streaming. - TiXmlNode* node = Identify( tag->c_str() + tagIndex ); - - if ( node ) - { - node->StreamIn( in, tag ); - bool isElement = node->ToElement() != 0; - delete node; - node = 0; - - // If this is the root element, we're done. Parsing will be - // done by the >> operator. - if ( isElement ) - { - return; - } - } - else - { - SetError( TIXML_ERROR, 0, 0 ); - return; - } - } - } - // We should have returned sooner. - SetError( TIXML_ERROR, 0, 0 ); + // The basic issue with a document is that we don't know what we're + // streaming. Read something presumed to be a tag (and hope), then + // identify it, and call the appropriate stream method on the tag. + // + // This "pre-streaming" will never read the closing ">" so the + // sub-tag can orient itself. + + if ( !StreamTo( in, '<', tag ) ) + { + SetError( TIXML_ERROR_PARSING_EMPTY, 0, 0 ); + return; + } + + while ( in->good() ) + { + unsigned long tagIndex = tag->length(); + while ( in->good() && in->peek() != '>' ) + { + char c = '\0'; + in->get(c); + (*tag) += c; + } + + if ( in->good() ) + { + // We now have something we presume to be a node of + // some sort. Identify it, and call the node to + // continue streaming. + TiXmlNode* node = Identify( tag->c_str() + tagIndex ); + + if ( node ) + { + node->StreamIn( in, tag ); + bool isElement = node->ToElement() != 0; + delete node; + node = 0; + + // If this is the root element, we're done. Parsing will be + // done by the >> operator. + if ( isElement ) + { + return; + } + } + else + { + SetError( TIXML_ERROR, 0, 0 ); + return; + } + } + } + // We should have returned sooner. + SetError( TIXML_ERROR, 0, 0 ); } #endif const char* TiXmlDocument::Parse( const char* p, TiXmlParsingData* prevData ) { - ClearError(); - - // Parse away, at the document level. Since a document - // contains nothing but other tags, most of what happens - // here is skipping white space. - if ( !p || !*p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0 ); - return 0; - } - - // Note that, for a document, this needs to come - // before the while space skip, so that parsing - // starts from the pointer we are given. - location.Clear(); - if ( prevData ) - { - location.row = prevData->cursor.row; - location.col = prevData->cursor.col; - } - else - { - location.row = 0; - location.col = 0; - } - TiXmlParsingData data( p, TabSize(), location.row, location.col ); - location = data.Cursor(); + ClearError(); + + // Parse away, at the document level. Since a document + // contains nothing but other tags, most of what happens + // here is skipping white space. + if ( !p || !*p ) + { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0 ); + return 0; + } + + // Note that, for a document, this needs to come + // before the while space skip, so that parsing + // starts from the pointer we are given. + location.Clear(); + if ( prevData ) + { + location.row = prevData->cursor.row; + location.col = prevData->cursor.col; + } + else + { + location.row = 0; + location.col = 0; + } + TiXmlParsingData data( p, TabSize(), location.row, location.col ); + location = data.Cursor(); p = SkipWhiteSpace( p ); - if ( !p ) - { - SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0 ); - return 0; - } - - while ( p && *p ) - { - TiXmlNode* node = Identify( p ); - if ( node ) - { - p = node->Parse( p, &data ); - LinkEndChild( node ); - } - else - { - break; - } - p = SkipWhiteSpace( p ); - } - - // All is well. - return p; + if ( !p ) + { + SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0 ); + return 0; + } + + while ( p && *p ) + { + TiXmlNode* node = Identify( p ); + if ( node ) + { + p = node->Parse( p, &data ); + LinkEndChild( node ); + } + else + { + break; + } + p = SkipWhiteSpace( p ); + } + + // All is well. + return p; } void TiXmlDocument::SetError( int err, const char* pError, TiXmlParsingData* data ) -{ - // The first error in a chain is more accurate - don't set again! - if ( error ) - return; - - assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); - error = true; - errorId = err; - errorDesc = errorString[ errorId ]; - - errorLocation.Clear(); - if ( pError && data ) - { - //TiXmlParsingData data( pError, prevData ); - data->Stamp( pError ); - errorLocation = data->Cursor(); - } +{ + // The first error in a chain is more accurate - don't set again! + if ( error ) + return; + + assert( err > 0 && err < TIXML_ERROR_STRING_COUNT ); + error = true; + errorId = err; + errorDesc = errorString[ errorId ]; + + errorLocation.Clear(); + if ( pError && data ) + { + //TiXmlParsingData data( pError, prevData ); + data->Stamp( pError ); + errorLocation = data->Cursor(); + } } TiXmlNode* TiXmlNode::Identify( const char* p ) { - TiXmlNode* returnNode = 0; - - p = SkipWhiteSpace( p ); - if( !p || !*p || *p != '<' ) - { - return 0; - } - - TiXmlDocument* doc = GetDocument(); - p = SkipWhiteSpace( p ); - - if ( !p || !*p ) - { - return 0; - } - - // What is this thing? - // - Elements start with a letter or underscore, but xml is reserved. - // - Comments: "; - - if ( !StringEqual( p, startTag, false ) ) - { - document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data ); - return 0; - } - p += strlen( startTag ); - p = ReadText( p, &value, false, endTag, false ); - return p; + TiXmlDocument* document = GetDocument(); + value = ""; + + p = SkipWhiteSpace( p ); + +// TiXmlParsingData data( p, prevData ); + if ( data ) + { + data->Stamp( p ); + location = data->Cursor(); + } + const char* startTag = ""; + + if ( !StringEqual( p, startTag, false ) ) + { + document->SetError( TIXML_ERROR_PARSING_COMMENT, p, data ); + return 0; + } + p += strlen( startTag ); + p = ReadText( p, &value, false, endTag, false ); + return p; } const char* TiXmlAttribute::Parse( const char* p, TiXmlParsingData* data ) { - p = SkipWhiteSpace( p ); - if ( !p || !*p ) return 0; - - int tabsize = 4; - if ( document ) - tabsize = document->TabSize(); - -// TiXmlParsingData data( p, prevData ); - if ( data ) - { - data->Stamp( p ); - location = data->Cursor(); - } - // Read the name, the '=' and the value. - const char* pErr = p; - p = ReadName( p, &name ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data ); - return 0; - } - p = SkipWhiteSpace( p ); - if ( !p || !*p || *p != '=' ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); - return 0; - } - - ++p; // skip '=' - p = SkipWhiteSpace( p ); - if ( !p || !*p ) - { - if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); - return 0; - } - - const char* end; - - if ( *p == '\'' ) - { - ++p; - end = "\'"; - p = ReadText( p, &value, false, end, false ); - } - else if ( *p == '"' ) - { - ++p; - end = "\""; - p = ReadText( p, &value, false, end, false ); - } - else - { - // All attribute values should be in single or double quotes. - // But this is such a common error that the parser will try - // its best, even without them. - value = ""; - while ( p && *p // existence - && !isspace( *p ) && *p != '\n' && *p != '\r' // whitespace - && *p != '/' && *p != '>' ) // tag end - { - value += *p; - ++p; - } - } - return p; + p = SkipWhiteSpace( p ); + if ( !p || !*p ) return 0; + + int tabsize = 4; + if ( document ) + tabsize = document->TabSize(); + +// TiXmlParsingData data( p, prevData ); + if ( data ) + { + data->Stamp( p ); + location = data->Cursor(); + } + // Read the name, the '=' and the value. + const char* pErr = p; + p = ReadName( p, &name ); + if ( !p || !*p ) + { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data ); + return 0; + } + p = SkipWhiteSpace( p ); + if ( !p || !*p || *p != '=' ) + { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); + return 0; + } + + ++p; // skip '=' + p = SkipWhiteSpace( p ); + if ( !p || !*p ) + { + if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, p, data ); + return 0; + } + + const char* end; + + if ( *p == '\'' ) + { + ++p; + end = "\'"; + p = ReadText( p, &value, false, end, false ); + } + else if ( *p == '"' ) + { + ++p; + end = "\""; + p = ReadText( p, &value, false, end, false ); + } + else + { + // All attribute values should be in single or double quotes. + // But this is such a common error that the parser will try + // its best, even without them. + value = ""; + while ( p && *p // existence + && !isspace( *p ) && *p != '\n' && *p != '\r' // whitespace + && *p != '/' && *p != '>' ) // tag end + { + value += *p; + ++p; + } + } + return p; } #ifdef TIXML_USE_STL void TiXmlText::StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->peek(); - if ( c == '<' ) - return; - - (*tag) += c; - in->get(); - } + while ( in->good() ) + { + int c = in->peek(); + if ( c == '<' ) + return; + + (*tag) += static_cast(c); + in->get(); + } } #endif const char* TiXmlText::Parse( const char* p, TiXmlParsingData* data ) { - value = ""; -// TiXmlParsingData data( p, prevData ); - if ( data ) - { - data->Stamp( p ); - location = data->Cursor(); - } - bool ignoreWhite = true; - - const char* end = "<"; - p = ReadText( p, &value, ignoreWhite, end, false ); - if ( p ) - return p-1; // don't truncate the '<' - return 0; + value = ""; +// TiXmlParsingData data( p, prevData ); + if ( data ) + { + data->Stamp( p ); + location = data->Cursor(); + } + bool ignoreWhite = true; + + const char* end = "<"; + p = ReadText( p, &value, ignoreWhite, end, false ); + if ( p ) + return p-1; // don't truncate the '<' + return 0; } #ifdef TIXML_USE_STL void TiXmlDeclaration::StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag ) { - while ( in->good() ) - { - int c = in->get(); - (*tag) += c; - - if ( c == '>' ) - { - // All is well. - return; - } - } + while ( in->good() ) + { + char c = '\0'; + in->get(c); + (*tag) += c; + + if ( c == '>' ) + { + // All is well. + return; + } + } } #endif const char* TiXmlDeclaration::Parse( const char* p, TiXmlParsingData* data ) { - p = SkipWhiteSpace( p ); - // Find the beginning, find the end, and look for - // the stuff in-between. - TiXmlDocument* document = GetDocument(); - if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0 ); - return 0; - } -// TiXmlParsingData data( p, prevData ); - if ( data ) - { - data->Stamp( p ); - location = data->Cursor(); - } - p += 5; - - version = ""; - encoding = ""; - standalone = ""; - - while ( p && *p ) - { - if ( *p == '>' ) - { - ++p; - return p; - } - - p = SkipWhiteSpace( p ); - if ( StringEqual( p, "version", true ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data ); - version = attrib.Value(); - } - else if ( StringEqual( p, "encoding", true ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data ); - encoding = attrib.Value(); - } - else if ( StringEqual( p, "standalone", true ) ) - { - TiXmlAttribute attrib; - p = attrib.Parse( p, data ); - standalone = attrib.Value(); - } - else - { - // Read over whatever it is. - while( p && *p && *p != '>' && !isspace( *p ) ) - ++p; - } - } - return 0; + p = SkipWhiteSpace( p ); + // Find the beginning, find the end, and look for + // the stuff in-between. + TiXmlDocument* document = GetDocument(); + if ( !p || !*p || !StringEqual( p, "SetError( TIXML_ERROR_PARSING_DECLARATION, 0, 0 ); + return 0; + } +// TiXmlParsingData data( p, prevData ); + if ( data ) + { + data->Stamp( p ); + location = data->Cursor(); + } + p += 5; + + version = ""; + encoding = ""; + standalone = ""; + + while ( p && *p ) + { + if ( *p == '>' ) + { + ++p; + return p; + } + + p = SkipWhiteSpace( p ); + if ( StringEqual( p, "version", true ) ) + { + TiXmlAttribute attrib; + p = attrib.Parse( p, data ); + version = attrib.Value(); + } + else if ( StringEqual( p, "encoding", true ) ) + { + TiXmlAttribute attrib; + p = attrib.Parse( p, data ); + encoding = attrib.Value(); + } + else if ( StringEqual( p, "standalone", true ) ) + { + TiXmlAttribute attrib; + p = attrib.Parse( p, data ); + standalone = attrib.Value(); + } + else + { + // Read over whatever it is. + while( p && *p && *p != '>' && !isspace( *p ) ) + ++p; + } + } + return 0; } bool TiXmlText::Blank() const { - for ( unsigned i=0; iToElement(); - assert( todoElement ); - - // Going to the toy store is now our second priority... - // So set the "priority" attribute of the first item in the list. - node = todoElement->FirstChildElement(); // This skips the "PDA" comment. - assert( node ); - itemElement = node->ToElement(); - assert( itemElement ); - itemElement->SetAttribute( "priority", 2 ); - - // Change the distance to "doing bills" from - // "none" to "here". It's the next sibling element. - itemElement = itemElement->NextSiblingElement(); - assert( itemElement ); - itemElement->SetAttribute( "distance", "here" ); - - // Remove the "Look for Evil Dinosours!" item. - // It is 1 more sibling away. We ask the parent to remove - // a particular child. - itemElement = itemElement->NextSiblingElement(); - todoElement->RemoveChild( itemElement ); - - itemElement = 0; - - // -------------------------------------------------------- - // What follows is an example of created elements and text - // nodes and adding them to the document. - // -------------------------------------------------------- - - // Add some meetings. - TiXmlElement item( "Item" ); - item.SetAttribute( "priority", "1" ); - item.SetAttribute( "distance", "far" ); - - TiXmlText text( "Talk to:" ); - - TiXmlElement meeting1( "Meeting" ); - meeting1.SetAttribute( "where", "School" ); - - TiXmlElement meeting2( "Meeting" ); - meeting2.SetAttribute( "where", "Lunch" ); - - TiXmlElement attendee1( "Attendee" ); - attendee1.SetAttribute( "name", "Marple" ); - attendee1.SetAttribute( "position", "teacher" ); - - TiXmlElement attendee2( "Attendee" ); - attendee2.SetAttribute( "name", "Vo‚" ); - attendee2.SetAttribute( "position", "counselor" ); - - // Assemble the nodes we've created: - meeting1.InsertEndChild( attendee1 ); - meeting1.InsertEndChild( attendee2 ); - - item.InsertEndChild( text ); - item.InsertEndChild( meeting1 ); - item.InsertEndChild( meeting2 ); - - // And add the node to the existing list after the first child. - node = todoElement->FirstChild( "Item" ); - assert( node ); - itemElement = node->ToElement(); - assert( itemElement ); - - todoElement->InsertAfterChild( itemElement, item ); - - printf( "\n** Demo doc processed: ** \n\n" ); - doc.Print( stdout ); - - + ostringstream outputStream( ostringstream::out ); + { + TiXmlDocument doc( "demotest.xml" ); + bool loadOkay = doc.LoadFile(); + + if ( !loadOkay ) + { + printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() ); + exit( 1 ); + } + + printf( "** Demo doc read from disk: ** \n\n" ); + doc.Print( stdout ); + + TiXmlNode* node = 0; + TiXmlElement* todoElement = 0; + TiXmlElement* itemElement = 0; + + + // -------------------------------------------------------- + // An example of changing existing attributes, and removing + // an element from the document. + // -------------------------------------------------------- + + // Get the "ToDo" element. + // It is a child of the document, and can be selected by name. + node = doc.FirstChild( "ToDo" ); + assert( node ); + todoElement = node->ToElement(); + assert( todoElement ); + + // Going to the toy store is now our second priority... + // So set the "priority" attribute of the first item in the list. + node = todoElement->FirstChildElement(); // This skips the "PDA" comment. + assert( node ); + itemElement = node->ToElement(); + assert( itemElement ); + itemElement->SetAttribute( "priority", 2 ); + + // Change the distance to "doing bills" from + // "none" to "here". It's the next sibling element. + itemElement = itemElement->NextSiblingElement(); + assert( itemElement ); + itemElement->SetAttribute( "distance", "here" ); + + // Remove the "Look for Evil Dinosours!" item. + // It is 1 more sibling away. We ask the parent to remove + // a particular child. + itemElement = itemElement->NextSiblingElement(); + todoElement->RemoveChild( itemElement ); + + itemElement = 0; + + // -------------------------------------------------------- + // What follows is an example of created elements and text + // nodes and adding them to the document. + // -------------------------------------------------------- + + // Add some meetings. + TiXmlElement item( "Item" ); + item.SetAttribute( "priority", "1" ); + item.SetAttribute( "distance", "far" ); + + TiXmlText text( "Talk to:" ); + + TiXmlElement meeting1( "Meeting" ); + meeting1.SetAttribute( "where", "School" ); + + TiXmlElement meeting2( "Meeting" ); + meeting2.SetAttribute( "where", "Lunch" ); + + TiXmlElement attendee1( "Attendee" ); + attendee1.SetAttribute( "name", "Marple" ); + attendee1.SetAttribute( "position", "teacher" ); + + TiXmlElement attendee2( "Attendee" ); + attendee2.SetAttribute( "name", "Vo‚" ); + attendee2.SetAttribute( "position", "counselor" ); + + // Assemble the nodes we've created: + meeting1.InsertEndChild( attendee1 ); + meeting1.InsertEndChild( attendee2 ); + + item.InsertEndChild( text ); + item.InsertEndChild( meeting1 ); + item.InsertEndChild( meeting2 ); + + // And add the node to the existing list after the first child. + node = todoElement->FirstChild( "Item" ); + assert( node ); + itemElement = node->ToElement(); + assert( itemElement ); + + todoElement->InsertAfterChild( itemElement, item ); + + printf( "\n** Demo doc processed: ** \n\n" ); + doc.Print( stdout ); + + #ifdef TIXML_USE_STL - printf( "** Demo doc processed to stream: ** \n\n" ); - cout << doc << endl << endl; + printf( "** Demo doc processed to stream: ** \n\n" ); + cout << doc << endl << endl; #endif // -------------------------------------------------------- @@ -248,12 +249,11 @@ int main() #ifdef TIXML_USE_STL cout << "** Basic structure. **\n"; - ostringstream outputStream( ostringstream::out ); outputStream << doc; XmlTest( "Output stream correct.", string( demoEnd ).c_str(), - outputStream.str().c_str(), true ); + outputStream.str().c_str(), true ); #endif - + node = doc.RootElement(); XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) ); XmlTest ( "Root element value is 'ToDo'.", "ToDo", node->Value()); @@ -345,19 +345,18 @@ int main() XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) ); } #endif - + } { - const char* error = "\n" - "\n" - " \n" - ""; - - TiXmlDocument doc; - doc.Parse( error ); - XmlTest( "Error row", doc.ErrorRow(), 3 ); - XmlTest( "Error column", doc.ErrorCol(), 17 ); - //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); - + const char* error = "\n" + "\n" + " \n" + ""; + + TiXmlDocument doc; + doc.Parse( error ); + XmlTest( "Error row", doc.ErrorRow(), 3 ); + XmlTest( "Error column", doc.ErrorCol(), 17 ); + //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 ); } { const char* str = "\t\t\n" @@ -448,9 +447,9 @@ int main() result = ele->QueryDoubleAttribute( "attr0", &dVal ); XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS ); - XmlTest( "Query attribute: int as double", (int)dVal, 1 ); + XmlTest( "Query attribute: int as double", static_cast(dVal), 1 ); result = ele->QueryDoubleAttribute( "attr1", &dVal ); - XmlTest( "Query attribute: double as double", (int)dVal, 2 ); + XmlTest( "Query attribute: double as double", static_cast(dVal), 2 ); result = ele->QueryIntAttribute( "attr1", &iVal ); XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS ); XmlTest( "Query attribute: double as int", iVal, 2 ); From da0ada7a19a2335be486f43f7845c1f77ceb990d Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sat, 6 Dec 2014 23:59:58 -0800 Subject: [PATCH 061/149] Fixing macro vararg warnings. Should be more standards-compliant now. --- src/PLASMA/Utils/base/DebugMsg.hh | 2 - src/PLASMA/Utils/base/Error.hh | 213 ++++++++++++++++-------------- 2 files changed, 114 insertions(+), 101 deletions(-) diff --git a/src/PLASMA/Utils/base/DebugMsg.hh b/src/PLASMA/Utils/base/DebugMsg.hh index ae94131b1..92ac24a6a 100755 --- a/src/PLASMA/Utils/base/DebugMsg.hh +++ b/src/PLASMA/Utils/base/DebugMsg.hh @@ -157,7 +157,6 @@ private: * @param file File containing the debug message instance. * @param line Line on which it is declared/created. * @param marker Name for the particular instance (not required to be unique within the process). - * @param enabled Whether the instance is enabled at creation. * @note Only constructor that should be used. * @note Should only be called from static member functions. */ @@ -281,7 +280,6 @@ public: /** @brief Enable all debug messages, including ones not yet created. - @param val @par Errors thrown: @li If no debug stream has been assigned. @see DebugMessage::setStream diff --git a/src/PLASMA/Utils/base/Error.hh b/src/PLASMA/Utils/base/Error.hh index a678b74b8..5f158d998 100644 --- a/src/PLASMA/Utils/base/Error.hh +++ b/src/PLASMA/Utils/base/Error.hh @@ -36,13 +36,14 @@ #define _H_Error /* $Id: Error.hh,v 1.6 2007-04-29 04:36:18 miatauro Exp $ */ - #include #include #include -#include #include +#define _ARG3(_0, _1, _2, _3, ...) _3 +#define NARG3(...) _ARG3(__VA_ARGS__, 3, 2, 1, 0) + /** * @def ALWAYS_FAIL * False. @@ -62,31 +63,32 @@ return(sl_lblStr); \ } -#ifndef _MSC_VER -#define assertTrue(cond, optarg...) { \ - if (!(cond)) { \ - Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} +#define EUROPA_ERROR(__e__) if(Error::throwEnabled()) {throw __e__;} else {__e__.handleAssert();} -#define assertFalse(cond, optarg...) { \ - if (cond) { \ - Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#else -#define assertTrue(cond, ...) { \ - if (!(cond)) { \ - Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} +#define assert1(value, cond) { \ + if((cond) == value) { \ + Error __e__(#cond, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } + +#define assert2(value, cond, msg) { \ + if((cond) == value) { \ + Error __e__(#cond, msg, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } + +#define assert3(value, cond, msg, type) { \ + if((cond) == value) { \ + Error __e__(#cond, msg, type, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } + +#define __assert_(value, N, ...) assert ## N (value, __VA_ARGS__) +#define _assert(value, N, ...) __assert_(value, N, __VA_ARGS__) + +#define assertTrue(...) _assert(true, NARG3(__VA_ARGS__), __VA_ARGS__) +#define assertFalse(...) _assert(false, NARG3(__VA_ARGS__), __VA_ARGS__) -#define assertFalse(cond, ...) { \ - if (cond) { \ - Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#endif #define check_error_function __attribute__ ((unused)) @@ -96,7 +98,7 @@ * @def check_error_variable * Declare a variable as only being used for checkError (supresses warnings when compiling optimized). */ -#define check_error_variable(decl) +# define check_error_variable(decl) /** @@ -106,22 +108,22 @@ * @param optarg Other values to pass to the class Error constructor when creating the error instance. * @note When EUROPA_FAST is defined, these are ignored. */ -#ifndef _MSC_VER -#define check_error(cond, optarg...) -#define checkError(cond, msg, optarg...) -#else -#define check_error(cond, ...) -#define checkError(cond, msg) -#endif +# define check_error1(cond) +# define check_error2(cond, msg) +# define check_error3(cond, msg, type) +# define checkError1(cond) +# define checkError2(cond, msg) +# define checkError3(cond, msg, type) + /** * @def warn * Print a warning if such is enabled. * @param msg The information to print. * @note When EUROPA_FAST is defined, these are ignored */ -#ifndef warn -#define europaWarn(msg) -#endif +# ifndef warn +# define europaWarn(msg) +# endif /** * @def condWarning @@ -130,11 +132,11 @@ * @param msg The information to print in the warning. * @note When EUROPA_FAST is defined, these are ignored */ -#define condWarning(cond, msg) +# define condWarning(cond, msg) -#else +#else //EUROPA_FAST -#define check_error_variable(decl) decl +# define check_error_variable(decl) decl /** * @def check_error @@ -159,60 +161,57 @@ * * @see assertTrue, assertFalse, ALWAYS_FAIL */ -#ifndef _MSC_VER -#define check_error(cond, optarg...) { \ - if (!(cond)) { \ - Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#else -#define check_error(cond, ...) { \ - if (!(cond)) { \ - Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#endif +# define check_error1(cond) { \ + if(!(cond)) { \ + Error __e__(#cond, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } +# define check_error2(cond, msg) { \ + if(!(cond)) { \ + Error __e__(#cond, msg, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } +# define check_error3(cond, msg, type) { \ + if(!(cond)) { \ + Error __e__(#cond, msg, type, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } -#ifndef _MSC_VER -#define checkError(cond, msg, optarg...) { \ - if (!(cond)) { \ - std::stringstream sstr; \ - sstr << msg; \ - Error __e__(#cond, sstr.str(), ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#else +# define checkError1(cond) { \ + if(!(cond)) { \ + Error __e__(#cond, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } -//TODO: mcr - some calls to this are ambiguous .. do you want an error or a msg? -#define checkError(cond, msg) { \ - if (!(cond)) { \ - std::stringstream sstr; \ - sstr << msg; \ - Error __e__(#cond, sstr.str(), __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} +# define checkError2(cond, msg) { \ + if (!(cond)) { \ + std::stringstream sstr; \ + sstr << msg; \ + Error __e__(#cond, sstr.str(), __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } -#define check_Error(cond, msg, errorType) { \ - if (!(cond)) { \ - std::stringstream sstr; \ - sstr << msg; \ - Error __e__(#cond, sstr.str(), __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#endif +# define checkError3(cond, msg, type) { \ + if (!(cond)) { \ + std::stringstream sstr; \ + sstr << msg; \ + Error __e__(#cond, sstr.str(), #type, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } -#ifndef warn -#define europaWarn(msg) (Error::printWarning((msg), __FILE__, __LINE__)) -#endif +# ifndef warn +# define europaWarn(msg) (Error::printWarning((msg), __FILE__, __LINE__)) +# endif -#define condWarning(cond, msg) { \ - if (!(cond)) { \ - Error::printWarning((msg), __FILE__, __LINE__); \ - } \ -} +# define condWarning(cond, msg) { \ + if (!(cond)) { \ + Error::printWarning((msg), __FILE__, __LINE__); \ + } \ + } #endif /* EUROPA_FAST */ + /** * @def check_runtime_error * @brief If the condition is false, throw an exception @@ -227,19 +226,35 @@ * removing check_error has to do with debug levels. * removing check_runtime_error doesn't have to do with debugging, but with leaving behavior out for speed sake. */ -#ifndef _MSC_VER -#define check_runtime_error(cond, optarg...) { \ - if (!(cond)) { \ - Error __e__(#cond, ##optarg, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#else -#define check_runtime_error(cond, ...) { \ - if (!(cond)) { \ - Error __e__(#cond, __VA_ARGS__, __FILE__, __LINE__); if(Error::throwEnabled()){throw __e__;}else{__e__.handleAssert();} \ - } \ -} -#endif + +# define check_runtime_error1(cond) { \ + if(!(cond)) { \ + Error __e__(#cond, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } +# define check_runtime_error2(cond, msg) { \ + if(!(cond)) { \ + Error __e__(#cond, msg, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } +# define check_runtime_error3(cond, msg, type) { \ + if(!(cond)) { \ + Error __e__(#cond, msg, type, __FILE__, __LINE__); EUROPA_ERROR(__e__); \ + } \ + } +#define __check_error(N, ...) check_error ## N(__VA_ARGS__) +#define _check_error(N, ...) __check_error(N, __VA_ARGS__) +#define check_error(...) _check_error(NARG3(__VA_ARGS__), __VA_ARGS__) + +#define __checkError(N, ...) checkError ## N(__VA_ARGS__) +#define _checkError(N, ...) __checkError(N, __VA_ARGS__) +#define checkError(...) _checkError(NARG3(__VA_ARGS__), __VA_ARGS__) + +#define __check_runtime_error(N, ...) check_runtime_error ## N(__VA_ARGS__) +#define _check_runtime_error(N, ...) __check_runtime_error(N, __VA_ARGS__) +#define check_runtime_error(...) _check_runtime_error(NARG3(__VA_ARGS__), __VA_ARGS__) + + #define checkRuntimeError(cond, msg) { \ if (!(cond)) { \ std::stringstream sstr; \ @@ -348,7 +363,7 @@ public: return(m_condition); } - inline const int getLine() const { + inline int getLine() const { return(m_line); } From 53cf9ad0e0dfefe6aeabd03a6dce96384e079517 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sun, 7 Dec 2014 12:06:05 -0800 Subject: [PATCH 062/149] Code cleanups for clang's -Weverything --- src/PLASMA/Utils/Number.hh | 9 +- src/PLASMA/Utils/NumberHash.hh | 26 ++++ src/PLASMA/Utils/base/DebugMsg.hh | 38 ++--- src/PLASMA/Utils/base/Engine.cc | 162 ++++++++++++---------- src/PLASMA/Utils/base/Entity.cc | 18 +-- src/PLASMA/Utils/base/Entity.hh | 6 +- src/PLASMA/Utils/base/Error.hh | 2 +- src/PLASMA/Utils/base/Factory.cc | 19 ++- src/PLASMA/Utils/base/Id.hh | 21 +-- src/PLASMA/Utils/base/IdTable.cc | 8 +- src/PLASMA/Utils/base/IdTable.hh | 3 +- src/PLASMA/Utils/base/LabelStr.cc | 11 +- src/PLASMA/Utils/base/LabelStr.hh | 10 +- src/PLASMA/Utils/base/Pdlfcn.cc | 4 +- src/PLASMA/Utils/base/TestData.cc | 14 +- src/PLASMA/Utils/base/Utils.cc | 16 +-- src/PLASMA/Utils/base/Utils.hh | 14 +- src/PLASMA/Utils/base/XMLUtils.cc | 34 ++--- src/PLASMA/Utils/test/util-test-module.cc | 27 ++-- 19 files changed, 237 insertions(+), 205 deletions(-) create mode 100644 src/PLASMA/Utils/NumberHash.hh diff --git a/src/PLASMA/Utils/Number.hh b/src/PLASMA/Utils/Number.hh index 327aeed5e..ed9628b3e 100644 --- a/src/PLASMA/Utils/Number.hh +++ b/src/PLASMA/Utils/Number.hh @@ -8,7 +8,6 @@ #include #include #include -#include #ifdef _MSC_VER # if ( LONG_MAX > INT_MAX) @@ -53,6 +52,7 @@ namespace EUROPA { } namespace boost { +template struct hash; template<> struct hash { inline size_t operator()(EUROPA::edouble __x) const; @@ -63,6 +63,7 @@ template<> struct hash { }; } + namespace std { template<> struct numeric_limits { @@ -801,12 +802,6 @@ inline EUROPA::edouble pow(const EUROPA::edouble d, const EUROPA::eint i) {retur } -namespace boost { - //I'm not entirely sure this is safe, but it's worked so far. Maybe this should be changed to -//*((size_t*)&(__x.m_v)) -size_t hash::operator()(EUROPA::edouble __x) const {return static_cast(__x.m_v);} -size_t hash::operator()(EUROPA::eint __x) const {return static_cast(static_cast(__x.m_v));} -} // #define min MIN_COPY // #define max MAX_COPY diff --git a/src/PLASMA/Utils/NumberHash.hh b/src/PLASMA/Utils/NumberHash.hh new file mode 100644 index 000000000..2432b8d65 --- /dev/null +++ b/src/PLASMA/Utils/NumberHash.hh @@ -0,0 +1,26 @@ +#ifndef _NUMBERHASH_H_ +#define _NUMBERHASH_H_ + +#include "Number.hh" +#include + +namespace boost { + +template<> struct hash { + inline size_t operator()(EUROPA::edouble __x) const; +}; + +template<> struct hash { + inline size_t operator()(EUROPA::eint __x) const; +}; +} + +namespace boost { + //I'm not entirely sure this is safe, but it's worked so far. Maybe this should be changed to +//*((size_t*)&(__x.m_v)) +size_t hash::operator()(EUROPA::edouble __x) const {return reinterpret_cast(__x.m_v);} +size_t hash::operator()(EUROPA::eint __x) const {return reinterpret_cast(static_cast(__x.m_v));} +} + + +#endif /* _NUMBERHASH_H_ */ diff --git a/src/PLASMA/Utils/base/DebugMsg.hh b/src/PLASMA/Utils/base/DebugMsg.hh index 92ac24a6a..1c7e86305 100755 --- a/src/PLASMA/Utils/base/DebugMsg.hh +++ b/src/PLASMA/Utils/base/DebugMsg.hh @@ -225,9 +225,9 @@ public: /** @brief Create a new DebugMessage. Should only be called from the debugMsg() macro and readConfigFile(). - @param file - @param line - @param marker + @param file The originating file + @param line The line number + @param marker The message marker for matching @par Errors thrown: @li If no debug stream has been assigned. @see DebugMessage::enable @@ -240,10 +240,10 @@ public: /** @brief Create a new DebugMessage. Should only be called from the debugMsg() macro and readConfigFile(). - @param file - @param line - @param marker - @param level + @param file The originating file + @param line The line number + @param marker The message marker for matching + @param level The message level @par Errors thrown: @li If no debug stream has been assigned. @see DebugMessage::enable @@ -256,8 +256,8 @@ public: /** @brief Find any matching DebugMessage. - @param file - @param pattern + @param file The originating file + @param pattern The pattern to match markers against */ static DebugMessage *findMsg(const std::string& file, const std::string& pattern); @@ -265,9 +265,9 @@ public: /** @brief Find all matching DebugMessages and appends them to matches parameter without emptying it first. - @param file - @param pattern - @param matches + @param file The originating file + @param pattern The pattern to match markers against + @param matches Destination for matches */ static void findMatchingMsgs(const std::string& file, const std::string& pattern, @@ -293,7 +293,7 @@ public: /** @brief Assign a stream to which all debug messages will be sent. - @param os + @param os The output stream to send messages to */ inline static void setStream(std::ostream& os) { streamPtr() = &os; @@ -309,7 +309,7 @@ public: /** @brief Read a list of debug message enablements from the stream argument. - @param is + @param is Input stream to read @par Errors thrown: @li If the stream is not good. @li If setStream() has not been called @@ -374,7 +374,7 @@ public: /** @brief Print the data members of the debug message in a format that Emacs can use to display the corresponding source code. - @param + @param os The output stream to write to */ inline void print(std::ostream *os = streamPtr()) const { try { @@ -389,8 +389,8 @@ public: /** @brief Enable matching debug messages, including those created later. - @param file - @param marker + @param file The originating file + @param marker Marker to match messages against @par Errors thrown: @li If a message would be enabled but no debug stream has been set. @see DebugMessage::setStream @@ -400,8 +400,8 @@ public: /** @brief Disable matching debug messages, including those created later. - @param file - @param marker + @param file The originating file + @param marker Marker to match messages against */ static void disableMatchingMsgs(const std::string& file, diff --git a/src/PLASMA/Utils/base/Engine.cc b/src/PLASMA/Utils/base/Engine.cc index 86d7790dd..320b0e2ab 100644 --- a/src/PLASMA/Utils/base/Engine.cc +++ b/src/PLASMA/Utils/base/Engine.cc @@ -76,56 +76,61 @@ namespace EUROPA { xml = m_doc->RootElement(); if (xml == NULL) return 0; - if(strcmp((const char *)xml->Value(),"EuropaConfig") == 0) + if(strcmp(static_cast(xml->Value()),"EuropaConfig") == 0) { parseXML(xml); status = 1; } else - debugMsg("EngineConfig","Expected , Found: " << (const char *)xml->Value()); + debugMsg("EngineConfig", + "Expected , Found: " << + static_cast(xml->Value())); } else { - assert("LOAD FAIL"); + assertTrue(ALWAYS_FAIL, "LOAD FAIL"); } delete m_doc; return status; } - void EngineConfig::parseXML(TiXmlNode * pParent){ - TiXmlNode * pChild = 0; - TiXmlNode * pChildEle = 0; - const char * comp_name = ""; - const char * prop_name = ""; - const char * prop_value = ""; - while(( pChild = pParent->IterateChildren( pChild ) )) - { - if( pParent->Type() == TiXmlNode::ELEMENT ) - { - if(strcmp((const char *)pChild->ToElement()->Value(),"Component") == 0 - && pChild->ToElement()) - { - comp_name = (const char *)pChild->ToElement()->FirstAttribute()->Value(); - } - - while((pChildEle = pChild->IterateChildren(pChildEle)) - && strcmp((const char *)pChild->ToElement()->FirstChildElement()->Value(),"Property") == 0) - { - if(pChildEle->FirstChild()) - { - prop_name = (const char *)pChildEle->ToElement()->FirstAttribute()->Value(); - prop_value = (const char *)pChildEle->FirstChild()->ToText()->Value(); - if(std::string(prop_name).compare("") != 0) - { - setProperty(std::string(comp_name).append(".").append(prop_name), std::string(prop_value)); - } - } - } - } - - } - } +void EngineConfig::parseXML(TiXmlNode * pParent){ + TiXmlNode * pChild = 0; + TiXmlNode * pChildEle = 0; + const char * comp_name = ""; + const char * prop_name = ""; + const char * prop_value = ""; + while(( pChild = pParent->IterateChildren( pChild ) )) + { + if( pParent->Type() == TiXmlNode::ELEMENT ) + { + if(strcmp(static_cast(pChild->ToElement()->Value()),"Component") == 0 + && pChild->ToElement()) + { + comp_name = + static_cast(pChild->ToElement()->FirstAttribute()->Value()); + } + + while((pChildEle = pChild->IterateChildren(pChildEle)) + && strcmp(static_cast(pChild->ToElement()->FirstChildElement()->Value()), + "Property") == 0) + { + if(pChildEle->FirstChild()) + { + prop_name = + static_cast(pChildEle->ToElement()->FirstAttribute()->Value()); + prop_value = static_cast(pChildEle->FirstChild()->ToText()->Value()); + if(std::string(prop_name).compare("") != 0) + { + setProperty(std::string(comp_name).append(".").append(prop_name), std::string(prop_value)); + } + } + } + } + + } +} void EngineConfig::writeFromXML(const char* file_name){ TiXmlDocument * m_doc = new TiXmlDocument(file_name); @@ -231,11 +236,10 @@ namespace EUROPA initializeModule(m_modules[i]); } - void EngineBase::uninitializeModules() - { - for (unsigned int i=m_modules.size(); i>0 ;i--) - uninitializeModule(m_modules[i-1]); - } +void EngineBase::uninitializeModules() { + for (std::vector::size_type i=m_modules.size(); i>0 ;i--) + uninitializeModule(m_modules[i-1]); +} bool EngineBase::isStarted() { @@ -288,36 +292,45 @@ namespace EUROPA m_modules.erase(it); } +template +struct fptr_cast_helper { + union helper { + void* v; + T fn; + }; + helper h; +}; // Basically a copy of PSEngineImpl::loadModel - void EngineBase::loadModule(const std::string& moduleFileName) - { - check_runtime_error(m_started,"Engine has not been started"); - - #ifdef _MSC_VER - void* libHandle = p_dlopen(moduleFileName.c_str(), RTLD_NOW); - checkRuntimeError(libHandle != NULL, - "Error opening module " << moduleFileName << ": " << p_dlerror()); - - Module* (*fcn_module)(); - fcn_module = (Module* (*)()) p_dlsym(libHandle, "initializeModule"); - checkError(fcn_module != NULL, - "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << - p_dlerror()); - #else - void* libHandle = dlopen(moduleFileName.c_str(), RTLD_NOW); - checkRuntimeError(libHandle != NULL, - "Error opening module " << moduleFileName << ": " << dlerror()); - - Module* (*fcn_module)(); - fcn_module = (Module* (*)()) dlsym(libHandle, "initializeModule"); - checkError(fcn_module != NULL, - "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << - dlerror()); - #endif - - ModuleId module = (*fcn_module)()->getId(); - addModule(module); - } +void EngineBase::loadModule(const std::string& moduleFileName) { + check_runtime_error(m_started,"Engine has not been started"); + +#ifdef _MSC_VER + void* libHandle = p_dlopen(moduleFileName.c_str(), RTLD_NOW); + checkRuntimeError(libHandle != NULL, + "Error opening module " << moduleFileName << ": " << p_dlerror()); + + Module* (*fcn_module)(); + fcn_module = (Module* (*)()) p_dlsym(libHandle, "initializeModule"); + checkError(fcn_module != NULL, + "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << + p_dlerror()); +#else + void* libHandle = dlopen(moduleFileName.c_str(), RTLD_NOW); + checkRuntimeError(libHandle != NULL, + "Error opening module " << moduleFileName << ": " << dlerror()); + + Module* (*fcn_module)(); + fptr_cast_helper helper; + helper.h.v = dlsym(libHandle, "initializeModule"); + fcn_module = helper.h.fn; + checkError(fcn_module != NULL, + "Error locating symbol 'initializeModule' in " << moduleFileName << ": " << + dlerror()); +#endif + + ModuleId module = (*fcn_module)()->getId(); + addModule(module); +} void EngineBase::initializeByModule(ModuleId module) @@ -338,11 +351,10 @@ namespace EUROPA initializeByModule(m_modules[i]); } - void EngineBase::uninitializeByModules() - { - for (int i=m_modules.size(); i>0; i--) - uninitializeByModule(m_modules[i-1]); - } +void EngineBase::uninitializeByModules() { + for (std::vector::size_type i=m_modules.size(); i>0; i--) + uninitializeByModule(m_modules[i-1]); +} std::string EngineBase::executeScript(const std::string& language, const std::string& script, bool isFile) { diff --git a/src/PLASMA/Utils/base/Entity.cc b/src/PLASMA/Utils/base/Entity.cc index 6767d21c4..4566cf410 100644 --- a/src/PLASMA/Utils/base/Entity.cc +++ b/src/PLASMA/Utils/base/Entity.cc @@ -66,7 +66,7 @@ class EntityInternals { debugMsg("Entity:garbageCollect", "Garbage collecting entity " << entity->getEntityName() << "(" << entity->getKey() << ")"); - delete (Entity*) entity; + delete entity; count++; } @@ -213,14 +213,14 @@ const std::string& Entity::getEntityType() const { clearExternalEntity(); } - const EntityId& Entity::getExternalEntity() const{ - check_error(m_externalEntity.isNoId() || m_externalEntity.isValid()); - return m_externalEntity; - } +const EntityId& Entity::getExternalEntity() const{ + check_error(m_externalEntity.isNoId() || m_externalEntity.isValid()); + return m_externalEntity; +} - const PSEntity* Entity::getExternalPSEntity() const { - return (const PSEntity*) getExternalEntity(); - } +const PSEntity* Entity::getExternalPSEntity() const { + return dynamic_cast(static_cast(getExternalEntity())); +} void Entity::purgeStarted(){ internals().second.get().purgeStarted(); @@ -281,7 +281,7 @@ bool Entity::isPurging(){ m_dependents.erase(entity); } - void Entity::notifyDiscarded(const Entity* entity) {} + void Entity::notifyDiscarded(const Entity*) {} bool Entity::isPooled(Entity* entity) { return internals().second.get().isPooled(entity); diff --git a/src/PLASMA/Utils/base/Entity.hh b/src/PLASMA/Utils/base/Entity.hh index 6735d7302..af9c23fe1 100644 --- a/src/PLASMA/Utils/base/Entity.hh +++ b/src/PLASMA/Utils/base/Entity.hh @@ -41,7 +41,7 @@ namespace EUROPA{ typedef typename COLLECTION::iterator object_iterator; for(object_iterator it = objects.begin(); it != objects.end(); ++it){ check_error((*it).isValid()); - Entity* elem = (Entity*) (*it); + Entity* elem = static_cast(*it); elem->discard(); } objects.clear(); @@ -50,7 +50,7 @@ namespace EUROPA{ virtual ~Entity(); inline eint getKey() const {return m_key;} - inline PSEntityKey getEntityKey() const {return cast_int(m_key);} + inline PSEntityKey getEntityKey() const {return static_cast(cast_int(m_key));} virtual const std::string& getEntityName() const; @@ -202,7 +202,7 @@ namespace EUROPA{ return t1->getKey() < t2->getKey(); } - bool operator==(const EntityComparator& c){return true;} + bool operator==(const EntityComparator&){return true;} }; } diff --git a/src/PLASMA/Utils/base/Error.hh b/src/PLASMA/Utils/base/Error.hh index 5f158d998..807e32bb8 100644 --- a/src/PLASMA/Utils/base/Error.hh +++ b/src/PLASMA/Utils/base/Error.hh @@ -515,7 +515,7 @@ public: * @note Which is done depends on throwEnabled(). * @see throwEnabled */ - void handleAssert(); + void handleAssert() __attribute__((noreturn)); private: diff --git a/src/PLASMA/Utils/base/Factory.cc b/src/PLASMA/Utils/base/Factory.cc index d087856b9..a14bc64b8 100644 --- a/src/PLASMA/Utils/base/Factory.cc +++ b/src/PLASMA/Utils/base/Factory.cc @@ -43,22 +43,21 @@ FactoryMgrId& FactoryMgr::getId() return m_id; } -void FactoryMgr::registerFactory(FactoryId& factory) -{ - std::map::iterator it = m_factoryMap.find(factory->getName()); - if(it != m_factoryMap.end()) { - delete ((Factory*)it->second); - m_factoryMap.erase(it); - debugMsg("FactoryMgr:registerFactory","Registered new factory for " << factory->getName().toString()); - } - m_factoryMap.insert(std::make_pair(factory->getName(), factory)); +void FactoryMgr::registerFactory(FactoryId& factory) { + std::map::iterator it = m_factoryMap.find(factory->getName()); + if(it != m_factoryMap.end()) { + delete (static_cast(it->second)); + m_factoryMap.erase(it); + debugMsg("FactoryMgr:registerFactory","Registered new factory for " << factory->getName().toString()); + } + m_factoryMap.insert(std::make_pair(factory->getName(), factory)); } void FactoryMgr::purgeAll() { std::map::iterator factories_iter = m_factoryMap.begin(); while (factories_iter != m_factoryMap.end()) { - Factory* factory = (Factory*)((factories_iter++)->second); + Factory* factory = static_cast((factories_iter++)->second); debugMsg("FactoryMgr:purgeAll","Removing factory for " << factory->getName().toString()); delete factory; } diff --git a/src/PLASMA/Utils/base/Id.hh b/src/PLASMA/Utils/base/Id.hh index 355064e1d..81c8df352 100644 --- a/src/PLASMA/Utils/base/Id.hh +++ b/src/PLASMA/Utils/base/Id.hh @@ -124,7 +124,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim #ifndef EUROPA_FAST check_error(ptr != 0, std::string("Cannot generate an Id<") + typeid(T).name() + "> for 0 pointer.", IdErr::IdMgrInvalidItemPtrError()); - m_key = IdTable::insert((unsigned long int)(ptr), typeid(T).name()); + m_key = IdTable::insert(reinterpret_cast(ptr), typeid(T).name()); check_error(m_key != 0, std::string("Cannot generate an Id<") + typeid(T).name() + "> for a pointer that has not been cleaned up.", IdErr::IdMgrInvalidItemPtrError()); #endif @@ -163,14 +163,14 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim if (val == 0) m_key = 0; else { - m_key = IdTable::getKey((unsigned long int) val); + m_key = IdTable::getKey(static_cast(val)); checkError(m_key != 0, "Cannot instantiate an Id<" << typeid(T).name() << "> for this address: " << - std::hex << (unsigned long int) val << ". No instance present.", + std::hex << static_cast(val) << ". No instance present.", IdErr::IdMgrInvalidItemPtrError()); } #endif - m_ptr = (T*) (unsigned long int) val; + m_ptr = static_cast(static_cast(val)); } @@ -185,7 +185,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim std::hex << val << ". No instance present.", IdErr::IdMgrInvalidItemPtrError()); } #endif - m_ptr = (T*) val; + m_ptr = reinterpret_cast(val); } /** * @brief Copy constructor from an Id of a different type. @@ -220,7 +220,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim /** * @brief Equality test for mixed types. No casting used - * @param An Id of a possibly different type. + * @param org An Id of a possibly different type. * @return true if the addresses match */ template @@ -316,7 +316,8 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim */ inline bool isValid() const { #ifndef EUROPA_FAST - return(m_ptr != 0 && m_key != 0 && IdTable::getKey((unsigned long int)m_ptr) == m_key); + return(m_ptr != 0 && m_key != 0 && + IdTable::getKey(reinterpret_cast(m_ptr)) == m_key); #else return(m_ptr != 0); #endif @@ -406,7 +407,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim check_error(isValid(), std::string("Cannot release an invalid Id<") + typeid(T).name() + ">.", IdErr::IdMgrInvalidItemPtrError()); m_key = 0; - IdTable::remove((unsigned long int) ptr); + IdTable::remove(reinterpret_cast(ptr)); #endif m_ptr = 0; delete ptr; @@ -421,7 +422,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim #ifndef EUROPA_FAST check_error(isValid(), std::string("Cannot remove an invalid Id<") + typeid(T).name() + ">.", IdErr::IdMgrInvalidItemPtrError()); - IdTable::remove((unsigned long int) m_ptr); + IdTable::remove(reinterpret_cast(m_ptr)); m_key = 0; #endif m_ptr = 0; @@ -439,7 +440,7 @@ Baz* baz = (Baz*) fooId; // Will not compile.@endverbatim } check_error(Id::convertable(org), std::string("Invalid cast from Id<") + typeid(X).name() + "> to Id<" + typeid(T).name() + ">.", IdErr::IdMgrInvalidItemPtrError()); - m_key = IdTable::getKey((unsigned long int) m_ptr); + m_key = IdTable::getKey(reinterpret_cast(m_ptr)); check_error(m_key != 0, std::string("Cannot create an Id<") + typeid(X).name() + "> for this address since no instance is present.", IdErr::IdMgrInvalidItemPtrError()); #endif diff --git a/src/PLASMA/Utils/base/IdTable.cc b/src/PLASMA/Utils/base/IdTable.cc index 66ddf241a..082ed66e5 100644 --- a/src/PLASMA/Utils/base/IdTable.cc +++ b/src/PLASMA/Utils/base/IdTable.cc @@ -60,10 +60,10 @@ namespace EUROPA { static IdTable sl_instance; return(sl_instance); } - unsigned int IdTable::size() { - MutexGrabber mg(IdTableMutex()); - return(getInstance().m_collection.size()); - } +unsigned long IdTable::size() { + MutexGrabber mg(IdTableMutex()); + return(getInstance().m_collection.size()); +} bool IdTable::allocated(unsigned long int id) { MutexGrabber mg(IdTableMutex()); diff --git a/src/PLASMA/Utils/base/IdTable.hh b/src/PLASMA/Utils/base/IdTable.hh index 7e2704ae8..8dd5783e2 100644 --- a/src/PLASMA/Utils/base/IdTable.hh +++ b/src/PLASMA/Utils/base/IdTable.hh @@ -21,7 +21,6 @@ /** - * @file IdTable.hh * @author Conor McGann * @brief Defines a singleton class managing allocation and deallocation of ids for pointers. * @date July, 2003 @@ -44,7 +43,7 @@ namespace EUROPA { public: ~IdTable(); // deallocating statics requires public access on beos - static unsigned int size(); + static unsigned long size(); static unsigned int insert(unsigned long int id, const char* baseType); static void remove(unsigned long int id); diff --git a/src/PLASMA/Utils/base/LabelStr.cc b/src/PLASMA/Utils/base/LabelStr.cc index e780691b5..0c03462c2 100644 --- a/src/PLASMA/Utils/base/LabelStr.cc +++ b/src/PLASMA/Utils/base/LabelStr.cc @@ -100,10 +100,9 @@ namespace EUROPA { return m_key != lbl.m_key; } - unsigned int LabelStr::getSize() { + unsigned long LabelStr::getSize() { check_error(keysFromString().size() == stringFromKeys().size()); - int toRet = keysFromString().size(); - return toRet; + return keysFromString().size(); } edouble LabelStr::getKey(const std::string& label) { @@ -155,12 +154,12 @@ namespace EUROPA { bool LabelStr::contains(const LabelStr& lblStr) const{ const std::string& thisStr = toString(); - int index = thisStr.find(lblStr.c_str()); - return (index >= 0); + std::string::size_type index = thisStr.find(lblStr.c_str()); + return index != std::string::npos; } - unsigned int LabelStr::countElements(const char* delimiter) const{ + unsigned long LabelStr::countElements(const char* delimiter) const{ check_error(delimiter != NULL && delimiter != 0 && delimiter[0] != '\0', "'NULL' and '\\0' are not valid delimiters"); //allocate a results vector diff --git a/src/PLASMA/Utils/base/LabelStr.hh b/src/PLASMA/Utils/base/LabelStr.hh index 3a7502a32..1357aa945 100644 --- a/src/PLASMA/Utils/base/LabelStr.hh +++ b/src/PLASMA/Utils/base/LabelStr.hh @@ -12,7 +12,7 @@ #include "Error.hh" #include #include -#include +//#include namespace EUROPA { @@ -44,7 +44,7 @@ namespace EUROPA { /** * @brief Constructor - * @param The symbolic value as a string + * @param label The symbolic value as a string */ LabelStr(const std::string& label); @@ -133,7 +133,7 @@ namespace EUROPA { * @return The number of elements found. * @see getElement */ - unsigned int countElements(const char* delimiter) const; + unsigned long countElements(const char* delimiter) const; /** * @brief Return the requested element in a delimited string @@ -144,14 +144,14 @@ namespace EUROPA { * 2. 'A:B:C:DEF', > 3 => error * * @param index The position of the requested element - * @param delimeter The delimeter to mark + * @param delimiter The delimeter to mark */ LabelStr getElement(unsigned int index, const char* delimiter) const; /** * @brief Return the number of strings stored. */ - static unsigned int getSize(); + static unsigned long getSize(); /** * @brief Obtain the key for the given string and possibly conducting an insertion into keysFromString. diff --git a/src/PLASMA/Utils/base/Pdlfcn.cc b/src/PLASMA/Utils/base/Pdlfcn.cc index 6917ac015..bbf3cb322 100644 --- a/src/PLASMA/Utils/base/Pdlfcn.cc +++ b/src/PLASMA/Utils/base/Pdlfcn.cc @@ -28,12 +28,12 @@ #include #include -#define DLERROR_STR_MAX_LEN 256 + namespace EUROPA { #if defined(__APPLE__) && (__GNUC__ < 4) - +#define DLERROR_STR_MAX_LEN 256 /* * Provide portable dl functions using Apple's API for gcc prior to v4 */ diff --git a/src/PLASMA/Utils/base/TestData.cc b/src/PLASMA/Utils/base/TestData.cc index 0fc03f856..fc490cd8e 100644 --- a/src/PLASMA/Utils/base/TestData.cc +++ b/src/PLASMA/Utils/base/TestData.cc @@ -23,30 +23,30 @@ #include "TestData.hh" -void TestData::failedCompare(const std::string& macro, const std::string& one, +void TestData::failedCompare(const std::string&, const std::string& one, const std::string& two, const std::string& file, const int& line) { std::cerr << file << ':' << line << ": comparison failed: " << one << " is not equal to " << two << std::endl; } -void TestData::unexpectedException(const std::string& macro, const Error& exception, +void TestData::unexpectedException(const std::string& , const Error& exception, const std::string& file, const int& line) { std::cerr << file << ':' << line << ": unexpected exception " << exception << std::endl; } -void TestData::missingException(const std::string& macro, const std::string& msg, +void TestData::missingException(const std::string& , const std::string& msg, const std::string& file, const int& line) { std::cerr << file << ':' << line << ": unexpected success; " << msg << std::endl; } -void TestData::missingException(const std::string& macro, const Error& exception, +void TestData::missingException(const std::string& , const Error& exception, const std::string& file, const int& line) { std::cerr << file << ':' << line << ": unexpected success; expected exception: " << exception << std::endl; } -void TestData::wrongException(const std::string& macro, +void TestData::wrongException(const std::string& , const Error& caughtException, const Error& expectedException, const std::string& file, const int& line) { @@ -54,13 +54,13 @@ void TestData::wrongException(const std::string& macro, << caughtException << " is not the expected " << expectedException << std::endl; } -void TestData::areEqual(const std::string& macro, +void TestData::areEqual(const std::string& , const std::string& one, const std::string& two) { std::cerr << one << " equals " << two << '\n'; } -void TestData::correctException(const std::string& macro, +void TestData::correctException(const std::string& , const Error& exception) { std::cout << "Caught expected exception " << exception << '\n'; } diff --git a/src/PLASMA/Utils/base/Utils.cc b/src/PLASMA/Utils/base/Utils.cc index 14d193ebe..b6c7bd809 100644 --- a/src/PLASMA/Utils/base/Utils.cc +++ b/src/PLASMA/Utils/base/Utils.cc @@ -7,17 +7,11 @@ DEFINE_GLOBAL_CONST(bool, g_alwaysFails, false); namespace EUROPA { - std::string toString(double value) { - std::stringstream s; - s << std::setprecision(MAX_PRECISION) << value; - return(s.str()); - } - - std::string toString(edouble value) { - std::stringstream s; - s << std::setprecision(MAX_PRECISION) << value; - return(s.str()); - } +std::string toString(edouble value) { + std::stringstream s; + s << std::setprecision(MAX_PRECISION) << value; + return(s.str()); +} void tokenize(const std::string& str, std::vector& tokens, diff --git a/src/PLASMA/Utils/base/Utils.hh b/src/PLASMA/Utils/base/Utils.hh index 7ce081c80..b938d564d 100644 --- a/src/PLASMA/Utils/base/Utils.hh +++ b/src/PLASMA/Utils/base/Utils.hh @@ -121,7 +121,7 @@ namespace EUROPA { object_iterator it = objects.begin(); while(it != objects.end()){ check_error((*it).isValid()); - delete (TYPE*) (*it++); + delete static_cast(*it++); } objects.clear(); } @@ -132,7 +132,7 @@ namespace EUROPA { object_iterator it = objects.begin(); while(it != objects.end()){ check_error((*it).isValid()); - delete (TYPE*) (*it++); + delete static_cast(*it++); } objects.clear(); } @@ -143,7 +143,7 @@ namespace EUROPA { object_iterator it = objects.begin(); while(it != objects.end()){ check_error((*it).isValid()); - delete (TYPE*) (*it++); + delete static_cast(*it++); } objects.clear(); } @@ -154,7 +154,7 @@ namespace EUROPA { object_iterator it = objects.begin(); while(it != objects.end()){ checkError((*it).isValid(), *it); - delete (TYPE*) (*it++); + delete static_cast(*it++); } objects.clear(); } @@ -196,7 +196,7 @@ namespace EUROPA { Id object = *it; if(!object.isNoId()){ check_error(object.isValid()); - delete (TYPE*) (*it++); + delete static_cast(*it++); } else ++it; @@ -211,7 +211,7 @@ namespace EUROPA { while(it != objects.end()){ Id item = (it++)->second; check_error(item.isValid()); - delete (TYPE2*) item; + delete static_cast(item); } objects.clear(); } @@ -223,7 +223,7 @@ namespace EUROPA { while(it != objects.end()){ Id item = (it++)->second; check_error(item.isValid()); - delete (TYPE2*) item; + delete static_cast(item); } objects.clear(); } diff --git a/src/PLASMA/Utils/base/XMLUtils.cc b/src/PLASMA/Utils/base/XMLUtils.cc index 54ce8093c..a671530a4 100644 --- a/src/PLASMA/Utils/base/XMLUtils.cc +++ b/src/PLASMA/Utils/base/XMLUtils.cc @@ -17,25 +17,25 @@ namespace EUROPA { return data; } - TiXmlElement* initXml(const char* sourceFile, const char* element){ - TiXmlDocument* doc = new TiXmlDocument(sourceFile); - doc->LoadFile(); - checkError(!doc->Error(), "Invalid or malformed XML file '" << sourceFile << "'"); - TiXmlElement * xmlElement = doc->RootElement(); - debugMsg("Tests", "Loading element " << *xmlElement); - if(element == NULL) - return xmlElement; - while(xmlElement != NULL && strcmp(xmlElement->Value(), element) != 0) - xmlElement = (TiXmlElement*)xmlElement->NextSibling(); - if(xmlElement == NULL) { - // here's a bit of a hack to do string concatination. - // it's in an if statement so we don't construct the string otherwise. - std::string message = "\""; - message = message + element + "\" could not be found in " + sourceFile; - assertTrue(xmlElement != NULL, message); - } +TiXmlElement* initXml(const char* sourceFile, const char* element) { + TiXmlDocument* doc = new TiXmlDocument(sourceFile); + doc->LoadFile(); + checkError(!doc->Error(), "Invalid or malformed XML file '" << sourceFile << "'"); + TiXmlElement * xmlElement = doc->RootElement(); + debugMsg("Tests", "Loading element " << *xmlElement); + if(element == NULL) return xmlElement; + while(xmlElement != NULL && strcmp(xmlElement->Value(), element) != 0) + xmlElement = static_cast(xmlElement->NextSibling()); + if(xmlElement == NULL) { + // here's a bit of a hack to do string concatination. + // it's in an if statement so we don't construct the string otherwise. + std::string message = "\""; + message = message + element + "\" could not be found in " + sourceFile; + assertTrue(xmlElement != NULL, message); } + return xmlElement; +} TiXmlElement* initXml(std::string& xmlStr) { std::stringstream is; diff --git a/src/PLASMA/Utils/test/util-test-module.cc b/src/PLASMA/Utils/test/util-test-module.cc index c7175fb7a..b665d5595 100644 --- a/src/PLASMA/Utils/test/util-test-module.cc +++ b/src/PLASMA/Utils/test/util-test-module.cc @@ -313,11 +313,11 @@ class Bing: public Root } }; -void overloadFunc(const Id& arg) { +void overloadFunc(const Id&) { CPPUNIT_ASSERT(true); } -void overloadFunc(const Id& arg) { +void overloadFunc(const Id&) { CPPUNIT_ASSERT(true); } @@ -354,7 +354,7 @@ bool IdTests::test() { bool IdTests::testBasicAllocation() { #ifndef EUROPA_FAST - unsigned int initialSize = IdTable::size(); + unsigned long initialSize = IdTable::size(); #endif Foo *fooPtr = new Foo(); Id fId1(fooPtr); @@ -388,7 +388,7 @@ bool IdTests::testTypicalConversionsAndComparisons() CPPUNIT_ASSERT(fId1 == fId2); // Equality operator CPPUNIT_ASSERT(&*fId1 == &*fId2); // Dereferencing operator CPPUNIT_ASSERT(foo1 == &*fId2); // Dereferencing operator - CPPUNIT_ASSERT(foo1 == (Foo*) fId2); // Dereferencing operator + CPPUNIT_ASSERT(foo1 == static_cast(fId2)); // Dereferencing operator CPPUNIT_ASSERT(foo1 == fId2.operator->()); CPPUNIT_ASSERT( ! (fId1 > fId2)); CPPUNIT_ASSERT( ! (fId1 < fId2)); @@ -424,14 +424,14 @@ bool IdTests::testCastingSupport() { Foo* foo = new Foo(); Id fId(foo); - Foo* fooByCast = (Foo*) fId; + Foo* fooByCast = static_cast(fId); CPPUNIT_ASSERT(foo == fooByCast); CPPUNIT_ASSERT(Id::convertable(fId) == false); fId.release(); Foo* bar = new Bar(); - Id bId((Bar*) bar); + Id bId(dynamic_cast(bar)); fId = bId; CPPUNIT_ASSERT(Id::convertable(fId) == true); bId.release(); @@ -490,7 +490,7 @@ bool IdTests::testBadAllocationErrorHandling() // This exception simply isn't being caught on Cygwin for some reason. try { Error::doNotDisplayErrors(); - Id fId0((Foo*) 0); + Id fId0(static_cast(NULL)); CPPUNIT_ASSERT_MESSAGE("Id fId0((Foo*) 0); failed to error out.", false); success = false; } @@ -499,10 +499,10 @@ bool IdTests::testBadAllocationErrorHandling() // Path of Id.hh may vary depending on where test is run from. // Match only the filename and not the full path std::string pathMsg = e.getFile(); - int end = pathMsg.length(); + std::string::size_type end = pathMsg.length(); std::string name = "Id.hh"; - int start = pathMsg.find(name); - if (start >= 0) { + std::string::size_type start = pathMsg.find(name); + if (start != std::string::npos) { std::string fileMsg = pathMsg.substr(start, end); e.setFile(fileMsg); } @@ -880,6 +880,7 @@ class XMLIOTest { class NumberTest { public: static bool test() { + EUROPA_runTest(testSize); EUROPA_runTest(testEint); EUROPA_runTest(testEintInfinity); EUROPA_runTest(testEdouble); @@ -887,6 +888,12 @@ class NumberTest { return true; } private: + + static bool testSize() { + CPPUNIT_ASSERT_EQUAL(sizeof(eint::basis_type), sizeof(eint)); + CPPUNIT_ASSERT_EQUAL(sizeof(edouble::basis_type), sizeof(edouble)); + return true; + } static bool testEint() { EUROPA::eint e(3); #ifdef E2_LONG_INT From a5c3948336380828d0fc13a00367ea8c761e3932 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Sun, 7 Dec 2014 13:29:21 -0800 Subject: [PATCH 063/149] Got the assert macro backwards --- src/PLASMA/ConstraintEngine/base/ConstraintType.hh | 7 ++++--- src/PLASMA/ConstraintEngine/component/Constraints.cc | 2 +- src/PLASMA/Utils/base/Error.hh | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintType.hh b/src/PLASMA/ConstraintEngine/base/ConstraintType.hh index 8c3ca7d10..5616d4ea7 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintType.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstraintType.hh @@ -141,7 +141,8 @@ namespace EUROPA { , m_otherName(otherName) , m_rotateCount(rotateCount) { - assertTrue(name != otherName); + checkError(name != otherName, + "Rotated name " << name << " is the same as un-rotated " << otherName); } ConstraintId createConstraint( @@ -179,8 +180,8 @@ namespace EUROPA { const LabelStr& otherName, const int& first, const int& second) : ConstraintType(name, propagatorName), m_otherName(otherName), m_first(first), m_second(second) { - assertTrue(name != otherName); - assertTrue(first != second); + checkError(name != otherName); + checkError(first != second); } ConstraintId createConstraint( diff --git a/src/PLASMA/ConstraintEngine/component/Constraints.cc b/src/PLASMA/ConstraintEngine/component/Constraints.cc index f4ca1fe5a..4e0352544 100644 --- a/src/PLASMA/ConstraintEngine/component/Constraints.cc +++ b/src/PLASMA/ConstraintEngine/component/Constraints.cc @@ -1457,7 +1457,7 @@ namespace EUROPA { // Could just add to current unionOfDomains rather than failing here, but // very messy to implement using current interface to *Domain classes. - assertFalse(newUnion == 0); + assertFalse(newUnion == NULL); delete *unionOfDomains; *unionOfDomains = newUnion; return; diff --git a/src/PLASMA/Utils/base/Error.hh b/src/PLASMA/Utils/base/Error.hh index 807e32bb8..a9111be9e 100644 --- a/src/PLASMA/Utils/base/Error.hh +++ b/src/PLASMA/Utils/base/Error.hh @@ -86,8 +86,8 @@ #define __assert_(value, N, ...) assert ## N (value, __VA_ARGS__) #define _assert(value, N, ...) __assert_(value, N, __VA_ARGS__) -#define assertTrue(...) _assert(true, NARG3(__VA_ARGS__), __VA_ARGS__) -#define assertFalse(...) _assert(false, NARG3(__VA_ARGS__), __VA_ARGS__) +#define assertTrue(...) _assert(false, NARG3(__VA_ARGS__), __VA_ARGS__) +#define assertFalse(...) _assert(true, NARG3(__VA_ARGS__), __VA_ARGS__) #define check_error_function __attribute__ ((unused)) From ecc9c07acde1ae44645c0b2c3db2aa48a3d6028c Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Mon, 8 Dec 2014 07:29:28 -0800 Subject: [PATCH 064/149] Fixing solver test that never ran --- src/PLASMA/Solvers/test/solvers-test-module.cc | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/PLASMA/Solvers/test/solvers-test-module.cc b/src/PLASMA/Solvers/test/solvers-test-module.cc index 2c2809d5a..cd926a4b5 100644 --- a/src/PLASMA/Solvers/test/solvers-test-module.cc +++ b/src/PLASMA/Solvers/test/solvers-test-module.cc @@ -428,15 +428,18 @@ class FilterTests { nukeToken(db->getClient(),token); } - // test R*, R9 and R10 + // test R8, R9 and R10 { TokenId token = db->getClient()->createToken("D.predicateG", NULL, false); token->activate(); TokenId E_predicateC = *(token->slaves().begin()); - + // Expect to fire R8, R9 and R10 + //TODO: Fix this test. It claims to fire R8, but for no apparent reason. std::set expectedRules; - expectedRules.insert(LabelStr("[R8]*.*.*.*.B.*")); + expectedRules.insert(LabelStr("[R0]*.*.*.*.*.*")); + expectedRules.insert(LabelStr("[R7]*.*.duration.*.Object.*")); + // expectedRules.insert(LabelStr("[R8]*.*.*.*.B.*")); expectedRules.insert(LabelStr("[R9]*.*.*.meets.D.predicateG")); expectedRules.insert(LabelStr("[R10]*.*.*.before.*.*")); std::vector rules; From c56c2f27f7c9c3404a64903d9e00c102d3ba6ea3 Mon Sep 17 00:00:00 2001 From: Michael Iatauro Date: Fri, 12 Dec 2014 16:49:36 -0800 Subject: [PATCH 065/149] Part-way through fixing compilation warnings --- src/PLASMA/ConstraintEngine/CMakeLists.txt | 2 +- .../ConstraintEngine/ConstraintEngineDefs.hh | 2 +- .../ModuleConstraintEngine.cc | 20 +- src/PLASMA/ConstraintEngine/base/CESchema.cc | 8 +- src/PLASMA/ConstraintEngine/base/CFunction.cc | 3 +- src/PLASMA/ConstraintEngine/base/CFunction.hh | 39 +- .../base/ConstrainedVariable.cc | 222 +++--- .../base/ConstrainedVariable.hh | 37 +- .../ConstraintEngine/base/Constraint.cc | 42 +- .../ConstraintEngine/base/Constraint.hh | 9 +- .../ConstraintEngine/base/ConstraintEngine.cc | 217 +++--- .../ConstraintEngine/base/ConstraintEngine.hh | 46 +- .../base/ConstraintEngineListener.cc | 47 ++ .../base/ConstraintEngineListener.hh | 46 +- .../ConstraintEngine/base/ConstraintType.hh | 163 +++-- src/PLASMA/ConstraintEngine/base/DataType.cc | 12 +- src/PLASMA/ConstraintEngine/base/DataType.hh | 14 +- src/PLASMA/ConstraintEngine/base/Domain.hh | 12 +- .../ConstraintEngine/base/DomainListener.hh | 4 +- .../base/PSConstraintEngineListener.cc | 24 +- .../base/PSConstraintEngineListener.hh | 52 +- .../ConstraintEngine/base/PSVarValue.cc | 17 +- .../ConstraintEngine/base/PSVarValue.hh | 12 +- .../ConstraintEngine/base/Propagator.cc | 5 + .../ConstraintEngine/base/Propagator.hh | 11 +- .../ConstraintEngine/component/CFunctions.cc | 7 + .../ConstraintEngine/component/CFunctions.hh | 7 +- .../ConstraintEngine/component/Constraints.cc | 664 +++++++++--------- .../ConstraintEngine/component/Constraints.hh | 320 +++++---- .../ConstraintEngine/component/DataTypes.cc | 16 +- .../ConstraintEngine/component/DataTypes.hh | 2 +- .../ConstraintEngine/component/Domains.cc | 20 +- .../ConstraintEngine/component/Domains.hh | 23 +- .../component/EquivalenceClassCollection.cc | 2 +- .../component/EquivalenceClassCollection.hh | 2 +- .../ConstraintEngine/component/Propagators.cc | 106 +-- .../ConstraintEngine/component/Propagators.hh | 4 +- .../ConstraintEngine/component/Variable.hh | 4 +- src/PLASMA/NDDL/NddlDefs.hh | 20 +- src/PLASMA/NDDL/base/NddlRules.cc | 1 + src/PLASMA/NDDL/base/NddlRules.hh | 6 +- src/PLASMA/NDDL/base/NddlToken.cc | 2 + src/PLASMA/NDDL/base/NddlToken.hh | 21 +- src/PLASMA/NDDL/base/NddlUtils.cc | 2 +- src/PLASMA/NDDL/base/NddlUtils.hh | 13 +- src/PLASMA/NDDL/component/Interpreter.cc | 664 +++++++++--------- src/PLASMA/NDDL/component/Interpreter.hh | 49 +- src/PLASMA/NDDL/component/NddlInterpreter.hh | 12 +- src/PLASMA/PlanDatabase/CMakeLists.txt | 2 +- src/PLASMA/PlanDatabase/ModulePlanDatabase.cc | 114 +-- .../base/CommonAncestorConstraint.cc | 12 +- .../base/CommonAncestorConstraint.hh | 4 +- src/PLASMA/PlanDatabase/base/DbClient.cc | 86 ++- src/PLASMA/PlanDatabase/base/DbClient.hh | 24 +- .../PlanDatabase/base/DbClientListener.cc | 29 + .../PlanDatabase/base/DbClientListener.hh | 44 +- .../base/DefaultTemporalAdvisor.cc | 66 +- .../base/HasAncestorConstraint.cc | 34 +- .../base/HasAncestorConstraint.hh | 4 +- src/PLASMA/PlanDatabase/base/MergeMemento.cc | 6 +- src/PLASMA/PlanDatabase/base/Object.cc | 286 ++++---- src/PLASMA/PlanDatabase/base/Object.hh | 34 +- .../PlanDatabase/base/ObjectTokenRelation.cc | 18 +- .../PlanDatabase/base/ObjectTokenRelation.hh | 4 +- src/PLASMA/PlanDatabase/base/ObjectType.cc | 152 ++-- src/PLASMA/PlanDatabase/base/ObjectType.hh | 5 +- .../PlanDatabase/base/PDBInterpreter.cc | 11 +- .../PlanDatabase/base/PDBInterpreter.hh | 31 +- .../base/PSPlanDatabaseListener.cc | 29 +- .../base/PSPlanDatabaseListener.hh | 74 +- src/PLASMA/PlanDatabase/base/PlanDatabase.cc | 259 ++++--- src/PLASMA/PlanDatabase/base/PlanDatabase.hh | 22 +- .../PlanDatabase/base/PlanDatabaseListener.cc | 32 +- src/PLASMA/PlanDatabase/base/Schema.cc | 113 ++- src/PLASMA/PlanDatabase/base/Schema.hh | 31 +- src/PLASMA/PlanDatabase/base/StackMemento.cc | 12 +- src/PLASMA/PlanDatabase/base/Token.cc | 319 ++++----- src/PLASMA/PlanDatabase/base/Token.hh | 5 +- src/PLASMA/PlanDatabase/base/TokenType.cc | 10 +- src/PLASMA/PlanDatabase/base/TokenVariable.hh | 4 +- .../component/DbClientTransactionLog.cc | 121 ++-- .../component/DbClientTransactionLog.hh | 4 +- .../component/DbClientTransactionPlayer.cc | 317 +++++---- src/PLASMA/PlanDatabase/component/Methods.cc | 31 +- src/PLASMA/PlanDatabase/component/Timeline.cc | 16 +- src/PLASMA/PlanDatabase/component/Timeline.hh | 2 +- src/PLASMA/RulesEngine/ModuleRulesEngine.cc | 51 +- .../RulesEngine/base/ProxyVariableRelation.cc | 5 +- .../RulesEngine/base/ProxyVariableRelation.hh | 2 +- src/PLASMA/RulesEngine/base/Rule.cc | 13 +- src/PLASMA/RulesEngine/base/RuleInstance.cc | 164 ++--- src/PLASMA/RulesEngine/base/RuleInstance.hh | 7 +- .../RulesEngine/base/RuleVariableListener.cc | 8 +- .../RulesEngine/base/RuleVariableListener.hh | 2 +- src/PLASMA/RulesEngine/base/RulesEngine.cc | 34 +- .../RulesEngine/base/RulesEngineListener.cc | 4 + .../RulesEngine/base/RulesEngineListener.hh | 4 +- src/PLASMA/Solvers/ModuleSolvers.cc | 131 ++-- src/PLASMA/Solvers/SolverDefs.hh | 4 +- src/PLASMA/Solvers/base/ComponentFactory.cc | 9 +- src/PLASMA/Solvers/base/ComponentFactory.hh | 12 +- src/PLASMA/Solvers/base/FlawHandler.cc | 4 +- src/PLASMA/Solvers/base/FlawHandler.hh | 6 +- src/PLASMA/Solvers/base/FlawManager.cc | 8 +- src/PLASMA/Solvers/base/FlawManager.hh | 7 +- src/PLASMA/Solvers/base/MatchingEngine.hh | 11 +- src/PLASMA/Solvers/base/Solver.hh | 2 +- .../Solvers/base/SolverDecisionPoint.cc | 6 +- .../Solvers/base/SolverDecisionPoint.hh | 5 +- .../Solvers/test/solvers-test-module.cc | 18 +- .../TemporalNetwork/ModuleTemporalNetwork.cc | 52 +- .../TemporalNetwork/base/DispatchGraph.cc | 52 +- .../TemporalNetwork/base/DistanceGraph.cc | 98 +-- .../TemporalNetwork/base/DistanceGraph.hh | 10 +- .../TemporalNetwork/base/TemporalNetwork.cc | 125 ++-- .../TemporalNetwork/base/TemporalNetwork.hh | 55 +- src/PLASMA/TemporalNetwork/base/queues.cc | 2 +- .../component/STNTemporalAdvisor.cc | 17 +- .../component/STNTemporalAdvisor.hh | 4 +- .../component/TemporalNetworkListener.cc | 22 + .../component/TemporalNetworkListener.hh | 27 +- .../component/TemporalPropagator.cc | 96 +-- .../component/TemporalPropagator.hh | 2 +- .../component/TimepointWrapper.hh | 4 +- src/PLASMA/Utils/base/Id.hh | 5 + src/PLASMA/Utils/base/IdTable.cc | 21 +- src/PLASMA/Utils/base/LabelStr.cc | 13 +- src/PLASMA/Utils/base/LabelStr.hh | 2 +- src/PLASMA/Utils/base/PSUtils.hh | 80 ++- src/PLASMA/Utils/base/Pdlfcn.cc | 242 +++---- src/PLASMA/Utils/base/Pdlfcn.hh | 5 - src/PLASMA/Utils/base/Utils.hh | 17 +- src/PLASMA/Utils/unused.hh | 6 + 133 files changed, 3503 insertions(+), 3371 deletions(-) create mode 100644 src/PLASMA/ConstraintEngine/component/CFunctions.cc create mode 100644 src/PLASMA/PlanDatabase/base/DbClientListener.cc create mode 100644 src/PLASMA/Utils/unused.hh diff --git a/src/PLASMA/ConstraintEngine/CMakeLists.txt b/src/PLASMA/ConstraintEngine/CMakeLists.txt index 3bcd91eb8..43e43eb00 100644 --- a/src/PLASMA/ConstraintEngine/CMakeLists.txt +++ b/src/PLASMA/ConstraintEngine/CMakeLists.txt @@ -3,7 +3,7 @@ include(EuropaModule) set(internal_dependencies Utils) set(root_sources ModuleConstraintEngine.cc) set(base_sources CESchema.cc DataType.cc CFunction.cc Domain.cc ConstrainedVariable.cc DomainListener.cc Constraint.cc PSConstraintEngineListener.cc ConstraintEngine.cc PSVarValue.cc ConstraintEngineListener.cc Propagator.cc ConstraintType.cc VariableChangeListener.cc) -set(component_sources Constraints.cc EquivalenceClassCollection.cc DataTypes.cc Propagators.cc Domains.cc) +set(component_sources Constraints.cc EquivalenceClassCollection.cc DataTypes.cc Propagators.cc Domains.cc CFunctions.cc) #set(test_sources ConstraintTesting.cc ce-test-module.cc module-tests.cc DomainTest.cc domain-tests.cc) set(test_sources ConstraintTesting.cc ce-test-module.cc module-tests.cc domain-tests.cc) diff --git a/src/PLASMA/ConstraintEngine/ConstraintEngineDefs.hh b/src/PLASMA/ConstraintEngine/ConstraintEngineDefs.hh index 24dfdf0ee..8e31777fb 100644 --- a/src/PLASMA/ConstraintEngine/ConstraintEngineDefs.hh +++ b/src/PLASMA/ConstraintEngine/ConstraintEngineDefs.hh @@ -43,7 +43,7 @@ namespace EUROPA { typedef Id ConstraintEngineId; class ConstraintEngineListener; typedef Id ConstraintEngineListenerId; - typedef std::pair ConstraintEntry; + typedef std::pair ConstraintEntry; typedef std::list ConstraintList; class PostPropagationCallback; diff --git a/src/PLASMA/ConstraintEngine/ModuleConstraintEngine.cc b/src/PLASMA/ConstraintEngine/ModuleConstraintEngine.cc index 87240e9f0..74b793635 100644 --- a/src/PLASMA/ConstraintEngine/ModuleConstraintEngine.cc +++ b/src/PLASMA/ConstraintEngine/ModuleConstraintEngine.cc @@ -5,6 +5,8 @@ #include "Propagators.hh" #include "CFunctions.hh" +#include + namespace EUROPA { ModuleConstraintEngine::ModuleConstraintEngine() @@ -53,14 +55,14 @@ namespace EUROPA { engine->addComponent("ConstraintEngine",ce); } - void ModuleConstraintEngine::uninitialize(EngineId engine) - { - ConstraintEngine* ce = (ConstraintEngine*)engine->removeComponent("ConstraintEngine"); - delete ce; +void ModuleConstraintEngine::uninitialize(EngineId engine) { + ConstraintEngine* ce = + boost::polymorphic_cast(engine->removeComponent("ConstraintEngine")); + delete ce; - CESchema* ces = (CESchema*)engine->removeComponent("CESchema"); - delete ces; - } + CESchema* ces = boost::polymorphic_cast(engine->removeComponent("CESchema")); + delete ces; +} /**************************************************************************************/ @@ -85,7 +87,7 @@ namespace EUROPA { { debugMsg("ModuleConstraintLibrary:initialize", "Initializing the constraint library"); - CESchema* ces = (CESchema*)engine->getComponent("CESchema"); + CESchema* ces = boost::polymorphic_cast(engine->getComponent("CESchema")); // Register constraint Factories REGISTER_CONSTRAINT_TYPE(ces,AbsoluteValueCT, "absVal", "Default"); @@ -210,7 +212,7 @@ namespace EUROPA { void ModuleConstraintLibrary::uninitialize(EngineId engine) { - CESchema* ces = (CESchema*)engine->getComponent("CESchema"); + CESchema* ces = boost::polymorphic_cast(engine->getComponent("CESchema")); // TODO: should be more selective and only remove the constraints we added above ces->purgeConstraintTypes(); } diff --git a/src/PLASMA/ConstraintEngine/base/CESchema.cc b/src/PLASMA/ConstraintEngine/base/CESchema.cc index ca084c356..bd6ccb067 100644 --- a/src/PLASMA/ConstraintEngine/base/CESchema.cc +++ b/src/PLASMA/ConstraintEngine/base/CESchema.cc @@ -50,7 +50,7 @@ namespace EUROPA debugMsg("CESchema::registerDataType", "Over-writing prior registration for " << dt->getName().toString()); DataTypeId oldFactory = m_dataTypes.find(dt->getName().getKey())->second; m_dataTypes.erase(dt->getName().getKey()); - delete (DataType*) oldFactory; + delete static_cast(oldFactory); } checkError(m_dataTypes.find(dt->getName().getKey()) == m_dataTypes.end(), "Already have '" + dt->getName().toString() + "' registered."); @@ -73,7 +73,7 @@ namespace EUROPA DataTypeId dt = (it++)->second; debugMsg("DataType:purgeAll", "Removing data type " << dt->getName().toString()); - delete (DataType *) dt; + delete static_cast(dt); } m_dataTypes.clear(); } @@ -130,7 +130,7 @@ namespace EUROPA debugMsg("CESchema::registerCFunction", "Over-writing prior registration for " << cf->getName().toString()); CFunctionId old = m_cfunctions.find(cf->getName().getKey())->second; m_cfunctions.erase(cf->getName().getKey()); - delete (CFunction*) old; + delete static_cast(old); } checkError(m_cfunctions.find(cf->getName().getKey()) == m_cfunctions.end(), "Already have '" + cf->getName().toString() + "' registered."); @@ -157,7 +157,7 @@ namespace EUROPA CFunctionId cf = (it++)->second; debugMsg("CESchema:purgeAll", "Removing CFunction " << cf->getName().toString()); - delete (CFunction *) cf; + delete static_cast(cf); } m_cfunctions.clear(); } diff --git a/src/PLASMA/ConstraintEngine/base/CFunction.cc b/src/PLASMA/ConstraintEngine/base/CFunction.cc index 3c3b12b77..c71f499c8 100644 --- a/src/PLASMA/ConstraintEngine/base/CFunction.cc +++ b/src/PLASMA/ConstraintEngine/base/CFunction.cc @@ -29,6 +29,7 @@ namespace EUROPA { { return m_name; } - +void CFunction::checkArgTypes(const std::vector&) {} } + diff --git a/src/PLASMA/ConstraintEngine/base/CFunction.hh b/src/PLASMA/ConstraintEngine/base/CFunction.hh index e0716e896..bd9e11800 100644 --- a/src/PLASMA/ConstraintEngine/base/CFunction.hh +++ b/src/PLASMA/ConstraintEngine/base/CFunction.hh @@ -16,27 +16,26 @@ namespace EUROPA { class CFunction; typedef Id CFunctionId; -class CFunction -{ +class CFunction { public: - CFunction(const char* name); - virtual ~CFunction(); - - const CFunctionId& getId() const; - - const LabelStr& getName(); - - // TODO: this API probably needs to be re-evaluated - // TODO: CFunction should know how to evaluate itself - virtual const char* getConstraint() = 0; - virtual const DataTypeId getReturnType() = 0; - virtual unsigned int getArgumentCount() = 0; - - virtual void checkArgTypes(const std::vector& argTypes) {} - -protected: - CFunctionId m_id; - LabelStr m_name; + CFunction(const char* name); + virtual ~CFunction(); + + const CFunctionId& getId() const; + + const LabelStr& getName(); + + // TODO: this API probably needs to be re-evaluated + // TODO: CFunction should know how to evaluate itself + virtual const char* getConstraint() = 0; + virtual const DataTypeId getReturnType() = 0; + virtual unsigned int getArgumentCount() = 0; + + virtual void checkArgTypes(const std::vector& argTypes); + + protected: + CFunctionId m_id; + LabelStr m_name; }; } diff --git a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc index 5f1173c57..c8d3ad0c5 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc +++ b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.cc @@ -10,31 +10,36 @@ namespace EUROPA { - ConstrainedVariableListener::ConstrainedVariableListener(const ConstrainedVariableId& var) +ConstrainedVariableListener::ConstrainedVariableListener(const ConstrainedVariableId& var) : m_id(this), m_var(var) { - var->notifyAdded(m_id); - } + var->notifyAdded(m_id); +} - const ConstrainedVariableListenerId& ConstrainedVariableListener::getId() const { - return(m_id); - } +const ConstrainedVariableListenerId& ConstrainedVariableListener::getId() const { + return(m_id); +} - ConstrainedVariableListener::~ConstrainedVariableListener() { - m_var->notifyRemoved(m_id); - m_id.remove(); - } +void ConstrainedVariableListener::notifyDiscard() {} +void ConstrainedVariableListener::notifyConstraintAdded(const ConstraintId&, + unsigned int) {} +void ConstrainedVariableListener::notifyConstraintRemoved(const ConstraintId&, + unsigned int) {} + +ConstrainedVariableListener::~ConstrainedVariableListener() { + m_var->notifyRemoved(m_id); + m_id.remove(); +} ConstrainedVariable::ConstrainedVariable(const ConstraintEngineId& constraintEngine, const bool internal, bool canBeSpecified, const LabelStr& name, const EntityId& parent, - int index) + unsigned long index) : Entity(), m_id(this), m_lastRelaxed(0), m_constraintEngine(constraintEngine), m_name(name), m_internal(internal), m_canBeSpecified(canBeSpecified), m_specifiedFlag(false), m_specifiedValue(0), m_index(index), m_parent(parent), m_deactivationRefCount(0), m_deleted(false) { check_error(m_constraintEngine.isValid()); - check_error(m_index >= NO_INDEX); check_error(m_index == NO_INDEX || parent.isValid()); m_constraintEngine->add(m_id); m_listener = m_constraintEngine->allocateVariableListener(m_id, m_constraints); @@ -46,7 +51,7 @@ namespace EUROPA { discard(false); - delete (DomainListener*) m_listener; + delete static_cast(m_listener); m_id.remove(); } @@ -120,9 +125,9 @@ namespace EUROPA { } - int ConstrainedVariable::getIndex() const { - return(m_index); - } +unsigned long ConstrainedVariable::getIndex() const { + return(m_index); +} void ConstrainedVariable::deactivate() { check_error(!Entity::isPurging()); @@ -191,35 +196,37 @@ namespace EUROPA { return m_constraintEngine; } - void ConstrainedVariable::addConstraint(const ConstraintId& constraint, int argIndex) { - check_error(!Entity::isPurging()); - check_error(constraint.isValid()); - debugMsg("ConstrainedVariable:addConstraint", "Adding " << constraint->toString() << " to " << toString()); - m_constraints.push_back(ConstraintEntry(constraint, argIndex)); +void ConstrainedVariable::addConstraint(const ConstraintId& constraint, + unsigned int argIndex) { + check_error(!Entity::isPurging()); + check_error(constraint.isValid()); + debugMsg("ConstrainedVariable:addConstraint", "Adding " << constraint->toString() << " to " << toString()); + m_constraints.push_back(ConstraintEntry(constraint, argIndex)); - handleConstraintAdded(constraint); - for(std::set::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - (*it)->notifyConstraintAdded(constraint, argIndex); + handleConstraintAdded(constraint); + for(std::set::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) + (*it)->notifyConstraintAdded(constraint, argIndex); - check_error(isConstrainedBy(constraint)); - } + check_error(isConstrainedBy(constraint)); +} - void ConstrainedVariable::removeConstraint(const ConstraintId& constraint, int argIndex) { - if(m_deleted) // Nothing to do - return; +void ConstrainedVariable::removeConstraint(const ConstraintId& constraint, + unsigned int argIndex) { + if(m_deleted) // Nothing to do + return; - debugMsg("ConstrainedVariable:removeConstraint", "Unlinking " << constraint->toString()); + debugMsg("ConstrainedVariable:removeConstraint", "Unlinking " << constraint->toString()); - check_error(!Entity::isPurging()); - check_error(constraint.isValid()); - check_error(isConstrainedBy(constraint)); - check_error(!Entity::isPurging()); // Should not be getting this message - m_constraints.remove(ConstraintEntry(constraint, argIndex)); + check_error(!Entity::isPurging()); + check_error(constraint.isValid()); + check_error(isConstrainedBy(constraint)); + check_error(!Entity::isPurging()); // Should not be getting this message + m_constraints.remove(ConstraintEntry(constraint, argIndex)); - handleConstraintRemoved(constraint); - for(std::set::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - (*it)->notifyConstraintRemoved(constraint, argIndex); - } + handleConstraintRemoved(constraint); + for(std::set::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) + (*it)->notifyConstraintRemoved(constraint, argIndex); +} bool ConstrainedVariable::isSpecified() const { return m_specifiedFlag; @@ -257,14 +264,14 @@ namespace EUROPA { return(false); } - void ConstrainedVariable::updateLastRelaxed(int cycleCount) { + void ConstrainedVariable::updateLastRelaxed(unsigned int cycleCount) { check_error(!Entity::isPurging()); check_error(m_lastRelaxed < cycleCount); m_lastRelaxed = cycleCount; debugMsg("ConstrainedVariable:updateLastRelaxed",getName().toString() << " lastRelaxed updated to " << m_lastRelaxed); } - int ConstrainedVariable::lastRelaxed() const { + unsigned int ConstrainedVariable::lastRelaxed() const { return(m_lastRelaxed); } @@ -282,7 +289,7 @@ namespace EUROPA { results.insert(it->first); } - unsigned int ConstrainedVariable::constraintCount() const{ + unsigned long ConstrainedVariable::constraintCount() const{ return m_constraints.size(); } @@ -309,6 +316,10 @@ namespace EUROPA { return(m_canBeSpecified); } +void ConstrainedVariable::handleBase(const Domain&) {} +void ConstrainedVariable::handleSpecified(edouble) {} + + bool ConstrainedVariable::isClosed() const { return(baseDomain().isClosed()); } @@ -557,18 +568,17 @@ namespace EUROPA { return retval; } - PSList ConstrainedVariable::getConstraints() const - { - check_runtime_error(isValid()); - check_error(!Entity::isPurging()); - PSList retval; - ConstraintList::const_iterator it = m_constraints.begin(); - for ( ; it != m_constraints.end(); ++it) { - ConstraintId cId = it->first; - retval.push_back( (PSConstraint *) cId); - } - return retval; - } +PSList ConstrainedVariable::getConstraints() const { + check_runtime_error(isValid()); + check_error(!Entity::isPurging()); + PSList retval; + ConstraintList::const_iterator it = m_constraints.begin(); + for ( ; it != m_constraints.end(); ++it) { + ConstraintId cId = it->first; + retval.push_back(dynamic_cast(static_cast(cId))); + } + return retval; +} @@ -604,57 +614,57 @@ namespace EUROPA { debugMsg("ConstrainedVariable:specify","After propagate for var:" << toString()); } - PSEntity* ConstrainedVariable::getParent() const { - //EntityId parent(m_parent);//getParentEntity()); - if(m_parent.isNoId()) - return NULL; - - /* TODO: fix this - else if(TokenId::convertable(parent)) - return new PSTokenImpl((TokenId) parent); - else if(ObjectId::convertable(parent)) - return new PSObjectImpl((ObjectId) parent); - else if(RuleInstanceId::convertable(parent)) - return new PSTokenImpl(((RuleInstanceId)parent)->getToken()); - else { - checkRuntimeError(ALWAYS_FAIL, - "Variable " << toString() << " has a parent that isn't a token, " << - "object, or rule: " << m_var->getParent()->toString()); +PSEntity* ConstrainedVariable::getParent() const { + //EntityId parent(m_parent);//getParentEntity()); + if(m_parent.isNoId()) + return NULL; + + /* TODO: fix this + else if(TokenId::convertable(parent)) + return new PSTokenImpl((TokenId) parent); + else if(ObjectId::convertable(parent)) + return new PSObjectImpl((ObjectId) parent); + else if(RuleInstanceId::convertable(parent)) + return new PSTokenImpl(((RuleInstanceId)parent)->getToken()); + else { + checkRuntimeError(ALWAYS_FAIL, + "Variable " << toString() << " has a parent that isn't a token, " << + "object, or rule: " << m_var->getParent()->toString()); + } + */ + + return dynamic_cast(static_cast(m_parent)); +} + +std::string ConstrainedVariable::toString() const { + std::ostringstream os; + + if (isNull()) + os << "NULL"; + else if (isSingleton()) + os << getSingletonValue().toString(); + else if (isInterval()) + os << "[" << getLowerBound() << "," << getUpperBound() << "]"; + else if (isEnumerated()) { + os << "{"; + PSList values = getValues(); + for (unsigned int i=0;i 0) + os << ", "; + os << values.get(i).toString(); } - */ - - return (PSEntity *) m_parent; - } - - std::string ConstrainedVariable::toString() const { - std::ostringstream os; - - if (isNull()) - os << "NULL"; - else if (isSingleton()) - os << getSingletonValue().toString(); - else if (isInterval()) - os << "[" << getLowerBound() << "," << getUpperBound() << "]"; - else if (isEnumerated()) { - os << "{"; - PSList values = getValues(); - for (int i=0;i 0) - os << ", "; - os << values.get(i).toString(); - } - os << "}"; - } - else - os << "ERROR!"; - - return os.str(); - } - - // Used to be toString, but the above is shorter and more user-friendly - std::string ConstrainedVariable::toLongString() const{ - std::stringstream sstr; - sstr << Entity::toString() << (specifiedFlag() ? " (S) " : "") << " DERIVED=" << lastDomain().toString() << " BASE=" << baseDomain().toString(); - return sstr.str(); - } + os << "}"; + } + else + os << "ERROR!"; + + return os.str(); +} + +// Used to be toString, but the above is shorter and more user-friendly +std::string ConstrainedVariable::toLongString() const{ + std::stringstream sstr; + sstr << Entity::toString() << (specifiedFlag() ? " (S) " : "") << " DERIVED=" << lastDomain().toString() << " BASE=" << baseDomain().toString(); + return sstr.str(); +} } diff --git a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.hh b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.hh index 75386460a..c644b108a 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstrainedVariable.hh @@ -14,6 +14,7 @@ #include "Entity.hh" #include "LabelStr.hh" #include "Domain.hh" +#include "unused.hh" #include namespace EUROPA { @@ -25,9 +26,9 @@ namespace EUROPA { public: virtual ~ConstrainedVariableListener(); const ConstrainedVariableListenerId& getId() const; - virtual void notifyDiscard() {} // message for listener creator to immediately delete listener - virtual void notifyConstraintAdded(const ConstraintId& constr, int argIndex) {} - virtual void notifyConstraintRemoved(const ConstraintId& constr, int argIndex) {} + virtual void notifyDiscard(); // message for listener creator to immediately delete listener + virtual void notifyConstraintAdded(const ConstraintId& constr, unsigned int argIndex); + virtual void notifyConstraintRemoved(const ConstraintId& constr, unsigned int argIndex); protected: ConstrainedVariableListener(const ConstrainedVariableId& var); ConstrainedVariableListenerId m_id; @@ -100,7 +101,7 @@ namespace EUROPA { /** * @brief Retrive the count of constraints direclt on this variable */ - unsigned int constraintCount() const; + unsigned long constraintCount() const; /** * @brief Retrieve one constraint on this variable. Returns noId if there are none. @@ -169,7 +170,7 @@ namespace EUROPA { * * @note I don't think this is adequate since it provides no * feedback whether the lock was acquired or not. - * --wedgingt@ptolemy.arc.nasa.gov 2004 Feb 11 + * --wedgingt 2004 Feb 11 * * CMG: Wrong. if you try lock, and already locked it will error * out. There is a method to test if a lock is already present. @@ -179,7 +180,7 @@ namespace EUROPA { * before either gets the lock and then both would try to get the * lock, causing one to error out despite following the * interface's requirement to test if unlocked first. - * --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 21 + * --wedgingt 2004 Apr 21 * * This does not have any support in a multi-theraded environment. One must first * obtain a mutex elsewhere. Therefore, this is quite adequate. @@ -221,7 +222,7 @@ namespace EUROPA { virtual std::string toString() const; virtual std::string toLongString() const; - static const int NO_INDEX = -1; + static const unsigned long NO_INDEX = 0; /** * @brief Access the index. @@ -229,7 +230,7 @@ namespace EUROPA { * a ConstrainedVariable to have an index reflecting its location in the parent. * @return NO_INDEX if there is no parent, otherwise a value > 0 indicating a position relevant to the caller. */ - int getIndex() const; + unsigned long getIndex() const; /** * @brief Retrieve the last computed domain of the variable. @@ -322,12 +323,12 @@ namespace EUROPA { /** * @brief Supports the merging of variables by propagating messages on restriction of a base domain of a variable */ - virtual void handleBase(const Domain&) {} + virtual void handleBase(const Domain& dom); /** * @brief Supports the merging of variables by propagating messages on specification of a variable */ - virtual void handleSpecified(edouble value) {} + virtual void handleSpecified(edouble value); /** * @brief Supports the merging of variables by propagating message on reset of a specified domain @@ -401,7 +402,7 @@ namespace EUROPA { bool canBeSpecified, const LabelStr& name, const EntityId& parent = EntityId::noId(), - int index = NO_INDEX); + unsigned long index = NO_INDEX); /** * @brief Allows subclass to add specific extra-work without over-riding core behavior. @@ -432,7 +433,7 @@ namespace EUROPA { friend class ConstraintEngine; /**< Grant access so the ConstraintEngine can reset the variable domain without exposing this behaviour publicly.*/ - friend class Propagator; /* Constraint::getVariables() const - { - PSList retval; - for(size_t i = 0; i < m_variables.size(); ++i) - { - ConstrainedVariableId id = m_variables[i]; - retval.push_back((PSVariable *) id); - } - return retval; - } +PSList Constraint::getVariables() const { + PSList retval; + for(std::vector::const_iterator it = m_variables.begin(); + it != m_variables.end(); ++it) { + ConstrainedVariableId id = *it; + retval.push_back(dynamic_cast(static_cast(id))); + } + return retval; +} const ConstraintId& Constraint::getId() const { return m_id; @@ -186,8 +185,8 @@ namespace EUROPA { } void Constraint::execute(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { + unsigned int argIndex, + const DomainListener::ChangeType& changeType) { for(unsigned int i=0;isetCurrentPropagatingConstraint(m_id); @@ -198,21 +197,22 @@ namespace EUROPA { m_variables[i]->setCurrentPropagatingConstraint(ConstraintId::noId()); } - void Constraint::handleExecute(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { + void Constraint::handleExecute(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&) { handleExecute(); } - bool Constraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { + bool Constraint::canIgnore(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&) { return false; } - const std::vector& Constraint::getModifiedVariables(const ConstrainedVariableId& variable) const { - return getScope(); - } +const std::vector& +Constraint::getModifiedVariables(const ConstrainedVariableId&) const { + return getScope(); +} const std::vector& Constraint::getModifiedVariables() const { return getScope(); diff --git a/src/PLASMA/ConstraintEngine/base/Constraint.hh b/src/PLASMA/ConstraintEngine/base/Constraint.hh index 2eb1fa944..498904dc3 100644 --- a/src/PLASMA/ConstraintEngine/base/Constraint.hh +++ b/src/PLASMA/ConstraintEngine/base/Constraint.hh @@ -205,7 +205,9 @@ namespace EUROPA { * */ virtual void execute(); - virtual void execute(const ConstrainedVariableId& variable,int argIndex,const DomainListener::ChangeType& changeType); + virtual void execute(const ConstrainedVariableId& variable, + unsigned int argIndex, + const DomainListener::ChangeType& changeType); /** * @brief Called when no specific change event on a variable is reported. @@ -227,7 +229,7 @@ namespace EUROPA { * @see ConstraintEngine::execute(), ConstraintEngine::PENDING, DomainListener::ChangeType */ virtual void handleExecute(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); /** @@ -243,7 +245,7 @@ namespace EUROPA { * @see ConstraintEngine::notify() */ virtual bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); @@ -276,7 +278,6 @@ namespace EUROPA { /** * @brief Allow implementation class to take action in the event of deactivation - * @param delegate The constraint which will justify deactivation */ virtual void handleDeactivate(){} diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.cc b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.cc index cbba08439..1dcbb1542 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.cc +++ b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.cc @@ -104,15 +104,14 @@ namespace EUROPA return retval; } - PSList ViolationMgrImpl::getAllViolations() const - { - PSList retval; - for (ConstraintSet::const_iterator it = m_violatedConstraints.begin(); it != m_violatedConstraints.end(); ++it) { - ConstraintId id = *it; - retval.push_back((PSConstraint *) id); - } - return retval; +PSList ViolationMgrImpl::getAllViolations() const { + PSList retval; + for (ConstraintSet::const_iterator it = m_violatedConstraints.begin(); it != m_violatedConstraints.end(); ++it) { + ConstraintId id = *it; + retval.push_back(id_cast(id)); } + return retval; +} bool ViolationMgrImpl::isViolated(ConstraintId c) const { @@ -230,22 +229,21 @@ namespace EUROPA m_relaxing = false; } -#ifndef _MSC_VER - static bool allActiveVariables(const std::vector& vars) check_error_function; -#endif - static bool allActiveVariables(const std::vector& vars) { - for (std::vector::const_iterator it = vars.begin(); it != vars.end(); ++it) { - ConstrainedVariableId var = *it; - check_error(var.isValid()); - condDebugMsg(!var->isActive(), "allActiveVariables", - var->toString() << " is not active but it participates in an active constraint."); - +namespace { +bool allActiveVariables(const std::vector& vars) { + for (std::vector::const_iterator it = vars.begin(); it != vars.end(); ++it) { + ConstrainedVariableId var = *it; + check_error(var.isValid()); + condDebugMsg(!var->isActive(), "allActiveVariables", + var->toString() << " is not active but it participates in an active constraint."); + if(!var->isActive()) - return false; - } - - return true; + return false; } + + return true; +} +} std::string DomainListener::toString(const ChangeType& changeType){ switch (changeType) { @@ -294,10 +292,10 @@ namespace EUROPA /** DEFINE CONSTANTS DECLARED IN COMMON DEFS **/ DEFINE_GLOBAL_CONST(char*, g_noVarName, "NO_NAME"); - DomainListenerId ConstraintEngine::allocateVariableListener(const ConstrainedVariableId& variable, - const ConstraintList& constraints) const{ - return ((new VariableChangeListener(variable, m_id))->getId()); - } +DomainListenerId ConstraintEngine::allocateVariableListener(const ConstrainedVariableId& variable, + const ConstraintList&) const{ + return ((new VariableChangeListener(variable, m_id))->getId()); +} ConstraintEngine::ConstraintEngine(const CESchemaId& schema) : m_id(this) @@ -389,7 +387,7 @@ namespace EUROPA for(std::list::iterator it = m_callbacks.begin(); it != m_callbacks.end(); ++it) { PostPropagationCallbackId callback = *it; check_error(callback.isValid()); - delete (PostPropagationCallback*) callback; + delete static_cast(callback); } } @@ -762,48 +760,50 @@ namespace EUROPA return result; } - void ConstraintEngine::notify(const ConstrainedVariableId& source, const DomainListener::ChangeType& changeType){ - check_error(!Entity::isPurging()); - check_error(source.isValid()); - - m_dirty = true; - - // If variable is inavtice, no impact. - if(!source->isActive()) - return; - - if(changeType == DomainListener::EMPTIED) - handleEmpty(source); - else if (changeType == DomainListener::RELAXED || - changeType == DomainListener::OPENED) - handleRelax(source); - else - handleRestrict(source); - - - // In all cases, notify the propagators as well, unless over-ruled by by an empty variable or a decision to ignore it - for(ConstraintList::const_iterator it = source->m_constraints.begin(); it != source->m_constraints.end(); ++it){ - const ConstraintId& constraint = it->first; - checkError(constraint.isValid(), "Constraint is invalid on " << source->toLongString()); - unsigned int argIndex = it->second; - if(constraint->isActive() && !constraint->isDiscarded() && - changeType != DomainListener::EMPTIED && !constraint->canIgnore(source, argIndex, changeType)) - constraint->getPropagator()->handleNotification(source, argIndex, constraint, changeType); - } - - publish(notifyChanged(source, changeType)); - - notifyMsg(UPPER_BOUND_DECREASED, source); - notifyMsg(LOWER_BOUND_INCREASED, source); - notifyMsg(BOUNDS_RESTRICTED, source); - notifyMsg(VALUE_REMOVED, source); - notifyMsg(RESTRICT_TO_SINGLETON, source); - notifyMsg(SET_TO_SINGLETON, source); - notifyMsg(RESET, source); - notifyMsg(RELAXED, source); - notifyMsg(CLOSED, source); - notifyMsg(EMPTIED, source); - } +void ConstraintEngine::notify(const ConstrainedVariableId& source, + const DomainListener::ChangeType& changeType){ + check_error(!Entity::isPurging()); + check_error(source.isValid()); + + m_dirty = true; + + // If variable is inavtice, no impact. + if(!source->isActive()) + return; + + if(changeType == DomainListener::EMPTIED) + handleEmpty(source); + else if (changeType == DomainListener::RELAXED || + changeType == DomainListener::OPENED) + handleRelax(source); + else + handleRestrict(source); + + + // In all cases, notify the propagators as well, unless over-ruled by by an empty variable or a decision to ignore it + for(ConstraintList::const_iterator it = source->m_constraints.begin(); it != source->m_constraints.end(); ++it){ + const ConstraintId& constraint = it->first; + checkError(constraint.isValid(), "Constraint is invalid on " << source->toLongString()); + unsigned int argIndex = it->second; + if(constraint->isActive() && !constraint->isDiscarded() && + changeType != DomainListener::EMPTIED && + !constraint->canIgnore(source, argIndex, changeType)) + constraint->getPropagator()->handleNotification(source, argIndex, constraint, changeType); + } + + publish(notifyChanged(source, changeType)); + + notifyMsg(UPPER_BOUND_DECREASED, source); + notifyMsg(LOWER_BOUND_INCREASED, source); + notifyMsg(BOUNDS_RESTRICTED, source); + notifyMsg(VALUE_REMOVED, source); + notifyMsg(RESTRICT_TO_SINGLETON, source); + notifyMsg(SET_TO_SINGLETON, source); + notifyMsg(RESET, source); + notifyMsg(RELAXED, source); + notifyMsg(CLOSED, source); + notifyMsg(EMPTIED, source); +} void ConstraintEngine::handleEmpty(const ConstrainedVariableId& variable){ check_error(variable.isValid()); @@ -908,7 +908,7 @@ namespace EUROPA void ConstraintEngine::execute(const ConstraintId& constraint, const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType){ check_error(!provenInconsistent() && constraint.isValid()); check_error(constraint->isActive()); @@ -999,7 +999,7 @@ namespace EUROPA ConstraintSet::iterator it = m_constraints.find(constr); check_error(it != m_constraints.end()); check_error(it->isValid()); - return (unsigned int) std::distance(m_constraints.begin(), it); + return static_cast(std::distance(m_constraints.begin(), it)); } const PropagatorId& ConstraintEngine::getPropagatorByName(const LabelStr& name) const { @@ -1036,7 +1036,7 @@ namespace EUROPA void ConstraintEngine::setAllowViolations(bool v) { if (v) - m_violationMgr->setMaxViolationsAllowed((unsigned int)INT_MAX); + m_violationMgr->setMaxViolationsAllowed(UINT_MAX); else m_violationMgr->setMaxViolationsAllowed(0); } @@ -1086,16 +1086,15 @@ namespace EUROPA } // TODO: this needs to be optimized - PSVariable* ConstraintEngine::getVariableByName(const std::string& name) - { - const ConstrainedVariableSet& vars = getVariables(); - for(ConstrainedVariableSet::const_iterator it = vars.begin(); it != vars.end(); ++it) { - ConstrainedVariableId id = *it; - if (id->getName().toString() == name) - return (PSVariable *) id; - } - return NULL; - } +PSVariable* ConstraintEngine::getVariableByName(const std::string& name) { + const ConstrainedVariableSet& vars = getVariables(); + for(ConstrainedVariableSet::const_iterator it = vars.begin(); it != vars.end(); ++it) { + ConstrainedVariableId id = *it; + if (id->getName().toString() == name) + return id_cast(id); + } + return NULL; +} int ConstraintEngine::addLinkedVarsForRelaxation(const ConstrainedVariableId& var, @@ -1130,34 +1129,32 @@ namespace EUROPA return count; } - ConstrainedVariableId - ConstraintEngine::createVariable(const char* typeName, - const bool internal, - bool canBeSpecified, - const char* name, - const EntityId& parent, - int index) - { - DataTypeId dt = getCESchema()->getDataType(typeName); - check_error(dt.isValid(), "no DataType found for type '" + std::string(typeName) + "'"); - return createVariable(typeName, dt->baseDomain(), internal, canBeSpecified, name, parent, index); - } +ConstrainedVariableId +ConstraintEngine::createVariable(const char* typeName, + const bool internal, + bool canBeSpecified, + const char* name, + const EntityId& parent, + unsigned int index) { + DataTypeId dt = getCESchema()->getDataType(typeName); + check_error(dt.isValid(), "no DataType found for type '" + std::string(typeName) + "'"); + return createVariable(typeName, dt->baseDomain(), internal, canBeSpecified, name, parent, index); +} - ConstrainedVariableId - ConstraintEngine::createVariable(const char* typeName, - const Domain& baseDomain, - const bool internal, - bool canBeSpecified, - const char* name, - const EntityId& parent, - int index) - { - DataTypeId dt = getCESchema()->getDataType(typeName); - check_error(dt.isValid(), "no DataType found for type '" + std::string(typeName) + "'"); - ConstrainedVariableId variable = dt->createVariable(getId(), baseDomain, internal, canBeSpecified, name, parent, index); - check_error(variable.isValid()); - return variable; - } +ConstrainedVariableId +ConstraintEngine::createVariable(const char* typeName, + const Domain& baseDomain, + const bool internal, + bool canBeSpecified, + const char* name, + const EntityId& parent, + unsigned int index) { + DataTypeId dt = getCESchema()->getDataType(typeName); + check_error(dt.isValid(), "no DataType found for type '" + std::string(typeName) + "'"); + ConstrainedVariableId variable = dt->createVariable(getId(), baseDomain, internal, canBeSpecified, name, parent, index); + check_error(variable.isValid()); + return variable; +} ConstraintId ConstraintEngine::createConstraint(const LabelStr& name, const std::vector& scope, @@ -1177,7 +1174,7 @@ namespace EUROPA void ConstraintEngine::deleteConstraint(const ConstraintId& c) { check_error(c.isValid()); - delete (Constraint*)c; + delete static_cast(c); if (shouldAutoPropagate()) propagate(); diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh index 20a8d8b02..02debbef6 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstraintEngine.hh @@ -147,7 +147,7 @@ namespace EUROPA { * @brief Count of possible constraint events. * @note Depends on the first Event having an int value of 0. */ - static const int EVENT_COUNT = (int)LAST_EVENT; + static const int EVENT_COUNT = static_cast(LAST_EVENT); /** * @brief Constructor currently creates a basic configuration of propagators. @@ -317,22 +317,22 @@ namespace EUROPA { * @brief Create a variable */ ConstrainedVariableId createVariable(const char* typeName, - const bool internal = false, - bool canBeSpecified = true, - const char* name = NO_VAR_NAME, - const EntityId& parent = EntityId::noId(), - int index = ConstrainedVariable::NO_INDEX); - + const bool internal = false, + bool canBeSpecified = true, + const char* name = NO_VAR_NAME, + const EntityId& parent = EntityId::noId(), + unsigned int index = ConstrainedVariable::NO_INDEX); + /** * @brief Create a variable */ ConstrainedVariableId createVariable(const char* typeName, - const Domain& baseDomain, - const bool internal = false, - bool canBeSpecified = true, - const char* name = NO_VAR_NAME, - const EntityId& parent = EntityId::noId(), - int index = ConstrainedVariable::NO_INDEX); + const Domain& baseDomain, + const bool internal = false, + bool canBeSpecified = true, + const char* name = NO_VAR_NAME, + const EntityId& parent = EntityId::noId(), + unsigned int index = ConstrainedVariable::NO_INDEX); ConstraintId createConstraint(const LabelStr& name, @@ -390,22 +390,22 @@ namespace EUROPA { * @brief Called by the VariableListener when a change occurs on its varible. * * This method provides the core event control logic of the ConstraintEngine. - * @param listener The listener with the necessary data for the variable. - * @param change Type the type of change that occured on the variable. + * @param source The changed variable + * @param changeType Type the type of change that occured on the variable. * @see DomainListener::ChangeType, handleEmptied, handleRelaxed, Propagator::handleNotification(), Constraint::canIgnore() */ void notify(const ConstrainedVariableId& source, const DomainListener::ChangeType& changeType); /** * @brief Update appropriately when a variabe domain has been emptied. - * @param the variable that has been emptied. + * @param variable The variable that has been emptied. * @see notify(const ConstrainedVariableId& source, const DomainListener::ChangeType& changeType) */ void handleEmpty(const ConstrainedVariableId& variable); /** * @brief Update appropriately when a variable has been relaxed. - * @param the variable that has been relaxed. + * @param variable The variable that has been relaxed. * @see notify(const ConstrainedVariableId& source, const DomainListener::ChangeType& changeType) */ void handleRelax(const ConstrainedVariableId& variable); @@ -413,7 +413,7 @@ namespace EUROPA { /** * @brief Update appropriately when a variable has been restricted but not emptied. - * @param the variable that has been restricted. + * @param variable The variable that has been restricted. * @see notify(const ConstrainedVariableId& source, const DomainListener::ChangeType& changeType) */ void handleRestrict(const ConstrainedVariableId& variable); @@ -440,7 +440,7 @@ namespace EUROPA { void notifyRedundant(const ConstraintId& redundantConstraint); /** - * @breif Notification from a variable when it has been deactivated + * @brief Notification from a variable when it has been deactivated */ void notifyDeactivated(const ConstrainedVariableId& var); @@ -469,7 +469,7 @@ namespace EUROPA { */ void execute(const ConstraintId& constraint, const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); friend class ConstrainedVariable; @@ -558,8 +558,8 @@ namespace EUROPA { bool m_purged; /*!< Indicates if the engine has been purged of its data */ bool m_dirty; /*!< Flag to record if any messages handled without propagating consequences */ - int m_cycleCount; /*!< A monotonically increasing count of propagation cycles. Identifies - when propagation events have already been queued or handled. */ + unsigned int m_cycleCount; /*!< A monotonically increasing count of propagation cycles. Identifies + when propagation events have already been queued or handled. */ unsigned int m_mostRecentRepropagation; /*!< A monotonically increasing record of cycles where a relaxation occurred. */ std::set m_listeners; /*!< Stores the set of registered listeners. */ @@ -588,7 +588,7 @@ namespace EUROPA { /** * @brief Constructor with initial constraint engine. * - * @param ce + * @param ce The constraint engine to register with */ PostPropagationCallback(const ConstraintEngineId& ce) : m_id(this), m_ce(ce) {ce->addCallback(m_id);} diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.cc b/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.cc index d15c334e9..99b04d7d8 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.cc +++ b/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.cc @@ -30,4 +30,51 @@ namespace EUROPA { check_error(m_constraintEngine.isValid()); m_constraintEngine->add(m_id); } + +void ConstraintEngineListener::notifyPropagationCommenced(){ +} + +void ConstraintEngineListener::notifyPropagationCompleted(){ +} + +void ConstraintEngineListener::notifyPropagationPreempted(){ +} + +void ConstraintEngineListener::notifyAdded(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyActivated(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyDeactivated(const ConstrainedVariableId&){ +} + +void ConstraintEngineListener::notifyActivated(const ConstrainedVariableId&){ +} + +void ConstraintEngineListener::notifyDeactivated(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyRemoved(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyExecuted(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyAdded(const ConstrainedVariableId&){ +} + +void ConstraintEngineListener::notifyRemoved(const ConstrainedVariableId&){ +} + +void ConstraintEngineListener::notifyChanged(const ConstrainedVariableId&, + const DomainListener::ChangeType&){ +} + +void ConstraintEngineListener::notifyViolationAdded(const ConstraintId&){ +} + +void ConstraintEngineListener::notifyViolationRemoved(const ConstraintId&){ +} + } diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.hh b/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.hh index 15234505c..fbf78dad6 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstraintEngineListener.hh @@ -19,50 +19,36 @@ namespace EUROPA{ public: virtual ~ConstraintEngineListener(); - virtual void notifyPropagationCommenced(){ - } + virtual void notifyPropagationCommenced(); - virtual void notifyPropagationCompleted(){ - } + virtual void notifyPropagationCompleted(); - virtual void notifyPropagationPreempted(){ - } + virtual void notifyPropagationPreempted(); - virtual void notifyAdded(const ConstraintId& constraint){ - } + virtual void notifyAdded(const ConstraintId& constraint); - virtual void notifyActivated(const ConstraintId& constraint){ - } + virtual void notifyActivated(const ConstraintId& constraint); - virtual void notifyDeactivated(const ConstrainedVariableId& var){ - } + virtual void notifyDeactivated(const ConstrainedVariableId& var); - virtual void notifyActivated(const ConstrainedVariableId& var){ - } + virtual void notifyActivated(const ConstrainedVariableId& var); - virtual void notifyDeactivated(const ConstraintId& constraint){ - } + virtual void notifyDeactivated(const ConstraintId& constraint); - virtual void notifyRemoved(const ConstraintId& constraint){ - } + virtual void notifyRemoved(const ConstraintId& constraint); - virtual void notifyExecuted(const ConstraintId& constraint){ - } + virtual void notifyExecuted(const ConstraintId& constraint); - virtual void notifyAdded(const ConstrainedVariableId& variable){ - } + virtual void notifyAdded(const ConstrainedVariableId& variable); - virtual void notifyRemoved(const ConstrainedVariableId& variable){ - } + virtual void notifyRemoved(const ConstrainedVariableId& variable); - virtual void notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType){ - } + virtual void notifyChanged(const ConstrainedVariableId& variable, + const DomainListener::ChangeType& changeType); - virtual void notifyViolationAdded(const ConstraintId& constraint){ - } + virtual void notifyViolationAdded(const ConstraintId& constraint); - virtual void notifyViolationRemoved(const ConstraintId& constraint){ - } + virtual void notifyViolationRemoved(const ConstraintId& constraint); const ConstraintEngineListenerId& getId() const; diff --git a/src/PLASMA/ConstraintEngine/base/ConstraintType.hh b/src/PLASMA/ConstraintEngine/base/ConstraintType.hh index 5616d4ea7..39bc90c7d 100644 --- a/src/PLASMA/ConstraintEngine/base/ConstraintType.hh +++ b/src/PLASMA/ConstraintEngine/base/ConstraintType.hh @@ -6,6 +6,7 @@ #include "LabelStr.hh" #include "Constraint.hh" #include "DataType.hh" +#include "unused.hh" #include #include @@ -52,95 +53,92 @@ namespace EUROPA { /**********************************************************/ - template - ConstraintId makeConstraintInstance( - const LabelStr& name, - const LabelStr& propagatorName, - const ConstraintEngineId constraintEngine, - const std::vector& scope, - const char* violationExpl) - { - check_error(constraintEngine.isValid()); - check_error(scope.size() >= 1); - Constraint* constraint = new ConstraintInstance(name, propagatorName, constraintEngine, scope); - check_error(constraint != 0); - check_error(constraint->getId().isValid()); - if (violationExpl != NULL) - constraint->setViolationExpl(violationExpl); - - return(constraint->getId()); - } - - template - class ConcreteConstraintType : public ConstraintType { - public: - // TODO: remove this constructor after all constraint types have been updated to check arg types - ConcreteConstraintType(const LabelStr& name, - const LabelStr& propagatorName, - bool systemDefined = false) - : ConstraintType(name, propagatorName, systemDefined) - { - } +template +ConstraintId makeConstraintInstance( + const LabelStr& name, + const LabelStr& propagatorName, + const ConstraintEngineId constraintEngine, + const std::vector& scope, + const char* violationExpl) { + check_error(constraintEngine.isValid()); + check_error(scope.size() >= 1); + Constraint* constraint = new ConstraintInstance(name, propagatorName, constraintEngine, scope); + check_error(constraint != 0); + check_error(constraint->getId().isValid()); + if (violationExpl != NULL) + constraint->setViolationExpl(violationExpl); + + return(constraint->getId()); +} - ConcreteConstraintType(const LabelStr& name, - const LabelStr& propagatorName, - const std::vector& argTypes, - bool systemDefined = false) +template +class ConcreteConstraintType : public ConstraintType { + public: + // TODO: remove this constructor after all constraint types have been updated to check arg types + ConcreteConstraintType(const LabelStr& name, + const LabelStr& propagatorName, + bool systemDefined = false) + : ConstraintType(name, propagatorName, systemDefined) {} + + ConcreteConstraintType(const LabelStr& name, + const LabelStr& propagatorName, + const std::vector& argTypes, + bool systemDefined = false) : ConstraintType(name, propagatorName, systemDefined) , m_argTypes(argTypes) - { - } + { + } - virtual ConstraintId createConstraint( - const ConstraintEngineId constraintEngine, - const std::vector& scope, - const char* violationExpl) - { - return makeConstraintInstance(m_name, m_propagatorName, constraintEngine, scope, violationExpl); - } + virtual ConstraintId createConstraint( + const ConstraintEngineId constraintEngine, + const std::vector& scope, + const char* violationExpl) + { + return makeConstraintInstance(m_name, m_propagatorName, constraintEngine, scope, violationExpl); + } - virtual void checkArgTypes(const std::vector& types) const - { - // TODO: remove this after all constraint types have been updated to check arg types - if (m_argTypes.size() == 0) - return; - - if (m_argTypes.size() != types.size()) { - std::ostringstream os; - os << "Constraint "<< m_name.toString() - << " can't take " << types.size() << " parameters." - << " It expects " << m_argTypes.size() << "."; - throw os.str(); - } - - for (unsigned int i=0;iisAssignableFrom(types[i])) { - std::ostringstream os; - os << "Constraint "<< m_name.toString() - << " can't take a " << types[i]->getName().toString() - << " as parameter number " << i << "." - << " It expects " << m_argTypes[i]->getName().toString() << "."; - throw os.str(); - } - } + virtual void checkArgTypes(const std::vector& types) const + { + // TODO: remove this after all constraint types have been updated to check arg types + if (m_argTypes.size() == 0) + return; + + if (m_argTypes.size() != types.size()) { + std::ostringstream os; + os << "Constraint "<< m_name.toString() + << " can't take " << types.size() << " parameters." + << " It expects " << m_argTypes.size() << "."; + throw os.str(); } - protected: - std::vector m_argTypes; - }; + for (unsigned int i=0;iisAssignableFrom(types[i])) { + std::ostringstream os; + os << "Constraint "<< m_name.toString() + << " can't take a " << types[i]->getName().toString() + << " as parameter number " << i << "." + << " It expects " << m_argTypes[i]->getName().toString() << "."; + throw os.str(); + } + } + } - template - class RotatedNaryConstraintType : public ConstraintType { - public: - RotatedNaryConstraintType(const LabelStr& name, - const LabelStr& propagatorName, - const LabelStr& otherName, - const int& rotateCount) + protected: + std::vector m_argTypes; +}; + +template +class RotatedNaryConstraintType : public ConstraintType { + public: + RotatedNaryConstraintType(const LabelStr& name, + const LabelStr& propagatorName, + const LabelStr& otherName, + const int& rotateCount) : ConstraintType(name, propagatorName) , m_otherName(otherName) , m_rotateCount(rotateCount) - { + { checkError(name != otherName, "Rotated name " << name << " is the same as un-rotated " << otherName); } @@ -163,10 +161,9 @@ namespace EUROPA { return(constraint->getId()); } - virtual void checkArgTypes(const std::vector& argTypes) const - { - // TODO: implement this - } + virtual void checkArgTypes(unused(const std::vector& argTypes)) const { + // TODO: implement this + } protected: const LabelStr m_otherName; @@ -201,7 +198,7 @@ namespace EUROPA { return(constraint->getId()); } - virtual void checkArgTypes(const std::vector& argTypes) const + virtual void checkArgTypes(unused(const std::vector& argTypes)) const { // TODO: implement this } diff --git a/src/PLASMA/ConstraintEngine/base/DataType.cc b/src/PLASMA/ConstraintEngine/base/DataType.cc index cedcd3cf2..a4c3f972c 100644 --- a/src/PLASMA/ConstraintEngine/base/DataType.cc +++ b/src/PLASMA/ConstraintEngine/base/DataType.cc @@ -87,12 +87,12 @@ edouble DataType::minDelta() const ConstrainedVariableId DataType::createVariable(const ConstraintEngineId& constraintEngine, - const Domain& baseDomain, - const bool internal, - bool canBeSpecified, - const char* name, - const EntityId& parent, - int index) const + const Domain& baseDomain, + const bool internal, + bool canBeSpecified, + const char* name, + const EntityId& parent, + unsigned int index) const { // TODO: perform stronger checks here check_error(Domain::canBeCompared(*m_baseDomain,baseDomain), diff --git a/src/PLASMA/ConstraintEngine/base/DataType.hh b/src/PLASMA/ConstraintEngine/base/DataType.hh index fed41c2f1..fe948ba58 100644 --- a/src/PLASMA/ConstraintEngine/base/DataType.hh +++ b/src/PLASMA/ConstraintEngine/base/DataType.hh @@ -120,13 +120,13 @@ public: /** * @brief Create a variable */ - virtual ConstrainedVariableId createVariable(const ConstraintEngineId& constraintEngine, - const Domain& baseDomain, - const bool internal = false, - bool canBeSpecified = true, - const char* name = NO_VAR_NAME, - const EntityId& parent = EntityId::noId(), - int index = ConstrainedVariable::NO_INDEX) const; + virtual ConstrainedVariableId createVariable(const ConstraintEngineId& constraintEngine, + const Domain& baseDomain, + const bool internal = false, + bool canBeSpecified = true, + const char* name = NO_VAR_NAME, + const EntityId& parent = EntityId::noId(), + unsigned int index = ConstrainedVariable::NO_INDEX) const; protected: DataTypeId m_id; diff --git a/src/PLASMA/ConstraintEngine/base/Domain.hh b/src/PLASMA/ConstraintEngine/base/Domain.hh index ab0bbf82b..cbeb4d592 100644 --- a/src/PLASMA/ConstraintEngine/base/Domain.hh +++ b/src/PLASMA/ConstraintEngine/base/Domain.hh @@ -257,7 +257,7 @@ namespace EUROPA { /** * @brief Remove the given element form the domain. - * @param value. The value to be removed. + * @param value The value to be removed. * @note If the value was in the domain, this call will generate a value removal event. * @see DomainListener::VALUE_REMOVED */ @@ -292,7 +292,7 @@ namespace EUROPA { * @note Can only be called on domains that have no listeners attached, * since it will not cause propagation. It is more of a utility. */ - virtual Domain& operator=(const Domain& dom) { + virtual Domain& operator=(const Domain&) { return(*this); } @@ -316,14 +316,14 @@ namespace EUROPA { /** * @brief Test if this domain is a subset of dom. * @param dom the domain tested against. - * @param true if all elements of this domain are in dom. Otherwise false. + * @return true if all elements of this domain are in dom. Otherwise false. */ virtual bool isSubsetOf(const Domain& dom) const = 0; /** * @brief Test if the intersection between this domain and the given domain is empty. * @param dom the domain tested against. - * @param true if any elements of this domain are in dom. Otherwise false. + * @return true if any elements of this domain are in dom. Otherwise false. */ virtual bool intersects(const Domain& dom) const = 0; @@ -424,10 +424,10 @@ namespace EUROPA { protected: /** * @brief Constructor. + * @param dataType indicates the type name to use + * @param enumerated true if this is an explicit enumeration. * @param closed indicates if the domain is to be dynamic or closed on construction. Once closed, no * additions to extend the contents of the domain will be permitted. - * @param enumerated true if this is an explicit enumeration. - * @param typeName indicates the type name to use * @todo Review how semantics of closed can be enforced in operations. */ Domain(const DataTypeId& dataType, bool enumerated, bool closed); diff --git a/src/PLASMA/ConstraintEngine/base/DomainListener.hh b/src/PLASMA/ConstraintEngine/base/DomainListener.hh index 4269d3518..cf3a0a194 100644 --- a/src/PLASMA/ConstraintEngine/base/DomainListener.hh +++ b/src/PLASMA/ConstraintEngine/base/DomainListener.hh @@ -58,7 +58,7 @@ namespace EUROPA{ * modified when ChangeType is added to. * @see ChangeType */ - static const int EVENT_COUNT = (int)LAST_CHANGE_TYPE; + static const int EVENT_COUNT = static_cast(LAST_CHANGE_TYPE); static std::string toString(const ChangeType& changeType); @@ -87,7 +87,7 @@ namespace EUROPA{ /** * @brief The critical method to implement in order to define how events are to be propagated. - * @param changetype the type of change occuring on the domain. + * @param changeType the type of change occuring on the domain. */ virtual void notifyChange(const ChangeType& changeType) = 0; diff --git a/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.cc b/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.cc index 87afd63d6..5500317aa 100644 --- a/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.cc +++ b/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.cc @@ -13,17 +13,33 @@ namespace EUROPA { // Methods to convert notifications involving internal Europa types to notifications involving 'PS' types: void PSConstraintEngineListener::notifyViolationAdded(const ConstraintId& constraint){ - notifyViolationAdded((PSConstraint *) constraint); + notifyViolationAdded(id_cast(constraint)); } void PSConstraintEngineListener::notifyViolationRemoved(const ConstraintId& constraint){ - notifyViolationRemoved((PSConstraint *) constraint); + notifyViolationRemoved(id_cast(constraint)); } -void PSConstraintEngineListener::notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType) { - notifyChanged((PSVariable *) variable, (PSChangeType) changeType); +void PSConstraintEngineListener::notifyChanged(const ConstrainedVariableId& variable, + const DomainListener::ChangeType& changeType) { + notifyChanged(id_cast(variable), static_cast(changeType)); } +void PSConstraintEngineListener::notifyViolationAdded(PSConstraint*) {} +void PSConstraintEngineListener::notifyViolationRemoved(PSConstraint*) {} +void PSConstraintEngineListener::notifyChanged(PSVariable*, PSChangeType){} + +void PSConstraintEngineListener::notifyAdded(const ConstraintId&) {} +void PSConstraintEngineListener::notifyActivated(const ConstraintId&) {} +void PSConstraintEngineListener::notifyDeactivated(const ConstraintId&) {} +void PSConstraintEngineListener::notifyRemoved(const ConstraintId&) {} +void PSConstraintEngineListener::notifyExecuted(const ConstraintId&) {} + +void PSConstraintEngineListener::notifyDeactivated(const ConstrainedVariableId&) {} +void PSConstraintEngineListener::notifyActivated(const ConstrainedVariableId&) {} +void PSConstraintEngineListener::notifyAdded(const ConstrainedVariableId&) {} +void PSConstraintEngineListener::notifyRemoved(const ConstrainedVariableId&) {} + } diff --git a/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.hh b/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.hh index 1a89153eb..e1125b4d5 100644 --- a/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.hh +++ b/src/PLASMA/ConstraintEngine/base/PSConstraintEngineListener.hh @@ -27,35 +27,35 @@ public: virtual ~PSConstraintEngineListener() {} /* The subset of notifications available through PSEngine interface */ - virtual void notifyViolationAdded(PSConstraint* constraint) {} - virtual void notifyViolationRemoved(PSConstraint* constraint) {} - virtual void notifyChanged(PSVariable* variable, PSChangeType changeType){} + virtual void notifyViolationAdded(PSConstraint* constraint); + virtual void notifyViolationRemoved(PSConstraint* constraint); + virtual void notifyChanged(PSVariable* variable, PSChangeType changeType); private: - /* We override these base class methods (called by ConstraintEngine) - * to call the above PS interface versions of the same methods. - */ - virtual void notifyViolationAdded(const ConstraintId& variable); - virtual void notifyViolationRemoved(const ConstraintId& variable); - virtual void notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType); - - /* These methods are likely unnecessary to a user. We override the base - * class version only to make private (they still don't do anything) - */ - virtual void notifyPropagationCommenced() {} - virtual void notifyPropagationCompleted() {} - virtual void notifyPropagationPreempted() {} - virtual void notifyAdded(const ConstraintId& constraint) {} - virtual void notifyActivated(const ConstraintId& constraint) {} - virtual void notifyDeactivated(const ConstraintId& constraint) {} - virtual void notifyRemoved(const ConstraintId& constraint) {} - virtual void notifyExecuted(const ConstraintId& constraint) {} - - virtual void notifyDeactivated(const ConstrainedVariableId& variable) {} - virtual void notifyActivated(const ConstrainedVariableId& variable) {} - virtual void notifyAdded(const ConstrainedVariableId& variable) {} - virtual void notifyRemoved(const ConstrainedVariableId& variable) {} + /* We override these base class methods (called by ConstraintEngine) + * to call the above PS interface versions of the same methods. + */ + virtual void notifyViolationAdded(const ConstraintId& variable); + virtual void notifyViolationRemoved(const ConstraintId& variable); + virtual void notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType); + + /* These methods are likely unnecessary to a user. We override the base + * class version only to make private (they still don't do anything) + */ + virtual void notifyPropagationCommenced() {} + virtual void notifyPropagationCompleted() {} + virtual void notifyPropagationPreempted() {} + virtual void notifyAdded(const ConstraintId& constraint); + virtual void notifyActivated(const ConstraintId& constraint); + virtual void notifyDeactivated(const ConstraintId& constraint); + virtual void notifyRemoved(const ConstraintId& constraint); + virtual void notifyExecuted(const ConstraintId& constraint); + + virtual void notifyDeactivated(const ConstrainedVariableId& variable); + virtual void notifyActivated(const ConstrainedVariableId& variable); + virtual void notifyAdded(const ConstrainedVariableId& variable); + virtual void notifyRemoved(const ConstrainedVariableId& variable); }; } diff --git a/src/PLASMA/ConstraintEngine/base/PSVarValue.cc b/src/PLASMA/ConstraintEngine/base/PSVarValue.cc index 5036fb4dd..272caa069 100644 --- a/src/PLASMA/ConstraintEngine/base/PSVarValue.cc +++ b/src/PLASMA/ConstraintEngine/base/PSVarValue.cc @@ -29,9 +29,6 @@ namespace EUROPA { os << "OBJECT:" << obj->toString(); } break; - - default: - check_error(ALWAYS_FAILS, "Unknown type"); } return os.str(); @@ -42,11 +39,17 @@ namespace EUROPA { PSVarType PSVarValue::getType() const {return m_type;} - int PSVarValue::asInt() const {check_runtime_error(m_type == INTEGER); return (int) m_val;} +int PSVarValue::asInt() const { + check_runtime_error(m_type == INTEGER); + return static_cast(m_val); +} double PSVarValue::asDouble() const {return m_val;} - bool PSVarValue::asBoolean() const {check_runtime_error(m_type == BOOLEAN); return (bool) m_val;} +bool PSVarValue::asBoolean() const { + check_runtime_error(m_type == BOOLEAN); + return static_cast(m_val); +} const std::string& PSVarValue::asString() const { check_runtime_error(m_type == STRING); @@ -58,8 +61,8 @@ namespace EUROPA { // only works if PSEntity remains pure virtual //Id id(Entity::getEntity(edouble(m_val))); //EntityId entity = Entity::getEntity(edouble(m_val)); - EntityId entity = Entity::getEntity((edouble) m_val); - return (PSEntity *) entity; + EntityId entity = Entity::getEntity(edouble(m_val)); + return id_cast(entity); } diff --git a/src/PLASMA/ConstraintEngine/base/PSVarValue.hh b/src/PLASMA/ConstraintEngine/base/PSVarValue.hh index 858c43ebf..c9f4bf39f 100644 --- a/src/PLASMA/ConstraintEngine/base/PSVarValue.hh +++ b/src/PLASMA/ConstraintEngine/base/PSVarValue.hh @@ -21,11 +21,17 @@ namespace EUROPA { std::string toString() const; - static PSVarValue getInstance(const std::string& val) {return PSVarValue(cast_double((edouble)LabelStr(val)), STRING);} - static PSVarValue getInstance(int val) {return PSVarValue((double)val, INTEGER);} + static PSVarValue getInstance(const std::string& val) { + return PSVarValue(cast_double(static_cast(LabelStr(val))), STRING); + } + static PSVarValue getInstance(int val) { + return PSVarValue(static_cast(val), INTEGER); + } static PSVarValue getInstance(double val) {return PSVarValue(val, DOUBLE);} static PSVarValue getInstance(edouble val) {return PSVarValue(val, DOUBLE);} - static PSVarValue getInstance(bool val) {return PSVarValue((double)val, BOOLEAN);} + static PSVarValue getInstance(bool val) { + return PSVarValue(static_cast(val), BOOLEAN); + } static PSVarValue getObjectInstance(double obj) {return PSVarValue(obj, OBJECT);} private: diff --git a/src/PLASMA/ConstraintEngine/base/Propagator.cc b/src/PLASMA/ConstraintEngine/base/Propagator.cc index 294087b54..7d1233949 100644 --- a/src/PLASMA/ConstraintEngine/base/Propagator.cc +++ b/src/PLASMA/ConstraintEngine/base/Propagator.cc @@ -70,4 +70,9 @@ namespace EUROPA { getConstraintEngine()->getViolationMgr().addEmptyVariable(v); } + +void Propagator::handleVariableDeactivated(const ConstrainedVariableId&){} +void Propagator::handleVariableActivated(const ConstrainedVariableId&){} + + } diff --git a/src/PLASMA/ConstraintEngine/base/Propagator.hh b/src/PLASMA/ConstraintEngine/base/Propagator.hh index e5e578ee1..1b474c3b9 100644 --- a/src/PLASMA/ConstraintEngine/base/Propagator.hh +++ b/src/PLASMA/ConstraintEngine/base/Propagator.hh @@ -104,13 +104,13 @@ namespace EUROPA { * This notification is information rich, so that agenda management and constraints can take advantage * of as much data as possibel if they are sophisticated enough. * @param variable The variable that has changed - * @param argIndiex The position of the variable in the scope of the given Constraint. + * @param argIndex The position of the variable in the scope of the given Constraint. * @param constraint The constraint that may need to be woken up. * @param changeType The nature of the change on the variable. Will always be a restriction * @see ConstraintEngine::notify() */ virtual void handleNotification(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const ConstraintId& constraint, const DomainListener::ChangeType& changeType) = 0; /** @@ -151,24 +151,25 @@ namespace EUROPA { */ virtual void handleConstraintActivated(const ConstraintId& constraint) = 0; + //TODO: Figure out why these aren't pure virtual but the other functions are /** * @brief Handle a variable deactivation. * @param var The inactive variable */ - virtual void handleVariableDeactivated(const ConstrainedVariableId& var){} + virtual void handleVariableDeactivated(const ConstrainedVariableId& var); /** * @brief Handle a variable Activation. * @param var The active variable */ - virtual void handleVariableActivated(const ConstrainedVariableId& var){} + virtual void handleVariableActivated(const ConstrainedVariableId& var); /** * @brief Request execution of a Constraint. * * It is not possible to directly execute a Constraint. This is because we want to ensure control policies defined * can be enforced and not circumvented in derived classes. This call will delegate execution to the ConstraintEngine. - * @param The constraint to be executed. It must be part in m_constraints. + * @param constraint The constraint to be executed. It must be part in m_constraints. */ virtual void execute(const ConstraintId& constraint); diff --git a/src/PLASMA/ConstraintEngine/component/CFunctions.cc b/src/PLASMA/ConstraintEngine/component/CFunctions.cc new file mode 100644 index 000000000..9874c9e72 --- /dev/null +++ b/src/PLASMA/ConstraintEngine/component/CFunctions.cc @@ -0,0 +1,7 @@ +#include "CFunctions.hh" + +namespace EUROPA { +void IsSingleton::checkArgTypes(const std::vector& ) {} + +void IsSpecified::checkArgTypes(const std::vector& ) {} +} diff --git a/src/PLASMA/ConstraintEngine/component/CFunctions.hh b/src/PLASMA/ConstraintEngine/component/CFunctions.hh index 902d17ff6..cbd96a033 100644 --- a/src/PLASMA/ConstraintEngine/component/CFunctions.hh +++ b/src/PLASMA/ConstraintEngine/component/CFunctions.hh @@ -10,6 +10,7 @@ #include "CFunction.hh" #include "DataTypes.hh" +#include "unused.hh" namespace EUROPA { @@ -24,7 +25,7 @@ public: virtual unsigned int getArgumentCount() { return 1; } // TODO: implement this - virtual void checkArgTypes(const std::vector& argTypes) {} + virtual void checkArgTypes(const std::vector& argTypes); }; class IsSpecified : public CFunction @@ -38,7 +39,7 @@ public: virtual unsigned int getArgumentCount() { return 1; } // TODO: implement this - virtual void checkArgTypes(const std::vector& argTypes) {} + virtual void checkArgTypes(const std::vector& argTypes); }; #define DECLARE_FUNCTION_TYPE(cname, fname, constraint, type, args) \ @@ -51,7 +52,7 @@ public: virtual const char* getConstraint() { return constraint; } \ virtual const DataTypeId getReturnType() { return type::instance(); } \ virtual unsigned int getArgumentCount() { return args; } \ - virtual void checkArgTypes(const std::vector& argTypes) {} \ + virtual void checkArgTypes(unused(const std::vector& argTypes)) {} \ }; // Check args TODO. diff --git a/src/PLASMA/ConstraintEngine/component/Constraints.cc b/src/PLASMA/ConstraintEngine/component/Constraints.cc index 4e0352544..596ac6387 100644 --- a/src/PLASMA/ConstraintEngine/component/Constraints.cc +++ b/src/PLASMA/ConstraintEngine/component/Constraints.cc @@ -6,52 +6,54 @@ #include "Utils.hh" #include "Debug.hh" #include +#include namespace EUROPA { - void requireArgCount(std::string name, const std::vector& argTypes, const unsigned int count) { - if (argTypes.size() != count) { - std::ostringstream msg; msg << "Constraint " << name << " takes 2 args, not " << argTypes.size(); - throw msg.str(); - } +namespace { +void requireArgCount(std::string name, const std::vector& argTypes, const unsigned int count) { + if (argTypes.size() != count) { + std::ostringstream msg; msg << "Constraint " << name << " takes 2 args, not " << argTypes.size(); + throw msg.str(); } +} - void mutuallyAssignable(std::string name, DataTypeId a, DataTypeId b) { - if (b->isNumeric() && b->isNumeric()) { - //This is a hopefully temporary hack that makes the constraints work so the tests can pass. Waiting for agreement on the - //mailling list before deciding what to do in this case. Tony T. Pratkanis: 9/11/09. - return; - } - if (!b->isAssignableFrom(a) || !a->isAssignableFrom(b)) { - std::ostringstream msg; msg << "Constraint " << name << " args must be assignable. In this case, " - << a->getName().c_str() << " and " << b->getName().c_str() - << " are not assignable."; - throw msg.str(); - } +void mutuallyAssignable(std::string name, DataTypeId a, DataTypeId b) { + if (b->isNumeric() && b->isNumeric()) { + //This is a hopefully temporary hack that makes the constraints work so the tests can pass. Waiting for agreement on the + //mailling list before deciding what to do in this case. Tony T. Pratkanis: 9/11/09. + return; } + if (!b->isAssignableFrom(a) || !a->isAssignableFrom(b)) { + std::ostringstream msg; msg << "Constraint " << name << " args must be assignable. In this case, " + << a->getName().c_str() << " and " << b->getName().c_str() + << " are not assignable."; + throw msg.str(); + } +} - void requireNumeric(std::string name, DataTypeId a) { - if (!a->isNumeric()) { - std::ostringstream msg; msg << "Constraint " << name << " args must be numeric. " << a->getName().c_str() << " is not."; - throw msg.str(); - } +void requireNumeric(std::string name, DataTypeId a) { + if (!a->isNumeric()) { + std::ostringstream msg; msg << "Constraint " << name << " args must be numeric. " << a->getName().c_str() << " is not."; + throw msg.str(); } +} - void requireBoolean(std::string name, DataTypeId a) { - if (!a->isBool()) { - std::ostringstream msg; msg << "Constraint " << name << " args must be numeric. " << a->getName().c_str() << " is not."; - throw msg.str(); - } +void requireBoolean(std::string name, DataTypeId a) { + if (!a->isBool()) { + std::ostringstream msg; msg << "Constraint " << name << " args must be numeric. " << a->getName().c_str() << " is not."; + throw msg.str(); } +} - void requireAllSame(std::string name, const std::vector& argTypes) { - for (unsigned int i = 0; i < argTypes.size(); i++) { - for (unsigned int u = i + 1; u < argTypes.size(); u++) { - mutuallyAssignable(name, argTypes[i], argTypes[u]); - } +void requireAllSame(std::string name, const std::vector& argTypes) { + for (unsigned int i = 0; i < argTypes.size(); i++) { + for (unsigned int u = i + 1; u < argTypes.size(); u++) { + mutuallyAssignable(name, argTypes[i], argTypes[u]); } } - +} +} void TwoSameArgumentsCT::checkArgTypes(const std::vector& argTypes) const { @@ -164,8 +166,8 @@ namespace EUROPA { m_x = 0; } - bool UnaryConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, + bool UnaryConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, const DomainListener::ChangeType& changeType){ checkError(argIndex == 0, "Cannot have more than one variable in scope."); @@ -179,7 +181,7 @@ namespace EUROPA { void UnaryConstraint::setSource(const ConstraintId& sourceConstraint){ checkError(m_x == 0, "Already set domain for " << toString() << " and not using " << sourceConstraint->toString()); - UnaryConstraint* source = (UnaryConstraint*) sourceConstraint; + UnaryConstraint* source = id_cast(sourceConstraint); m_x = source->m_x->copy(); } @@ -221,7 +223,7 @@ namespace EUROPA { m_y(getCurrentDomain(m_variables[Y])), m_z(getCurrentDomain(m_variables[Z])) { - check_error(variables.size() == (unsigned int) ARG_COUNT); + check_error(variables.size() == ARG_COUNT); } void AddEqualConstraint::handleExecute() { @@ -298,8 +300,8 @@ namespace EUROPA { const ConstraintEngineId& constraintEngine, const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); - for (int i = 0; i < ARG_COUNT; i++) + check_error(variables.size() == ARG_COUNT); + for (unsigned int i = 0; i < ARG_COUNT; i++) check_error(!getCurrentDomain(m_variables[i]).isEnumerated()); } /* @@ -406,109 +408,110 @@ namespace EUROPA { */ // Update Z's domain bounds using domains of X and Y in: X * Y = Z. // Return TRUE if we have new bounds for Z - bool updateMultBounds(IntervalDomain& domZ, +namespace { +bool updateMultBounds(IntervalDomain& domZ, const IntervalDomain& domX, const IntervalDomain& domY) - { - // Can not do any update if the domain of any variable is empty - if(domX.isEmpty() || domY.isEmpty() || domZ.isEmpty()) - return false; - - edouble xMin, yMin, xMax, yMax, zMin, zMax, a, b, c, d; - domX.getBounds(xMin, xMax); - domY.getBounds(yMin, yMax); - - a = xMin * yMin; - b = xMin * yMax; - c = xMax * yMin; - d = xMax * yMax; - - zMin = std::min(std::min(a,b),std::min(c,d)); - zMax = std::max(std::max(a,b),std::max(c,d)); +{ + // Can not do any update if the domain of any variable is empty + if(domX.isEmpty() || domY.isEmpty() || domZ.isEmpty()) + return false; - return domZ.intersect(zMin,zMax); - } + edouble xMin, yMin, xMax, yMax, zMin, zMax, a, b, c, d; + domX.getBounds(xMin, xMax); + domY.getBounds(yMin, yMax); + + a = xMin * yMin; + b = xMin * yMax; + c = xMax * yMin; + d = xMax * yMax; + + zMin = std::min(std::min(a,b),std::min(c,d)); + zMax = std::max(std::max(a,b),std::max(c,d)); + + return domZ.intersect(zMin,zMax); +} + +// Update Z's domain bounds using domains of X and Y in: X / Y = Z. +// Return TRUE if we have new bounds for Z +// NOTE: given the division-by-zero problem, there will be many different scenarios that need +// special treatments +bool updateDivBounds(IntervalDomain& domZ, + const IntervalDomain& domX, + const IntervalDomain& domY) +{ + // Can not do any update if the domain of any variable is empty + if(domX.isEmpty() || domY.isEmpty() || domZ.isEmpty()) + return false; - // Update Z's domain bounds using domains of X and Y in: X / Y = Z. - // Return TRUE if we have new bounds for Z - // NOTE: given the division-by-zero problem, there will be many different scenarios that need - // special treatments - bool updateDivBounds(IntervalDomain& domZ, - const IntervalDomain& domX, - const IntervalDomain& domY) - { - // Can not do any update if the domain of any variable is empty - if(domX.isEmpty() || domY.isEmpty() || domZ.isEmpty()) - return false; + edouble xMin, yMin, xMax, yMax, zMin, zMax, a, b, c, d; + domX.getBounds(xMin, xMax); + domY.getBounds(yMin, yMax); - edouble xMin, yMin, xMax, yMax, zMin, zMax, a, b, c, d; - domX.getBounds(xMin, xMax); - domY.getBounds(yMin, yMax); - - - // if [Y] = {0} (singleton 0 value) - if(yMin == 0.0 && yMax == 0.0) { - // If [X] doesn't contain 0 then inconsistent -> empty Z domain - // NOTE: alternatively, [X] can be emptied instead of [Z] but it doesn't matter - // with the current mechanism in Europa - if((xMin > 0.0 || xMax < 0.0)) { - domZ.empty(); - return true; - } else { - // If 0 \in [X] then no bound tightening (because 0/0 can be anything) - return false; - } - } - // If 0 \in [Y] but 0 is not one of the bounds then no tightening - // NOTE: regardless of the bounds of X because [Y] contains both positive & negative values - if(yMin < 0.0 && yMax > 0.0) + // if [Y] = {0} (singleton 0 value) + if(yMin == 0.0 && yMax == 0.0) { + // If [X] doesn't contain 0 then inconsistent -> empty Z domain + // NOTE: alternatively, [X] can be emptied instead of [Z] but it doesn't matter + // with the current mechanism in Europa + if((xMin > 0.0 || xMax < 0.0)) { + domZ.empty(); + return true; + } else { + // If 0 \in [X] then no bound tightening (because 0/0 can be anything) return false; - - // If [Y] doesn't contain 0. Safely compute the two possible new bounds - if(yMin > 0.0 || yMax < 0.0) { - a = xMin / yMin; - b = xMin / yMax; - c = xMax / yMin; - d = xMax / yMax; - - zMin = std::min(std::min(a,b),std::min(c,d)); - zMax = std::max(std::max(a,b),std::max(c,d)); - return domZ.intersect(zMin,zMax); } + } - // if lb[Y] = 0 OR ub[Y] = 0 and ub[Y] > lb[Y] (i.e., 0 is one but not both bounds of [Y]) - // and 0 \in [X] then there is no bound tightening (because 0/0 can be anything) - if((yMin == 0.0 || yMax == 0.0) && (xMin <= 0.0 && xMax >= 0.0)) - return false; - - /* - * if lb[Y] = 0 OR ub[Y] = 0 and [X] doesn't contain 0, then we can compute one of the bounds - */ - // One of the bounds will be \infinity so we will initialize both of the potential - // new [Z]'s bounds with the existing bounds on [Z] - domZ.getBounds(zMin, zMax); - - // Case 1 [+,+] / [0,+]: new bounds [xMin / yMax, +infinity] - if(yMin == 0.0 && xMin > 0.0) - zMin = xMin / yMax; - - // Case 2 [-,-] / [0,+] : new bounds [-infinity, xMax / yMax] - if(yMin == 0.0 && xMax < 0.0) - zMax = xMax / yMax; - - // Case 3 [+,+] / [-,0]: new bounds [-infinity, xMin /yMin] - if(yMax == 0.0 && xMin > 0.0) - zMax = xMin / yMin; + // If 0 \in [Y] but 0 is not one of the bounds then no tightening + // NOTE: regardless of the bounds of X because [Y] contains both positive & negative values + if(yMin < 0.0 && yMax > 0.0) + return false; - // Case 4 [-,-] / [-,0]: new bounds [xMax / yMin, +infinity ] - if(yMax == 0.0 && xMax < 0.0) - zMin = xMax / yMin; + // If [Y] doesn't contain 0. Safely compute the two possible new bounds + if(yMin > 0.0 || yMax < 0.0) { + a = xMin / yMin; + b = xMin / yMax; + c = xMax / yMin; + d = xMax / yMax; - // Set the new bounds + zMin = std::min(std::min(a,b),std::min(c,d)); + zMax = std::max(std::max(a,b),std::max(c,d)); return domZ.intersect(zMin,zMax); } + // if lb[Y] = 0 OR ub[Y] = 0 and ub[Y] > lb[Y] (i.e., 0 is one but not both bounds of [Y]) + // and 0 \in [X] then there is no bound tightening (because 0/0 can be anything) + if((yMin == 0.0 || yMax == 0.0) && (xMin <= 0.0 && xMax >= 0.0)) + return false; + + /* + * if lb[Y] = 0 OR ub[Y] = 0 and [X] doesn't contain 0, then we can compute one of the bounds + */ + // One of the bounds will be \infinity so we will initialize both of the potential + // new [Z]'s bounds with the existing bounds on [Z] + domZ.getBounds(zMin, zMax); + + // Case 1 [+,+] / [0,+]: new bounds [xMin / yMax, +infinity] + if(yMin == 0.0 && xMin > 0.0) + zMin = xMin / yMax; + + // Case 2 [-,-] / [0,+] : new bounds [-infinity, xMax / yMax] + if(yMin == 0.0 && xMax < 0.0) + zMax = xMax / yMax; + + // Case 3 [+,+] / [-,0]: new bounds [-infinity, xMin /yMin] + if(yMax == 0.0 && xMin > 0.0) + zMax = xMin / yMin; + + // Case 4 [-,-] / [-,0]: new bounds [xMax / yMin, +infinity ] + if(yMax == 0.0 && xMax < 0.0) + zMin = xMax / yMin; + + // Set the new bounds + return domZ.intersect(zMin,zMax); +} +} void MultEqualConstraint::handleExecute() { IntervalDomain& domX = static_cast(getCurrentDomain(m_variables[X])); IntervalDomain& domY = static_cast(getCurrentDomain(m_variables[Y])); @@ -548,8 +551,8 @@ namespace EUROPA { const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); - for (int i = 0; i < ARG_COUNT; i++) + check_error(variables.size() == ARG_COUNT); + for (unsigned int i = 0; i < ARG_COUNT; i++) check_error(!getCurrentDomain(m_variables[i]).isEnumerated()); } @@ -616,7 +619,7 @@ namespace EUROPA { //is now equal to the intersection of all of the variables, //we can just equate backwards and they should all be equal if(changed && m_argCount > 2) { - for(unsigned int i = m_argCount - 2; i >= 1; i--) { + for(unsigned long i = m_argCount - 2; i >= 1; i--) { ConstrainedVariableId v1 = m_variables[i]; ConstrainedVariableId v2 = m_variables[i-1]; bool isEmpty = false; @@ -701,17 +704,17 @@ namespace EUROPA { m_currentDomain.intersect(m_superSetDomain); } - bool SubsetOfConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ - // If not a relaxation, and if it is the first argument, then we can ignore it as it will already be a subset - if(changeType == DomainListener::RESET || - changeType == DomainListener::RELAXED || - argIndex == 1) - return false; - else - return true; - } +bool SubsetOfConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, + const DomainListener::ChangeType& changeType){ + // If not a relaxation, and if it is the first argument, then we can ignore it as it will already be a subset + if(changeType == DomainListener::RESET || + changeType == DomainListener::RELAXED || + argIndex == 1) + return false; + else + return true; +} /*********** LessThanEqualConstraint *************/ LessThanEqualConstraint::LessThanEqualConstraint(const LabelStr& name, @@ -721,7 +724,7 @@ namespace EUROPA { : Constraint(name, propagatorName, constraintEngine, variables), m_x(getCurrentDomain(variables[X])), m_y(getCurrentDomain(variables[Y])){ - checkError(variables.size() == (unsigned int) ARG_COUNT, toString()); + checkError(variables.size() == ARG_COUNT, toString()); checkError(m_x.isNumeric(), variables[X]->toString()); checkError(m_y.isNumeric(), variables[Y]->toString()); } @@ -751,26 +754,24 @@ namespace EUROPA { m_y.intersect(m_x.getLowerBound(), m_y.getUpperBound()); } - bool LessThanEqualConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { - return((argIndex == X && - (changeType == DomainListener::UPPER_BOUND_DECREASED)) || - (argIndex == Y && - (changeType == DomainListener::LOWER_BOUND_INCREASED))); - } - /** - * @todo - */ - bool LessThanEqualConstraint::testIsRedundant(const ConstrainedVariableId& var) const{ - if(Constraint::testIsRedundant(var)) - return true; - - if(getScope()[X]->baseDomain().getUpperBound() <= getScope()[Y]->baseDomain().getLowerBound()) - return true; +bool LessThanEqualConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, + const DomainListener::ChangeType& changeType) { + return((argIndex == X && + (changeType == DomainListener::UPPER_BOUND_DECREASED)) || + (argIndex == Y && + (changeType == DomainListener::LOWER_BOUND_INCREASED))); +} - return false; - } +bool LessThanEqualConstraint::testIsRedundant(const ConstrainedVariableId& var) const{ + if(Constraint::testIsRedundant(var)) + return true; + + if(getScope()[X]->baseDomain().getUpperBound() <= getScope()[Y]->baseDomain().getLowerBound()) + return true; + + return false; +} /*********** NotEqualConstraint *************/ @@ -779,7 +780,7 @@ namespace EUROPA { const ConstraintEngineId& constraintEngine, const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); + check_error(variables.size() == ARG_COUNT); } void NotEqualConstraint::handleExecute() { @@ -833,20 +834,20 @@ namespace EUROPA { return(false); } - bool NotEqualConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { - if(changeType==DomainListener::RESET || changeType == DomainListener::RELAXED) - return false; +bool NotEqualConstraint::canIgnore(const ConstrainedVariableId& variable, + unsigned int, + const DomainListener::ChangeType& changeType) { + if(changeType==DomainListener::RESET || changeType == DomainListener::RELAXED) + return false; - const Domain& domain = variable->lastDomain(); + const Domain& domain = variable->lastDomain(); - if(domain.isSingleton() || - (domain.isInterval() && domain.isFinite() && domain.getSize() <=2 )) // Since this transition is key for propagation - return false; + if(domain.isSingleton() || + (domain.isInterval() && domain.isFinite() && domain.getSize() <=2 )) // Since this transition is key for propagation + return false; - return true; - } + return true; +} /*********** LessThanConstraint *************/ LessThanConstraint::LessThanConstraint(const LabelStr& name, @@ -854,7 +855,7 @@ namespace EUROPA { const ConstraintEngineId& constraintEngine, const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); + check_error(variables.size() == ARG_COUNT); } void LessThanConstraint::handleExecute() { @@ -894,20 +895,16 @@ namespace EUROPA { } } - bool LessThanConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType) { - return((argIndex == X && - (changeType == DomainListener::UPPER_BOUND_DECREASED)) || - (argIndex == Y && - (changeType == DomainListener::LOWER_BOUND_INCREASED))); - } +bool LessThanConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, + const DomainListener::ChangeType& changeType) { + return((argIndex == X && + (changeType == DomainListener::UPPER_BOUND_DECREASED)) || + (argIndex == Y && + (changeType == DomainListener::LOWER_BOUND_INCREASED))); +} - /** - * @class AddMultEqualConstraint - * @brief A + (B*C) == D - */ AddMultEqualConstraint::AddMultEqualConstraint(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, @@ -918,7 +915,7 @@ namespace EUROPA { makeScope(m_variables[B], m_variables[C], m_interimVariable.getId())), m_addEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, makeScope(m_interimVariable.getId(), m_variables[A], m_variables[D])) { - check_error(m_variables.size() == (unsigned int) ARG_COUNT); + check_error(m_variables.size() == ARG_COUNT); } AddMultEqualConstraint::~AddMultEqualConstraint(){ @@ -931,22 +928,22 @@ namespace EUROPA { } /*********** EqualSumConstraint *************/ - EqualSumConstraint::EqualSumConstraint(const LabelStr& name, - const LabelStr& propagatorName, - const ConstraintEngineId& constraintEngine, - const std::vector& variables) +EqualSumConstraint::EqualSumConstraint(const LabelStr& name, + const LabelStr& propagatorName, + const ConstraintEngineId& constraintEngine, + const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables), ARG_COUNT(variables.size()), m_sum1(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqSumVariable"), getId()), m_sum2(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqSumVariable"), getId()), m_sum3(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqSumVariable"), getId()), m_sum4(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqSumVariable"), getId()) { - check_error(ARG_COUNT > 2 && ARG_COUNT == (unsigned int)m_variables.size()); - std::vector scope; - // B is always first and C is always second for the first set, so: - scope.push_back(m_variables[1]); // B + ... - scope.push_back(m_variables[2]); // ... C ... - switch (ARG_COUNT) { + check_error(ARG_COUNT > 2 && ARG_COUNT == m_variables.size()); + std::vector scope; + // B is always first and C is always second for the first set, so: + scope.push_back(m_variables[1]); // B + ... + scope.push_back(m_variables[2]); // ... C ... + switch (ARG_COUNT) { case 3: // A = B + C scope.push_back(m_variables[0]); // ... = A m_eqSumC1 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); @@ -976,36 +973,36 @@ namespace EUROPA { scope.push_back(m_variables[3]); // D + ... scope.push_back(m_variables[4]); // E ... switch (ARG_COUNT) { - case 5: - scope.push_back(m_sum2.getId()); // ... = (D + E) - m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - break; - case 6: - scope.push_back(m_sum3.getId()); // ... = (D + E) - m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - scope.clear(); - scope.push_back(m_sum3.getId()); // (D + E) + ... - scope.push_back(m_variables[5]); // ... F = ... - scope.push_back(m_sum2.getId()); // ... (D + E + F) - m_eqSumC4 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - break; - case 7: - scope.push_back(m_sum3.getId()); // ... = (D + E) - m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - scope.clear(); - scope.push_back(m_sum3.getId()); // (D + E) + ... - scope.push_back(m_sum4.getId()); // ... (F + G) = ... - scope.push_back(m_sum2.getId()); // (D + E + F + G) - m_eqSumC4 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - scope.clear(); - scope.push_back(m_variables[5]); // F + ... - scope.push_back(m_variables[6]); // ... G = ... - scope.push_back(m_sum4.getId()); // ... (F + G) - m_eqSumC5 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); - break; - default: - check_error(ALWAYS_FAILS); - break; + case 5: + scope.push_back(m_sum2.getId()); // ... = (D + E) + m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + break; + case 6: + scope.push_back(m_sum3.getId()); // ... = (D + E) + m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + scope.clear(); + scope.push_back(m_sum3.getId()); // (D + E) + ... + scope.push_back(m_variables[5]); // ... F = ... + scope.push_back(m_sum2.getId()); // ... (D + E + F) + m_eqSumC4 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + break; + case 7: + scope.push_back(m_sum3.getId()); // ... = (D + E) + m_eqSumC3 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + scope.clear(); + scope.push_back(m_sum3.getId()); // (D + E) + ... + scope.push_back(m_sum4.getId()); // ... (F + G) = ... + scope.push_back(m_sum2.getId()); // (D + E + F + G) + m_eqSumC4 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + scope.clear(); + scope.push_back(m_variables[5]); // F + ... + scope.push_back(m_variables[6]); // ... G = ... + scope.push_back(m_sum4.getId()); // ... (F + G) + m_eqSumC5 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); + break; + default: + check_error(ALWAYS_FAILS); + break; } // switch (ARGCOUNT) 5, 6, 7 break; default: @@ -1018,8 +1015,8 @@ namespace EUROPA { m_eqSumC1 = (new AddEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, scope))->getId(); scope.clear(); scope.push_back(m_sum1.getId()); // first_half = ... - unsigned int half = ARG_COUNT/2; - unsigned int i = 1; + unsigned long half = ARG_COUNT/2; + unsigned long i = 1; for ( ; i <= half; i++) scope.push_back(m_variables[i]); // ... X + ... m_eqSumC2 = (new EqualSumConstraint(LabelStr("EqualSum"), propagatorName, constraintEngine, scope))->getId(); @@ -1030,9 +1027,8 @@ namespace EUROPA { m_eqSumC3 = (new EqualSumConstraint(LabelStr("EqualSum"), propagatorName, constraintEngine, scope))->getId(); break; } - break; - } } +} EqualSumConstraint::~EqualSumConstraint() { discard(false); @@ -1060,7 +1056,7 @@ namespace EUROPA { m_product2(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqProductVariable"), getId()), m_product3(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqProductVariable"), getId()), m_product4(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalEqProductVariable"), getId()) { - check_error(ARG_COUNT > 2 && ARG_COUNT == (unsigned int)m_variables.size()); + check_error(ARG_COUNT > 2 && ARG_COUNT == m_variables.size()); std::vector scope; // B is always first and C is always second for the first set, so: scope.push_back(m_variables[1]); // B * ... @@ -1137,8 +1133,8 @@ namespace EUROPA { m_eqProductC1 = (new MultEqualConstraint(LabelStr("MultEqual"), propagatorName, constraintEngine, scope))->getId(); scope.clear(); scope.push_back(m_product1.getId()); // first_half = ... - unsigned int half = ARG_COUNT/2; - unsigned int i = 1; + unsigned long half = ARG_COUNT/2; + unsigned long i = 1; for ( ; i <= half; i++) scope.push_back(m_variables[i]); // ... X * ... m_eqProductC2 = (new EqualProductConstraint(LabelStr("EqualProduct"), propagatorName, constraintEngine, scope))->getId(); @@ -1149,7 +1145,6 @@ namespace EUROPA { m_eqProductC3 = (new EqualProductConstraint(LabelStr("EqualProduct"), propagatorName, constraintEngine, scope))->getId(); break; } - break; } } @@ -1410,6 +1405,7 @@ namespace EUROPA { getCurrentDomain(m_variables[i]))); } +namespace { /** * @brief Helper function: add domToAdd to unionOfDomains "usefully". * Adds all of the members of domToAdd and, if needed and useful, @@ -1424,79 +1420,80 @@ namespace EUROPA { * simply returning a single larger interval that 'covers' both * original intervals. */ - static void addToUnion(Domain **unionOfDomains, - const Domain& domToAdd) { - check_error(unionOfDomains != 0 && *unionOfDomains != 0); - check_error(!(*unionOfDomains)->isEmpty() && !(*unionOfDomains)->isOpen()); - check_error(!domToAdd.isEmpty() && !domToAdd.isOpen()); - Domain *newUnion = 0; - std::list membersToAdd; - std::list newMembers; - if (((*unionOfDomains)->isEnumerated() || (*unionOfDomains)->isSingleton()) - && (domToAdd.isEnumerated() || domToAdd.isSingleton())) { - if (domToAdd.isEnumerated()) - domToAdd.getValues(membersToAdd); - else - membersToAdd.push_back(domToAdd.getSingletonValue()); - if ((*unionOfDomains)->isEnumerated()) - (*unionOfDomains)->getValues(newMembers); - else - newMembers.push_back((*unionOfDomains)->getSingletonValue()); - for (std::list::const_iterator it = membersToAdd.begin(); - it != membersToAdd.end(); it++) { - std::list::const_iterator it2 = newMembers.begin(); - for ( ; it2 != newMembers.end(); it2++) - if (*it == *it2) - break; - if (it2 == newMembers.end()) - newMembers.push_back(*it); - } - newUnion = new EnumeratedDomain( - (*unionOfDomains)->getDataType(), - newMembers); - - // Could just add to current unionOfDomains rather than failing here, but - // very messy to implement using current interface to *Domain classes. - assertFalse(newUnion == NULL); - delete *unionOfDomains; - *unionOfDomains = newUnion; - return; - } - // At least one is a non-singleton interval, so the result will be - // also be one. - edouble toAddMin, toAddMax, newMin, newMax; - domToAdd.getBounds(toAddMin, toAddMax); - (*unionOfDomains)->getBounds(newMin, newMax); - bool changing = false; - if (toAddMin < newMin) { - newMin = toAddMin; - changing = true; - } - if (newMax < toAddMax) { - newMax = toAddMax; - changing = true; - } - if (changing) { - if((*unionOfDomains)->minDelta() < 1.0) - newUnion = new IntervalDomain(newMin, newMax); - else - newUnion = new IntervalIntDomain((eint)newMin, (eint)newMax); - - /* BOOL should be not get to here since both are non-singleton - * but then unionOfDomains "covers" domToAdd and changing - * would be false. - * USER_DEFINED and REAL_ENUMERATION should not get to here - * since enumerations are dealt with above. - * As above, a memory failure here could be dealt with, but - * messy to implement, but note that this also checks the - * assumptions/logic earlier in this comment. - */ - checkError(newUnion != 0, "Failed to allocate memory."); - delete *unionOfDomains; - *unionOfDomains = newUnion; - return; +void addToUnion(Domain **unionOfDomains, + const Domain& domToAdd) { + check_error(unionOfDomains != 0 && *unionOfDomains != 0); + check_error(!(*unionOfDomains)->isEmpty() && !(*unionOfDomains)->isOpen()); + check_error(!domToAdd.isEmpty() && !domToAdd.isOpen()); + Domain *newUnion = 0; + std::list membersToAdd; + std::list newMembers; + if (((*unionOfDomains)->isEnumerated() || (*unionOfDomains)->isSingleton()) + && (domToAdd.isEnumerated() || domToAdd.isSingleton())) { + if (domToAdd.isEnumerated()) + domToAdd.getValues(membersToAdd); + else + membersToAdd.push_back(domToAdd.getSingletonValue()); + if ((*unionOfDomains)->isEnumerated()) + (*unionOfDomains)->getValues(newMembers); + else + newMembers.push_back((*unionOfDomains)->getSingletonValue()); + for (std::list::const_iterator it = membersToAdd.begin(); + it != membersToAdd.end(); it++) { + std::list::const_iterator it2 = newMembers.begin(); + for ( ; it2 != newMembers.end(); it2++) + if (*it == *it2) + break; + if (it2 == newMembers.end()) + newMembers.push_back(*it); } + newUnion = new EnumeratedDomain( + (*unionOfDomains)->getDataType(), + newMembers); + + // Could just add to current unionOfDomains rather than failing here, but + // very messy to implement using current interface to *Domain classes. + assertFalse(newUnion == NULL); + delete *unionOfDomains; + *unionOfDomains = newUnion; + return; + } + // At least one is a non-singleton interval, so the result will be + // also be one. + edouble toAddMin, toAddMax, newMin, newMax; + domToAdd.getBounds(toAddMin, toAddMax); + (*unionOfDomains)->getBounds(newMin, newMax); + bool changing = false; + if (toAddMin < newMin) { + newMin = toAddMin; + changing = true; + } + if (newMax < toAddMax) { + newMax = toAddMax; + changing = true; + } + if (changing) { + if((*unionOfDomains)->minDelta() < 1.0) + newUnion = new IntervalDomain(newMin, newMax); + else + newUnion = new IntervalIntDomain(static_cast(newMin), static_cast(newMax)); + + /* BOOL should be not get to here since both are non-singleton + * but then unionOfDomains "covers" domToAdd and changing + * would be false. + * USER_DEFINED and REAL_ENUMERATION should not get to here + * since enumerations are dealt with above. + * As above, a memory failure here could be dealt with, but + * messy to implement, but note that this also checks the + * assumptions/logic earlier in this comment. + */ + checkError(newUnion != 0, "Failed to allocate memory."); + delete *unionOfDomains; + *unionOfDomains = newUnion; + return; } +} +} void CondAllDiffConstraint::handleExecute() { BoolDomain& boolDom = static_cast(getCurrentDomain(m_variables[0])); @@ -1539,7 +1536,7 @@ namespace EUROPA { canProveTrue = false; // Add members of current to unionOfOthers "usefully". addToUnion(&unionOfOthers, current); - if (unionOfOthers->isFinite() && (unsigned int)(unionOfOthers->getSize()) < i) { + if (unionOfOthers->isFinite() && (unionOfOthers->getSize()) < i) { // At least two of the variables must have same value. boolDom.remove(true); canProveTrue = false; @@ -1756,7 +1753,7 @@ namespace EUROPA { : Constraint(name, propagatorName, constraintEngine, variables), m_zeros(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalCountNonZerosVar"), getId()), m_otherVars(constraintEngine, IntervalDomain(), true, false, LabelStr("InternalCountNonZerosOtherVars"), getId()), - m_superset(constraintEngine, IntervalDomain((edouble)(variables.size() - 1)), true, false, LabelStr("InternalCountNonZerosSuperset"), getId()), + m_superset(constraintEngine, IntervalDomain(static_cast(variables.size() - 1)), true, false, LabelStr("InternalCountNonZerosSuperset"), getId()), m_addEqualConstraint(LabelStr("AddEqual"), propagatorName, constraintEngine, makeScope(m_zeros.getId(), m_variables[0], m_otherVars.getId())) { @@ -1995,6 +1992,8 @@ namespace EUROPA { check_error(m_eqSumConstraint.isValid()); } + + RotateScopeRightConstraint::RotateScopeRightConstraint(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, @@ -2003,21 +2002,24 @@ namespace EUROPA { const int& rotateCount) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error((unsigned) abs(rotateCount) < m_variables.size()); + check_error(static_cast(abs(rotateCount)) < m_variables.size()); std::vector otherScope; otherScope.reserve(m_variables.size()); - unsigned int i; + + unsigned long i; if (rotateCount > 0) { + unsigned long realCount = static_cast(rotateCount); // Rotate to right: last var becomes first, pushing others to the right. - for (i = rotateCount; i > 0; i--) + for (i = realCount; i > 0; i--) otherScope.push_back(m_variables[m_variables.size() - i]); - for (i = 0; i < m_variables.size() - rotateCount; i++) + for (i = 0; i < m_variables.size() - realCount; i++) otherScope.push_back(m_variables[i]); - } else { + } + else { // Rotate to left: first var becomes last, pushing others to the left. - for (i = (unsigned) abs(rotateCount); i < m_variables.size(); i++) + for (i = static_cast(abs(rotateCount)); i < m_variables.size(); i++) otherScope.push_back(m_variables[i]); - for (i = 0; i < (unsigned) abs(rotateCount); i++) + for (i = 0; i < static_cast(abs(rotateCount)); i++) otherScope.push_back(m_variables[i]); } check_error(m_variables.size() == otherScope.size()); @@ -2032,16 +2034,19 @@ namespace EUROPA { int firstIndex, int secondIndex) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error((unsigned) abs(firstIndex) < m_variables.size()); - check_error((unsigned) abs(secondIndex) < m_variables.size()); + check_error(static_cast(abs(firstIndex)) < m_variables.size()); + check_error(static_cast(abs(secondIndex)) < m_variables.size()); check_error(firstIndex != secondIndex); - if (firstIndex < 0) - firstIndex = m_variables.size() - firstIndex; - if (secondIndex < 0) - secondIndex = m_variables.size() - secondIndex; + unsigned long realFirstIndex = (firstIndex < 0 ? + (m_variables.size() - static_cast(std::abs(firstIndex))) : + static_cast(firstIndex)); + unsigned long realSecondIndex = (secondIndex < 0 ? + (m_variables.size() - static_cast(std::abs(secondIndex))) : + static_cast(secondIndex)); + check_error(realFirstIndex != realSecondIndex); std::vector otherScope(m_variables); - otherScope[firstIndex] = m_variables[secondIndex]; - otherScope[secondIndex] = m_variables[firstIndex]; + otherScope[realFirstIndex] = m_variables[realSecondIndex]; + otherScope[realSecondIndex] = m_variables[realFirstIndex]; m_otherConstraint = constraintEngine->createConstraint(otherName, otherScope); } @@ -2482,7 +2487,7 @@ namespace EUROPA { const ConstraintEngineId& constraintEngine, const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); + check_error(variables.size() == ARG_COUNT); } /** @@ -2515,7 +2520,7 @@ namespace EUROPA { const ConstraintEngineId& constraintEngine, const std::vector& variables) : Constraint(name, propagatorName, constraintEngine, variables) { - check_error(variables.size() == (unsigned int) ARG_COUNT); + check_error(variables.size() == ARG_COUNT); } /** @@ -2640,9 +2645,10 @@ namespace EUROPA { getCurrentDomain(m_variables[0]).intersect(m_rvalue, m_rvalue); } - eint mod(eint a, eint b) { return a % b; } - eint mod(edouble a, edouble b) {return cast_int(a) % cast_int(b);} - +namespace { +eint mod(eint a, eint b) { return a % b; } +eint mod(edouble a, edouble b) {return static_cast(std::fmod(cast_basis(a), cast_basis(b)));} +} CREATE_FUNCTION_CONSTRAINT_TWO_ARG(Max, std::max, edouble); CREATE_FUNCTION_CONSTRAINT_TWO_ARG(Min, std::min, edouble); CREATE_FUNCTION_CONSTRAINT_ONE_ARG(Abs, std::abs, edouble); diff --git a/src/PLASMA/ConstraintEngine/component/Constraints.hh b/src/PLASMA/ConstraintEngine/component/Constraints.hh index 3f4e8186a..a6e7a5f7d 100644 --- a/src/PLASMA/ConstraintEngine/component/Constraints.hh +++ b/src/PLASMA/ConstraintEngine/component/Constraints.hh @@ -166,10 +166,10 @@ namespace EUROPA { Domain& m_y; Domain& m_z; - static const int X = 0; - static const int Y = 1; - static const int Z = 2; - static const int ARG_COUNT = 3; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int Z = 2; + static const unsigned int ARG_COUNT = 3; }; class AddEqualCT : public ConstraintType { @@ -203,10 +203,10 @@ namespace EUROPA { void handleExecute(); private: - static const int X = 0; - static const int Y = 1; - static const int Z = 2; - static const int ARG_COUNT = 3; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int Z = 2; + static const unsigned int ARG_COUNT = 3; }; @@ -220,10 +220,10 @@ namespace EUROPA { void handleExecute(); private: - static const int X = 0; - static const int Y = 1; - static const int Z = 2; - static const int ARG_COUNT = 3; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int Z = 2; + static const unsigned int ARG_COUNT = 3; }; @@ -241,17 +241,22 @@ namespace EUROPA { inline void handleExecute() { } void handleDiscard(); - static const int A = 0; - static const int B = 1; - static const int C = 2; - static const int D = 3; - static const int ARG_COUNT = 4; + static const unsigned int A = 0; + static const unsigned int B = 1; + static const unsigned int C = 2; + static const unsigned int D = 3; + static const unsigned int ARG_COUNT = 4; Variable m_interimVariable; MultEqualConstraint m_multEqualConstraint; AddEqualConstraint m_addEqualConstraint; }; + /** + * @class AllDiff + * @brief A != B && A != C && B != C && A != D && B != D && ... + */ + class AllDiffConstraint : public Constraint { public: AllDiffConstraint(const LabelStr& name, @@ -276,6 +281,9 @@ namespace EUROPA { ConstraintId m_condAllDiffConstraint; }; + /** + * @brief Calculate the euclidean distance in 2-d space between between 2 points + */ class CalcDistanceConstraint : public Constraint { public: CalcDistanceConstraint(const LabelStr& name, @@ -322,7 +330,7 @@ class LessThanEqualConstraint : public Constraint { void handleExecute(); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); static void propagate(Domain& domx, Domain& domy); @@ -332,12 +340,22 @@ class LessThanEqualConstraint : public Constraint { Domain& m_x; Domain& m_y; - static const int X = 0; - static const int Y = 1; - static const int ARG_COUNT = 2; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int ARG_COUNT = 2; }; CREATE_CONSTRAINT_TYPE(TwoSameNumericArgumentsCT, LessThanEqualCT, LessThanEqualConstraint); + + /** + * @class CardinalityConstraint + * @brief First variable must be greater than or equal the count of the + * other variables that are true. + * @note Supports numeric domains for the other variables with the + * usual C/C++ convention of false being zero and true being + * any non-zero value. + */ + class CardinalityConstraint : public Constraint { public: CardinalityConstraint(const LabelStr& name, @@ -365,6 +383,11 @@ class CardinalityConstraint : public Constraint { ConstraintId m_countNonZerosConstraint; }; + /** + * @class CondAllDiff + * @brief If A, then B != C && B != D && C != D && ... ; if not A, then !(B != C && B != D && C != D && ...). + */ + class CondAllDiffConstraint : public Constraint { public: CondAllDiffConstraint(const LabelStr& name, @@ -377,9 +400,14 @@ class CondAllDiffConstraint : public Constraint { void handleExecute(); private: - const unsigned int ARG_COUNT; + const unsigned long ARG_COUNT; }; + /** + * @class CondAllSame + * @brief If A, then B == C && B == D && C == D && ... ; if not A, then !(B == C && B == D && C == D && ...). + */ + class CondAllSameConstraint : public Constraint { public: CondAllSameConstraint(const LabelStr& name, @@ -392,9 +420,15 @@ class CondAllSameConstraint : public Constraint { void handleExecute(); private: - const unsigned int ARG_COUNT; + const unsigned long ARG_COUNT; }; + /** + * @class CondEqualSumConstraint + * @brief If A is true, then B = C + D ...; if A is false, B != C + D ... + * Converted into two constraints: CondAllSame(A, B, sum) and EqualSum(sum, C, D, ...). + */ + class CondEqualSumConstraint : public Constraint { public: CondEqualSumConstraint(const LabelStr& name, @@ -453,6 +487,12 @@ class CountNonZerosConstraint : public Constraint { ConstraintId m_countZerosConstraint; }; + /** + * @class CountZerosConstraint + * @brief First variable is the count of the rest that can be zero. + * @note Supports boolean domains with the usual C/C++ convention of false + * being zero and true being non-zero. + */ class CountZerosConstraint : public Constraint { public: CountZerosConstraint(const LabelStr& name, @@ -465,12 +505,13 @@ class CountZerosConstraint : public Constraint { void handleExecute(); }; - /** - * @class CountNonZerosConstraint - * @brief First variable is the count of the rest that can be non-zero. - * @note Supports boolean domains with the usual C/C++ convention of false - * being zero and true being non-zero. + + /** + * @brief DistanceFromSquaresConstraint(x, y, a) maintains the relation + * @li a = sqrt(x + y) + * if x and y are singleton */ + class DistanceFromSquaresConstraint : public Constraint { public: DistanceFromSquaresConstraint(const LabelStr& name, @@ -481,10 +522,10 @@ class CountZerosConstraint : public Constraint { void handleExecute(); private: - static const int V1 = 0; - static const int V2 = 1; - static const int RES = 2; - static const int ARG_COUNT = 3; + static const unsigned int V1 = 0; + static const unsigned int V2 = 1; + static const unsigned int RES = 2; + static const unsigned int ARG_COUNT = 3; }; class EqualConstraint : public Constraint { @@ -503,10 +544,15 @@ class CountZerosConstraint : public Constraint { private: bool equate(const ConstrainedVariableId& v1, const ConstrainedVariableId& v2, bool& isEmpty); - const unsigned int m_argCount; + const unsigned long m_argCount; }; CREATE_CONSTRAINT_TYPE(AllSameArgumentsCT, EqualCT, EqualConstraint); + /** + * @class EqualMaximumConstraint + * @brief First variable is the maximum value of the others. + */ + class EqualMaximumConstraint : public Constraint { public: EqualMaximumConstraint(const LabelStr& name, @@ -519,6 +565,11 @@ class CountZerosConstraint : public Constraint { void handleExecute(); }; + /** + * @class EqualMinimumConstraint + * @brief First variable is the minimum value of the others. + */ + class EqualMinimumConstraint : public Constraint { public: EqualMinimumConstraint(const LabelStr& name, @@ -531,6 +582,12 @@ class EqualMinimumConstraint : public Constraint { void handleExecute(); }; + /** + * @class EqualProductConstraint + * @brief A = B * C where B and C can each be products. + * Converted into an AddEqualConstraint and/or two EqProductConstraints with fewer variables. + */ + class EqualProductConstraint : public Constraint { public: EqualProductConstraint(const LabelStr& name, @@ -547,12 +604,17 @@ class EqualProductConstraint : public Constraint { void handleDiscard(); - const unsigned int ARG_COUNT; + const unsigned long ARG_COUNT; ConstraintId m_eqProductC1, m_eqProductC2, m_eqProductC3, m_eqProductC4, m_eqProductC5; Variable m_product1, m_product2, m_product3, m_product4; }; +/** + * @class EqualSumConstraint + * @brief A = B + C where B and C can each be sums. + * Converted into an AddEqualConstraint and/or two EqSumConstraints with fewer variables. + */ class EqualSumConstraint : public Constraint { public: EqualSumConstraint(const LabelStr& name, @@ -569,12 +631,18 @@ class EqualSumConstraint : public Constraint { void handleDiscard(); - const unsigned int ARG_COUNT; + const unsigned long ARG_COUNT; ConstraintId m_eqSumC1, m_eqSumC2, m_eqSumC3, m_eqSumC4, m_eqSumC5; Variable m_sum1, m_sum2, m_sum3, m_sum4; }; + /** + * @class GreaterOrEqThanSumConstraint + * @brief A >= B + C + ... + * Converted into two constraints: A >= temp and temp equal to the sum of the rest. + */ + class GreaterOrEqThanSumConstraint : public Constraint { public: GreaterOrEqThanSumConstraint(const LabelStr& name, @@ -613,18 +681,24 @@ class LessThanConstraint : public Constraint { void handleExecute(); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); static void propagate(IntervalDomain& domx, IntervalDomain& domy); private: - static const int X = 0; - static const int Y = 1; - static const int ARG_COUNT = 2; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int ARG_COUNT = 2; }; CREATE_CONSTRAINT_TYPE(TwoSameNumericArgumentsCT, LessThanCT, LessThanConstraint); + /** + * @class GreaterThanSumConstraint + * @brief A > B + C + ... + * Converted into two constraints: A < temp and temp equal to the sum of the rest. + */ + class GreaterThanSumConstraint : public Constraint { public: GreaterThanSumConstraint(const LabelStr& name, @@ -652,6 +726,12 @@ class GreaterThanSumConstraint : public Constraint { ConstraintId m_eqSumConstraint; }; + /** + * @class LessOrEqThanSumConstraint + * @brief A <= B + C + ... + * Converted into two constraints: A <= temp and temp equal to the sum of the rest. + */ + class LessOrEqThanSumConstraint : public Constraint { public: LessOrEqThanSumConstraint(const LabelStr& name, @@ -669,6 +749,12 @@ class LessOrEqThanSumConstraint : public Constraint { ConstraintId m_eqSumConstraint; }; + /** + * @class LessThanSumConstraint + * @brief A < B + C + ... + * Converted into two constraints: A < temp and temp equal to the sum of the rest. + */ + class LessThanSumConstraint : public Constraint { public: LessThanSumConstraint(const LabelStr& name, @@ -724,8 +810,8 @@ class NegateConstraint : public Constraint { void handleExecute(); private: - static const int X=0; - static const int Y=1; + static const unsigned int X=0; + static const unsigned int Y=1; }; class NotEqualConstraint : public Constraint { @@ -738,7 +824,7 @@ class NotEqualConstraint : public Constraint { void handleExecute(); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); /** * @brief Helper method to do domain comparisons, and process removals if necessary @@ -746,57 +832,15 @@ class NotEqualConstraint : public Constraint { static bool checkAndRemove(const Domain& domx, Domain& domy); private: - static const int X = 0; - static const int Y = 1; - static const int ARG_COUNT = 2; + static const unsigned int X = 0; + static const unsigned int Y = 1; + static const unsigned int ARG_COUNT = 2; }; /** * Enforces the relation x < y */ - /** - * @class EqualSumConstraint - * @brief A = B + C where B and C can each be sums. - * Converted into an AddEqualConstraint and/or two EqSumConstraints with fewer variables. - */ - /** - * @class EqualProductConstraint - * @brief A = B * C where B and C can each be products. - * Converted into an AddEqualConstraint and/or two EqProductConstraints with fewer variables. - */ - /** - * @class LessOrEqThanSumConstraint - * @brief A <= B + C + ... - * Converted into two constraints: A <= temp and temp equal to the sum of the rest. - */ - /** - * @class LessThanSumConstraint - * @brief A < B + C + ... - * Converted into two constraints: A < temp and temp equal to the sum of the rest. - */ - /** - * @class GreaterOrEqThanSumConstraint - * @brief A >= B + C + ... - * Converted into two constraints: A >= temp and temp equal to the sum of the rest. - */ - /** - * @class GreaterThanSumConstraint - * @brief A > B + C + ... - * Converted into two constraints: A < temp and temp equal to the sum of the rest. - */ - /** - * @class CondAllSame - * @brief If A, then B == C && B == D && C == D && ... ; if not A, then !(B == C && B == D && C == D && ...). - */ - /** - * @class CondAllDiff - * @brief If A, then B != C && B != D && C != D && ... ; if not A, then !(B != C && B != D && C != D && ...). - */ - /** - * @class AllDiff - * @brief A != B && A != C && B != C && A != D && B != D && ... - */ /** * @class MemberImplyConstraint * @brief If A is subset of B, then require that C is subset of D. @@ -813,23 +857,9 @@ class NotEqualConstraint : public Constraint { void handleExecute(); private: - const unsigned int ARG_COUNT; + const unsigned long ARG_COUNT; }; - /** - * @class CountZerosConstraint - * @brief First variable is the count of the rest that can be zero. - * @note Supports boolean domains with the usual C/C++ convention of false - * being zero and true being non-zero. - */ - /** - * @class CardinalityConstraint - * @brief First variable must be greater than or equal the count of the - * other variables that are true. - * @note Supports numeric domains for the other variables with the - * usual C/C++ convention of false being zero and true being - * any non-zero value. - */ /** * @class OrConstraint * @brief At least one of the variables must be true. @@ -877,19 +907,6 @@ class NotEqualConstraint : public Constraint { unsigned int m_rvalue; }; - /** - * @class EqualMinimumConstraint - * @brief First variable is the minimum value of the others. - */ - /** - * @class EqualMaximumConstraint - * @brief First variable is the maximum value of the others. - */ - /** - * @class CondEqualSumConstraint - * @brief If A is true, then B = C + D ...; if A is false, B != C + D ... - * Converted into two constraints: CondAllSame(A, B, sum) and EqualSum(sum, C, D, ...). - */ /** * @class RotateScopeRightConstraint * @brief Rotate the scope right rotateCount places and call the otherName @@ -903,7 +920,7 @@ class NotEqualConstraint : public Constraint { RotateScopeRightConstraint(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, - const std::vector& variables) + const std::vector& variables) __attribute__((noreturn)) : Constraint(name, propagatorName, constraintEngine, variables) { // Called via REGISTER_NARY() macro's factory rather than via the // REGISTER_ROTATED_NARY() macro's factory: not enough information @@ -937,6 +954,11 @@ class NotEqualConstraint : public Constraint { * @class SwapTwoVarsConstraint * @brief Swap two variables in the scope and call the otherName * constraint. + */ + + /** + * @brief Computes the sine of a given variable. Varable is in degrees. The constraint is a function + * rather than a relation. The range of the source variable must be in [0 90]. */ class SineFunction : public Constraint { public: @@ -953,6 +975,12 @@ class NotEqualConstraint : public Constraint { Domain& m_source; }; + /** + * @brief SquareOfDifference(x, y, a) maintains the relation: + * @li a = (x - y)^2 + * if x and y are singleton. + */ + class SquareOfDifferenceConstraint : public Constraint { public: SquareOfDifferenceConstraint(const LabelStr& name, @@ -963,12 +991,17 @@ class SquareOfDifferenceConstraint : public Constraint { void handleExecute(); private: - static const int V1 = 0; - static const int V2 = 1; - static const int RES = 2; - static const int ARG_COUNT = 3; + static const unsigned int V1 = 0; + static const unsigned int V2 = 1; + static const unsigned int RES = 2; + static const unsigned int ARG_COUNT = 3; }; + /** + * @brief Maintains a unary relation from a constant to a variable such that the variable + * is a subset of the given constant. + */ + class SubsetOfConstraint : public Constraint { public: SubsetOfConstraint(const LabelStr& name, @@ -981,7 +1014,7 @@ class SubsetOfConstraint : public Constraint { void handleExecute(); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); private: @@ -990,18 +1023,18 @@ class SubsetOfConstraint : public Constraint { }; class SwapTwoVarsConstraint : public Constraint { - public: - SwapTwoVarsConstraint(const LabelStr& name, - const LabelStr& propagatorName, - const ConstraintEngineId& constraintEngine, - const std::vector& variables) + public: + SwapTwoVarsConstraint(const LabelStr& name, + const LabelStr& propagatorName, + const ConstraintEngineId& constraintEngine, + const std::vector& variables) __attribute__((noreturn)) : Constraint(name, propagatorName, constraintEngine, variables) { - // Called via REGISTER_NARY() macro's factory rather than via the - // REGISTER_SWAP_TWO_VARS_NARY() macro's factory: not enough information - // to create the constraint. - assertTrue(false); - } - + // Called via REGISTER_NARY() macro's factory rather than via the + // REGISTER_SWAP_TWO_VARS_NARY() macro's factory: not enough information + // to create the constraint. + assertTrue(false); + } + SwapTwoVarsConstraint(const LabelStr& name, const LabelStr& propagatorName, const ConstraintEngineId& constraintEngine, @@ -1094,27 +1127,6 @@ class SwapTwoVarsConstraint : public Constraint { CREATE_CONSTRAINT_TYPE(TestTwoSameNumericArgumentsCT, TestLEQCT, TestLEQ); - /** - * @brief Calculate the euclidean distance in 2-d space between between 2 points - */ - /** - * @brief Computes the sign of a given variable. Varable is in degrees. The constraint is a function - * rather than a relation. The range of the source variable must be in [0 90]. - */ - /** - * @brief SquareOfDifference(x, y, a) maintains the relation: - * @li a = (x - y)^2 - * if x and y are singleton. - */ - /** - * @brief DistanceFromSquaresConstraint(x, y, a) maintains the relation - * @li a = sqrt(x + y) - * if x and y are singleton - */ - /** - * @brief Maintains a unary relation from a constant to a variable such that the variable - * is a subset of the given constant. - */ class TestNEQ : public Constraint { public: TestNEQ(const LabelStr& name, @@ -1209,7 +1221,7 @@ class UnaryConstraint : public Constraint { void handleDiscard(); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); void setSource(const ConstraintId& sourceConstraint); diff --git a/src/PLASMA/ConstraintEngine/component/DataTypes.cc b/src/PLASMA/ConstraintEngine/component/DataTypes.cc index 078b0bebf..7448a6ba8 100644 --- a/src/PLASMA/ConstraintEngine/component/DataTypes.cc +++ b/src/PLASMA/ConstraintEngine/component/DataTypes.cc @@ -40,20 +40,20 @@ bool VoidDT::isNumeric() const { return false; } bool VoidDT::isBool() const { return false; } bool VoidDT::isString() const { return false; } -edouble VoidDT::createValue(const std::string& value) const +edouble VoidDT::createValue(const std::string&) const { check_error(ALWAYS_FAILS, "can't create void value"); return -1; } ConstrainedVariableId -VoidDT::createVariable(const ConstraintEngineId& constraintEngine, - const Domain& baseDomain, - const bool internal, - bool canBeSpecified, - const char* name, - const EntityId& parent, - int index) const +VoidDT::createVariable(const ConstraintEngineId&, + const Domain&, + const bool, + bool, + const char*, + const EntityId&, + unsigned int) const { check_error(ALWAYS_FAILS, "can't create void variable"); return ConstrainedVariableId::noId(); diff --git a/src/PLASMA/ConstraintEngine/component/DataTypes.hh b/src/PLASMA/ConstraintEngine/component/DataTypes.hh index e20f8ce25..e4cdaf8ab 100644 --- a/src/PLASMA/ConstraintEngine/component/DataTypes.hh +++ b/src/PLASMA/ConstraintEngine/component/DataTypes.hh @@ -29,7 +29,7 @@ public: bool canBeSpecified = true, const char* name = NO_VAR_NAME, const EntityId& parent = EntityId::noId(), - int index = ConstrainedVariable::NO_INDEX) const; + unsigned int index = ConstrainedVariable::NO_INDEX) const; static const std::string& NAME(); static const DataTypeId& instance(); diff --git a/src/PLASMA/ConstraintEngine/component/Domains.cc b/src/PLASMA/ConstraintEngine/component/Domains.cc index 3c68b5e0e..0339bf487 100644 --- a/src/PLASMA/ConstraintEngine/component/Domains.cc +++ b/src/PLASMA/ConstraintEngine/component/Domains.cc @@ -548,6 +548,8 @@ namespace EUROPA { os << "}"; } +void EnumeratedDomain::testPrecision(const edouble&) const {} + std::string EnumeratedDomain::toString() const { return Domain::toString(); @@ -669,11 +671,11 @@ namespace EUROPA { relax(dom.getLowerBound(), dom.getUpperBound()); } - void IntervalDomain::insert(edouble value) { + void IntervalDomain::insert(edouble) { check_error(ALWAYS_FAILS, "Cannot insert to an interval domain"); } - void IntervalDomain::insert(const std::list& values){ + void IntervalDomain::insert(const std::list&){ check_error(ALWAYS_FAILS, "Cannot insert to an interval domain"); } @@ -902,9 +904,9 @@ namespace EUROPA { else if (isSingleton()) // Need to test separately in case of rounding errors return(1); else if(isFinite()) - return(cast_int(m_ub - m_lb + 1)); + return static_cast(cast_int(m_ub - m_lb + 1)); else - return cast_int(PLUS_INFINITY); + return static_cast(cast_int(PLUS_INFINITY)); } void IntervalDomain::getValues(std::list& results) const { @@ -920,7 +922,7 @@ namespace EUROPA { } - void IntervalDomain::testPrecision(const edouble& value) const {} + void IntervalDomain::testPrecision(const edouble&) const {} void IntervalDomain::operator>>(ostream& os) const { Domain::operator>>(os); @@ -1020,17 +1022,17 @@ StringDomain::StringDomain(const std::list& values, const DataTypeId& void StringDomain::set(const std::string& value){ LabelStr lbl(value); - set((edouble) lbl); + set(static_cast(lbl)); } bool StringDomain::isMember(const std::string& value) const{ LabelStr lbl(value); - return isMember((edouble) lbl); + return isMember(static_cast(lbl)); } void StringDomain::insert(const std::string& value){ LabelStr lbl(value); - EnumeratedDomain::insert((edouble) lbl); + EnumeratedDomain::insert(static_cast(lbl)); } void StringDomain::insert(edouble value){ @@ -1088,7 +1090,7 @@ StringDomain::StringDomain(const std::list& values, const DataTypeId& void IntervalIntDomain::testPrecision(const edouble& value) const { #ifndef EUROPA_FAST eint::basis_type intValue = cast_int(value); - edouble::basis_type dblValue = (edouble::basis_type) intValue; + edouble::basis_type dblValue = static_cast(intValue); checkError(dblValue == value, value << " must be an integer."); // confirms no loss in precision #endif diff --git a/src/PLASMA/ConstraintEngine/component/Domains.hh b/src/PLASMA/ConstraintEngine/component/Domains.hh index 8d124fb6c..e566c5683 100644 --- a/src/PLASMA/ConstraintEngine/component/Domains.hh +++ b/src/PLASMA/ConstraintEngine/component/Domains.hh @@ -105,7 +105,7 @@ namespace EUROPA { /** * @brief Remove the given element form the domain. - * @param value. The value to be removed. If present, removal will generate a value removal event + * @param value The value to be removed. If present, removal will generate a value removal event * @see DomainListener::VALUE_REMOVED */ void remove(edouble value); @@ -127,14 +127,14 @@ namespace EUROPA { /** * @brief Indicates assigment to the target domain as a relaxation triggered internally. - * @param value the target singleton value. + * @param dom The target domain * @see relax */ void relax(const Domain& dom); /** * @brief Indicates relaxation to a singleton value. Occurs when domain has been emptied previously - * @param The value to relax to + * @param value The value to relax to */ void relax(edouble value); @@ -143,7 +143,7 @@ namespace EUROPA { * * This method is provided as a more efficient way to handle the common operation of equating 2 EnumeratedDomain domains. * Tackling changes to both domains at once allows us to take advantage of the sorted order of the domains. - * @param The domain to be equated with this object. It may change. + * @param dom The domain to be equated with this object. It may change. * @return true if a change to either domain has occurred. * @see DomainListener::EMPTIED, DomainListener::SET_TO_SINGLETON, DomainListener::VALUE_REMOVED */ @@ -258,7 +258,7 @@ namespace EUROPA { /** * @brief test if the intersection between this domain and the given domain is empty * @param dom the domain tested against. - * @param true if any elements of this domain are in dom. Otherwise false. + * @return true if any elements of this domain are in dom. Otherwise false. */ bool intersects(const Domain& dom) const; @@ -281,7 +281,7 @@ namespace EUROPA { * @note Will be compiled out for fast version. * @note No-op for enumerations. */ - virtual void testPrecision(const edouble& value) const {} + virtual void testPrecision(const edouble& value) const; /** * @brief Implements equate where both are closed enumerations @@ -299,7 +299,7 @@ namespace EUROPA { * * @todo Possible additions: support for open ended intervals and multiple intervals, * preferably as new classes rather than impacting the performance of this class. - * --wedgingt@email.arc.nasa.gov 2004 Feb 26 + * --wedgingt 2004 Feb 26 */ class IntervalDomain : public Domain { public: @@ -360,7 +360,7 @@ namespace EUROPA { /** * @brief Indicates assigment to the target domain as a relaxation triggered externally. - * @param value the target singleton value. + * @param dom the target singleton domain. * @see relax */ void reset(const Domain& dom); @@ -437,7 +437,7 @@ namespace EUROPA { /** * @brief Remove the given element form the domain. - * @param value. The value to be removed. + * @param value The value to be removed. * @note If the value was in the domain, this call will generate a * value removal event. * @note An error for real intervals unless not in the set or was @@ -491,14 +491,14 @@ namespace EUROPA { /** * @brief Test if this domain is a subset of dom. * @param dom the domain tested against. - * @param true if all elements of this domain are in dom, otherwise false. + * @return true if all elements of this domain are in dom, otherwise false. */ bool isSubsetOf(const Domain& dom) const; /** * @brief Test if the intersection between this domain and the given domain is empty. * @param dom the domain tested against. - * @param true if any elements of this domain are in dom, otherwise false. + * @return true if any elements of this domain are in dom, otherwise false. */ bool intersects(const Domain& dom) const; @@ -591,6 +591,7 @@ namespace EUROPA { bool isMember(const std::string& value) const; void insert(const std::string& value); void insert(edouble value); + void insert(const std::list& values) {EnumeratedDomain::insert(values);} }; /** diff --git a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc index a404c95be..b38e2f9a8 100644 --- a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc +++ b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.cc @@ -82,7 +82,7 @@ namespace EUROPA{ m_requiresUpdate = true; } - int EquivalenceClassCollection::getGraphCount(){ +unsigned long EquivalenceClassCollection::getGraphCount(){ recomputeIfNecessary(); return m_graphsByKey.size(); } diff --git a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh index e0fc73de0..ac77c377f 100644 --- a/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh +++ b/src/PLASMA/ConstraintEngine/component/EquivalenceClassCollection.hh @@ -90,7 +90,7 @@ namespace EUROPA{ void removeConnection(const ConstrainedVariableId& v1, const ConstrainedVariableId& v2); bool updateRequired() const {return m_requiresUpdate;} - int getGraphCount(); + unsigned long getGraphCount(); int getGraphKey(const ConstrainedVariableId& variable); void getGraphKeys(std::set& keys); const std::set& getGraphVariables(int key) const; diff --git a/src/PLASMA/ConstraintEngine/component/Propagators.cc b/src/PLASMA/ConstraintEngine/component/Propagators.cc index f1ed85953..88b618a4e 100644 --- a/src/PLASMA/ConstraintEngine/component/Propagators.cc +++ b/src/PLASMA/ConstraintEngine/component/Propagators.cc @@ -48,7 +48,7 @@ namespace EUROPA { } void DefaultPropagator::handleNotification(const ConstrainedVariableId& variable, - int argIndex, + unsigned int, const ConstraintId& constraint, const DomainListener::ChangeType& changeType){ checkError(!constraint->isDiscarded(), constraint); @@ -165,9 +165,9 @@ namespace EUROPA { } void EqualityConstraintPropagator::handleNotification(const ConstrainedVariableId& variable, - int argIndex, + unsigned int, const ConstraintId& constraint, - const DomainListener::ChangeType& changeType){ + const DomainListener::ChangeType&){ check_error(Id::convertable(constraint)); if(!m_fullReprop && !m_active){ @@ -178,61 +178,63 @@ namespace EUROPA { } } - void processScope(const std::set& scope) { - Domain& domain(EqualConstraint::getCurrentDomain(* (scope.begin()))); +namespace { +void processScope(const std::set& scope) { + Domain& domain(EqualConstraint::getCurrentDomain(* (scope.begin()))); - if (domain.isOpen()) + if (domain.isOpen()) + return; + + // Set up the initial values to match others against. + bool isFinite = domain.isFinite(); + + // int domainType = domain.getType(); // Unused; see below. + + // Iterate over, restricting domain as we go. + for (std::set::const_iterator it = scope.begin(); + it != scope.end(); ++it) { + Domain& currentDomain = EqualConstraint::getCurrentDomain(*it); + + // This next check is incorrect: could be false when they can be + // compared (real enumerations and integer intervals, e.g.) and + // could be true when they cannot be compared (e.g., two distinct + // label sets, which both have a DomainType of USER_DEFINED). + // The correct check follows. + // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 21 + // check_error(currentDomain.getType() == domainType); + + check_error(Domain::canBeCompared(domain, currentDomain)); + + // This will preclude possible propagation to the point of allowing + // an arbitrary amount of useless search during planning, including + // not even intersecting with closed domains later in the scope. + // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 21 + if (currentDomain.isOpen()) return; - // Set up the initial values to match others against. - bool isFinite = domain.isFinite(); - - // int domainType = domain.getType(); // Unused; see below. - - // Iterate over, restricting domain as we go. - for (std::set::const_iterator it = scope.begin(); - it != scope.end(); ++it) { - Domain& currentDomain = EqualConstraint::getCurrentDomain(*it); - - // This next check is incorrect: could be false when they can be - // compared (real enumerations and integer intervals, e.g.) and - // could be true when they cannot be compared (e.g., two distinct - // label sets, which both have a DomainType of USER_DEFINED). - // The correct check follows. - // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 21 - // check_error(currentDomain.getType() == domainType); - - check_error(Domain::canBeCompared(domain, currentDomain)); - - // This will preclude possible propagation to the point of allowing - // an arbitrary amount of useless search during planning, including - // not even intersecting with closed domains later in the scope. - // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 21 - if (currentDomain.isOpen()) - return; - - // What if the domains are (numeric) [-Inf Inf] and (integer) [0 1] ? - // This would appear to incorrectly provoke an inconsistency in that case. - // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 22 - // - //I don't even know what this is supposed to express. It seems wrong in every case. - //I'm adding parens here in the most sensible-ish place to quiet a warning. ~MJI - if ((currentDomain.isFinite() != isFinite || - domain.intersect(currentDomain)) && domain.isEmpty()) { - currentDomain.empty(); - return; - } + // What if the domains are (numeric) [-Inf Inf] and (integer) [0 1] ? + // This would appear to incorrectly provoke an inconsistency in that case. + // --wedgingt@ptolemy.arc.nasa.gov 2004 Apr 22 + // + //I don't even know what this is supposed to express. It seems wrong in every case. + //I'm adding parens here in the most sensible-ish place to quiet a warning. ~MJI + if ((currentDomain.isFinite() != isFinite || + domain.intersect(currentDomain)) && domain.isEmpty()) { + currentDomain.empty(); + return; } + } - // If we get to here, we have computed the new domain for all - // variables in the scope and we know that no domain has been - // emptied (this could be optimized by recording the last change - // to domain). - for (std::set::const_iterator it = scope.begin(); it != scope.end(); ++it) { - Domain& currentDomain = EqualConstraint::getCurrentDomain(*it); - currentDomain.intersect(domain); - } + // If we get to here, we have computed the new domain for all + // variables in the scope and we know that no domain has been + // emptied (this could be optimized by recording the last change + // to domain). + for (std::set::const_iterator it = scope.begin(); it != scope.end(); ++it) { + Domain& currentDomain = EqualConstraint::getCurrentDomain(*it); + currentDomain.intersect(domain); } +} +} void EqualityConstraintPropagator::equate(const std::set& scope) { check_error(!scope.empty()); diff --git a/src/PLASMA/ConstraintEngine/component/Propagators.hh b/src/PLASMA/ConstraintEngine/component/Propagators.hh index 69c902638..7faf83dbb 100644 --- a/src/PLASMA/ConstraintEngine/component/Propagators.hh +++ b/src/PLASMA/ConstraintEngine/component/Propagators.hh @@ -27,7 +27,7 @@ namespace EUROPA { virtual void handleConstraintActivated(const ConstraintId& constrain); virtual void handleConstraintDeactivated(const ConstraintId& constraint); virtual void handleNotification(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const ConstraintId& constraint, const DomainListener::ChangeType& changeType); @@ -74,7 +74,7 @@ namespace EUROPA { void handleConstraintDeactivated(const ConstraintId& constraint); void handleNotification(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const ConstraintId& constraint, const DomainListener::ChangeType& changeType); diff --git a/src/PLASMA/ConstraintEngine/component/Variable.hh b/src/PLASMA/ConstraintEngine/component/Variable.hh index 229bdee7c..7c50797c6 100644 --- a/src/PLASMA/ConstraintEngine/component/Variable.hh +++ b/src/PLASMA/ConstraintEngine/component/Variable.hh @@ -38,7 +38,7 @@ namespace EUROPA { bool canBeSpecified = true, const LabelStr& name = ConstrainedVariable::NO_NAME(), const EntityId& parent = EntityId::noId(), - int index = ConstrainedVariable::NO_INDEX); + unsigned long index = ConstrainedVariable::NO_INDEX); /** * Destructor. @@ -112,7 +112,7 @@ namespace EUROPA { bool canBeSpecified, const LabelStr& name, const EntityId& parent, - int index) + unsigned long index) : ConstrainedVariable(constraintEngine, internal, canBeSpecified, name, parent, index), m_baseDomain(static_cast(baseDomain.copy())), m_derivedDomain(static_cast(baseDomain.copy())) { diff --git a/src/PLASMA/NDDL/NddlDefs.hh b/src/PLASMA/NDDL/NddlDefs.hh index b64db8bde..13bb31953 100644 --- a/src/PLASMA/NDDL/NddlDefs.hh +++ b/src/PLASMA/NDDL/NddlDefs.hh @@ -3,20 +3,20 @@ #include "RulesEngineDefs.hh" -using namespace EUROPA; +namespace EUROPA { +class ObjectFilterConstraint; +typedef Id ObjectFilterConstraintId; -namespace NDDL { - - class NddlToken; - typedef Id NddlTokenId; +class ObjectFilterCondition; +typedef Id ObjectFilterConditionId; +} - class ObjectFilterConstraint; - typedef Id ObjectFilterConstraintId; +namespace NDDL { - class ObjectFilterCondition; - typedef Id ObjectFilterConditionId; +class NddlToken; +typedef EUROPA::Id NddlTokenId; - #define inf PLUS_INFINITY +#define inf PLUS_INFINITY } // namespace NDDL diff --git a/src/PLASMA/NDDL/base/NddlRules.cc b/src/PLASMA/NDDL/base/NddlRules.cc index b881358f5..7db73389b 100644 --- a/src/PLASMA/NDDL/base/NddlRules.cc +++ b/src/PLASMA/NDDL/base/NddlRules.cc @@ -8,6 +8,7 @@ * @author Conor McGann * @date December, 2004 */ +using namespace EUROPA; namespace NDDL { /** diff --git a/src/PLASMA/NDDL/base/NddlRules.hh b/src/PLASMA/NDDL/base/NddlRules.hh index 8a0aaf918..7d80bf6b9 100644 --- a/src/PLASMA/NDDL/base/NddlRules.hh +++ b/src/PLASMA/NDDL/base/NddlRules.hh @@ -29,12 +29,14 @@ namespace NDDL { /** * @brief Function to detokenize a delimited list into a list. */ - std::list listFromString(const std::string& str, bool isNumeric); +std::list listFromString(const std::string& str, bool isNumeric); /** * @brief Function to allocate a token on the same object as the master */ - TokenId allocateOnSameObject(const TokenId& parent, const LabelStr& predicateSuffix, const LabelStr& relationToMaster); +EUROPA::TokenId allocateOnSameObject(const EUROPA::TokenId& parent, + const EUROPA::LabelStr& predicateSuffix, + const EUROPA::LabelStr& relationToMaster); /** * Macro declaration and definition for the Rule which provides a factory diff --git a/src/PLASMA/NDDL/base/NddlToken.cc b/src/PLASMA/NDDL/base/NddlToken.cc index 72cbfdae2..88b732160 100644 --- a/src/PLASMA/NDDL/base/NddlToken.cc +++ b/src/PLASMA/NDDL/base/NddlToken.cc @@ -1,6 +1,8 @@ #include "NddlToken.hh" #include "Utils.hh" #include "Object.hh" + +using namespace EUROPA; namespace NDDL { NddlToken::NddlToken(const PlanDatabaseId& planDatabase, const LabelStr& predicateName, const bool& rejectable, const bool& isFact, const bool& close) diff --git a/src/PLASMA/NDDL/base/NddlToken.hh b/src/PLASMA/NDDL/base/NddlToken.hh index 55a39087c..49b4710f9 100644 --- a/src/PLASMA/NDDL/base/NddlToken.hh +++ b/src/PLASMA/NDDL/base/NddlToken.hh @@ -17,19 +17,24 @@ namespace NDDL { * @brief Constructor for goal tokens. * @see PLASMA::IntervalToken */ - NddlToken(const PlanDatabaseId& planDatabase, const LabelStr& predicateName, const bool& rejectable = false, const bool& isFact = false, const bool& close = false); + NddlToken(const EUROPA::PlanDatabaseId& planDatabase, + const EUROPA::LabelStr& predicateName, + const bool& rejectable = false, const bool& isFact = false, + const bool& close = false); /** * @brief Constructor for subgoal tokens. * @see PLASMA::IntervalToken */ - NddlToken(const TokenId& master, const LabelStr& predicateName, const LabelStr& relation, const bool& close = false); - - StateVarId state; /** - ConstrainedVariableId allocateVariable(const ConstraintEngineId& ce, - std::vector& vars, + EUROPA::ConstrainedVariableId allocateVariable(const EUROPA::ConstraintEngineId& ce, + std::vector& vars, const ELEMENT_TYPE& domain, - const EntityId& parent){ + const EUROPA::EntityId& parent){ + using namespace EUROPA; std::stringstream sstr; sstr << "PSEDUO_VARIABLE_" << vars.size(); ConstrainedVariableId var = (new Variable< ELEMENT_TYPE >(ce, @@ -41,9 +42,9 @@ namespace NDDL { /** * Should all be moved to the rule instance class. */ - TokenId tok(const RuleInstanceId& rule, const std::string name) ; - ConstrainedVariableId var(const RuleInstanceId& entity, const std::string name) ; - ConstrainedVariableId var(const TokenId& entity, const std::string name) ; +EUROPA::TokenId tok(const EUROPA::RuleInstanceId& rule, const std::string name) ; +EUROPA::ConstrainedVariableId var(const EUROPA::RuleInstanceId& entity, const std::string name) ; +EUROPA::ConstrainedVariableId var(const EUROPA::TokenId& entity, const std::string name) ; } diff --git a/src/PLASMA/NDDL/component/Interpreter.cc b/src/PLASMA/NDDL/component/Interpreter.cc index a42c6db71..032a0cb66 100644 --- a/src/PLASMA/NDDL/component/Interpreter.cc +++ b/src/PLASMA/NDDL/component/Interpreter.cc @@ -32,53 +32,56 @@ namespace EUROPA { - // TODO: keep using pdbClient? - const DbClientId& getPDB(EvalContext& context) - { - // TODO: Add this behavior to EvalContext instead? - DbClient* dbClient = (DbClient*)context.getElement("DbClient"); - if (dbClient != NULL) - return dbClient->getId(); - - PlanDatabase* pdb = (PlanDatabase*)context.getElement("PlanDatabase"); - check_error(pdb != NULL,"Could not find Plan Database in eval context"); - return pdb->getClient(); - } - - const SchemaId& getSchema(EvalContext& context) - { - /* TODO why doesn't this work??? - Schema* schema = (Schema*)context.getElement("Schema"); - check_error(schema != NULL,"Could not find Schema in eval context"); - return schema->getId(); - */ - return getPDB(context)->getSchema(); - } - - // TODO: move this to the eval contexts to make it cleaner - void makeConstraint(EvalContext& context, - const LabelStr& name, - const std::vector& vars, - const char* violationExpl) - { - PlanDatabase* pdb = (PlanDatabase*)(context.getElement("PlanDatabase")); - ConstraintId c = pdb->getClient()->createConstraint(name.c_str(), vars, violationExpl); - debugMsg("Interpreter","Added Constraint : " << c->toString()); +namespace { +// TODO: keep using pdbClient? +const DbClientId& getPDB(EvalContext& context) +{ + // TODO: Add this behavior to EvalContext instead? + DbClient* dbClient = reinterpret_cast(context.getElement("DbClient")); + if (dbClient != NULL) + return dbClient->getId(); + + PlanDatabase* pdb = reinterpret_cast(context.getElement("PlanDatabase")); + check_error(pdb != NULL,"Could not find Plan Database in eval context"); + return pdb->getClient(); +} - InterpretedRuleInstance* rule = (InterpretedRuleInstance*)(context.getElement("RuleInstance")); - if (rule != NULL) { - rule->addConstraint(c); - debugMsg("Interpreter:InterpretedRule","Added Constraint : " << c->toString()); - return; - } +const SchemaId& getSchema(EvalContext& context) +{ + /* TODO why doesn't this work??? + Schema* schema = (Schema*)context.getElement("Schema"); + check_error(schema != NULL,"Could not find Schema in eval context"); + return schema->getId(); + */ + return getPDB(context)->getSchema(); +} - Token* t = (Token*)(context.getElement("Token")); - if (t != NULL) { - t->addStandardConstraint(c); - debugMsg("Interpreter:InterpretedToken","Added Constraint : " << c->toString()); - return; - } +// TODO: move this to the eval contexts to make it cleaner +void makeConstraint(EvalContext& context, + const LabelStr& name, + const std::vector& vars, + const char* violationExpl) +{ + PlanDatabase* pdb = reinterpret_cast(context.getElement("PlanDatabase")); + ConstraintId c = pdb->getClient()->createConstraint(name.c_str(), vars, violationExpl); + debugMsg("Interpreter","Added Constraint : " << c->toString()); + + InterpretedRuleInstance* rule = + reinterpret_cast(context.getElement("RuleInstance")); + if (rule != NULL) { + rule->addConstraint(c); + debugMsg("Interpreter:InterpretedRule","Added Constraint : " << c->toString()); + return; + } + + Token* t = reinterpret_cast(context.getElement("Token")); + if (t != NULL) { + t->addStandardConstraint(c); + debugMsg("Interpreter:InterpretedToken","Added Constraint : " << c->toString()); + return; } +} +} /* @@ -100,13 +103,14 @@ namespace EUROPA { return m_domain->getDataType(); } - std::string getAutoName(const char* prefix) - { - static int cnt = 0; - std::stringstream sstr; - sstr << prefix << ++cnt; - return sstr.str(); - } +namespace { +std::string getAutoName(const char* prefix) { + static int cnt = 0; + std::stringstream sstr; + sstr << prefix << ++cnt; + return sstr.str(); +} +} DataRef ExprConstant::eval(EvalContext& context) const { @@ -473,11 +477,13 @@ namespace EUROPA { } } - bool isTimepoint(DataRef var) { - ConstrainedVariable *cvar = var.getValue(); - return dynamic_cast< TokenVariable* >(cvar) != NULL +namespace { +bool isTimepoint(DataRef var) { + ConstrainedVariable *cvar = var.getValue(); + return dynamic_cast< TokenVariable* >(cvar) != NULL && (cvar->getName().toString() == "end" || cvar->getName().toString() == "start"); - } +} +} bool CExprBinary::isSingleton() { return false; @@ -649,156 +655,142 @@ namespace EUROPA { m_args.clear(); } - std::string varsToString(const std::vector& vars) - { - std::ostringstream os; - for (unsigned int i=0; i < vars.size(); i++) { - if (i>0) os << ","; - os << vars[i]->toString(); - } - - return os.str(); +DataRef ExprConstraint::eval(EvalContext& context) const +{ + std::vector vars; + for (unsigned int i=0; i < m_args.size(); i++) { + DataRef arg = m_args[i]->eval(context); + vars.push_back(arg.getValue()); } - DataRef ExprConstraint::eval(EvalContext& context) const - { - std::vector vars; - for (unsigned int i=0; i < m_args.size(); i++) { - DataRef arg = m_args[i]->eval(context); - vars.push_back(arg.getValue()); - } + makeConstraint(context,m_name,vars,m_violationExpl.c_str()); - makeConstraint(context,m_name,vars,m_violationExpl.c_str()); + return DataRef::null; +} - return DataRef::null; - } +std::string ExprConstraint::toString() const +{ + std::stringstream os; - std::string ExprConstraint::toString() const - { - std::stringstream os; + os << "{CONSTRAINT:" << m_name.c_str() << " ("; - os << "{CONSTRAINT:" << m_name.c_str() << " ("; + for (unsigned int i=0;itoString() << " "; + os << ") " << m_violationExpl << "}"; - for (unsigned int i=0;itoString() << " "; - os << ") " << m_violationExpl << "}"; + return os.str(); +} - return os.str(); - } +namespace { +bool isClass(EvalContext& ctx,const LabelStr& className) { + return getSchema(ctx)->isObjectType(className); +} - bool isClass(EvalContext& ctx,const LabelStr& className) - { - return getSchema(ctx)->isObjectType(className); - } // see ModelAccessor.isConstrained in Nddl compiler - bool isConstrained(EvalContext& context, const LabelStr& predicateInstance) - { - unsigned int tokenCnt = predicateInstance.countElements("."); +bool isConstrained(EvalContext& context, const LabelStr& predicateInstance){ + unsigned long tokenCnt = predicateInstance.countElements("."); - // If the predicate is not qualified that means it belongs to the object in scope - if (tokenCnt == 1) - return true; + // If the predicate is not qualified that means it belongs to the object in scope + if (tokenCnt == 1) + return true; - // If the prefix is a class, it means it can be any object instance, so it must not be constrained - LabelStr prefix(predicateInstance.getElement(0,".")); - if (!isClass(context,prefix)) - return true; + // If the prefix is a class, it means it can be any object instance, so it must not be constrained + LabelStr prefix(predicateInstance.getElement(0,".")); + if (!isClass(context,prefix)) + return true; - return false; - } + return false; +} - LabelStr checkPredicateType(EvalContext& ctx,const LabelStr& type) - { - check_runtime_error(getSchema(ctx)->isPredicate(type),type.toString()+" is not a Type"); - return type; - } +LabelStr checkPredicateType(EvalContext& ctx,const LabelStr& type) { + check_runtime_error(getSchema(ctx)->isPredicate(type),type.toString()+" is not a Type"); + return type; +} - LabelStr getObjectVarClass(EvalContext& ctx,const LabelStr& className,const LabelStr& var) - { +LabelStr getObjectVarClass(EvalContext& ctx,const LabelStr& className,const LabelStr& var) { + const SchemaId& schema = getSchema(ctx); + check_runtime_error(schema->hasMember(className,var),className.toString()+" has no member called "+var.toString()); + return schema->getMemberType(className,var); +} + +LabelStr getTokenVarClass(EvalContext& ctx,const LabelStr& className,const LabelStr& predName,const LabelStr& var){ + if (strcmp(var.c_str(),"object") == 0) // is it the object variable? + return className; + else { // look through the parameters to the token const SchemaId& schema = getSchema(ctx); - check_runtime_error(schema->hasMember(className,var),className.toString()+" has no member called "+var.toString()); - return schema->getMemberType(className,var); + if (schema->hasMember(predName,var)) + return schema->getMemberType(predName,var); } - LabelStr getTokenVarClass(EvalContext& ctx,const LabelStr& className,const LabelStr& predName,const LabelStr& var) - { - if (strcmp(var.c_str(),"object") == 0) // is it the object variable? - return className; - else { // look through the parameters to the token - const SchemaId& schema = getSchema(ctx); - if (schema->hasMember(predName,var)) - return schema->getMemberType(predName,var); - } - - // if everything else fails, see if it's an object member - return getObjectVarClass(ctx,className,var); - } + // if everything else fails, see if it's an object member + return getObjectVarClass(ctx,className,var); +} /* * figures out the type of a predicate given an instance * */ - LabelStr predicateInstanceToType( - EvalContext& ctx, - const char* predicateName, - const char* predicateInstance) - { - // see ModelAccessor.getSlaveObjectType() in NDDL compiler - ConstrainedVariableId obj = ctx.getVar("object"); - check_error(obj.isId(),"Failed to find 'object' var in predicateInstanceToType()"); - const char* className = obj->baseDomain().getTypeName().c_str(); - LabelStr str(predicateInstance); - - unsigned int tokenCnt = str.countElements("."); - - if (tokenCnt == 1) { - std::string retval = std::string(className)+"."+predicateInstance; - return checkPredicateType(ctx,LabelStr(retval)); - } - else if (tokenCnt == 2) { - LabelStr prefix(str.getElement(0,".")); - LabelStr suffix(str.getElement(1,".")); - - if (prefix.toString() == "object") { - std::string retval = std::string(className)+"."+suffix.toString(); - return checkPredicateType(ctx,LabelStr(retval.c_str())); - } - else if (isClass(ctx,prefix)) { - return checkPredicateType(ctx,LabelStr(predicateInstance)); - } - else { - ConstrainedVariableId var = ctx.getVar(prefix.c_str()); - if (var.isId()) { - std::string clazz = var->baseDomain().getTypeName().c_str(); - return checkPredicateType(ctx,clazz+"."+suffix.toString()); - } - else { - LabelStr clazz = getTokenVarClass(ctx,className,predicateName,prefix); - std::string retval = clazz.toString()+"."+suffix.toString(); - return checkPredicateType(ctx,LabelStr(retval.c_str())); - } - } +LabelStr predicateInstanceToType( + EvalContext& ctx, + const char* predicateName, + const char* predicateInstance){ + // see ModelAccessor.getSlaveObjectType() in NDDL compiler + ConstrainedVariableId obj = ctx.getVar("object"); + check_error(obj.isId(),"Failed to find 'object' var in predicateInstanceToType()"); + const char* className = obj->baseDomain().getTypeName().c_str(); + LabelStr str(predicateInstance); + + unsigned long tokenCnt = str.countElements("."); + + if (tokenCnt == 1) { + std::string retval = std::string(className)+"."+predicateInstance; + return checkPredicateType(ctx,LabelStr(retval)); + } + else if (tokenCnt == 2) { + LabelStr prefix(str.getElement(0,".")); + LabelStr suffix(str.getElement(1,".")); + + if (prefix.toString() == "object") { + std::string retval = std::string(className)+"."+suffix.toString(); + return checkPredicateType(ctx,LabelStr(retval.c_str())); + } + else if (isClass(ctx,prefix)) { + return checkPredicateType(ctx,LabelStr(predicateInstance)); + } + else { + ConstrainedVariableId var = ctx.getVar(prefix.c_str()); + if (var.isId()) { + std::string clazz = var->baseDomain().getTypeName().c_str(); + return checkPredicateType(ctx,clazz+"."+suffix.toString()); } else { - LabelStr var = str.getElement(0,"."); - LabelStr clazz; - ConstrainedVariableId v = ctx.getVar(var.c_str()); - if (v.isId()) - clazz = v->baseDomain().getTypeName().c_str(); - else - clazz = getTokenVarClass(ctx,className,predicateName,var); + LabelStr clazz = getTokenVarClass(ctx,className,predicateName,prefix); + std::string retval = clazz.toString()+"."+suffix.toString(); + return checkPredicateType(ctx,LabelStr(retval.c_str())); + } + } + } + else { + LabelStr var = str.getElement(0,"."); + LabelStr clazz; + ConstrainedVariableId v = ctx.getVar(var.c_str()); + if (v.isId()) + clazz = v->baseDomain().getTypeName().c_str(); + else + clazz = getTokenVarClass(ctx,className,predicateName,var); - for (unsigned int i=1;iaddAttributes(m_attributes); - } - else - result = createGlobalToken(context, isFact, isRejectable); - } - - //TODO: In the future, this might be a hook into the NDDL error reporting system. - checkError(result != TokenId() && result.isId(), "Error, no token " << m_predicateInstance << " " - << m_predicateName << " in relation: " << relationName << "."); - return result; +TokenId PredicateInstanceRef::getToken(EvalContext& context, const char* relationName, bool isFact, bool isRejectable) +{ + TokenId result; + if (m_predicateInstance.length() == 0) { + result = context.getToken(m_predicateName.c_str()); + } + else { + InterpretedRuleInstance* rule = reinterpret_cast(context.getElement("RuleInstance")); + if (rule != NULL) { + result = createSubgoal(context,rule,relationName); + result->addAttributes(m_attributes); + } + else + result = createGlobalToken(context, isFact, isRejectable); } + //TODO: In the future, this might be a hook into the NDDL error reporting system. + checkError(result != TokenId() && result.isId(), "Error, no token " << m_predicateInstance << " " + << m_predicateName << " in relation: " << relationName << "."); + return result; +} + TokenId PredicateInstanceRef::createGlobalToken(EvalContext& context, bool isFact, bool isRejectable) { debugMsg("Interpreter:createToken", "creating Token:" << m_predicateInstance << " " << m_predicateName); @@ -872,38 +864,38 @@ namespace EUROPA { return token; } - TokenId PredicateInstanceRef::createSubgoal(EvalContext& context, InterpretedRuleInstance* rule, const char* relationName) - { - // TODO: cache this? new parser is able to pass this in, do it when nddl-xml is gone. - LabelStr predicateType = predicateInstanceToType(context,m_predicateName.c_str(),m_predicateInstance.c_str()); - debugMsg("Interpreter:InterpretedRule","Creating subgoal " << predicateType.c_str() << ":" << m_predicateName); +TokenId PredicateInstanceRef::createSubgoal(EvalContext& context, InterpretedRuleInstance* rule, const char* relationName) +{ + // TODO: cache this? new parser is able to pass this in, do it when nddl-xml is gone. + LabelStr predicateType = predicateInstanceToType(context,m_predicateName.c_str(),m_predicateInstance.c_str()); + debugMsg("Interpreter:InterpretedRule","Creating subgoal " << predicateType.c_str() << ":" << m_predicateName); - LabelStr predicateName(m_predicateName); // TODO: auto-generate name if not provided? - LabelStr predicateInstance(m_predicateInstance); - bool constrained = isConstrained(context,predicateInstance); - ConstrainedVariableId owner; - if (constrained) { - unsigned int tokenCnt = predicateInstance.countElements("."); - if (tokenCnt == 1) - owner = context.getVar("object"); - else - owner = context.getVar(predicateInstance.getElement(0,".").c_str()); - } + LabelStr predicateName(m_predicateName); // TODO: auto-generate name if not provided? + LabelStr predicateInstance(m_predicateInstance); + bool constrained = isConstrained(context,predicateInstance); + ConstrainedVariableId owner; + if (constrained) { + unsigned long tokenCnt = predicateInstance.countElements("."); + if (tokenCnt == 1) + owner = context.getVar("object"); + else + owner = context.getVar(predicateInstance.getElement(0,".").c_str()); + } - TokenId slave = rule->createSubgoal( - predicateName, - predicateType, - predicateInstance, - relationName, - constrained, - owner - ); + TokenId slave = rule->createSubgoal( + predicateName, + predicateType, + predicateInstance, + relationName, + constrained, + owner + ); - context.addToken(predicateName.c_str(),slave); - debugMsg("Interpreter:InterpretedRule","Created subgoal " << predicateType.toString() << ":" << m_predicateName); + context.addToken(predicateName.c_str(),slave); + debugMsg("Interpreter:InterpretedRule","Created subgoal " << predicateType.toString() << ":" << m_predicateName); - return slave; - } + return slave; +} int PredicateInstanceRef::getAttributes( ) const { @@ -955,7 +947,7 @@ namespace EUROPA { #define makeStrictPrecedenceRelation(origin, originvar, target, targetvar) { \ - PlanDatabase* db = (PlanDatabase*)(context.getElement("PlanDatabase"));\ + PlanDatabase* db = reinterpret_cast(context.getElement("PlanDatabase"));\ std::vector vars; \ ConstrainedVariableId var = (new Variable(db->getConstraintEngine(), IntervalIntDomain(1, PLUS_INFINITY)))->getId(); \ vars.push_back(origin->originvar()); \ @@ -964,92 +956,93 @@ namespace EUROPA { makeConstraint(context, "temporalDistance", vars, NULL); \ } - void createRelation(EvalContext& context, - const char* relationName, - TokenId origin, - TokenId target) - { - // Allen Relations according to EUROPA - // See ConstraintLibraryReference on the wiki - if (strcmp(relationName,"meets") == 0) { - makeRelation(concurrent, origin, end, target, start); - } - else if (strcmp(relationName,"met_by") == 0) { - makeRelation(concurrent, target, end, origin, start); - } - else if (strcmp(relationName,"contains") == 0) { - makeRelation(precedes, origin, start, target, start); - makeRelation(precedes, target, end, origin, end); - makeRelation(leq, target, duration, origin, duration); - } - else if (strcmp(relationName,"contained_by") == 0) { - makeRelation(precedes, target, start, origin, start); - makeRelation(precedes, origin, end, target, end); - makeRelation(leq, origin, duration, target, duration); - } - else if (strcmp(relationName,"before") == 0) { - makeRelation(precedes, origin, end, target, start); - } - else if (strcmp(relationName,"after") == 0) { - makeRelation(precedes, target, end, origin, start); - } - else if (strcmp(relationName,"starts") == 0) { - makeRelation(concurrent, origin, start, target, start); - } - else if (strcmp(relationName,"ends") == 0) { - makeRelation(concurrent, target, end, origin, end); - } - else if (strcmp(relationName, "parallels") == 0) { - makeRelation(precedes, origin, start, target, start); - makeRelation(precedes, origin, end, target, end); - } - else if (strcmp(relationName, "paralleled_by") == 0) { - makeRelation(precedes, target, start, origin, start); - makeRelation(precedes, target, end, origin, end); - } - else if (strcmp(relationName,"ends_after") == 0) { - makeStrictPrecedenceRelation(target, end, origin, end); - } - else if (strcmp(relationName,"ends_before") == 0) { - makeStrictPrecedenceRelation(origin, end, target, end); - } - else if (strcmp(relationName,"ends_after_start") == 0) { - makeStrictPrecedenceRelation(target, start, origin, end); - } - else if (strcmp(relationName,"starts_before_end") == 0) { - makeStrictPrecedenceRelation(origin, start, target, end); - } - else if (strcmp(relationName,"starts_during") == 0) { - makeRelation(precedes, target, start, origin, start); - makeStrictPrecedenceRelation(origin, start, target, end); - } - else if (strcmp(relationName,"ends_during") == 0) { - makeStrictPrecedenceRelation(target, start, origin, end); - makeRelation(precedes, origin, end, target, end); - } - else if (strcmp(relationName,"contains_start") == 0) { - makeRelation(precedes, origin, start, target, start); - makeStrictPrecedenceRelation(target, start, origin, end); - } - else if (strcmp(relationName,"contains_end") == 0) { - makeStrictPrecedenceRelation(origin, start, target, end); - makeRelation(precedes, origin, end, target, end); - } - else if (strcmp(relationName,"starts_after") == 0) { - makeStrictPrecedenceRelation(target, start, origin, start); - } - else if (strcmp(relationName,"starts_before") == 0) { - makeStrictPrecedenceRelation(origin, start, target, start); - } - else if (strcmp(relationName,"equals") == 0) { - makeRelation(concurrent, origin, start, target, start); - makeRelation(concurrent, target, end, origin, end); - makeRelation(eq, origin, duration, target, duration); - } - else { - check_runtime_error(strcmp(relationName,"any") == 0,std::string("Unrecognized relation:")+relationName); - } +namespace { +void createRelation(EvalContext& context, + const char* relationName, + TokenId origin, + TokenId target) { + // Allen Relations according to EUROPA + // See ConstraintLibraryReference on the wiki + if (strcmp(relationName,"meets") == 0) { + makeRelation(concurrent, origin, end, target, start); + } + else if (strcmp(relationName,"met_by") == 0) { + makeRelation(concurrent, target, end, origin, start); + } + else if (strcmp(relationName,"contains") == 0) { + makeRelation(precedes, origin, start, target, start); + makeRelation(precedes, target, end, origin, end); + makeRelation(leq, target, duration, origin, duration); + } + else if (strcmp(relationName,"contained_by") == 0) { + makeRelation(precedes, target, start, origin, start); + makeRelation(precedes, origin, end, target, end); + makeRelation(leq, origin, duration, target, duration); + } + else if (strcmp(relationName,"before") == 0) { + makeRelation(precedes, origin, end, target, start); + } + else if (strcmp(relationName,"after") == 0) { + makeRelation(precedes, target, end, origin, start); + } + else if (strcmp(relationName,"starts") == 0) { + makeRelation(concurrent, origin, start, target, start); + } + else if (strcmp(relationName,"ends") == 0) { + makeRelation(concurrent, target, end, origin, end); + } + else if (strcmp(relationName, "parallels") == 0) { + makeRelation(precedes, origin, start, target, start); + makeRelation(precedes, origin, end, target, end); + } + else if (strcmp(relationName, "paralleled_by") == 0) { + makeRelation(precedes, target, start, origin, start); + makeRelation(precedes, target, end, origin, end); + } + else if (strcmp(relationName,"ends_after") == 0) { + makeStrictPrecedenceRelation(target, end, origin, end); + } + else if (strcmp(relationName,"ends_before") == 0) { + makeStrictPrecedenceRelation(origin, end, target, end); + } + else if (strcmp(relationName,"ends_after_start") == 0) { + makeStrictPrecedenceRelation(target, start, origin, end); + } + else if (strcmp(relationName,"starts_before_end") == 0) { + makeStrictPrecedenceRelation(origin, start, target, end); + } + else if (strcmp(relationName,"starts_during") == 0) { + makeRelation(precedes, target, start, origin, start); + makeStrictPrecedenceRelation(origin, start, target, end); + } + else if (strcmp(relationName,"ends_during") == 0) { + makeStrictPrecedenceRelation(target, start, origin, end); + makeRelation(precedes, origin, end, target, end); } + else if (strcmp(relationName,"contains_start") == 0) { + makeRelation(precedes, origin, start, target, start); + makeStrictPrecedenceRelation(target, start, origin, end); + } + else if (strcmp(relationName,"contains_end") == 0) { + makeStrictPrecedenceRelation(origin, start, target, end); + makeRelation(precedes, origin, end, target, end); + } + else if (strcmp(relationName,"starts_after") == 0) { + makeStrictPrecedenceRelation(target, start, origin, start); + } + else if (strcmp(relationName,"starts_before") == 0) { + makeStrictPrecedenceRelation(origin, start, target, start); + } + else if (strcmp(relationName,"equals") == 0) { + makeRelation(concurrent, origin, start, target, start); + makeRelation(concurrent, target, end, origin, end); + makeRelation(eq, origin, duration, target, duration); + } + else { + check_runtime_error(strcmp(relationName,"any") == 0,std::string("Unrecognized relation:")+relationName); + } +} +} DataRef ExprRelation::eval(EvalContext& context) const { @@ -1082,7 +1075,7 @@ namespace EUROPA { Expr* ExprIfGuard::getLhs() const { return m_lhs; } Expr* ExprIfGuard::getRhs() const { return m_rhs; } - DataRef ExprIfGuard::eval(EvalContext& context) const + DataRef ExprIfGuard::eval(EvalContext&) const { // TODO: rework ExprIf implementation so that this can be evaluated check_runtime_error(ALWAYS_FAILS,"ExprIfGuard can't be evaluated"); @@ -1354,7 +1347,7 @@ namespace EUROPA { } else { token = parentType->createInstance(planDb,name,rejectable,isFact); - InterpretedToken* it = dynamic_cast((Token*)token); + InterpretedToken* it = id_cast(token); if (it != NULL) it->commonInit(m_body,false); } @@ -1381,7 +1374,7 @@ namespace EUROPA { token = parentType->createInstance(master,name,relation); // TODO: Hack! this makes it impossible to extend native tokens // class hierarchy needs to be fixed to avoid this cast - InterpretedToken* it = dynamic_cast((Token*)token); + InterpretedToken* it = id_cast(token); it->commonInit(m_body,false); } @@ -1407,9 +1400,9 @@ namespace EUROPA { { std::string str(name); if (str == "RuleInstance") - return (InterpretedRuleInstance*)m_ruleInstance; + return static_cast(m_ruleInstance); if (str == "PlanDatabase") - return (PlanDatabase*)m_ruleInstance->getPlanDatabase(); + return static_cast(m_ruleInstance->getPlanDatabase()); return EvalContext::getElement(name); } @@ -1478,7 +1471,8 @@ namespace EUROPA { { } - TokenId& TokenEvalContext::getToken() { return m_token; } +TokenId TokenEvalContext::getToken() { return m_token; } +TokenId TokenEvalContext::getToken(const char*) { return m_token; } ConstrainedVariableId TokenEvalContext::getVar(const char* name) { @@ -1492,16 +1486,15 @@ namespace EUROPA { return EvalContext::getVar(name); } - void* TokenEvalContext::getElement(const char* name) const - { - std::string str(name); - if (str == "Token") - return (Token*)m_token; - if (str == "PlanDatabase") - return (PlanDatabase*)m_token->getPlanDatabase(); +void* TokenEvalContext::getElement(const char* name) const { + std::string str(name); + if (str == "Token") + return static_cast(m_token); + if (str == "PlanDatabase") + return static_cast(m_token->getPlanDatabase()); - return EvalContext::getElement(name); - } + return EvalContext::getElement(name); +} bool TokenEvalContext::isClass(const LabelStr& className) const @@ -1592,7 +1585,7 @@ InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, { TokenId slave; - unsigned int tokenCnt = predicateInstance.countElements("."); + unsigned long tokenCnt = predicateInstance.countElements("."); bool isOnSameObject = ( tokenCnt == 1 || (tokenCnt==2 && (predicateInstance.getElement(0,".").toString() == "object")) @@ -1620,7 +1613,7 @@ InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, } else { // equivalent of constrainObject() in NddlRules.hh // TODO: this can be done more efficiently - int cnt = predicateInstance.countElements("."); + unsigned long int cnt = predicateInstance.countElements("."); std::string ownerName(predicateInstance.getElement(0,".").toString()); std::string tokenName(predicateInstance.getElement(cnt-1,".").toString()); std::string fullName = predicateInstance.toString(); @@ -2112,7 +2105,7 @@ InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, { if (!m_registered) { m_objType->purgeAll(); - delete (ObjectType*)m_objType; + delete static_cast(m_objType); } } @@ -2156,7 +2149,7 @@ InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, DataRef ExprRuleTypeDefinition::eval(EvalContext& context) const { - RuleSchema* rs = (RuleSchema*)context.getElement("RuleSchema"); + RuleSchema* rs = reinterpret_cast(context.getElement("RuleSchema")); rs->registerRule(m_ruleFactory); return DataRef::null; } @@ -2170,11 +2163,14 @@ InterpretedRuleInstance::InterpretedRuleInstance(const RuleInstanceId& parent, return os.str(); } - void evalArgs(EvalContext& context, std::vector& args,const std::vector& argExprs) - { - for (unsigned int i=0;ieval(context).getValue()); - } +namespace { +void evalArgs(EvalContext& context, + std::vector& args, + const std::vector& argExprs) { + for (unsigned int i=0;ieval(context).getValue()); +} +} ExprMethodCall::ExprMethodCall(const MethodId& m, Expr* varExpr, const std::vector& argExprs) : m_method(m) diff --git a/src/PLASMA/NDDL/component/Interpreter.hh b/src/PLASMA/NDDL/component/Interpreter.hh index c5c41ee40..00f345b67 100644 --- a/src/PLASMA/NDDL/component/Interpreter.hh +++ b/src/PLASMA/NDDL/component/Interpreter.hh @@ -15,6 +15,8 @@ #include "Rule.hh" #include "RuleInstance.hh" +#include + namespace EUROPA { class ExprConstant : public Expr @@ -484,23 +486,23 @@ namespace EUROPA { friend class ExprRelation; }; - class TokenEvalContext : public EvalContext - { - public: - TokenEvalContext(EvalContext* parent, const TokenId& tok); - virtual ~TokenEvalContext(); +class TokenEvalContext : public EvalContext { + public: + TokenEvalContext(EvalContext* parent, const TokenId& tok); + virtual ~TokenEvalContext(); - virtual ConstrainedVariableId getVar(const char* name); + virtual ConstrainedVariableId getVar(const char* name); - virtual void* getElement(const char* name) const; + virtual void* getElement(const char* name) const; - virtual bool isClass(const LabelStr& className) const; + virtual bool isClass(const LabelStr& className) const; - TokenId& getToken(); + TokenId getToken(); + TokenId getToken(const char* name); - protected: - TokenId m_token; - }; + protected: + TokenId m_token; +}; class InterpretedRuleInstance : public RuleInstance { @@ -608,18 +610,17 @@ namespace EUROPA { * */ - class RuleExpr : public Expr - { - public: - virtual DataRef eval(EvalContext& context) const - { - RuleInstanceEvalContext* ec = (RuleInstanceEvalContext*)&context; - return doEval(*ec); - } - - virtual DataRef doEval(RuleInstanceEvalContext& context) const = 0; - virtual ~RuleExpr(){} - }; +class RuleExpr : public Expr { + public: + virtual DataRef eval(EvalContext& context) const + { + RuleInstanceEvalContext* ec = boost::polymorphic_cast(&context); + return doEval(*ec); + } + + virtual DataRef doEval(RuleInstanceEvalContext& context) const = 0; + virtual ~RuleExpr(){} +}; class ExprIfGuard : public Expr { diff --git a/src/PLASMA/NDDL/component/NddlInterpreter.hh b/src/PLASMA/NDDL/component/NddlInterpreter.hh index 05bf41c57..b6e0a64fd 100644 --- a/src/PLASMA/NDDL/component/NddlInterpreter.hh +++ b/src/PLASMA/NDDL/component/NddlInterpreter.hh @@ -160,12 +160,12 @@ protected: class PSLanguageExceptionList { public: - PSLanguageExceptionList(const std::vector& exceptions); - friend std::ostream &operator<<(std::ostream &, const PSLanguageExceptionList &); - int getExceptionCount() const { return m_exceptions.size(); } - const PSLanguageException& getException(int index) const { - return m_exceptions[index]; - } + PSLanguageExceptionList(const std::vector& exceptions); + friend std::ostream &operator<<(std::ostream &, const PSLanguageExceptionList &); + long getExceptionCount() const { return static_cast(m_exceptions.size()); } + const PSLanguageException& getException(int index) const { + return m_exceptions[static_cast(index)]; + } protected: std::vector m_exceptions; }; diff --git a/src/PLASMA/PlanDatabase/CMakeLists.txt b/src/PLASMA/PlanDatabase/CMakeLists.txt index 1a22f5864..7fb625dfe 100644 --- a/src/PLASMA/PlanDatabase/CMakeLists.txt +++ b/src/PLASMA/PlanDatabase/CMakeLists.txt @@ -2,7 +2,7 @@ include(EuropaModule) #set(internal_dependencies ConstraintEngine Utils TinyXml) set(internal_dependencies ConstraintEngine) set(root_sources ModulePlanDatabase.cc) -set(base_sources CommonAncestorConstraint.cc DbClient.cc DefaultTemporalAdvisor.cc HasAncestorConstraint.cc MergeMemento.cc Method.cc Object.cc ObjectTokenRelation.cc ObjectType.cc PDBInterpreter.cc PSPlanDatabaseListener.cc PlanDatabase.cc PlanDatabaseListener.cc PlanDatabaseWriter.cc Schema.cc StackMemento.cc Token.cc TokenFactory.cc TokenType.cc TokenTypeMgr.cc UnifyMemento.cc) +set(base_sources CommonAncestorConstraint.cc DbClient.cc DefaultTemporalAdvisor.cc HasAncestorConstraint.cc MergeMemento.cc Method.cc Object.cc ObjectTokenRelation.cc ObjectType.cc PDBInterpreter.cc PSPlanDatabaseListener.cc PlanDatabase.cc PlanDatabaseListener.cc PlanDatabaseWriter.cc Schema.cc StackMemento.cc Token.cc TokenFactory.cc TokenType.cc TokenTypeMgr.cc UnifyMemento.cc DbClientListener.cc) set(component_sources DbClientTransactionLog.cc DbClientTransactionPlayer.cc EventToken.cc IntervalToken.cc Methods.cc Timeline.cc) set(test_sources module-tests.cc db-test-module.cc) diff --git a/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc b/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc index f19c80423..51e2d3055 100644 --- a/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc +++ b/src/PLASMA/PlanDatabase/ModulePlanDatabase.cc @@ -11,6 +11,8 @@ #include "Methods.hh" #include "Propagators.hh" +#include + namespace EUROPA { ModulePlanDatabase::ModulePlanDatabase() @@ -42,66 +44,66 @@ namespace EUROPA { DbClientTransactionPlayer m_interpreter; }; - std::string NddlXmlTxnInterpreter::interpret(std::istream& input, const std::string& script) + std::string NddlXmlTxnInterpreter::interpret(std::istream& input, const std::string&) { m_interpreter.play(input); return ""; } - void ModulePlanDatabase::initialize(EngineId engine) - { - ConstraintEngine* ce = (ConstraintEngine*)engine->getComponent("ConstraintEngine"); - CESchema* ceSchema = (CESchema*)engine->getComponent("CESchema"); - - new DefaultPropagator("PlanDatabaseSystemPropagator", ce->getId(), SYSTEM_PRIORITY); - REGISTER_SYSTEM_CONSTRAINT(ceSchema,ObjectTokenRelation, "ObjectTokenRelation", "PlanDatabaseSystemPropagator"); - - REGISTER_CONSTRAINT(ceSchema,CommonAncestorConstraint, "commonAncestor", "Default"); - REGISTER_CONSTRAINT(ceSchema,HasAncestorConstraint, "hasAncestor", "Default"); - - Schema* schema = new Schema("EngineSchema",ceSchema->getId()); // TODO: use engine name - schema->registerEnum("TokenStates",StateDomain()); - engine->addComponent("Schema",schema); - - ObjectType* ot; - const char* rootObjType = Schema::rootObject().c_str(); - - ot = new ObjectType(rootObjType,ObjectTypeId::noId(),true /*isNative*/); - schema->registerObjectType(ot->getId()); - - ot = new ObjectType("Timeline",ot->getId(),true /*isNative*/); - ot->addObjectFactory((new TimelineObjectFactory(ot->getId()))->getId()); - schema->registerObjectType(ot->getId()); - - // Exported Methods - schema->registerMethod((new PDBClose())->getId()); - schema->registerMethod((new SpecifyVariable())->getId()); - schema->registerMethod((new ResetVariable())->getId()); - schema->registerMethod((new CloseVariable())->getId()); - schema->registerMethod((new ConstrainToken())->getId()); - schema->registerMethod((new FreeToken())->getId()); - schema->registerMethod((new ActivateToken())->getId()); - schema->registerMethod((new MergeToken())->getId()); - schema->registerMethod((new RejectToken())->getId()); - schema->registerMethod((new CancelToken())->getId()); - schema->registerMethod((new CloseClass())->getId()); - - PlanDatabase* pdb = new PlanDatabase(ce->getId(), schema->getId()); - engine->addComponent("PlanDatabase",pdb); - - engine->addLanguageInterpreter("nddl-xml-txn", new NddlXmlTxnInterpreter(pdb->getClient())); - } - - void ModulePlanDatabase::uninitialize(EngineId engine) - { - LanguageInterpreter* old = engine->removeLanguageInterpreter("nddl-xml-txn"); - if (old) - delete old; - - PlanDatabase* pdb = (PlanDatabase*)engine->removeComponent("PlanDatabase"); - delete pdb; +void ModulePlanDatabase::initialize(EngineId engine) { + ConstraintEngine* ce = + boost::polymorphic_cast(engine->getComponent("ConstraintEngine")); + CESchema* ceSchema = boost::polymorphic_cast(engine->getComponent("CESchema")); + + new DefaultPropagator("PlanDatabaseSystemPropagator", ce->getId(), SYSTEM_PRIORITY); + REGISTER_SYSTEM_CONSTRAINT(ceSchema,ObjectTokenRelation, "ObjectTokenRelation", "PlanDatabaseSystemPropagator"); + + REGISTER_CONSTRAINT(ceSchema,CommonAncestorConstraint, "commonAncestor", "Default"); + REGISTER_CONSTRAINT(ceSchema,HasAncestorConstraint, "hasAncestor", "Default"); + + Schema* schema = new Schema("EngineSchema",ceSchema->getId()); // TODO: use engine name + schema->registerEnum("TokenStates",StateDomain()); + engine->addComponent("Schema",schema); + + ObjectType* ot; + const char* rootObjType = Schema::rootObject().c_str(); + + ot = new ObjectType(rootObjType,ObjectTypeId::noId(),true /*isNative*/); + schema->registerObjectType(ot->getId()); + + ot = new ObjectType("Timeline",ot->getId(),true /*isNative*/); + ot->addObjectFactory((new TimelineObjectFactory(ot->getId()))->getId()); + schema->registerObjectType(ot->getId()); + + // Exported Methods + schema->registerMethod((new PDBClose())->getId()); + schema->registerMethod((new SpecifyVariable())->getId()); + schema->registerMethod((new ResetVariable())->getId()); + schema->registerMethod((new CloseVariable())->getId()); + schema->registerMethod((new ConstrainToken())->getId()); + schema->registerMethod((new FreeToken())->getId()); + schema->registerMethod((new ActivateToken())->getId()); + schema->registerMethod((new MergeToken())->getId()); + schema->registerMethod((new RejectToken())->getId()); + schema->registerMethod((new CancelToken())->getId()); + schema->registerMethod((new CloseClass())->getId()); + + PlanDatabase* pdb = new PlanDatabase(ce->getId(), schema->getId()); + engine->addComponent("PlanDatabase",pdb); + + engine->addLanguageInterpreter("nddl-xml-txn", new NddlXmlTxnInterpreter(pdb->getClient())); +} - Schema* schema = (Schema*)engine->removeComponent("Schema"); - delete schema; - } +void ModulePlanDatabase::uninitialize(EngineId engine) { + LanguageInterpreter* old = engine->removeLanguageInterpreter("nddl-xml-txn"); + if (old) + delete old; + + PlanDatabase* pdb = + boost::polymorphic_cast(engine->removeComponent("PlanDatabase")); + delete pdb; + + Schema* schema = boost::polymorphic_cast(engine->removeComponent("Schema")); + delete schema; +} } diff --git a/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.cc b/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.cc index d1de0229a..5e4605085 100644 --- a/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.cc +++ b/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.cc @@ -30,15 +30,15 @@ namespace EUROPA{ apply(m_second, m_first); } - void CommonAncestorConstraint::handleExecute(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ + void CommonAncestorConstraint::handleExecute(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&){ handleExecute(); } - bool CommonAncestorConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ + bool CommonAncestorConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, + const DomainListener::ChangeType&){ check_error(argIndex <= 2); return (!m_first.isSingleton() && !m_second.isSingleton()); } diff --git a/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.hh b/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.hh index 2afe61be9..9306b5202 100644 --- a/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.hh +++ b/src/PLASMA/PlanDatabase/base/CommonAncestorConstraint.hh @@ -38,11 +38,11 @@ namespace EUROPA void handleExecute(); void handleExecute(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); private: void apply(ObjectDomain& singleton, ObjectDomain& other); diff --git a/src/PLASMA/PlanDatabase/base/DbClient.cc b/src/PLASMA/PlanDatabase/base/DbClient.cc index 3311e1cfc..56292966a 100644 --- a/src/PLASMA/PlanDatabase/base/DbClient.cc +++ b/src/PLASMA/PlanDatabase/base/DbClient.cc @@ -29,10 +29,8 @@ namespace EUROPA { - const char* DELIMITER = ":"; /*!< Used for delimiting streamed output */ - DbClient::DbClient(const PlanDatabaseId& db) - : m_id((DbClient*)this), m_deleted(false), m_transactionLoggingEnabled(false) { + : m_id(this), m_deleted(false), m_transactionLoggingEnabled(false) { check_error(db.isValid()); m_planDb = db; } @@ -91,20 +89,20 @@ namespace EUROPA { return variable; } - void DbClient::deleteVariable(const ConstrainedVariableId& var) { - if(isGlobalVariable(var->getName())) - m_planDb->unregisterGlobalVariable(var); - publish(notifyVariableDeleted(var)); - delete (ConstrainedVariable*) var; - } +void DbClient::deleteVariable(const ConstrainedVariableId& var) { + if(isGlobalVariable(var->getName())) + m_planDb->unregisterGlobalVariable(var); + publish(notifyVariableDeleted(var)); + delete static_cast(var); +} - ObjectId DbClient::createObject(const char* type, const char* name){ - static const std::vector noArguments; - ObjectId object = m_planDb->createObject(type, name, noArguments); - debugMsg("DbClient:createObject", object->toLongString()); - publish(notifyObjectCreated(object)); - return object; - } +ObjectId DbClient::createObject(const char* type, const char* name){ + static const std::vector noArguments; + ObjectId object = m_planDb->createObject(type, name, noArguments); + debugMsg("DbClient:createObject", object->toLongString()); + publish(notifyObjectCreated(object)); + return object; +} ObjectId DbClient::createObject(const char* type, const char* name, const std::vector& arguments){ ObjectId object = m_planDb->createObject(type, name, arguments); @@ -115,7 +113,7 @@ namespace EUROPA { void DbClient::deleteObject(const ObjectId& obj) { publish(notifyObjectDeleted(obj)); - delete (Object*) obj; + delete static_cast(obj); } void DbClient::close(){ @@ -141,28 +139,28 @@ namespace EUROPA { return(token); } - void DbClient::deleteToken(const TokenId& token, const std::string& name) { - check_error(token.isValid()); - checkError(token->isInactive() || token->isFact(), - "Attempted to delete active, non-fact token " << token->toLongString()); - if(isGlobalToken(token->getName())) - m_planDb->unregisterGlobalToken(token); - publish(notifyTokenDeleted(token, name)); - - //the keys are only recorded if logging is enabled - //this may not be the right thing... - if(!m_keysOfTokensCreated.empty()) { - if(m_keysOfTokensCreated.back() == token->getKey()) { - debugMsg("DbClient:deleteToken", - "Removing token key " << m_keysOfTokensCreated.back()); - m_keysOfTokensCreated.pop_back(); - } - checkError(std::find(m_keysOfTokensCreated.begin(), m_keysOfTokensCreated.end(), - token->getKey()) == m_keysOfTokensCreated.end(), - "Attempted to delete " << token->toString() << " out of order."); +void DbClient::deleteToken(const TokenId& token, const std::string& name) { + check_error(token.isValid()); + checkError(token->isInactive() || token->isFact(), + "Attempted to delete active, non-fact token " << token->toLongString()); + if(isGlobalToken(token->getName())) + m_planDb->unregisterGlobalToken(token); + publish(notifyTokenDeleted(token, name)); + + //the keys are only recorded if logging is enabled + //this may not be the right thing... + if(!m_keysOfTokensCreated.empty()) { + if(m_keysOfTokensCreated.back() == token->getKey()) { + debugMsg("DbClient:deleteToken", + "Removing token key " << m_keysOfTokensCreated.back()); + m_keysOfTokensCreated.pop_back(); } - delete (Token*) token; + checkError(std::find(m_keysOfTokensCreated.begin(), m_keysOfTokensCreated.end(), + token->getKey()) == m_keysOfTokensCreated.end(), + "Attempted to delete " << token->toString() << " out of order."); } + delete static_cast(token); +} void DbClient::constrain(const ObjectId& object, const TokenId& predecessor, const TokenId& successor){ object->constrain(predecessor, successor); @@ -284,7 +282,7 @@ namespace EUROPA { /** * @brief Traverse the path and obtain the right token */ - TokenId DbClient::getTokenByPath(const std::vector& relativePath) const + TokenId DbClient::getTokenByPath(const std::vector& relativePath) const { check_error(isTransactionLoggingEnabled()); check_error(!relativePath.empty()); @@ -292,7 +290,7 @@ namespace EUROPA { check_error(relativePath[0] >= 0); // Can never be a valid path // Quick check for the root of the path - if((unsigned)relativePath[0] >= m_keysOfTokensCreated.size()) // Cannot be a path for a token with this key set + if(relativePath[0] >= m_keysOfTokensCreated.size()) // Cannot be a path for a token with this key set return TokenId::noId(); // Obtain the root token key using the first element in the path to index the tokenKeys. @@ -358,7 +356,7 @@ namespace EUROPA { int indexOfMaster = -1; for(unsigned int i=0; i< m_keysOfTokensCreated.size(); i++) if(m_keysOfTokensCreated[i] == keyOfMaster){ - indexOfMaster = i; + indexOfMaster = static_cast(i); break; } @@ -464,7 +462,7 @@ namespace EUROPA { PSVariable* PSPlanDatabaseClientImpl::createVariable(const std::string& typeName, const std::string& name, bool isTmpVar) { ConstrainedVariableId var = m_client->createVariable(typeName.c_str(),name.c_str(),isTmpVar); - return dynamic_cast((ConstrainedVariable*)var); + return dynamic_cast(static_cast(var)); } void PSPlanDatabaseClientImpl::deleteVariable(PSVariable* var) @@ -475,7 +473,7 @@ namespace EUROPA { PSObject* PSPlanDatabaseClientImpl::createObject(const std::string& type, const std::string& name) { ObjectId obj = m_client->createObject(type.c_str(),name.c_str()); - return dynamic_cast((Object*)obj); + return dynamic_cast(static_cast(obj)); } //PSObject* PSPlanDatabaseClientImpl::createObject(const std::string& type, const std::string& name, const PSList& arguments){} @@ -488,7 +486,7 @@ namespace EUROPA { PSToken* PSPlanDatabaseClientImpl::createToken(const std::string& predicateName, bool rejectable, bool isFact) { TokenId tok = m_client->createToken(predicateName.c_str(),NULL, rejectable,isFact); - return dynamic_cast((Token*)tok); + return dynamic_cast(static_cast(tok)); } void PSPlanDatabaseClientImpl::deleteToken(PSToken* token) @@ -533,7 +531,7 @@ namespace EUROPA { idScope.push_back(toId(scope.get(i))); ConstraintId c = m_client->createConstraint(name.c_str(),idScope); - return dynamic_cast((Constraint*)c); + return dynamic_cast(static_cast(c)); } void PSPlanDatabaseClientImpl::deleteConstraint(PSConstraint* c) diff --git a/src/PLASMA/PlanDatabase/base/DbClient.hh b/src/PLASMA/PlanDatabase/base/DbClient.hh index a6b5ebb6f..1a1e474bf 100644 --- a/src/PLASMA/PlanDatabase/base/DbClient.hh +++ b/src/PLASMA/PlanDatabase/base/DbClient.hh @@ -34,7 +34,7 @@ namespace EUROPA { /** * @brief Create a variable - * @param type The type for the variable. + * @param typeName The type for the variable. * @param baseDomain The base domain of the new variable. * @param name The name for the variable. Must be unique. * @return The Id of the variable created. Will error out rather than return a noId. @@ -43,7 +43,7 @@ namespace EUROPA { /** * @brief Create a variable - * @param type The type for the variable. + * @param typeName The type for the variable. * @param name The name for the variable. Must be unique. * @return The Id of the variable created. Will error out rather than return a noId. */ @@ -56,8 +56,6 @@ namespace EUROPA { /** * @brief Create an object instance in the dabatase. - * @param key The expected key value for the object. This is used as a check to ensure we are creating values - * in the order we expect. * @param type The type of instance to create. Must match a name in the Schema. The daatabase must be open for * creation of instances of this type. * @param name The name for the instance. Must be unique. @@ -67,8 +65,6 @@ namespace EUROPA { /** * @brief Create an object instance in the dabatase, with a call to a specialized constructor - * @param key The expected key value for the object. This is used as a check to ensure we are creating values - * in the order we expect. * @param type The type of instance to create. Must match a name in the Schema. The database must be open for * creation of instances of this type. * @param name The name for the instance. Must be unique. @@ -96,7 +92,7 @@ namespace EUROPA { /** * @brief Constructs a Token instance. - * @param predicateName The name of the predicate for which this token is an instance. Must match a name in the + * @param tokenType The name of the predicate for which this token is an instance. Must match a name in the * schema. * @return The Id of the token created. Will error out rather than return a noId. */ @@ -112,11 +108,10 @@ namespace EUROPA { /** * @brief imposes a constraint such that token comes before successor, on the given object. - * @param object + * @param object The object to constrain to. * @param predecessor The token to be the predecessor * @param successor The token to be the successor. If 0, the Token is constrained to succeed all * other ordered tokens. - * @return The resulting 'precedes' constraint */ void constrain(const ObjectId& object, const TokenId& predecessor, const TokenId& successor); @@ -125,7 +120,6 @@ namespace EUROPA { * @param object The object to which the token has been constrained. * @param predecessor The token that is the predecessor * @param successor The token that is the successor. - * @param constraint The constraint to be removed. */ void free(const ObjectId& object, const TokenId& predecessor, const TokenId& successor); @@ -138,7 +132,7 @@ namespace EUROPA { /** * @brief Merge the given token * @param token The token to be merged. It must be inactive. - * @param activeTokenKey The token to be merged onto. + * @param activeToken The token to be merged onto. */ void merge(const TokenId& token, const TokenId& activeToken); @@ -182,7 +176,7 @@ namespace EUROPA { /** * @brief Restricts the base domain of a variable * @param variable The variable to be restricted - * @param value The new base domain of the variable. + * @param domain The new base domain of the variable. * @see getEntityByKey */ void restrict(const ConstrainedVariableId& variable, const Domain& domain); @@ -226,7 +220,7 @@ namespace EUROPA { /** * @brief Lookup a global variable by name. It is an error if not present - * @retrun The requested variable. + * @return The requested variable. */ const ConstrainedVariableId getGlobalVariable(const LabelStr& varName) const; @@ -238,7 +232,7 @@ namespace EUROPA { /** * @brief Lookup a global token by name. It is an error if not present - * @retrun The requested token. + * @return The requested token. */ const TokenId getGlobalToken(const LabelStr& name) const; @@ -257,7 +251,7 @@ namespace EUROPA { * @see Token::getChild(int slavePosition) * @see enableTransactionLogging */ - TokenId getTokenByPath(const std::vector& relativePath) const; + TokenId getTokenByPath(const std::vector& relativePath) const; /** * @brief Retrieve the relative path for obtaining the target token from a given root token. diff --git a/src/PLASMA/PlanDatabase/base/DbClientListener.cc b/src/PLASMA/PlanDatabase/base/DbClientListener.cc new file mode 100644 index 000000000..b58a603bd --- /dev/null +++ b/src/PLASMA/PlanDatabase/base/DbClientListener.cc @@ -0,0 +1,29 @@ +#include "DbClientListener.hh" + +namespace EUROPA { +void DbClientListener::notifyObjectCreated(const ObjectId&) {} +void DbClientListener::notifyObjectCreated(const ObjectId&, + const std::vector&){} +void DbClientListener::notifyObjectDeleted(const ObjectId&) {} +void DbClientListener::notifyClosed(){} +void DbClientListener::notifyClosed(const LabelStr&){} +void DbClientListener::notifyTokenCreated(const TokenId&){} +void DbClientListener::notifyTokenDeleted(const TokenId&, const std::string&){} +void DbClientListener::notifyConstrained(const ObjectId&, const TokenId&, + const TokenId&){} +void DbClientListener::notifyFreed(const ObjectId&, const TokenId&, + const TokenId&){} +void DbClientListener::notifyActivated(const TokenId&){} +void DbClientListener::notifyMerged(const TokenId&, const TokenId&){} +void DbClientListener::notifyMerged(const TokenId&){} +void DbClientListener::notifyRejected(const TokenId&){} +void DbClientListener::notifyCancelled(const TokenId&){} +void DbClientListener::notifyConstraintCreated(const ConstraintId&){} +void DbClientListener::notifyConstraintDeleted(const ConstraintId&){} +void DbClientListener::notifyVariableCreated(const ConstrainedVariableId&){} +void DbClientListener::notifyVariableDeleted(const ConstrainedVariableId&){} +void DbClientListener::notifyVariableSpecified(const ConstrainedVariableId&){} +void DbClientListener::notifyVariableRestricted(const ConstrainedVariableId&){} +void DbClientListener::notifyVariableClosed(const ConstrainedVariableId&){} +void DbClientListener::notifyVariableReset(const ConstrainedVariableId&){} +} diff --git a/src/PLASMA/PlanDatabase/base/DbClientListener.hh b/src/PLASMA/PlanDatabase/base/DbClientListener.hh index b968c0c8e..159c416e3 100644 --- a/src/PLASMA/PlanDatabase/base/DbClientListener.hh +++ b/src/PLASMA/PlanDatabase/base/DbClientListener.hh @@ -26,28 +26,28 @@ namespace EUROPA { const DbClientListenerId& getId() const {return m_id;} - virtual void notifyObjectCreated(const ObjectId& object) {} - virtual void notifyObjectCreated(const ObjectId& object, const std::vector& arguments){} - virtual void notifyObjectDeleted(const ObjectId& object) {} - virtual void notifyClosed(){} - virtual void notifyClosed(const LabelStr& objectType){} - virtual void notifyTokenCreated(const TokenId& token){} - virtual void notifyTokenDeleted(const TokenId& token, const std::string& name){} - virtual void notifyConstrained(const ObjectId& object, const TokenId& predecessor, const TokenId& successor){} - virtual void notifyFreed(const ObjectId& object, const TokenId& predecessor, const TokenId& successor){} - virtual void notifyActivated(const TokenId& token){} - virtual void notifyMerged(const TokenId& token, const TokenId& activeToken){} - virtual void notifyMerged(const TokenId& token){} - virtual void notifyRejected(const TokenId& token){} - virtual void notifyCancelled(const TokenId& token){} - virtual void notifyConstraintCreated(const ConstraintId& constraint){} - virtual void notifyConstraintDeleted(const ConstraintId& constraint){} - virtual void notifyVariableCreated(const ConstrainedVariableId& variable){} - virtual void notifyVariableDeleted(const ConstrainedVariableId& variable){} - virtual void notifyVariableSpecified(const ConstrainedVariableId& variable){} - virtual void notifyVariableRestricted(const ConstrainedVariableId& variable){} - virtual void notifyVariableClosed(const ConstrainedVariableId& variable){} - virtual void notifyVariableReset(const ConstrainedVariableId& variable){} + virtual void notifyObjectCreated(const ObjectId& object); + virtual void notifyObjectCreated(const ObjectId& object, const std::vector& arguments); + virtual void notifyObjectDeleted(const ObjectId& object); + virtual void notifyClosed(); + virtual void notifyClosed(const LabelStr& objectType); + virtual void notifyTokenCreated(const TokenId& token); + virtual void notifyTokenDeleted(const TokenId& token, const std::string& name); + virtual void notifyConstrained(const ObjectId& object, const TokenId& predecessor, const TokenId& successor); + virtual void notifyFreed(const ObjectId& object, const TokenId& predecessor, const TokenId& successor); + virtual void notifyActivated(const TokenId& token); + virtual void notifyMerged(const TokenId& token, const TokenId& activeToken); + virtual void notifyMerged(const TokenId& token); + virtual void notifyRejected(const TokenId& token); + virtual void notifyCancelled(const TokenId& token); + virtual void notifyConstraintCreated(const ConstraintId& constraint); + virtual void notifyConstraintDeleted(const ConstraintId& constraint); + virtual void notifyVariableCreated(const ConstrainedVariableId& variable); + virtual void notifyVariableDeleted(const ConstrainedVariableId& variable); + virtual void notifyVariableSpecified(const ConstrainedVariableId& variable); + virtual void notifyVariableRestricted(const ConstrainedVariableId& variable); + virtual void notifyVariableClosed(const ConstrainedVariableId& variable); + virtual void notifyVariableReset(const ConstrainedVariableId& variable); private: DbClientListenerId m_id; diff --git a/src/PLASMA/PlanDatabase/base/DefaultTemporalAdvisor.cc b/src/PLASMA/PlanDatabase/base/DefaultTemporalAdvisor.cc index cbb40377b..91b7a9e9b 100644 --- a/src/PLASMA/PlanDatabase/base/DefaultTemporalAdvisor.cc +++ b/src/PLASMA/PlanDatabase/base/DefaultTemporalAdvisor.cc @@ -52,50 +52,50 @@ namespace EUROPA { } - /** - * @brief Trivially return true since basic domain intersection tests have been done in - * the plan database already - */ - bool DefaultTemporalAdvisor::canBeConcurrent(const TokenId& first, const TokenId& second){ - return true; - } +/** + * @brief Trivially return true since basic domain intersection tests have been done in + * the plan database already + */ +bool DefaultTemporalAdvisor::canBeConcurrent(const TokenId&, const TokenId&){ + return true; +} const TemporalAdvisorId& DefaultTemporalAdvisor::getId() const {return m_id;} - /** - * @brief Default return that the distance is infinite - */ - const IntervalIntDomain DefaultTemporalAdvisor::getTemporalDistanceDomain(const TimeVarId& first, - const TimeVarId& second, - const bool exact){ - if( first->getExternalEntity().isNoId() - || - second->getExternalEntity().isNoId() ) - { - eint f_lb = cast_int(first->getDerivedDomain().getLowerBound()); - eint f_ub = cast_int(first->getDerivedDomain().getUpperBound()); +/** + * @brief Default return that the distance is infinite + */ +const IntervalIntDomain DefaultTemporalAdvisor::getTemporalDistanceDomain(const TimeVarId& first, + const TimeVarId& second, + const bool){ + if( first->getExternalEntity().isNoId() + || + second->getExternalEntity().isNoId() ) + { + eint f_lb = cast_int(first->getDerivedDomain().getLowerBound()); + eint f_ub = cast_int(first->getDerivedDomain().getUpperBound()); - eint s_lb = cast_int(second->getDerivedDomain().getLowerBound()); - eint s_ub = cast_int(second->getDerivedDomain().getUpperBound()); + eint s_lb = cast_int(second->getDerivedDomain().getLowerBound()); + eint s_ub = cast_int(second->getDerivedDomain().getUpperBound()); - eint min_distance = -g_infiniteTime(); + eint min_distance = -g_infiniteTime(); - if( s_lb > -g_infiniteTime() && f_ub < g_infiniteTime() ) { - min_distance = std::max( min_distance, s_lb - f_ub ); - } + if( s_lb > -g_infiniteTime() && f_ub < g_infiniteTime() ) { + min_distance = std::max( min_distance, s_lb - f_ub ); + } - eint max_distance = g_infiniteTime(); + eint max_distance = g_infiniteTime(); - if( f_lb > -g_infiniteTime() && s_ub < g_infiniteTime() ) { - max_distance = std::min( max_distance, s_ub - f_lb ); - } - - return(IntervalIntDomain( min_distance, max_distance )); - } + if( f_lb > -g_infiniteTime() && s_ub < g_infiniteTime() ) { + max_distance = std::min( max_distance, s_ub - f_lb ); + } - return(IntervalIntDomain(-g_infiniteTime(), g_infiniteTime())); + return(IntervalIntDomain( min_distance, max_distance )); } + return(IntervalIntDomain(-g_infiniteTime(), g_infiniteTime())); +} + void DefaultTemporalAdvisor::getTemporalDistanceDomains(const ConstrainedVariableId& first, const std::vector& seconds, diff --git a/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.cc b/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.cc index 50330fdbe..54d471eb2 100644 --- a/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.cc +++ b/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.cc @@ -23,22 +23,22 @@ namespace EUROPA{ apply(); } - void HasAncestorConstraint::handleExecute(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ - handleExecute(); - } - - bool HasAncestorConstraint::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ - check_error(argIndex <= 1); - - if(m_first.isOpen() || m_restrictions.isOpen()) - return true; +void HasAncestorConstraint::handleExecute(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&){ + handleExecute(); +} - return (false); - } +bool HasAncestorConstraint::canIgnore(const ConstrainedVariableId&, + unsigned int argIndex, + const DomainListener::ChangeType&){ + check_error(argIndex <= 1); + + if(m_first.isOpen() || m_restrictions.isOpen()) + return true; + + return (false); +} void HasAncestorConstraint::apply() { @@ -70,8 +70,8 @@ namespace EUROPA{ candidate->getAncestors(candidatesAncestors); bool removeCandidate = true; for(std::list::const_iterator it1 = candidatesAncestors.begin(); it1 != candidatesAncestors.end(); ++it1){ - ObjectId object = *it1; - if(setOfAncestors.isMember(object)){ // Found common ancestor + ObjectId ancestor = *it1; + if(setOfAncestors.isMember(ancestor)){ // Found common ancestor removeCandidate = false; break; } diff --git a/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.hh b/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.hh index 6ef977506..f633076ba 100644 --- a/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.hh +++ b/src/PLASMA/PlanDatabase/base/HasAncestorConstraint.hh @@ -23,11 +23,11 @@ namespace EUROPA void handleExecute(); void handleExecute(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); private: void apply(); diff --git a/src/PLASMA/PlanDatabase/base/MergeMemento.cc b/src/PLASMA/PlanDatabase/base/MergeMemento.cc index 513245cad..96cc96b50 100644 --- a/src/PLASMA/PlanDatabase/base/MergeMemento.cc +++ b/src/PLASMA/PlanDatabase/base/MergeMemento.cc @@ -50,10 +50,10 @@ namespace EUROPA{ std::set deactivatedConstraints; //Exclude this for the state variable, which will necessarily conflict with the target active token - for(unsigned int i=1; igetKey()) == varMap.end()); + for(unsigned long i=1; igetKey()) == varMap.end()); // Add to the map to support lookup and store all constraints on any variables - varMap.insert(std::make_pair((eint) inactiveVariables[i]->getKey(), activeVariables[i])); + varMap.insert(std::make_pair(inactiveVariables[i]->getKey(), activeVariables[i])); inactiveVariables[i]->constraints(deactivatedConstraints); // i.e. not a state variable diff --git a/src/PLASMA/PlanDatabase/base/Object.cc b/src/PLASMA/PlanDatabase/base/Object.cc index dc0d2450b..63bcd21af 100644 --- a/src/PLASMA/PlanDatabase/base/Object.cc +++ b/src/PLASMA/PlanDatabase/base/Object.cc @@ -56,6 +56,8 @@ namespace EUROPA { m_id.remove(); } +void Object::constructor(const std::vector&) {} + /* * Hack! Code generation currently skips the factories and directly calls the constructor that specifies the parent, * so this is necessary for the interpreter to provide the same behavior @@ -193,7 +195,8 @@ namespace EUROPA { debugMsg("Object:remove:token", "Also removing " << constraint->toString()); // If the constraint is a precedence constraint, the additional cleanup required - std::map::iterator pos = m_keyPairsByConstraintKey.find(constraint->getKey()); + std::map >::iterator pos = + m_keyPairsByConstraintKey.find(constraint->getKey()); if(pos != m_keyPairsByConstraintKey.end()) removePrecedenceConstraint(constraint); } @@ -232,25 +235,27 @@ namespace EUROPA { void Object::getOrderingChoices( const TokenId& token, std::vector< std::pair >& results, #ifdef _MSC_VER - unsigned int limit + unsigned long limit #else - unsigned int limit + unsigned long limit #endif ) { check_error(limit > 0, "Cannot set limit to less than 1."); results.push_back(std::make_pair(token, token)); } - unsigned int Object::countOrderingChoices(const TokenId& token, unsigned int limit){ - std::vector< std::pair > results; - getOrderingChoices(token, results, limit); - m_lastOrderingChoiceCount = results.size(); - return m_lastOrderingChoiceCount; - } +unsigned long Object::countOrderingChoices(const TokenId& token, unsigned long limit){ + std::vector< std::pair > results; + getOrderingChoices(token, results, limit); + m_lastOrderingChoiceCount = results.size(); + return m_lastOrderingChoiceCount; +} - unsigned int Object::lastOrderingChoiceCount(const TokenId& token) const{ return m_lastOrderingChoiceCount; } +unsigned long Object::lastOrderingChoiceCount(const TokenId&) const{ + return m_lastOrderingChoiceCount; +} - void Object::getTokensToOrder(std::vector& results) {} +void Object::getTokensToOrder(std::vector&) {} bool Object::hasTokensToOrder() const { return(false); @@ -260,60 +265,57 @@ namespace EUROPA { constrain(predecessor, successor, true); } - void Object::constrain(const TokenId& predecessor, const TokenId& successor, bool isExplicit) { - check_error(predecessor.isValid()); - checkError(predecessor->isActive(), predecessor->toString() << ": " << predecessor->getState()->toString()); - check_error(successor.isValid()); - checkError(successor->isActive(), successor->toString() << ": " << successor->getState()->toString()); +void Object::constrain(const TokenId& predecessor, const TokenId& successor, bool isExplicit) { + check_error(predecessor.isValid()); + checkError(predecessor->isActive(), predecessor->toString() << ": " << predecessor->getState()->toString()); + check_error(successor.isValid()); + checkError(successor->isActive(), successor->toString() << ": " << successor->getState()->toString()); - check_error(!isConstrainedToPrecede(predecessor, successor), - "Attempted to constrain previously constrained tokens."); + check_error(!isConstrainedToPrecede(predecessor, successor), + "Attempted to constrain previously constrained tokens."); - // Post constraints on object variable, predecessor only in event they are equal - constrainToThisObjectAsNeeded(predecessor); + // Post constraints on object variable, predecessor only in event they are equal + constrainToThisObjectAsNeeded(predecessor); - debugMsg("Object:constrain", - "Constraining " << predecessor->toString() << " to be before " << successor->toString() << - (isExplicit ? " explicitly." : " implicitly.")); - int encodedKey = makeKey(predecessor, successor); + debugMsg("Object:constrain", + "Constraining " << predecessor->toString() << " to be before " << successor->toString() << + (isExplicit ? " explicitly." : " implicitly.")); + std::pair encodedKey = std::make_pair(predecessor->getKey(), + successor->getKey()); - condDebugMsg(m_constraintsByKeyPair.find(encodedKey) != m_constraintsByKeyPair.end(), "Object:makeKey", - "Collision detected for " << predecessor->toString() << " and " << successor->toString() << - " with " << encodedKey); + ConstraintId constraint; - ConstraintId constraint; + // If successor is not noId then add the precede constraint. + if (predecessor != successor) { + constrainToThisObjectAsNeeded(successor); // Also constrain successor if necessary - // If successor is not noId then add the precede constraint. - if (predecessor != successor) { - constrainToThisObjectAsNeeded(successor); // Also constrain successor if necessary + // Create the precedence constraint + std::vector vars; + vars.push_back(predecessor->end()); + vars.push_back(successor->start()); + constraint = getPlanDatabase()->getConstraintEngine()->createConstraint( + LabelStr("precedes"), + vars); - // Create the precedence constraint - std::vector vars; - vars.push_back(predecessor->end()); - vars.push_back(successor->start()); - constraint = getPlanDatabase()->getConstraintEngine()->createConstraint( - LabelStr("precedes"), - vars); + // Store for bi-directional access by encoded key pair and constraint + m_constraintsByKeyPair.insert(std::make_pair(encodedKey, constraint)); + m_keyPairsByConstraintKey.insert(std::make_pair(constraint->getKey(), encodedKey)); - // Store for bi-directional access by encoded key pair and constraint - m_constraintsByKeyPair.insert(std::pair(encodedKey, constraint)); - m_keyPairsByConstraintKey.insert(std::make_pair(constraint->getKey(), encodedKey)); + // Store for access by token + m_constraintsByTokenKey.insert(std::make_pair(predecessor->getKey(), constraint)); + m_constraintsByTokenKey.insert(std::make_pair(successor->getKey(), constraint)); + } - // Store for access by token - m_constraintsByTokenKey.insert(std::make_pair(predecessor->getKey(), constraint)); - m_constraintsByTokenKey.insert(std::make_pair(successor->getKey(), constraint)); - } + if(isExplicit) + m_explicitConstraints.insert(constraint.isId() ? constraint->getKey() : predecessor->getKey()); - if(isExplicit) - m_explicitConstraints.insert(constraint.isId() ? constraint->getKey() : predecessor->getKey()); + m_planDatabase->notifyConstrained(m_id, predecessor, successor); + check_error(isValid()); - m_planDatabase->notifyConstrained(m_id, predecessor, successor); - check_error(isValid()); + if (getPlanDatabase()->getConstraintEngine()->getAutoPropagation()) + getPlanDatabase()->getConstraintEngine()->propagate(); - if (getPlanDatabase()->getConstraintEngine()->getAutoPropagation()) - getPlanDatabase()->getConstraintEngine()->propagate(); - - } +} void Object::free(const TokenId& predecessor, const TokenId& successor){ free(predecessor, successor, true); @@ -444,8 +446,9 @@ namespace EUROPA { } ConstraintId Object::getPrecedenceConstraint(const TokenId& predecessor, const TokenId& successor) const{ - int encodedKey = makeKey(predecessor, successor); - std::multimap::const_iterator it = m_constraintsByKeyPair.find(encodedKey); + std::pair encodedKey = std::make_pair(predecessor->getKey(), successor->getKey()); + std::multimap, ConstraintId>::const_iterator it = + m_constraintsByKeyPair.find(encodedKey); while(it != m_constraintsByKeyPair.end() && it->first == encodedKey){ ConstraintId constraint = it->second; if(constraint->getScope()[0] == predecessor->end() && @@ -480,7 +483,7 @@ namespace EUROPA { bool singletonFound = false; while(it != m_constraintsByTokenKey.end() && it->first == token->getKey()){ ConstraintId constraint = it->second; - std::map::const_iterator pos = m_keyPairsByConstraintKey.find(constraint->getKey()); + std::map >::const_iterator pos = m_keyPairsByConstraintKey.find(constraint->getKey()); if(pos == m_keyPairsByConstraintKey.end()){ check_error(singletonFound == false, "Can only find one singleton constraint per token."); @@ -583,10 +586,13 @@ namespace EUROPA { check_error(Entity::getEntity(it->first).isValid()); } - for(std::multimap::const_iterator it = m_constraintsByKeyPair.begin(); + for(std::multimap, ConstraintId>::const_iterator it = + m_constraintsByKeyPair.begin(); it != m_constraintsByKeyPair.end(); ++it){ - checkError(it->second.isValid(), "Invalid constraint for key pair " << LabelStr(it->first).toString()); + checkError(it->second.isValid(), + "Invalid constraint for key pair <" << it->first.first << " " << + it->first.second << ">"); checkError(m_keyPairsByConstraintKey.find(it->second->getKey())->second == it->first, "Lookup should be symmetric."); } @@ -594,57 +600,56 @@ namespace EUROPA { return true; } - ConstrainedVariableId Object::addVariable(const Domain& baseDomain, const char* name){ - std::string varTypeName = ""; - Schema::NameValueVector members = m_planDatabase->getSchema()->getMembers(m_type); - for (unsigned int i = 0; i < members.size(); i++) { - debugMsg("Object:typeForNewMember", "member [" << members[i].first.c_str() << ", " << members[i].second.c_str() << "]"); - if (strcmp( members[i].second.c_str(), name) == 0 ) { - varTypeName = members[i].first.c_str(); - } - } +ConstrainedVariableId Object::addVariable(const Domain& baseDomain, const char* name){ + std::string varTypeName = ""; + Schema::NameValueVector members = m_planDatabase->getSchema()->getMembers(m_type); + for (unsigned int i = 0; i < members.size(); i++) { + debugMsg("Object:typeForNewMember", "member [" << members[i].first.c_str() << ", " << members[i].second.c_str() << "]"); + if (strcmp( members[i].second.c_str(), name) == 0 ) { + varTypeName = members[i].first.c_str(); + } + } - if (varTypeName == "") { - varTypeName = baseDomain.getTypeName().c_str(); - } + if (varTypeName == "") { + varTypeName = baseDomain.getTypeName().c_str(); + } - const Domain& typeDomain = m_planDatabase->getConstraintEngine()->getCESchema()->baseDomain(varTypeName.c_str()); - check_error(baseDomain.isSubsetOf(typeDomain), "Variable " + std::string(name) + " of type " + - varTypeName.c_str() +" can not be set to " + baseDomain.toString()); + const Domain& typeDomain = m_planDatabase->getConstraintEngine()->getCESchema()->baseDomain(varTypeName.c_str()); + check_error(baseDomain.isSubsetOf(typeDomain), "Variable " + std::string(name) + " of type " + + varTypeName.c_str() +" can not be set to " + baseDomain.toString()); - check_error(!isComplete(), - "Cannot add variable " + std::string(name) + - " after completing object construction for " + m_name.toString()); + check_error(!isComplete(), + "Cannot add variable " + std::string(name) + + " after completing object construction for " + m_name.toString()); - check_error(m_planDatabase->getSchema()->canContain(m_type, varTypeName.c_str(), name), - "Cannot add a variable " + std::string(name) + " of type " + - baseDomain.getTypeName().toString() + - " to objects of type " + m_type.toString()); + check_error(m_planDatabase->getSchema()->canContain(m_type, varTypeName.c_str(), name), + "Cannot add a variable " + std::string(name) + " of type " + + baseDomain.getTypeName().toString() + + " to objects of type " + m_type.toString()); - if (!baseDomain.isSubsetOf(typeDomain)) { - return ConstrainedVariableId::noId(); - } + if (!baseDomain.isSubsetOf(typeDomain)) { + return ConstrainedVariableId::noId(); + } - std::string fullVariableName(m_name.toString() + "." + name); + std::string fullVariableName(m_name.toString() + "." + name); - ConstrainedVariableId id = - m_planDatabase->getConstraintEngine()->createVariable( - varTypeName.c_str(), - baseDomain, - false, // TODO: Should this be considered internal, I think so? - true, - fullVariableName.c_str(), - m_id, - m_variables.size() - ); + ConstrainedVariableId id = + m_planDatabase->getConstraintEngine()->createVariable( + varTypeName.c_str(), + baseDomain, + false, // TODO: Should this be considered internal, I think so? + true, + fullVariableName.c_str(), + m_id, + static_cast(m_variables.size())); - m_variables.push_back(id); + m_variables.push_back(id); - return(id); - } + return(id); +} void Object::notifyOrderingRequired(const TokenId& token){ @@ -657,9 +662,9 @@ namespace EUROPA { /** Stubs for notification handlers **/ - void Object::notifyMerged(const TokenId& token){} + void Object::notifyMerged(const TokenId&){} - void Object::notifyRejected(const TokenId& token){} + void Object::notifyRejected(const TokenId&){} void Object::notifyDeleted(const TokenId& token){ remove(token); @@ -691,17 +696,15 @@ namespace EUROPA { return sstr.str(); } - - int Object::makeKey(const TokenId& a, const TokenId& b){ - return (cast_int(a->getKey()) << 16) ^ cast_int(b->getKey()); - } - void Object::removePrecedenceConstraint(const ConstraintId& constraint){ TokenId predecessor = constraint->getScope()[0]->parent(); TokenId successor = constraint->getScope()[1]->parent(); - int encodedKey = makeKey(predecessor, successor); - std::multimap::iterator it = m_constraintsByKeyPair.find(encodedKey); + std::pair encodedKey = std::make_pair(predecessor->getKey(), + successor->getKey()); + std::multimap, ConstraintId>::iterator it = + m_constraintsByKeyPair.find(encodedKey); + while(it != m_constraintsByKeyPair.end() && it->first == encodedKey){ ConstraintId c = it->second; if(c == constraint){ @@ -735,43 +738,42 @@ namespace EUROPA { return getType().toString(); } - PSList Object::getMemberVariables() - { - PSList retval; - const std::vector& vars = getVariables(); - for(std::vector::const_iterator it = vars.begin(); it != vars.end(); - ++it) { - ConstrainedVariableId id = *it; - retval.push_back((PSVariable *) id); - } - - return retval; - } - - PSVariable* Object::getMemberVariable(const std::string& name) { - LabelStr realName(name); - PSVariable* retval = NULL; - const std::vector& vars = getVariables(); - for(std::vector::const_iterator it = vars.begin(); it != vars.end(); - ++it) { - ConstrainedVariableId id = *it; - if(id->getName() == realName) { - retval = (PSVariable*) id; - break; - } - } - return retval; - } - - PSList Object::getTokens() const { - PSList retval; - const TokenSet& t = tokens(); - for(TokenSet::const_iterator it = t.begin(); it != t.end(); ++it) { - TokenId id = *it; - retval.push_back((PSToken *) id); - } - return retval; +PSList Object::getMemberVariables() { + PSList retval; + const std::vector& vars = getVariables(); + for(std::vector::const_iterator it = vars.begin(); it != vars.end(); + ++it) { + ConstrainedVariableId id = *it; + retval.push_back(id_cast(id)); } + + return retval; +} + +PSVariable* Object::getMemberVariable(const std::string& name) { + LabelStr realName(name); + PSVariable* retval = NULL; + const std::vector& vars = getVariables(); + for(std::vector::const_iterator it = vars.begin(); it != vars.end(); + ++it) { + ConstrainedVariableId id = *it; + if(id->getName() == realName) { + retval = id_cast(id); + break; + } + } + return retval; +} + +PSList Object::getTokens() const { + PSList retval; + const TokenSet& t = tokens(); + for(TokenSet::const_iterator it = t.begin(); it != t.end(); ++it) { + TokenId id = *it; + retval.push_back(id_cast(id)); + } + return retval; +} void Object::addPrecedence(PSToken* pred,PSToken* succ) diff --git a/src/PLASMA/PlanDatabase/base/Object.hh b/src/PLASMA/PlanDatabase/base/Object.hh index 350fd95fe..b6bd6d6ff 100644 --- a/src/PLASMA/PlanDatabase/base/Object.hh +++ b/src/PLASMA/PlanDatabase/base/Object.hh @@ -41,14 +41,13 @@ namespace EUROPA { virtual ~Object(); - virtual void constructor(const std::vector& arguments) {} + virtual void constructor(const std::vector& arguments); /** * @brief Add a variable as a member to the object. This is used when building the object * and cannot be called once the specific object instance has been closed. * @param baseDomain The base domain to use to populate the variable * @param name The member name - * @error If a variable of the given type with the given name cannot be added * @see Scheme::hasMember, Schema::canContain, Object::close() */ virtual ConstrainedVariableId addVariable(const Domain& baseDomain, const char* name); @@ -115,9 +114,9 @@ namespace EUROPA { virtual void getOrderingChoices( const TokenId& token, std::vector< std::pair< TokenId, TokenId > >& results, #ifdef _MSC_VER - unsigned int limit = UINT_MAX //std::numeric_limits::max() + unsigned long limit = UINT_MAX //std::numeric_limits::max() #else - unsigned int limit = std::numeric_limits::max() + unsigned long limit = std::numeric_limits::max() #endif ); /** @@ -125,14 +124,14 @@ namespace EUROPA { * @param token The Token for which we want to count possible choices * @param limit The max we don't want to count past */ - unsigned int countOrderingChoices(const TokenId& token, unsigned int limit); + unsigned long countOrderingChoices(const TokenId& token, unsigned long limit); /** * @brief Retrieve the last computed value when a call was made to countOrderingChoices. * @param token The token for which we want choice count. * @return The last value obtained from countOrderingChoices */ - unsigned int lastOrderingChoiceCount(const TokenId& token) const; + unsigned long lastOrderingChoiceCount(const TokenId& token) const; /** * @brief Get all possible active tokens on this object which require ordering. @@ -150,7 +149,7 @@ namespace EUROPA { * @brief imposes a constraint such that token comes before successor. May additinally impose * the constraint that the object variable of each token is restricted to this object. We do not restrict * the case where predecessor == successor. This will simply constrain the token to this object. - * @param token The token to be the predecessor + * @param predecessor The token to be the predecessor * @param successor The token to be the successor. * @see free */ @@ -159,7 +158,7 @@ namespace EUROPA { /** * @brief Removes the specific constraint which must have been created by calling 'constrain'. May * additionally remove implied constraints to constrain tokens to an object. - * @param token The token that is the predecessor + * @param predecessor The token that is the predecessor * @param successor The token that is the successor * @see constrain */ @@ -172,17 +171,17 @@ namespace EUROPA { const std::vector& getVariables() const; /** - * @brief Obtain a variable by name. Variable names must be unique within the context of an object. + * @brief Obtain a variable by name. Variable names must be unique within the context + * of an object. Fails with an error if a variable of the given name cannot be + * found. * @param name The name for the requested variable. - * @error Will fail if a variable of the given name cannot be found */ const ConstrainedVariableId& getVariable(const LabelStr& name) const; /** * @brief Obtain the variable by traversing a path. Requires that all contained members along the way - * are singletons. + * are singletons. Error: Will fail if there are non-singleton fields or the path is not correct. * @param path The index based path for traversing objects structures. - * @error Will fail if there are non-singleton fields or the path is not correct. */ ConstrainedVariableId getVariable(const std::vector& path) const; @@ -325,11 +324,6 @@ namespace EUROPA { void removePrecedenceConstraint(const ConstraintId& constraint); - /** - * @brief Utility to generate a hashkey for a token pair - */ - static int makeKey(const TokenId& a, const TokenId& b); - ObjectId m_id; ObjectId m_parent; LabelStr m_type; @@ -341,10 +335,10 @@ namespace EUROPA { std::vector m_variables; std::set m_explicitConstraints; /*!< Stores list of explicitly posted constraints to order tokens. Either the key of the constraint is stored, or in cases where it is a straight assignment of a token, the key of the token is stored. */ - unsigned int m_lastOrderingChoiceCount; /*!< The last computed count of ordering choices */ + unsigned long m_lastOrderingChoiceCount; /*!< The last computed count of ordering choices */ std::multimap m_constraintsByTokenKey; /**< All Precedence Constraints by Token Key */ - std::multimap m_constraintsByKeyPair; /**< Precedence Constraints by encoded key pair */ - std::map m_keyPairsByConstraintKey; /**< Reverse lookup to obtain the key pair */ + std::multimap, ConstraintId> m_constraintsByKeyPair; /**< Precedence Constraints by encoded key pair */ + std::map > m_keyPairsByConstraintKey; /**< Reverse lookup to obtain the key pair */ ConstrainedVariableId m_thisVar; /**< Used to constrain against */ private: diff --git a/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.cc b/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.cc index b886d2904..f45392270 100644 --- a/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.cc +++ b/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.cc @@ -56,9 +56,9 @@ namespace EUROPA { check_error(isValid()); } - void ObjectTokenRelation::handleExecute(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ + void ObjectTokenRelation::handleExecute(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&){ handleExecute(); } @@ -66,7 +66,7 @@ namespace EUROPA { * Will handle changes immediately as long as the domain is open */ bool ObjectTokenRelation::canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int, const DomainListener::ChangeType& changeType){ if(m_currentDomain.isOpen()) @@ -167,11 +167,11 @@ namespace EUROPA { }*/ } - const std::vector& ObjectTokenRelation::getModifiedVariables(const ConstrainedVariableId& variable) const - { - static std::vector s_emptyScope; - return s_emptyScope; - } +const std::vector& +ObjectTokenRelation::getModifiedVariables(const ConstrainedVariableId&) const { + static std::vector s_emptyScope; + return s_emptyScope; +} const std::vector& ObjectTokenRelation::getModifiedVariables() const { diff --git a/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.hh b/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.hh index 3580d4a91..753b19eef 100644 --- a/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.hh +++ b/src/PLASMA/PlanDatabase/base/ObjectTokenRelation.hh @@ -30,11 +30,11 @@ namespace EUROPA void handleExecute(); void handleExecute(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); // This constraint doesn't modify any variables through inference diff --git a/src/PLASMA/PlanDatabase/base/ObjectType.cc b/src/PLASMA/PlanDatabase/base/ObjectType.cc index d283c9df1..e97f5763a 100644 --- a/src/PLASMA/PlanDatabase/base/ObjectType.cc +++ b/src/PLASMA/PlanDatabase/base/ObjectType.cc @@ -22,12 +22,11 @@ ObjectType::ObjectType(const char* name, const ObjectTypeId& parent, bool isNati { } -ObjectType::~ObjectType() -{ - // TODO: enable this when Schema API is cleaned up to reflect the fact that object factories and token factories are owned by the object type - // purgeAll(); - delete (ObjectDT*)m_varType; - m_id.remove(); +ObjectType::~ObjectType() { + // TODO: enable this when Schema API is cleaned up to reflect the fact that object factories and token factories are owned by the object type + // purgeAll(); + delete id_cast(m_varType); + m_id.remove(); } const DataTypeId& ObjectType::getVarType() const @@ -35,15 +34,9 @@ const DataTypeId& ObjectType::getVarType() const return m_varType; } -void ObjectType::purgeAll() -{ - for(std::map::const_iterator it = m_objectFactories.begin(); it != m_objectFactories.end(); ++it) - delete (ObjectFactory*) it->second; - m_objectFactories.clear(); - - for(std::map::const_iterator it = m_tokenTypes.begin(); it != m_tokenTypes.end(); ++it) - delete (TokenType*) it->second; - m_tokenTypes.clear(); +void ObjectType::purgeAll() { + cleanup(m_objectFactories); + cleanup(m_tokenTypes); } @@ -126,33 +119,31 @@ PSDataType* ObjectType::getMemberTypeRef(const std::string& name) const { return getMemberType(name.c_str()); } -void ObjectType::addObjectFactory(const ObjectFactoryId& factory) -{ - // TODO: allow redefinition of old one - m_objectFactories[(edouble)(factory->getSignature())] = factory; +void ObjectType::addObjectFactory(const ObjectFactoryId& factory) { + // TODO: allow redefinition of old one + m_objectFactories[static_cast(factory->getSignature())] = factory; } -void ObjectType::addTokenType(const TokenTypeId& factory) -{ - // TODO: allow redefinition of old one - m_tokenTypes[(edouble)(factory->getSignature())] = factory; +void ObjectType::addTokenType(const TokenTypeId& factory) { + // TODO: allow redefinition of old one + m_tokenTypes[static_cast(factory->getSignature())] = factory; } -const TokenTypeId& ObjectType::getTokenType(const LabelStr& signature) const -{ - check_error(signature.getElement(0,".")==getName(), - "Can't look for a token factory I don't own"); - - std::map::const_iterator it = m_tokenTypes.find((edouble)signature); - if (it != m_tokenTypes.end()) - return it->second; - - if (m_parent.isId()) { - std::string parentSignature = m_parent->getName().toString()+"."+signature.getElement(1,".").toString(); - return m_parent->getTokenType(parentSignature); - } +const TokenTypeId& ObjectType::getTokenType(const LabelStr& signature) const { + check_error(signature.getElement(0,".")==getName(), + "Can't look for a token factory I don't own"); + + std::map::const_iterator it = + m_tokenTypes.find(static_cast(signature)); + if (it != m_tokenTypes.end()) + return it->second; + + if (m_parent.isId()) { + std::string parentSignature = m_parent->getName().toString()+"."+signature.getElement(1,".").toString(); + return m_parent->getTokenType(parentSignature); + } - return TokenTypeId::noId(); + return TokenTypeId::noId(); } PSList ObjectType::getPredicates() const { @@ -233,8 +224,8 @@ std::string ObjectType::toString() const debugMsg("ObjectFactory:ObjectFactory", "Creating factory " << signature.toString()); // Now we want to populate the signature types - unsigned int count = signature.countElements(TYPE_DELIMITER); - for(unsigned int i=0;i& ObjectFactory::getSignatureTypes() const {return m_signatureTypes;} +ObjectId ObjectFactory::makeNewObject(const PlanDatabaseId&, + const LabelStr&, + const LabelStr&, + const std::vector&) const { + return ObjectId::noId(); +} + +void ObjectFactory::evalConstructorBody(ObjectId&, + const std::vector&) const { +} + + ObjectTypeMgr::ObjectTypeMgr() : m_id(this) { @@ -267,24 +270,21 @@ std::string ObjectType::toString() const return m_id; } - void ObjectTypeMgr::purgeAll(){ - debugMsg("ObjectFactory:purgeAll", "Purging all"); - - // TODO: this should be done by the object types - std::set alreadyDeleted; - for(std::map::const_iterator it = m_factories.begin(); it != m_factories.end(); ++it) { - if(alreadyDeleted.find(it->second) == alreadyDeleted.end()) { - alreadyDeleted.insert((ObjectFactory*)it->second); - delete (ObjectFactory*) it->second; - } +void ObjectTypeMgr::purgeAll(){ + debugMsg("ObjectFactory:purgeAll", "Purging all"); + + // TODO: this should be done by the object types + std::set alreadyDeleted; + for(std::map::const_iterator it = m_factories.begin(); it != m_factories.end(); ++it) { + if(alreadyDeleted.find(it->second) == alreadyDeleted.end()) { + alreadyDeleted.insert(static_cast(it->second)); + delete static_cast(it->second); } - m_factories.clear(); - - std::map::iterator it = m_objTypes.begin(); - for(;it != m_objTypes.end();++it) - delete (ObjectType*)it->second; - m_objTypes.clear(); } + m_factories.clear(); + + cleanup(m_objTypes); +} void ObjectTypeMgr::registerObjectType(const ObjectTypeId& objType) @@ -301,15 +301,12 @@ std::string ObjectType::toString() const debugMsg("Schema:registerObjectType","Registered object type:" << std::endl << objType->toString()); } - const ObjectTypeId& ObjectTypeMgr::getObjectType(const LabelStr& objType) const - { - std::map::const_iterator it = m_objTypes.find((edouble)objType); +const ObjectTypeId& ObjectTypeMgr::getObjectType(const LabelStr& objType) const { + std::map::const_iterator it = + m_objTypes.find(static_cast(objType)); - if (it == m_objTypes.end()) - return ObjectTypeId::noId(); - else - return it->second; - } + return (it == m_objTypes.end() ? ObjectTypeId::noId() : it->second); +} std::vector ObjectTypeMgr::getAllObjectTypes() const { @@ -415,7 +412,7 @@ std::string ObjectType::toString() const if(m_factories.find(factory->getSignature().getKey()) != m_factories.end()){ ObjectFactoryId oldFactory = m_factories.find(factory->getSignature().getKey())->second; m_factories.erase(factory->getSignature().getKey()); - delete (ObjectFactory*) oldFactory; + delete static_cast(oldFactory); debugMsg("ObjectFactory:registerFactory", "Over-riding registeration for factory with signature " << factory->getSignature().toString()); } @@ -474,13 +471,12 @@ std::string ObjectType::toString() const } } - void* ObjectEvalContext::getElement(const char* name) const - { - if (std::string(name)=="PlanDatabase") - return (PlanDatabase*)m_obj->getPlanDatabase(); - - return EvalContext::getElement(name); - } +void* ObjectEvalContext::getElement(const char* name) const { + if (std::string(name)=="PlanDatabase") + return static_cast(m_obj->getPlanDatabase()); + + return EvalContext::getElement(name); +} InterpretedObjectFactory::InterpretedObjectFactory( const ObjectTypeId& objType, @@ -563,13 +559,11 @@ std::string ObjectType::toString() const } } - void* ObjectFactoryEvalContext::getElement(const char* name) const - { - if (std::string(name)=="PlanDatabase") - return (PlanDatabase*)m_planDb; - - return EvalContext::getElement(name); - } +void* ObjectFactoryEvalContext::getElement(const char* name) const { + if (std::string(name)=="PlanDatabase") + return static_cast(m_planDb); + return EvalContext::getElement(name); +} ObjectId InterpretedObjectFactory::createInstance( const PlanDatabaseId& planDb, @@ -590,7 +584,7 @@ std::string ObjectType::toString() const return instance; } - bool InterpretedObjectFactory::checkArgs(const std::vector& arguments) const + bool InterpretedObjectFactory::checkArgs(const std::vector&) const { // TODO: implement this. is this even necessary?, parser should take care of it return true; diff --git a/src/PLASMA/PlanDatabase/base/ObjectType.hh b/src/PLASMA/PlanDatabase/base/ObjectType.hh index 77c3487ee..af6a027f7 100644 --- a/src/PLASMA/PlanDatabase/base/ObjectType.hh +++ b/src/PLASMA/PlanDatabase/base/ObjectType.hh @@ -178,13 +178,14 @@ public: const PlanDatabaseId& planDb, const LabelStr& objectType, const LabelStr& objectName, - const std::vector& arguments) const { return ObjectId::noId(); }; + const std::vector& arguments) const; /** * @brief The body of the constructor after the object is created * any operations done by createInstance to the object after it is created must be done by this method * so that calls to "super()" in subclasses can be supported correctly */ - virtual void evalConstructorBody(ObjectId& instance, const std::vector& arguments) const {}; + virtual void evalConstructorBody(ObjectId& instance, + const std::vector& arguments) const; private: ObjectFactoryId m_id; diff --git a/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc b/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc index 8c8f816fc..54cdfdb1a 100644 --- a/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc +++ b/src/PLASMA/PlanDatabase/base/PDBInterpreter.cc @@ -86,6 +86,8 @@ namespace EUROPA { return TokenId::noId(); } +void* EvalContext::getElement(const char*) const {return NULL;} + std::string EvalContext::toString() const { std::ostringstream os; @@ -171,10 +173,9 @@ namespace EUROPA { { } - DataRef ExprNoop::eval(EvalContext& context) const - { - std::cout << "Noop:" << m_str << std::endl; - return DataRef::null; - } +DataRef ExprNoop::eval(EvalContext&) const { + std::cout << "Noop:" << m_str << std::endl; + return DataRef::null; +} } diff --git a/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh b/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh index 03b078a70..7e1ebe2e4 100644 --- a/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh +++ b/src/PLASMA/PlanDatabase/base/PDBInterpreter.hh @@ -26,27 +26,26 @@ namespace EUROPA { ConstrainedVariableId m_value; }; - class EvalContext - { - public: - EvalContext(EvalContext* parent); - virtual ~EvalContext(); +class EvalContext { + public: + EvalContext(EvalContext* parent); + virtual ~EvalContext(); - virtual void addVar(const char* name,const ConstrainedVariableId& v); - virtual ConstrainedVariableId getVar(const char* name); + virtual void addVar(const char* name,const ConstrainedVariableId& v); + virtual ConstrainedVariableId getVar(const char* name); - virtual void addToken(const char* name,const TokenId& t); - virtual TokenId getToken(const char* name); + virtual void addToken(const char* name,const TokenId& t); + virtual TokenId getToken(const char* name); - virtual void* getElement(const char* name) const { return NULL; } + virtual void* getElement(const char* name) const; - virtual std::string toString() const; + virtual std::string toString() const; - protected: - EvalContext* m_parent; - std::map m_variables; - std::map m_tokens; - }; + protected: + EvalContext* m_parent; + std::map m_variables; + std::map m_tokens; +}; class Expr { diff --git a/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.cc b/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.cc index 6b477de11..33806bf17 100644 --- a/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.cc +++ b/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.cc @@ -4,41 +4,52 @@ namespace EUROPA { +void PSPlanDatabaseListener::notifyAdded(PSObject*) {} +void PSPlanDatabaseListener::notifyRemoved(PSObject*) {} +void PSPlanDatabaseListener::notifyActivated(PSToken*) {} +void PSPlanDatabaseListener::notifyDeactivated(PSToken*) {} +void PSPlanDatabaseListener::notifyRejected(PSToken*) {} +void PSPlanDatabaseListener::notifyMerged(PSToken*) {} +void PSPlanDatabaseListener::notifySplit(PSToken*) {} +void PSPlanDatabaseListener::notifyAdded(PSObject*, PSToken*) {} +void PSPlanDatabaseListener::notifyRemoved(PSObject*, PSToken*) {} + + // Methods to convert notifications involving internal Europa types to notifications involving 'PS' types: void PSPlanDatabaseListener::notifyAdded(const ObjectId& object) { - notifyAdded((PSObject *) object); + notifyAdded(id_cast(object)); } void PSPlanDatabaseListener::notifyRemoved(const ObjectId& object) { - notifyRemoved((PSObject *) object); + notifyRemoved(id_cast(object)); } void PSPlanDatabaseListener::notifyActivated(const TokenId& token) { - notifyActivated((PSToken *) token); + notifyActivated(id_cast(token)); } void PSPlanDatabaseListener::notifyDeactivated(const TokenId& token) { - notifyDeactivated((PSToken *) token); + notifyDeactivated(id_cast(token)); } void PSPlanDatabaseListener::notifyRejected(const TokenId& token) { - notifyRejected((PSToken *) token); + notifyRejected(id_cast(token)); } void PSPlanDatabaseListener::notifyMerged(const TokenId& token) { - notifyMerged((PSToken *) token); + notifyMerged(id_cast(token)); } void PSPlanDatabaseListener::notifySplit(const TokenId& token) { - notifySplit((PSToken *) token); + notifySplit(id_cast(token)); } void PSPlanDatabaseListener::notifyAdded(const ObjectId& object, const TokenId& token) { - notifyAdded((PSObject *) object, (PSToken *) token); + notifyAdded(id_cast(object), id_cast(token)); } void PSPlanDatabaseListener::notifyRemoved(const ObjectId& object, const TokenId& token) { - notifyRemoved((PSObject *) object, (PSToken *) token); + notifyRemoved(id_cast(object), id_cast(token)); } diff --git a/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.hh b/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.hh index f6c4b80d4..7e1e16c42 100644 --- a/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.hh +++ b/src/PLASMA/PlanDatabase/base/PSPlanDatabaseListener.hh @@ -24,47 +24,47 @@ namespace EUROPA { * Constraint.hh and ConstrainedVariable.hh above (forewarned is forearmed!) */ - class PSPlanDatabaseListener : public PlanDatabaseListener { - public: - virtual ~PSPlanDatabaseListener() {} +class PSPlanDatabaseListener : public PlanDatabaseListener { + public: + virtual ~PSPlanDatabaseListener() {} - /* The subset of notifications available through PSEngine interface */ - virtual void notifyAdded(PSObject* object) {} - virtual void notifyRemoved(PSObject* object) {} - virtual void notifyActivated(PSToken* token) {} - virtual void notifyDeactivated(PSToken* token) {} - virtual void notifyRejected(PSToken* token) {} - virtual void notifyMerged(PSToken* token) {} - virtual void notifySplit(PSToken* token) {} - virtual void notifyAdded(PSObject* object, PSToken* token) {} - virtual void notifyRemoved(PSObject* object, PSToken* token) {} + /* The subset of notifications available through PSEngine interface */ + virtual void notifyAdded(PSObject* object); + virtual void notifyRemoved(PSObject* object); + virtual void notifyActivated(PSToken* token); + virtual void notifyDeactivated(PSToken* token); + virtual void notifyRejected(PSToken* token); + virtual void notifyMerged(PSToken* token); + virtual void notifySplit(PSToken* token); + virtual void notifyAdded(PSObject* object, PSToken* token); + virtual void notifyRemoved(PSObject* object, PSToken* token); - private: + private: - /* We override these base class methods (called by PlanDatabase) - * to call the above PS interface versions of the same methods. - */ - virtual void notifyAdded(const ObjectId& object); - virtual void notifyRemoved(const ObjectId& object); - virtual void notifyActivated(const TokenId& token); - virtual void notifyDeactivated(const TokenId& token); - virtual void notifyRejected(const TokenId& token); - virtual void notifyMerged(const TokenId& token); - virtual void notifySplit(const TokenId& token); - virtual void notifyAdded(const ObjectId& object, const TokenId& token); - virtual void notifyRemoved(const ObjectId& object, const TokenId& token); + /* We override these base class methods (called by PlanDatabase) + * to call the above PS interface versions of the same methods. + */ + virtual void notifyAdded(const ObjectId& object); + virtual void notifyRemoved(const ObjectId& object); + virtual void notifyActivated(const TokenId& token); + virtual void notifyDeactivated(const TokenId& token); + virtual void notifyRejected(const TokenId& token); + virtual void notifyMerged(const TokenId& token); + virtual void notifySplit(const TokenId& token); + virtual void notifyAdded(const ObjectId& object, const TokenId& token); + virtual void notifyRemoved(const ObjectId& object, const TokenId& token); - /* These methods are likely unnecessary to a user. We override the base - * class version only to make private (they still don't do anything) - */ - virtual void notifyAdded(const TokenId& token) {} - virtual void notifyRemoved(const TokenId& token) {} - virtual void notifyReinstated(const TokenId& token) {} - virtual void notifyConstrained(const ObjectId& object, const TokenId& predecessor, const TokenId& successor) {} - virtual void notifyFreed(const ObjectId& object, const TokenId& predecessor, const TokenId& successor) {} - virtual void notifyCommitted(const TokenId& token) {} - virtual void notifyTerminated(const TokenId& token) {} - }; + /* These methods are likely unnecessary to a user. We override the base + * class version only to make private (they still don't do anything) + */ + virtual void notifyAdded(const TokenId&) {} + virtual void notifyRemoved(const TokenId&) {} + virtual void notifyReinstated(const TokenId&) {} + virtual void notifyConstrained(const ObjectId&, const TokenId&, const TokenId&) {} + virtual void notifyFreed(const ObjectId&, const TokenId&, const TokenId&) {} + virtual void notifyCommitted(const TokenId&) {} + virtual void notifyTerminated(const TokenId&) {} +}; } diff --git a/src/PLASMA/PlanDatabase/base/PlanDatabase.cc b/src/PLASMA/PlanDatabase/base/PlanDatabase.cc index af7b54afc..702549120 100644 --- a/src/PLASMA/PlanDatabase/base/PlanDatabase.cc +++ b/src/PLASMA/PlanDatabase/base/PlanDatabase.cc @@ -82,17 +82,17 @@ namespace EUROPA{ purge(); if (!m_temporalAdvisor.isNoId()) - delete (TemporalAdvisor*) m_temporalAdvisor; + delete static_cast(m_temporalAdvisor); // Delete the client check_error(m_client.isValid()); - delete (DbClient*) m_client; + delete static_cast(m_client); delete m_psClient; // Delete all object variable listeners: for(ObjVarsByObjType_CI it = m_objectVariablesByObjectType.begin(); it != m_objectVariablesByObjectType.end(); ++it) - delete (ObjectVariableListener*) it->second.second; + delete static_cast(it->second.second); m_id.remove(); } @@ -396,7 +396,7 @@ namespace EUROPA{ "PlanDatabase:getCompatibleTokens", "No candidates to evaluate for " << inactiveToken->toString()); const std::vector& inactiveTokenVariables = inactiveToken->getVariables(); - int variableCount = inactiveTokenVariables.size(); + unsigned long variableCount = inactiveTokenVariables.size(); unsigned int choiceCount = 0; // Used for comparison against given limit @@ -418,7 +418,7 @@ namespace EUROPA{ const std::vector& candidateTokenVariables = candidate->getVariables(); // Check assumption that the set of variables is the same - checkError(candidateTokenVariables.size() == (unsigned int) variableCount, + checkError(candidateTokenVariables.size() == static_cast(variableCount), "Candidate token (" << candidate->getKey() << ") has " << candidateTokenVariables.size() << " variables, while inactive token (" << inactiveToken->getKey() << ") has " << variableCount); @@ -432,7 +432,7 @@ namespace EUROPA{ check_error(inactiveTokenVariables[0] == inactiveToken->getState(), "We expect the first var to be the state var, which we must skip."); - for(int i=1;ilastDomain(); const Domain& domB = candidateTokenVariables[i]->lastDomain(); @@ -496,13 +496,13 @@ namespace EUROPA{ getCompatibleTokens(inactiveToken, results, std::numeric_limits::max(), false); } - unsigned int PlanDatabase::countCompatibleTokens(const TokenId& inactiveToken, - unsigned int limit, - bool useExactTest){ - std::vector results; - getCompatibleTokens(inactiveToken, results, limit, useExactTest); - return results.size(); - } +unsigned long PlanDatabase::countCompatibleTokens(const TokenId& inactiveToken, + unsigned int limit, + bool useExactTest){ + std::vector results; + getCompatibleTokens(inactiveToken, results, limit, useExactTest); + return results.size(); +} const std::map >& PlanDatabase::getTokensToOrder(){ return m_tokensToOrder; @@ -542,14 +542,14 @@ namespace EUROPA{ checkError(results.size() <= limit, "Cutoff must be enforced."); } - unsigned int PlanDatabase::countOrderingChoices(const TokenId& token, - unsigned int limit){ + unsigned long PlanDatabase::countOrderingChoices(const TokenId& token, + unsigned long limit){ if(!m_constraintEngine->propagate()) return 0; std::list objects; token->getObject()->lastDomain().getValues(objects); - unsigned int choiceCount = 0; + unsigned long choiceCount = 0; for(std::list::const_iterator it = objects.begin(); it != objects.end(); ++it){ ObjectId object = Entity::getTypedEntity(*it); choiceCount = choiceCount + object->countOrderingChoices(token, limit-choiceCount); @@ -560,11 +560,11 @@ namespace EUROPA{ return choiceCount; } - unsigned int PlanDatabase::lastOrderingChoiceCount(const TokenId& token) const{ + unsigned long PlanDatabase::lastOrderingChoiceCount(const TokenId& token) const{ checkError(m_constraintEngine->constraintConsistent(), "Cannot query for ordering choices while database is not constraintConsistent."); std::list objects; - unsigned int choiceCount = 0; + unsigned long choiceCount = 0; token->getObject()->lastDomain().getValues(objects); for(std::list::const_iterator it = objects.begin(); it != objects.end(); ++it){ ObjectId object = Entity::getTypedEntity(*it); @@ -652,7 +652,7 @@ namespace EUROPA{ check_error(connectedObjectVariable.isValid()); if(!connectedObjectVariable->isClosed()) connectedObjectVariable->close(); - delete (ObjectVariableListener*) it->second.second; + delete static_cast(it->second.second); m_objectVariablesByObjectType.erase(it++); } @@ -675,7 +675,7 @@ namespace EUROPA{ connectedObjectVariable->close(); debugMsg("PlanDatabase:close","Closing "+objectType.toString()+" closed "+connectedObjectVariable->toString()); } - delete (ObjectVariableListener*) it->second.second; + delete static_cast(it->second.second); m_objectVariablesByObjectType.erase(it++); } m_closedObjectTypes.insert(objectType); @@ -854,19 +854,19 @@ namespace EUROPA{ /** * @brief Remove */ - void PlanDatabase::handleObjectVariableDeletion(const ConstrainedVariableId& objectVar){ - - // Now iterate over objectVariables stored and remove them - should be at least one reference - for(ObjVarsByObjType_I it = m_objectVariablesByObjectType.begin(); - it != m_objectVariablesByObjectType.end();){ - if(it->second.first == objectVar){ - delete (ObjectVariableListener*) it->second.second; - m_objectVariablesByObjectType.erase(it++); - } - else - ++it; +void PlanDatabase::handleObjectVariableDeletion(const ConstrainedVariableId& objectVar){ + + // Now iterate over objectVariables stored and remove them - should be at least one reference + for(ObjVarsByObjType_I it = m_objectVariablesByObjectType.begin(); + it != m_objectVariablesByObjectType.end();){ + if(it->second.first == objectVar){ + delete static_cast(it->second.second); + m_objectVariablesByObjectType.erase(it++); } + else + ++it; } +} void PlanDatabase::handleObjectVariableCreation(const LabelStr& objectType, const ConstrainedVariableId& objectVar, @@ -883,50 +883,50 @@ namespace EUROPA{ return Entity::getEntity(key); } - unsigned int PlanDatabase::archive(eint tick){ - checkError(getConstraintEngine()->constraintConsistent(), - "Must be propagated to a consistent state before archiving."); +unsigned long PlanDatabase::archive(eint tick){ + checkError(getConstraintEngine()->constraintConsistent(), + "Must be propagated to a consistent state before archiving."); - const unsigned int initialCount = getTokens().size(); + const unsigned long initialCount = getTokens().size(); - // Build a collection of tokens ordered by earliest start time. This is done to make cleaning up - // of structures like a timeline more efficient. No measurements backing this up or evaluating the true cost - // of this algorithm - std::multimap tokensToRemove; - { - EntityIterator< TokenSet::const_iterator > tokenIterator(m_tokens.begin(), m_tokens.end()); - while(!tokenIterator.done()){ - TokenId token = tokenIterator.next(); + // Build a collection of tokens ordered by earliest start time. This is done to make cleaning up + // of structures like a timeline more efficient. No measurements backing this up or evaluating the true cost + // of this algorithm + std::multimap tokensToRemove; + { + EntityIterator< TokenSet::const_iterator > tokenIterator(m_tokens.begin(), m_tokens.end()); + while(!tokenIterator.done()){ + TokenId token = tokenIterator.next(); - // Do not store merged tokens for removal since we will terminate them when we terminate the - // supporting token. - if(token->isMerged()) - continue; + // Do not store merged tokens for removal since we will terminate them when we terminate the + // supporting token. + if(token->isMerged()) + continue; - eint latestEndTime = cast_int(token->end()->lastDomain().getUpperBound()); + eint latestEndTime = cast_int(token->end()->lastDomain().getUpperBound()); - if(latestEndTime <= tick && token->canBeTerminated(tick)){ - debugMsg("PlanDatabase:archive:remove", - token->toString() << " ending by " << latestEndTime << " for tick " << tick); - eint earliestStartTime = cast_int(token->start()->lastDomain().getLowerBound()); - tokensToRemove.insert(std::make_pair(earliestStartTime, token)); - } - else { - condDebugMsg(!token->isMerged(), "PlanDatabase:archive:skip", - token->toString() << " with end time " << token->end()->toString() << " for tick " << tick); - } + if(latestEndTime <= tick && token->canBeTerminated(tick)){ + debugMsg("PlanDatabase:archive:remove", + token->toString() << " ending by " << latestEndTime << " for tick " << tick); + eint earliestStartTime = cast_int(token->start()->lastDomain().getLowerBound()); + tokensToRemove.insert(std::make_pair(earliestStartTime, token)); + } + else { + condDebugMsg(!token->isMerged(), "PlanDatabase:archive:skip", + token->toString() << " with end time " << token->end()->toString() << " for tick " << tick); } } + } - for(std::multimap::const_iterator it = tokensToRemove.begin(); it != tokensToRemove.end(); ++it){ - TokenId token = it->second; - token->terminate(); - token->discard(); - } - - return initialCount-getTokens().size(); + for(std::multimap::const_iterator it = tokensToRemove.begin(); it != tokensToRemove.end(); ++it){ + TokenId token = it->second; + token->terminate(); + token->discard(); } + return initialCount-getTokens().size(); +} + void PlanDatabase::insertActiveToken(const TokenId& token){ static const LabelStr sl_objectRoot("Object"); static const LabelStr sl_timelineRoot("Timeline"); @@ -989,71 +989,68 @@ namespace EUROPA{ } // PSPlanDatabase methods - PSList PlanDatabase::getAllObjects() const { - PSList retval; - const ObjectSet& objects = getObjects(); - for(ObjectSet::const_iterator it = objects.begin(); it != objects.end(); ++it) - retval.push_back((PSObject*) *it); - return retval; - } - - PSList PlanDatabase::getObjectsByType(const std::string& objectType) const - { - PSList retval; - - const ObjectSet& objects = getObjects(); - for(ObjectSet::const_iterator it = objects.begin(); it != objects.end(); ++it){ - ObjectId object = *it; - if(m_schema->isA(object->getType(), objectType.c_str())) - retval.push_back((PSObject *) object); - } +PSList PlanDatabase::getAllObjects() const { + PSList retval; + const ObjectSet& objects = getObjects(); + for(ObjectSet::const_iterator it = objects.begin(); it != objects.end(); ++it) + retval.push_back(id_cast(*it)); + return retval; +} - return retval; - } +PSList PlanDatabase::getObjectsByType(const std::string& objectType) const { + PSList retval; - PSObject* PlanDatabase::getObjectByKey(PSEntityKey id) const - { - ObjectId object = Entity::getEntity(id); - check_runtime_error(object.isValid()); - return (PSObject *) object; + const ObjectSet& objects = getObjects(); + for(ObjectSet::const_iterator it = objects.begin(); it != objects.end(); ++it){ + ObjectId object = *it; + if(m_schema->isA(object->getType(), objectType.c_str())) + retval.push_back(id_cast(object)); } - PSObject* PlanDatabase::getObjectByName(const std::string& name) const { - ObjectId object = getObject(LabelStr(name)); - check_runtime_error(object.isValid()); - return (PSObject *) object; - } - - PSList PlanDatabase::getAllTokens() const { - const TokenSet& tokens = getTokens(); - PSList retval; + return retval; +} - for(TokenSet::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { - TokenId id = *it; - retval.push_back((PSToken *) id); - } +PSObject* PlanDatabase::getObjectByKey(PSEntityKey id) const { + ObjectId object = Entity::getEntity(id); + check_runtime_error(object.isValid()); + return id_cast(object); +} - return retval; - } +PSObject* PlanDatabase::getObjectByName(const std::string& name) const { + ObjectId object = getObject(LabelStr(name)); + check_runtime_error(object.isValid()); + return id_cast(object); +} - PSToken* PlanDatabase::getTokenByKey(PSEntityKey id) const - { - Id psId = Entity::getEntity(id); - check_runtime_error(psId.isValid()); - return (PSToken *) psId; +PSList PlanDatabase::getAllTokens() const { + const TokenSet& tokens = getTokens(); + PSList retval; + + for(TokenSet::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { + TokenId id = *it; + retval.push_back(id_cast(id)); } + + return retval; +} - PSList PlanDatabase::getAllGlobalVariables() const { +PSToken* PlanDatabase::getTokenByKey(PSEntityKey id) const { + Id psId = Entity::getEntity(id); + check_runtime_error(psId.isValid()); + return id_cast(psId); +} - const ConstrainedVariableSet& vars = getGlobalVariables(); - PSList retval; +PSList PlanDatabase::getAllGlobalVariables() const { - for(ConstrainedVariableSet::const_iterator it = vars.begin(); it != vars.end(); ++it) { - ConstrainedVariableId id = *it; - retval.push_back((PSVariable *) id); - } - return retval; + const ConstrainedVariableSet& vars = getGlobalVariables(); + PSList retval; + + for(ConstrainedVariableSet::const_iterator it = vars.begin(); it != vars.end(); ++it) { + ConstrainedVariableId id = *it; + retval.push_back(id_cast(id)); } + return retval; +} ObjectId PlanDatabase::createObject(const LabelStr& objectType, const LabelStr& objectName, @@ -1068,20 +1065,20 @@ namespace EUROPA{ return object; } - std::string autoLabel(const char* prefix) - { - static int cnt = 0; - std::ostringstream os; - - os << prefix << "_" << cnt++; - return os.str(); - } +namespace { +std::string autoLabel(const char* prefix) { + static int cnt = 0; + std::ostringstream os; + + os << prefix << "_" << cnt++; + return os.str(); +} +} - TokenId PlanDatabase::createToken(const char* tokenType, - const char* tokenName, - bool rejectable, - bool isFact) - { +TokenId PlanDatabase::createToken(const char* tokenType, + const char* tokenName, + bool rejectable, + bool isFact) { LabelStr ttype(tokenType); std::string nameStr = (tokenName != NULL ? tokenName : autoLabel("globalToken")); LabelStr tname(nameStr); diff --git a/src/PLASMA/PlanDatabase/base/PlanDatabase.hh b/src/PLASMA/PlanDatabase/base/PlanDatabase.hh index 6d6276e62..8fbde45f8 100644 --- a/src/PLASMA/PlanDatabase/base/PlanDatabase.hh +++ b/src/PLASMA/PlanDatabase/base/PlanDatabase.hh @@ -98,7 +98,7 @@ namespace EUROPA { /** * @brief Register an allocated global variable. - * @param var. The variable to be registered. Must not have a parent. Furthermore, the name of the variable must be unique in this scope. + * @param var The variable to be registered. Must not have a parent. Furthermore, the name of the variable must be unique in this scope. */ void registerGlobalVariable(const ConstrainedVariableId& var); @@ -134,7 +134,7 @@ namespace EUROPA { /** * @brief Test if the given inactive token has any tokens with which it can merge. - * @param inactiveToken + * @param inactiveToken The token to check for merge candidates. * @return true if there is 1 or more tokens with which to merge, otherwse false. * @see getCompatibleTokens, countCompatibleTokens */ @@ -172,13 +172,13 @@ namespace EUROPA { * @brief Returns a count of compatible tokens up to the given limit * @see getCompatibleTokens */ - unsigned int countCompatibleTokens(const TokenId& inactiveToken, + unsigned long countCompatibleTokens(const TokenId& inactiveToken, #ifdef _MSC_VER - unsigned int limit = UINT_MAX, //std::numeric_limits::max(), + unsigned int limit = UINT_MAX, //std::numeric_limits::max(), #else - unsigned int limit = std::numeric_limits::max(), + unsigned int limit = std::numeric_limits::max(), #endif //_MSC_VER - bool useExactTest = false); + bool useExactTest = false); /** * @brief Returns the last count obtained for the prior call to query the set of compatible tokens. This can be useful @@ -212,11 +212,11 @@ namespace EUROPA { * @brief Returns a count or all ordering choices for a token up to the given limit * @see Object::getOrderingChoices */ - unsigned int countOrderingChoices(const TokenId& token, + unsigned long countOrderingChoices(const TokenId& token, #ifdef _MSC_VER - unsigned int limit = UINT_MAX //std::numeric_limits::max(), + unsigned long limit = UINT_MAX //std::numeric_limits::max(), #else - unsigned int limit = std::numeric_limits::max() + unsigned long limit = std::numeric_limits::max() #endif //_MSC_VER ); /** @@ -224,7 +224,7 @@ namespace EUROPA { * @param token The token for which we want ordering choices. Cannot be rejected. * @return The last count value */ - unsigned int lastOrderingChoiceCount(const TokenId& token) const; + unsigned long lastOrderingChoiceCount(const TokenId& token) const; /** * @brief True if there is at least one ordering choice @@ -307,7 +307,7 @@ namespace EUROPA { * @note We can extend this to pass in a functor or some other object to allow it to handle archival details. * @see Object::archive */ - unsigned int archive(eint tick = PLUS_INFINITY); + unsigned long archive(eint tick = PLUS_INFINITY); // PSPlanDatabase methods diff --git a/src/PLASMA/PlanDatabase/base/PlanDatabaseListener.cc b/src/PLASMA/PlanDatabase/base/PlanDatabaseListener.cc index 947d44a27..a4e6ca040 100644 --- a/src/PLASMA/PlanDatabase/base/PlanDatabaseListener.cc +++ b/src/PLASMA/PlanDatabase/base/PlanDatabaseListener.cc @@ -29,37 +29,37 @@ namespace EUROPA { } - void PlanDatabaseListener::notifyAdded(const ObjectId& object){} + void PlanDatabaseListener::notifyAdded(const ObjectId&){} - void PlanDatabaseListener::notifyRemoved(const ObjectId& object){} + void PlanDatabaseListener::notifyRemoved(const ObjectId&){} - void PlanDatabaseListener::notifyAdded(const TokenId& token){} + void PlanDatabaseListener::notifyAdded(const TokenId&){} - void PlanDatabaseListener::notifyRemoved(const TokenId& token){} + void PlanDatabaseListener::notifyRemoved(const TokenId&){} - void PlanDatabaseListener::notifyActivated(const TokenId& token){} + void PlanDatabaseListener::notifyActivated(const TokenId&){} - void PlanDatabaseListener::notifyDeactivated(const TokenId& token){} + void PlanDatabaseListener::notifyDeactivated(const TokenId&){} - void PlanDatabaseListener::notifyMerged(const TokenId& token){} + void PlanDatabaseListener::notifyMerged(const TokenId&){} - void PlanDatabaseListener::notifySplit(const TokenId& token){} + void PlanDatabaseListener::notifySplit(const TokenId&){} - void PlanDatabaseListener::notifyRejected(const TokenId& token){} + void PlanDatabaseListener::notifyRejected(const TokenId&){} - void PlanDatabaseListener::notifyReinstated(const TokenId& token){} + void PlanDatabaseListener::notifyReinstated(const TokenId&){} - void PlanDatabaseListener::notifyConstrained(const ObjectId& object, const TokenId& predecessor, const TokenId& successor){} + void PlanDatabaseListener::notifyConstrained(const ObjectId&, const TokenId&, const TokenId& ){} - void PlanDatabaseListener::notifyFreed(const ObjectId& object, const TokenId& predecessor, const TokenId& successor){} + void PlanDatabaseListener::notifyFreed(const ObjectId&, const TokenId&, const TokenId&){} - void PlanDatabaseListener::notifyAdded(const ObjectId& object, const TokenId& token){} + void PlanDatabaseListener::notifyAdded(const ObjectId&, const TokenId&){} - void PlanDatabaseListener::notifyRemoved(const ObjectId& object, const TokenId& token){} + void PlanDatabaseListener::notifyRemoved(const ObjectId&, const TokenId&){} - void PlanDatabaseListener::notifyCommitted(const TokenId& token){} + void PlanDatabaseListener::notifyCommitted(const TokenId&){} - void PlanDatabaseListener::notifyTerminated(const TokenId& token){} + void PlanDatabaseListener::notifyTerminated(const TokenId&){} const PlanDatabaseListenerId& PlanDatabaseListener::getId() const{return m_id;} } diff --git a/src/PLASMA/PlanDatabase/base/Schema.cc b/src/PLASMA/PlanDatabase/base/Schema.cc index d49a0665e..f5c57931f 100644 --- a/src/PLASMA/PlanDatabase/base/Schema.cc +++ b/src/PLASMA/PlanDatabase/base/Schema.cc @@ -65,15 +65,11 @@ namespace EUROPA { Schema::~Schema() { - delete (TokenTypeMgr*)m_tokenTypeMgr; - delete (ObjectTypeMgr*)m_objectTypeMgr; + delete static_cast(m_tokenTypeMgr); + delete static_cast(m_objectTypeMgr); - std::map::iterator mit = m_methods.begin(); - for(;mit != m_methods.end();++mit) - delete (Method*)mit->second; - m_methods.clear(); - - m_id.remove(); + cleanup(m_methods); + m_id.remove(); } const SchemaId& Schema::getId() const {return m_id;} @@ -493,7 +489,7 @@ namespace EUROPA { return LabelStr("error"); } - unsigned int Schema::getParameterCount(const LabelStr& predicate) const { + unsigned long Schema::getParameterCount(const LabelStr& predicate) const { check_error(isPredicate(predicate), predicate.toString() + " is not defined as a Predicate"); // First see if we get a hit for the parentType std::map::const_iterator membershipRelation_it = @@ -589,7 +585,7 @@ namespace EUROPA { /** * @todo memberType is not checked yet. It can be a class, enum, or primitive */ - unsigned int Schema::addMember(const LabelStr& parentType, + unsigned long Schema::addMember(const LabelStr& parentType, const LabelStr& memberType, const LabelStr& memberName) { check_error(isType(parentType), parentType.toString() + " is undefined."); @@ -688,29 +684,30 @@ namespace EUROPA { results.push_back(it->first); } - const Id& createDefaultObjectFactory( +namespace { +const Id& createDefaultObjectFactory( const ObjectTypeId& objType, - bool canCreateObjects) - { - std::vector constructorArgNames; - std::vector constructorArgTypes; - std::vector constructorBody; - ExprConstructorSuperCall* superCallExpr = NULL; - - // If it can't create objects, generate default super call - if (!canCreateObjects) - superCallExpr = new ExprConstructorSuperCall(objType->getParent()->getName(),std::vector()); - - return (new InterpretedObjectFactory( - objType, - objType->getName(), - constructorArgNames, - constructorArgTypes, - superCallExpr, - constructorBody, - canCreateObjects) - )->getId(); - } + bool canCreateObjects) { + std::vector constructorArgNames; + std::vector constructorArgTypes; + std::vector constructorBody; + ExprConstructorSuperCall* superCallExpr = NULL; + + // If it can't create objects, generate default super call + if (!canCreateObjects) + superCallExpr = new ExprConstructorSuperCall(objType->getParent()->getName(),std::vector()); + + return (new InterpretedObjectFactory( + objType, + objType->getName(), + constructorArgNames, + constructorArgTypes, + superCallExpr, + constructorBody, + canCreateObjects) + )->getId(); +} +} void Schema::registerObjectType(const ObjectTypeId& objType) { @@ -810,48 +807,46 @@ namespace EUROPA { m_methods[m->getName()] = m; } - MethodId Schema::getMethod(const LabelStr& methodName, const DataTypeId& targetType, const std::vector& argTypes) + MethodId Schema::getMethod(const LabelStr& methodName, const DataTypeId&, const std::vector&) { // TODO: use target type and arg types to resolve std::map::iterator it = m_methods.find(methodName); return (it != m_methods.end() ? it->second : MethodId::noId()); } - std::vector Schema::getTypeSupporters( TokenTypeId type ) - { - edouble key = type->getSignature().getKey(); - std::vector retval; +std::vector Schema::getTypeSupporters( TokenTypeId type ) { + edouble key = type->getSignature().getKey(); + std::vector retval; - PSList actionTypes = getPSTokenTypesByAttr( PSTokenType::ACTION ); + PSList actionTypes = getPSTokenTypesByAttr( PSTokenType::ACTION ); - for( int i = 0; i < actionTypes.size(); i++){ + for( int i = 0; i < actionTypes.size(); i++){ - TokenType* tt = (TokenType*)actionTypes.get( i ); - PSList effects = tt->getSubgoalsByAttr( PSTokenType::EFFECT); + TokenType* tt = dynamic_cast(actionTypes.get( i )); + PSList effects = tt->getSubgoalsByAttr( PSTokenType::EFFECT); - for ( int i = 0; i < effects.size(); i++ ) { - TokenType* tt_effect = (TokenType*) effects.get(i); - if( tt_effect->getSignature().getKey() == key) - retval.push_back( tt->getId() ); - } + for (long j = 0; j < effects.size(); j++ ) { + TokenType* tt_effect = dynamic_cast(effects.get(j)); + if( tt_effect->getSignature().getKey() == key) + retval.push_back( tt->getId() ); } + } - return retval; + return retval; - } +} // PSSchema methods: - PSList Schema::getAllPredicates() const - { - PSList retval; - std::set predicates; - getPredicates(predicates); - for(std::set::const_iterator it = predicates.begin(); it != predicates.end(); ++it) - { - retval.push_back((*it).toString()); - } - return retval; - } +PSList Schema::getAllPredicates() const { + PSList retval; + std::set predicates_; + getPredicates(predicates_); + for(std::set::const_iterator it = predicates_.begin(); it != predicates_.end(); + ++it) { + retval.push_back((*it).toString()); + } + return retval; +} PSList Schema::getAllPSObjectTypes() const { PSList retval; diff --git a/src/PLASMA/PlanDatabase/base/Schema.hh b/src/PLASMA/PlanDatabase/base/Schema.hh index aad1873d5..adaf58fc1 100644 --- a/src/PLASMA/PlanDatabase/base/Schema.hh +++ b/src/PLASMA/PlanDatabase/base/Schema.hh @@ -98,10 +98,10 @@ namespace EUROPA { bool isEnum(const LabelStr& str) const; /** - * @brief Test if the given value is a member of the given enum + * @brief Test if the given value is a member of the given enum. Calling this + * function with a name that isn't an enum is an error. * @param enumName The name of the enumeration * @param value The value to be tested. - * @error !isEnum(enum) */ bool isEnumValue(const LabelStr& enumName, edouble value) const; @@ -199,10 +199,10 @@ namespace EUROPA { const std::vector& getAllObjectTypes(const LabelStr& objectType); /** - * @brief Obtains the set of values for an enumeration. + * @brief Obtains the set of values for an enumeration. Calling this function with a + * name not of an enumeration is an error. * @param enumName enumeration type name. * @return a const ref to the set of values for enumName. - * @error !isEnum(enumName). */ const std::set& getEnumValues(const LabelStr& enumName) const; @@ -213,11 +213,10 @@ namespace EUROPA { const LabelStr& getEnumForValue(edouble value) const; /** - * @brief Obtain the set of predicates for a given object type. + * @brief Obtain the set of predicates for a given object type. Errors if objectType + * doesn't name an object type. * @param objectType The ObjectType to use - * @return a const ref to a set of LabelStr (each of which is the name of a Predicate) * @see addObjectType, isType - * @error !isType(objecttype) */ void getPredicates(const LabelStr& objectType, std::set& results) const; @@ -242,10 +241,10 @@ namespace EUROPA { bool makeParentPredicateString(const LabelStr& predicate, std::string& predStr) const; /** - * @brief Obtain the object type for the given predicate. + * @brief Obtain the object type for the given predicate. Errors if predicate doesn't + * name an existing predicate. * @param predicate The predicate to use * @see addPredicate, isPredicateDefined - * @error !isPredicateDefined(predicate) */ const LabelStr getObjectTypeForPredicate(const LabelStr& predicate) const; @@ -270,17 +269,16 @@ namespace EUROPA { const LabelStr getEnumFromMember(const LabelStr& member) const; /** - * @brief Gets the number of parameters in a predicate + * @brief Gets the number of parameters in a predicate. Error: !isPredicateDefined(predicate) * @param predicate the name of the predicate - * @error !isPredicateDefined(predicate) */ - unsigned int getParameterCount(const LabelStr& predicate) const; + unsigned long getParameterCount(const LabelStr& predicate) const; /** - * @brief Gets the type of parameter at a particular index location in a predicate + * @brief Gets the type of parameter at a particular index location in a predicate. + * Errors: !isPredicateDefined(predicate) * @param predicate the name of the predicate * @param paramIndex the index of the parameter - * @error !isPredicateDefined(predicate) */ const LabelStr getParameterType(const LabelStr& predicate, unsigned int paramIndex) const; @@ -308,9 +306,8 @@ namespace EUROPA { const LabelStr& parent); /** - * @brief Adds a predicate. + * @brief Adds a predicate. Errors: !isObjectType(prefix), isPredicateDefined(suffix) * @param predicate The fully qualified name of the predicate. Must be of the form . - * @error !isObjectType(prefix), isPredicateDefined(suffix) */ void addPredicate(const LabelStr& predicate); @@ -321,7 +318,7 @@ namespace EUROPA { * @param memberName The name of the composed member * @return The indexed position of the parameter in the predicate list of parameters. */ - unsigned int addMember(const LabelStr& parentObjectType, + unsigned long addMember(const LabelStr& parentObjectType, const LabelStr& memberType, const LabelStr& memberName); diff --git a/src/PLASMA/PlanDatabase/base/StackMemento.cc b/src/PLASMA/PlanDatabase/base/StackMemento.cc index 69f308812..9af4703c6 100644 --- a/src/PLASMA/PlanDatabase/base/StackMemento.cc +++ b/src/PLASMA/PlanDatabase/base/StackMemento.cc @@ -39,16 +39,10 @@ namespace EUROPA{ void StackMemento::undo(bool){ check_error(!m_stackConstraints.empty()); // Delete all new constraints. - for(std::list::const_iterator it = m_stackConstraints.begin(); it!= m_stackConstraints.end(); ++it) { - ConstraintId constraint = *it; - check_error(constraint.isValid()); - delete (Constraint*) constraint; - } - - m_stackConstraints.clear(); + cleanup(m_stackConstraints); } - void StackMemento::handleAdditionOfInactiveConstraint(const ConstraintId& constraint){ } + void StackMemento::handleAdditionOfInactiveConstraint(const ConstraintId&){ } - void StackMemento::handleRemovalOfInactiveConstraint(const ConstraintId& constraint){ } + void StackMemento::handleRemovalOfInactiveConstraint(const ConstraintId&){ } } diff --git a/src/PLASMA/PlanDatabase/base/Token.cc b/src/PLASMA/PlanDatabase/base/Token.cc index 8cb89e306..064a40299 100644 --- a/src/PLASMA/PlanDatabase/base/Token.cc +++ b/src/PLASMA/PlanDatabase/base/Token.cc @@ -18,7 +18,6 @@ * @author Conor McGann */ -#define MERGING 1 namespace EUROPA{ @@ -179,16 +178,13 @@ namespace EUROPA{ /** * This works because we have key based comparators which allow us to rely on positions */ - const TokenId& Token::getSlave(int slavePosition) const{ - int i = 0; - for(TokenSet::const_iterator it = m_slaves.begin(); it != m_slaves.end(); ++it){ - if(i == slavePosition) - return *it; - else - i++; - } +const TokenId& Token::getSlave(unsigned int slavePosition) const{ + if(slavePosition >= m_slaves.size()) return TokenId::noId(); - } + TokenSet::const_iterator it = m_slaves.begin(); + std::advance(it, slavePosition); + return *it; +} int Token::getSlavePosition(const TokenId& slave) const{ int i = 0; @@ -728,110 +724,113 @@ void Token::doMerge(const TokenId& activeToken){ * @brief Tests if a token can be terminated. * @see terminate */ - bool Token::canBeTerminated(eint tick) const{ - if(isTerminated()) +bool Token::canBeTerminated(eint) const{ + if(isTerminated()) + return false; + + // Rejected tokens can be immediately terminated without any consideration of their variables or their constraints + if(isRejected()) + return true; + + // Now if it has any merged tokens, it cannot be terminated. The merged tokens must be removed first + if(!m_mergedTokens.empty()){ + debugMsg("Token:canBeTerminated", + "Cannot terminate " << toString() << + " because of remaining supported token " << + (*m_mergedTokens.begin())->toString()); + return false; + } + + // Use this count for iteration later + const unsigned long varCount = m_allVariables.size(); + + // If merged, it is redundant if the variables in its scope are supersets of the corresponding active token variable base domain + if(isMerged()){ + TokenId activeToken = getActiveToken(); + + // No basis for termination if active token is not committed. + if(!activeToken->isCommitted()){ + debugMsg("Token:canBeTerminated", "Cannot terminate " << toString() << " which is a slave of " << m_master->toString()); return false; + } - // Rejected tokens can be immediately terminated without any consideration of their variables or their constraints - if(isRejected()) + // Definitiely can terminate if the active token is terminated + if(activeToken->isTerminated()) return true; - // Now if it has any merged tokens, it cannot be terminated. The merged tokens must be removed first - if(!m_mergedTokens.empty()){ - debugMsg("Token:canBeTerminated", "Cannot terminate " << toString() << " because of remaining supported token " << ((TokenId) * (m_mergedTokens.begin()))->toString() ); - return false; + // Finally, we have to analyze the variables to see if the merged token is imposing restrictions on the active token + // that would be lost if it were removed. The anaylsis will check that the base domain of the active token is a subset of the + // derived domain of the merged token. + const std::vector& activeVariables = activeToken->getVariables(); + // All variables except state variable + for(unsigned int i = 1; i < varCount; i++){ + const Domain& activeBaseDomain = activeVariables[i]->baseDomain(); + const Domain& inactiveDerivedDomain = m_allVariables[i]->lastDomain(); + if(!activeBaseDomain.isSubsetOf(inactiveDerivedDomain)){ + debugMsg("Token:canBeTerminated", + "Cannot terminate " << this->toString() << activeBaseDomain.toString() << " can be further restricted by " << inactiveDerivedDomain.toString() << std::endl << + "Active Variable: " << activeVariables[i]->toString() << " Inactive Variable: " << m_allVariables[i]->toString()); + + return false; + } } - // Use this count for iteration later - const unsigned int varCount = m_allVariables.size(); + return true; + } - // If merged, it is redundant if the variables in its scope are supersets of the corresponding active token variable base domain - if(isMerged()){ - TokenId activeToken = getActiveToken(); + // + // Declare a set to pull together all variables in the scope of a token into a single easy to check collection. + // Could manage this incrementally on the token also for greater efficiency + std::set allVars; - // No basis for termination if active token is not committed. - if(!activeToken->isCommitted()){ - debugMsg("Token:canBeTerminated", "Cannot terminate " << toString() << " which is a slave of " << m_master->toString()); - return false; - } + // Construct the set of constraints on variables of this token. Use a constraint set to avoid memory dependent order. + ConstraintSet constraints; + for(unsigned int i = 0; i < varCount; i++){ + ConstrainedVariableId var = m_allVariables[i]; + var->constraints(constraints); + allVars.insert(var->getKey()); + } - // Definitiely can terminate if the active token is terminated - if(activeToken->isTerminated()) - return true; - - // Finally, we have to analyze the variables to see if the merged token is imposing restrictions on the active token - // that would be lost if it were removed. The anaylsis will check that the base domain of the active token is a subset of the - // derived domain of the merged token. - const std::vector& activeVariables = activeToken->getVariables(); - // All variables except state variable - for(unsigned int i = 1; i < varCount; i++){ - const Domain& activeBaseDomain = activeVariables[i]->baseDomain(); - const Domain& inactiveDerivedDomain = m_allVariables[i]->lastDomain(); - if(!activeBaseDomain.isSubsetOf(inactiveDerivedDomain)){ - debugMsg("Token:canBeTerminated", - "Cannot terminate " << this->toString() << activeBaseDomain.toString() << " can be further restricted by " << inactiveDerivedDomain.toString() << std::endl << - "Active Variable: " << activeVariables[i]->toString() << " Inactive Variable: " << m_allVariables[i]->toString()); - - return false; - } - } + for(ConstrainedVariableSet::const_iterator it = m_localVariables.begin(); it != m_localVariables.end(); ++it){ + ConstrainedVariableId var = *it; + var->constraints(constraints); + allVars.insert(var->getKey()); + } - return true; - } + for(ConstraintSet::const_iterator it = constraints.begin(); it != constraints.end(); ++it){ + ConstraintId constraint = *it; + checkError(constraint.isValid(), constraint); - // - // Declare a set to pull together all variables in the scope of a token into a single easy to check collection. - // Could manage this incrementally on the token also for greater efficiency - std::set allVars; + // No problem if the constraint has been deactivated already + if(!constraint->isActive() || constraint->isRedundant()) + continue; - // Construct the set of constraints on variables of this token. Use a constraint set to avoid memory dependent order. - ConstraintSet constraints; - for(unsigned int i = 0; i < varCount; i++){ - ConstrainedVariableId var = m_allVariables[i]; - var->constraints(constraints); - allVars.insert(var->getKey()); - } + // If it is active, then we should ensure it has at least one external variable + const std::vector& scope = constraint->getScope(); + for(unsigned int i=0;iconstraints(constraints); - allVars.insert(var->getKey()); - } + // If the variable has no parent, its scope is not defined temporally. This is typically only arising + // in initialization. + if (var->parent().isNoId()) + continue; - for(ConstraintSet::const_iterator it = constraints.begin(); it != constraints.end(); ++it){ - ConstraintId constraint = *it; - checkError(constraint.isValid(), constraint); - - // No problem if the constraint has been deactivated already - if(!constraint->isActive() || constraint->isRedundant()) - continue; - - // If it is active, then we should ensure it has at least one external variable - const std::vector& scope = constraint->getScope(); - for(unsigned int i=0;iparent().isNoId()) - continue; - - // If it is a culprit with an unbound domain, and an external variable, - // then it is an external constraint that must be retained and so we cannot terminate - if(allVars.find(var->getKey()) == allVars.end() && !var->baseDomain().isSingleton()){ - debugMsg("Token:canBeTerminated", - "Cannot terminate " << toString() << ". " - << var->toString() << " has an active external constraint " - << constraint->toString() << "."); - - return false; - } + // If it is a culprit with an unbound domain, and an external variable, + // then it is an external constraint that must be retained and so we cannot terminate + if(allVars.find(var->getKey()) == allVars.end() && !var->baseDomain().isSingleton()){ + debugMsg("Token:canBeTerminated", + "Cannot terminate " << toString() << ". " + << var->toString() << " has an active external constraint " + << constraint->toString() << "."); + + return false; } } - - return true; } + return true; +} + void Token::terminate(){ // Set this flag immediately so that other tokens can evaluate its state when we are dealing with cascaded effects m_terminated = true; @@ -985,16 +984,16 @@ PSObject* Token::getOwner() const { ObjectVarId objVar = getObject(); ObjectId id = Entity::getTypedEntity(objVar->lastDomain().getSingletonValue()); - return (PSObject *) id; + return id_cast(id); // return new PSObject(ObjectId(objVar->lastDomain().getSingletonValue())); } PSToken* Token::getMaster() const { - TokenId m = master(); - if (m.isNoId()) - return NULL; - - return (PSToken *) m; + TokenId m = master(); + if (m.isNoId()) + return NULL; + + return id_cast(m); } PSList Token::getSlaves() const { @@ -1004,14 +1003,14 @@ PSList Token::getSlaves() const { for(TokenSet::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { TokenId id = *it; //PSToken* tok = new PSToken(*it); - retval.push_back((PSToken *) id); + retval.push_back(id_cast(id)); } return retval; } PSToken* Token::getActive() const { - return (PSToken*)((Token*)getActiveToken()); + return id_cast(getActiveToken()); } PSList Token::getMerged() const @@ -1027,47 +1026,36 @@ PSList Token::getMerged() const } -PSTokenState Token::getTokenState() const -{ - if (isActive()) - return EUROPA::ACTIVE; +PSTokenState Token::getTokenState() const { + if (isActive()) + return EUROPA::ACTIVE; - if (isInactive()) - return EUROPA::INACTIVE; + if (isInactive()) + return EUROPA::INACTIVE; - if (isMerged()) - return EUROPA::MERGED; + if (isMerged()) + return EUROPA::MERGED; - if (isRejected()) - return EUROPA::REJECTED; + if (isRejected()) + return EUROPA::REJECTED; - check_error(ALWAYS_FAIL,"Unknown token state"); - return EUROPA::INACTIVE; + check_runtime_error(ALWAYS_FAIL,"Unknown token state"); } -PSVariable* Token::getStart() const -{ - return (PSVariable *) start(); -} +PSVariable* Token::getStart() const {return id_cast(start());} -PSVariable* Token::getEnd() const -{ - return (PSVariable *) end(); -} +PSVariable* Token::getEnd() const {return id_cast(end());} -PSVariable* Token::getDuration() const -{ - return (PSVariable *) duration(); -} +PSVariable* Token::getDuration() const {return id_cast(duration());} -PSList Token::getParameters() const -{ + +PSList Token::getParameters() const { PSList retval; const std::vector& vars = getVariables(); for(std::vector::const_iterator it = vars.begin(); it != vars.end();++it) { - ConstrainedVariableId id = *it; - PSVariable* psVar = (PSVariable *) id; - retval.push_back(psVar); + ConstrainedVariableId id = *it; + PSVariable* psVar = id_cast(id); + retval.push_back(psVar); } return retval; } @@ -1077,23 +1065,22 @@ PSList Token::getPredicateParameters() const { const std::vector& vars = parameters(); for(std::vector::const_iterator it = vars.begin(); it != vars.end();++it) { ConstrainedVariableId id = *it; - PSVariable* psVar = (PSVariable *) id; + PSVariable* psVar = id_cast(id); retval.push_back(psVar); } return retval; } -PSVariable* Token::getParameter(const std::string& name) const -{ +PSVariable* Token::getParameter(const std::string& name) const { LabelStr realName(name); PSVariable* retval = NULL; const std::vector& vars = getVariables(); for(std::vector::const_iterator it = vars.begin(); it != vars.end(); - ++it) { - ConstrainedVariableId id = *it; + ++it) { + ConstrainedVariableId id = *it; if((*it)->getName() == realName) { - retval = (PSVariable *) id; - break; + retval = id_cast(id); + break; } } return retval; @@ -1106,38 +1093,38 @@ void Token::merge(PSToken* activeToken) doMerge(tok); } -PSList Token::getCompatibleTokens(unsigned int limit, bool useExactTest) -{ - std::vector tokens; - getPlanDatabase()->getCompatibleTokens(this,tokens,limit,useExactTest); - PSList retval; - - for(unsigned int i=0;i Token::getCompatibleTokens(unsigned int limit, bool useExactTest) { + std::vector tokens; + getPlanDatabase()->getCompatibleTokens(this,tokens,limit,useExactTest); + PSList retval; + + for(unsigned int i=0;i(id)); + } + + return retval; } -std::string attrsToString(int attrs) -{ - std::ostringstream os; +namespace { +std::string attrsToString(int attrs) { + std::ostringstream os; - os << "{"; + os << "{"; - if (attrs & PSTokenType::ACTION) - os << " ACTION"; - if (attrs & PSTokenType::PREDICATE) - os << " PREDICATE"; - if (attrs & PSTokenType::CONDITION) - os << " CONDITION"; - if (attrs & PSTokenType::EFFECT) - os << " EFFECT"; + if (attrs & PSTokenType::ACTION) + os << " ACTION"; + if (attrs & PSTokenType::PREDICATE) + os << " PREDICATE"; + if (attrs & PSTokenType::CONDITION) + os << " CONDITION"; + if (attrs & PSTokenType::EFFECT) + os << " EFFECT"; - os << " }"; + os << " }"; - return os.str(); + return os.str(); +} } std::string Token::toLongString() const diff --git a/src/PLASMA/PlanDatabase/base/Token.hh b/src/PLASMA/PlanDatabase/base/Token.hh index 9b97cb881..ca4cf2253 100644 --- a/src/PLASMA/PlanDatabase/base/Token.hh +++ b/src/PLASMA/PlanDatabase/base/Token.hh @@ -87,7 +87,7 @@ namespace EUROPA { * @brief Obtain a slave token using a positional offset from this token * @return TokenId::noId() if no token is found at that location */ - const TokenId& getSlave(int slavePosition) const; + const TokenId& getSlave(unsigned int slavePosition) const; /** * @brief Obtain the position of the given slave token in its ordered set of slaves. @@ -378,9 +378,9 @@ namespace EUROPA { /** * @brief Add a parameter as a member to the object. This is used when building the instance * and cannot be called once the specific token instance has been closed. + * Errors: If a parameter of the given type with the given name cannot be added * @param baseDomain The base domain to use to populate the variable * @param name The member name - * @error If a parameter of the given type with the given name cannot be added * @see Scheme::hasMember, Schema::canContain, Token::close() */ template @@ -550,7 +550,6 @@ namespace EUROPA { TokenId m_activeToken; UnifyMementoId m_unifyMemento; bool m_committed; - unsigned int m_refCount; /*!< The number of sources requiring existence of the token */ bool m_deleted; bool m_terminated; ConstrainedVariableSet m_localVariables; /*!< Variables created external to the token but related to it. They are diff --git a/src/PLASMA/PlanDatabase/base/TokenType.cc b/src/PLASMA/PlanDatabase/base/TokenType.cc index 9d9f4e5cd..0075f979d 100644 --- a/src/PLASMA/PlanDatabase/base/TokenType.cc +++ b/src/PLASMA/PlanDatabase/base/TokenType.cc @@ -3,6 +3,8 @@ #include "Token.hh" #include "Utils.hh" +#include + namespace EUROPA { TokenType::TokenType(const ObjectTypeId& ot, const LabelStr& signature) @@ -125,7 +127,7 @@ namespace EUROPA { PSList conditions = getSubgoalsByAttr( PSTokenType::CONDITION); for ( int i = 0; i < conditions.size(); i++ ){ - TokenType* tt = (TokenType*) conditions.get(i); + TokenType* tt = boost::polymorphic_cast(conditions.get(i)); oss << "\t\t\t"; oss<< tt->toLongString(); } @@ -134,7 +136,7 @@ namespace EUROPA { PSList effects = getSubgoalsByAttr( PSTokenType::EFFECT); for ( int i = 0; i < effects.size(); i++ ){ - TokenType* tt = (TokenType*) effects.get(i); + TokenType* tt = boost::polymorphic_cast(effects.get(i)); oss << "\t\t\t"; oss<< tt->toLongString(); } @@ -148,7 +150,7 @@ namespace EUROPA { void TokenType::addSubgoalByAttr( TokenTypeId type, int attr ){ for( int attrMask = 1; attrMask <= attr; attrMask = attrMask << 1 ){ if( ( attr & attrMask ) == attrMask ){ - m_subgoalsByAttr[ attrMask ].push_back( (PSTokenType*) type ); + m_subgoalsByAttr[ attrMask ].push_back(id_cast(type)); } } } @@ -169,7 +171,7 @@ namespace EUROPA { } PSDataType* TokenType::getParameterType(int index) const { - check_error((unsigned int) index < m_args.size(), "Index out of bounds"); + check_error(static_cast(index) < m_args.size(), "Index out of bounds"); std::map::const_iterator it = m_args.begin(); while (index-- > 0) ++it; return it->second; diff --git a/src/PLASMA/PlanDatabase/base/TokenVariable.hh b/src/PLASMA/PlanDatabase/base/TokenVariable.hh index 082a18a05..2937a4eb0 100644 --- a/src/PLASMA/PlanDatabase/base/TokenVariable.hh +++ b/src/PLASMA/PlanDatabase/base/TokenVariable.hh @@ -26,7 +26,7 @@ namespace EUROPA{ class TokenVariable : public Variable { public: TokenVariable(const TokenId& parent, - int index, + unsigned long index, const ConstraintEngineId& constraintEngine, const Domain& baseDomain, const bool internal = false, @@ -82,7 +82,7 @@ namespace EUROPA{ template TokenVariable::TokenVariable(const TokenId& parent, - int index, + unsigned long index, const ConstraintEngineId& constraintEngine, const Domain& baseDomain, const bool internal, diff --git a/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.cc b/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.cc index 30bc8dbf1..59b767e0e 100644 --- a/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.cc +++ b/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.cc @@ -22,13 +22,13 @@ namespace EUROPA { const std::list& DbClientTransactionLog::getBufferedTransactions() const {return m_bufferedTransactions;} - const bool DbClientTransactionLog::isBool(const std::string& typeName) { + bool DbClientTransactionLog::isBool(const std::string& typeName) { return (strcmp(typeName.c_str(),"bool") == 0 || strcmp(typeName.c_str(), "BOOL" ) == 0 || strcmp(typeName.c_str(),BoolDT::NAME().c_str()) == 0); } - const bool DbClientTransactionLog::isInt(const std::string& typeName) { + bool DbClientTransactionLog::isInt(const std::string& typeName) { return (strcmp(typeName.c_str(),"int") == 0 || strcmp(typeName.c_str(),BoolDT::NAME().c_str()) == 0); } @@ -61,7 +61,7 @@ namespace EUROPA { } debugMsg("notifyVariableCreated"," variable name = " << variable->getName().c_str() << " typeName = " << type << " type = " << baseDomain.getTypeName().c_str()); - element->SetAttribute("index", m_client->getIndexByVariable(variable)); + element->SetAttribute("index", static_cast(m_client->getIndexByVariable(variable))); if (!baseDomain.isEmpty()) { TiXmlElement * value = abstractDomainAsXml(&baseDomain); @@ -71,15 +71,15 @@ namespace EUROPA { } } - void DbClientTransactionLog::notifyVariableDeleted(const ConstrainedVariableId& variable) { - if(!variable->isInternal()) { - TiXmlElement* element = allocateXmlElement("deletevar"); - element->SetAttribute("index", m_client->getIndexByVariable(variable)); - element->SetAttribute("name", variable->getName().toString() ); - element->SetAttribute("type", variable->baseDomain().getTypeName().toString() ); - pushTransaction(element); - } +void DbClientTransactionLog::notifyVariableDeleted(const ConstrainedVariableId& variable) { + if(!variable->isInternal()) { + TiXmlElement* element = allocateXmlElement("deletevar"); + element->SetAttribute("index", static_cast(m_client->getIndexByVariable(variable))); + element->SetAttribute("name", variable->getName().toString() ); + element->SetAttribute("type", variable->baseDomain().getTypeName().toString() ); + pushTransaction(element); } +} void DbClientTransactionLog::notifyObjectCreated(const ObjectId& object){ const std::vector noArguments; @@ -206,31 +206,31 @@ namespace EUROPA { pushTransaction(element); } - void DbClientTransactionLog::notifyConstraintCreated(const ConstraintId& constraint){ - TiXmlElement * element = allocateXmlElement("invoke"); - element->SetAttribute("name", constraint->getName().toString()); - element->SetAttribute("index", m_client->getIndexByConstraint(constraint)); - const std::vector& variables = constraint->getScope(); - std::vector::const_iterator iter; - for (iter = variables.begin() ; iter != variables.end() ; iter++) { - const ConstrainedVariableId variable = *iter; - element->LinkEndChild(variableAsXml(variable)); +void DbClientTransactionLog::notifyConstraintCreated(const ConstraintId& constraint){ + TiXmlElement * element = allocateXmlElement("invoke"); + element->SetAttribute("name", constraint->getName().toString()); + element->SetAttribute("index", static_cast(m_client->getIndexByConstraint(constraint))); + const std::vector& variables = constraint->getScope(); + std::vector::const_iterator iter; + for (iter = variables.begin() ; iter != variables.end() ; iter++) { + const ConstrainedVariableId variable = *iter; + element->LinkEndChild(variableAsXml(variable)); } - pushTransaction(element); - } + pushTransaction(element); +} - void DbClientTransactionLog::notifyConstraintDeleted(const ConstraintId& constraint) { - TiXmlElement* element = allocateXmlElement("deleteconstraint"); - element->SetAttribute("name", constraint->getName().toString()); - element->SetAttribute("index", m_client->getIndexByConstraint(constraint)); - const std::vector& variables = constraint->getScope(); - std::vector::const_iterator iter; - for (iter = variables.begin() ; iter != variables.end() ; iter++) { - const ConstrainedVariableId variable = *iter; - element->LinkEndChild(variableAsXml(variable)); - } - pushTransaction(element); - } +void DbClientTransactionLog::notifyConstraintDeleted(const ConstraintId& constraint) { + TiXmlElement* element = allocateXmlElement("deleteconstraint"); + element->SetAttribute("name", constraint->getName().toString()); + element->SetAttribute("index", static_cast(m_client->getIndexByConstraint(constraint))); + const std::vector& variables = constraint->getScope(); + std::vector::const_iterator iter; + for (iter = variables.begin() ; iter != variables.end() ; iter++) { + const ConstrainedVariableId variable = *iter; + element->LinkEndChild(variableAsXml(variable)); + } + pushTransaction(element); +} void DbClientTransactionLog::notifyVariableSpecified(const ConstrainedVariableId& variable){ if(!variable->isInternal()) { @@ -370,36 +370,39 @@ namespace EUROPA { return token_el; } - TiXmlElement * - DbClientTransactionLog::variableAsXml(const ConstrainedVariableId& variable) const - { - TiXmlElement * var_el = allocateXmlElement("variable"); - const EntityId& parent = variable->parent(); - if (parent != EntityId::noId()) { - if (TokenId::convertable(parent)) { - TokenId token = parent; - check_error(token.isValid()); - var_el->SetAttribute("token", m_client->getPathAsString(token)); - } else if (ObjectId::convertable(parent)) { - ObjectId object = parent; - check_error(object.isValid()); - var_el->SetAttribute("object", object->getName().toString()); - } else { - var_el->SetAttribute("index", m_client->getIndexByVariable(variable)); - return var_el; - } - } else { - var_el->SetAttribute("index", m_client->getIndexByVariable(variable)); - return var_el; +TiXmlElement * +DbClientTransactionLog::variableAsXml(const ConstrainedVariableId& variable) const { + TiXmlElement * var_el = allocateXmlElement("variable"); + const EntityId& parent = variable->parent(); + if (parent != EntityId::noId()) { + if (TokenId::convertable(parent)) { + TokenId token = parent; + check_error(token.isValid()); + var_el->SetAttribute("token", m_client->getPathAsString(token)); + } + else if (ObjectId::convertable(parent)) { + ObjectId object = parent; + check_error(object.isValid()); + var_el->SetAttribute("object", object->getName().toString()); } - if (variable->getIndex() != ConstrainedVariable::NO_INDEX) { - var_el->SetAttribute("index", variable->getIndex()); - } else { - var_el->SetAttribute("index", m_client->getIndexByVariable(variable)); + else { + var_el->SetAttribute("index", static_cast(m_client->getIndexByVariable(variable))); return var_el; } + } + else { + var_el->SetAttribute("index", static_cast(m_client->getIndexByVariable(variable))); + return var_el; + } + if (variable->getIndex() != ConstrainedVariable::NO_INDEX) { + var_el->SetAttribute("index", static_cast(variable->getIndex())); + } + else { + var_el->SetAttribute("index", static_cast(m_client->getIndexByVariable(variable))); return var_el; } + return var_el; +} TiXmlElement * DbClientTransactionLog::allocateXmlElement(const std::string& name) const { TiXmlElement * element = new TiXmlElement(name); diff --git a/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.hh b/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.hh index 10f948943..a3db0472c 100644 --- a/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.hh +++ b/src/PLASMA/PlanDatabase/component/DbClientTransactionLog.hh @@ -61,8 +61,8 @@ namespace EUROPA { void pushTransaction(TiXmlElement *); void popTransaction(); - const bool isBool(const std::string& typeName); - const bool isInt(const std::string& typeName); + bool isBool(const std::string& typeName); + bool isInt(const std::string& typeName); std::list m_bufferedTransactions; bool m_chronologicalBacktracking; diff --git a/src/PLASMA/PlanDatabase/component/DbClientTransactionPlayer.cc b/src/PLASMA/PlanDatabase/component/DbClientTransactionPlayer.cc index e6877c2d9..14ec330b7 100644 --- a/src/PLASMA/PlanDatabase/component/DbClientTransactionPlayer.cc +++ b/src/PLASMA/PlanDatabase/component/DbClientTransactionPlayer.cc @@ -67,10 +67,10 @@ namespace EUROPA { return sl_retval; } - static const std::vector + static const std::vector pathAsVector(const std::string & path) { size_t path_back, path_front, path_end; - std::vector result; + std::vector result; path_back = 0; path_end = path.size(); while (true) { @@ -79,11 +79,11 @@ namespace EUROPA { break; } std::string numstr = path.substr(path_back, path_front-path_back); - result.push_back(atoi(numstr.c_str())); + result.push_back(static_cast(atoi(numstr.c_str()))); path_back = path_front + 1; } std::string numstr = path.substr(path_back, path_end-path_back); - result.push_back(atoi(numstr.c_str())); + result.push_back(static_cast(atoi(numstr.c_str()))); return result; } @@ -105,7 +105,7 @@ namespace EUROPA { return m_client->getCESchema(); } - void DbClientTransactionPlayer::setFilter(const std::set& filters) { + void DbClientTransactionPlayer::setFilter(const std::set&) { } @@ -454,14 +454,14 @@ namespace EUROPA { { if (!schema->isPredicate(predicate)) { LabelStr typeStr(predicate); - int cnt = typeStr.countElements(Schema::getDelimiter()); + unsigned long cnt = typeStr.countElements(Schema::getDelimiter()); LabelStr prefix = typeStr.getElement(0, Schema::getDelimiter()); object = client->getObject(prefix.c_str()); check_error(object.isValid(), "Failed to find an object named " + prefix.toString()); LabelStr objType = object->getType(); LabelStr suffix = typeStr.getElement(1, Schema::getDelimiter()); - for (int i=2; igetMemberType(objType,suffix); suffix = typeStr.getElement(i, Schema::getDelimiter()); } @@ -524,30 +524,28 @@ namespace EUROPA { ); } - void DbClientTransactionPlayer::playTokenCreated(const TiXmlElement & element) { - const char * relation = element.Attribute("relation"); - if (relation != NULL) { - playTemporalRelationCreated(element); - return; - } - // simple token creation - TiXmlElement * child = element.FirstChildElement(); - check_error(child != NULL); - const char * type = child->Attribute("type"); - check_error(type != NULL); - - const char * mandatory = element.Attribute("mandatory"); - bool rejectable = true; - if(mandatory != NULL && (strcmp(mandatory, "true") == 0)) - rejectable = false; - - TokenId token = createToken( - child->Attribute("name"), - type, - rejectable, // rejectable - false // isFact - ); +void DbClientTransactionPlayer::playTokenCreated(const TiXmlElement & element) { + const char * relation = element.Attribute("relation"); + if (relation != NULL) { + playTemporalRelationCreated(element); + return; } + // simple token creation + TiXmlElement * child = element.FirstChildElement(); + check_error(child != NULL); + const char * type = child->Attribute("type"); + check_error(type != NULL); + + const char * mandatory = element.Attribute("mandatory"); + bool rejectable = true; + if(mandatory != NULL && (strcmp(mandatory, "true") == 0)) + rejectable = false; + + createToken(child->Attribute("name"), type, + rejectable, // rejectable + false // isFact + ); +} //bizarre... playTokenCreated will, separately, create a token and create a temporal relation //these should be separated! @@ -580,13 +578,13 @@ namespace EUROPA { std::vector tokens; tokenize(pathStr, tokens, "."); - std::vector path; + std::vector path; for(std::vector::iterator it = tokens.begin(); it != tokens.end(); ++it) { std::stringstream str; str << *it; - int element; - str >> element; - path.push_back(element); + unsigned int pathElement = 0; + str >> pathElement; + path.push_back(pathElement); } tok = m_client->getTokenByPath(path); } @@ -1123,9 +1121,9 @@ namespace EUROPA { template void DbClientTransactionPlayer::playVariableUnreset(const TiXmlElement& element, Iterator start, Iterator end) { - TiXmlElement * var_el = element.FirstChildElement(); - check_error(var_el != NULL); - ConstrainedVariableId var = xmlAsVariable(*var_el); + TiXmlElement * root_el = element.FirstChildElement(); + check_error(root_el != NULL); + ConstrainedVariableId var = xmlAsVariable(*root_el); for(Iterator it = start; it != end; ++it) { if(strcmp((*it)->Value(), "specify") == 0 || @@ -1182,7 +1180,7 @@ namespace EUROPA { std::stringstream str; str << index; - int key; + unsigned int key = 0; str >> key; ConstraintId constr = m_client->getConstraintByIndex(key); m_client->deleteConstraint(constr); @@ -1301,25 +1299,26 @@ namespace EUROPA { DbClientTransactionPlayer::parseVariable(const char * varString) { check_error(varString != NULL); - std::string variable = varString; + std::string variableName = varString; size_t ident_back, ident_front, variable_end; ident_back = 0; - variable_end = variable.size(); - ident_front = variable.find('.', ident_back); + variable_end = variableName.size(); + ident_front = variableName.find('.', ident_back); if ((ident_front == std::string::npos) || (ident_front > variable_end)) { // simple identifier (might be a symbol) - if (m_variables.find(variable) != m_variables.end()) { - return m_variables[variable]; - } else { + if (m_variables.find(variableName) != m_variables.end()) { + return m_variables[variableName]; + } + else { // presumably a symbol return ConstrainedVariableId::noId(); } } // compound identifier - std::string ident = variable.substr(ident_back, ident_front - ident_back); + std::string ident = variableName.substr(ident_back, ident_front - ident_back); TokenId token = m_tokens[ident]; if (token != token.noId()) { - std::string name = variable.substr(ident_front + 1); + std::string name = variableName.substr(ident_front + 1); LabelStr nameAsLabelStr(name.c_str()); const std::vector & variables = token->getVariables(); std::vector::const_iterator iter = variables.begin(); @@ -1366,8 +1365,8 @@ namespace EUROPA { return(new ObjectDomain(getCESchema()->getDataType(type), Entity::getTypedEntity(xmlAsValue(element, name)))); } if (strcmp(tag, "id") == 0) { - const char * name = element.Attribute("name"); - ConstrainedVariableId var = parseVariable(name); + const char * varName = element.Attribute("name"); + ConstrainedVariableId var = parseVariable(varName); check_error(var.isValid()); return(var->baseDomain().copy()); } @@ -1379,12 +1378,12 @@ namespace EUROPA { // New XML style for simple types. const char * type = element.Attribute("type"); check_error(type != NULL, "missing type for domain in transaction XML"); - const char * name = element.Attribute("name"); - check_error(name != NULL, "missing name for domain in transaction XML"); + const char * domainName = element.Attribute("name"); + check_error(domainName != NULL, "missing name for domain in transaction XML"); Domain * domain = getCESchema()->baseDomain(type).copy(); check_error(domain != 0, "unknown type, lack of memory, or other problem with domain in transaction XML"); - edouble value = m_client->createValue(type, name); + edouble value = m_client->createValue(type, domainName); if(domain->isOpen() && !domain->isMember(value)) domain->insert(value); domain->set(value); @@ -1438,114 +1437,114 @@ namespace EUROPA { return domain; } - EnumeratedDomain * - DbClientTransactionPlayer::xmlAsEnumeratedDomain(const TiXmlElement & element, - const char* otherTypeName) { - enum { ANY, BOOL, INT, FLOAT, STRING, SYMBOL, OBJECT } type = ANY; - std::string typeName; - // determine most specific type - for (TiXmlElement * child_el = element.FirstChildElement() ; - child_el != NULL ; child_el = child_el->NextSiblingElement()) { - std::string thisType; - if (strcmp(child_el->Value(), "value") == 0) - // New style XML for simple types: the type is within and tag is always 'value' - thisType = child_el->Attribute("type"); - else - // Non-simple type or old style XML for a simple type: type is the tag and/or within (e.g., specific type is within if symbol even old style) - thisType = child_el->Value(); - - debugMsg("DbClientTransactionPlayer:xmlAsEnumeratedDomain", " thisType= " << thisType); - - check_error(thisType != "", "no type for domain in XML"); - if (strcmp(thisType.c_str(), "bool") == 0 || - strcmp(thisType.c_str(), "BOOL") == 0 || - strcmp(thisType.c_str(), BoolDT::NAME().c_str()) == 0) { - if (type == ANY) { - type = BOOL; - typeName = "bool"; - } - if (type == BOOL) - continue; +EnumeratedDomain * +DbClientTransactionPlayer::xmlAsEnumeratedDomain(const TiXmlElement & element, + const char* otherTypeName) { + enum { ANY, BOOL, INT, FLOAT, STRING, SYMBOL, OBJECT } type = ANY; + std::string typeName; + // determine most specific type + for (TiXmlElement * child_el = element.FirstChildElement() ; + child_el != NULL ; child_el = child_el->NextSiblingElement()) { + std::string thisType; + if (strcmp(child_el->Value(), "value") == 0) + // New style XML for simple types: the type is within and tag is always 'value' + thisType = child_el->Attribute("type"); + else + // Non-simple type or old style XML for a simple type: type is the tag and/or within (e.g., specific type is within if symbol even old style) + thisType = child_el->Value(); + + debugMsg("DbClientTransactionPlayer:xmlAsEnumeratedDomain", " thisType= " << thisType); + + check_error(thisType != "", "no type for domain in XML"); + if (strcmp(thisType.c_str(), "bool") == 0 || + strcmp(thisType.c_str(), "BOOL") == 0 || + strcmp(thisType.c_str(), BoolDT::NAME().c_str()) == 0) { + if (type == ANY) { + type = BOOL; + typeName = "bool"; } - if (strcmp(thisType.c_str(), "int") == 0 || - strcmp(thisType.c_str(), "INT") == 0 || - strcmp(thisType.c_str(), IntDT::NAME().c_str()) == 0) { - if (type == ANY) { - type = INT; - typeName = "int"; - } - if ((type == FLOAT) || (type == INT)) - continue; + if (type == BOOL) + continue; + } + if (strcmp(thisType.c_str(), "int") == 0 || + strcmp(thisType.c_str(), "INT") == 0 || + strcmp(thisType.c_str(), IntDT::NAME().c_str()) == 0) { + if (type == ANY) { + type = INT; + typeName = "int"; } - if (strcmp(thisType.c_str(), "float") == 0 || - strcmp(thisType.c_str(), "FLOAT") == 0 || - strcmp(thisType.c_str(), FloatDT::NAME().c_str()) == 0) { - if ((type == ANY) || (type == INT)) { - type = FLOAT; - typeName = "float"; - } - if (type == FLOAT) - continue; + if ((type == FLOAT) || (type == INT)) + continue; + } + if (strcmp(thisType.c_str(), "float") == 0 || + strcmp(thisType.c_str(), "FLOAT") == 0 || + strcmp(thisType.c_str(), FloatDT::NAME().c_str()) == 0) { + if ((type == ANY) || (type == INT)) { + type = FLOAT; + typeName = "float"; } - if (strcmp(thisType.c_str(), "string") == 0 || - strcmp(thisType.c_str(), "STRING") == 0 || - strcmp(thisType.c_str(), StringDT::NAME().c_str()) == 0) { - if (type == ANY) { - type = STRING; - typeName = "string"; - } - if (type == STRING) - continue; + if (type == FLOAT) + continue; + } + if (strcmp(thisType.c_str(), "string") == 0 || + strcmp(thisType.c_str(), "STRING") == 0 || + strcmp(thisType.c_str(), StringDT::NAME().c_str()) == 0) { + if (type == ANY) { + type = STRING; + typeName = "string"; } - if (strcmp(thisType.c_str(), "symbol") == 0) { - if (type == ANY) { - type = SYMBOL; - typeName = child_el->Attribute("type"); - } - if (type == SYMBOL) { - check_error(strcmp(typeName.c_str(), child_el->Attribute("type")) == 0, - "symbols from different types in the same enumerated set"); - debugMsg("DbClientTransactionPlayer:xmlAsEnumeratedDomain:symbol", " thisType= " << thisType << " typeName = " <Attribute("type"); } -// if (strcmp(thisType.c_str(), "object") == 0) { -// if (type == ANY) { -// type = OBJECT; -// } -// if (type == OBJECT) -// //!!This needs a similar type check to SYMBOL, just above (but more complex due to inheritance?) -// continue; -// } - check_error(ALWAYS_FAILS, "unknown or inappropriately mixed type(s) for value(s) in an enumerated set"); - } - check_error(type != ANY); - // gather the values - std::list values; - for (TiXmlElement * child_el = element.FirstChildElement() ; - child_el != NULL ; child_el = child_el->NextSiblingElement()) { - const char * value_st = child_el->Attribute("value"); - if (value_st == NULL) // Check for the new style XML for simple types - value_st = child_el->Attribute("name"); - check_error(value_st != NULL); - switch (type) { - case BOOL: case INT: case FLOAT: case STRING: case SYMBOL: - values.push_back(m_client->createValue(typeName.c_str(), value_st)); - break; - case OBJECT: - values.push_back(m_client->getObject(value_st)->getKey()); - break; - default: - check_error(ALWAYS_FAILS); + if (type == SYMBOL) { + check_error(strcmp(typeName.c_str(), child_el->Attribute("type")) == 0, + "symbols from different types in the same enumerated set"); + debugMsg("DbClientTransactionPlayer:xmlAsEnumeratedDomain:symbol", " thisType= " << thisType << " typeName = " < values; + for (TiXmlElement * child_el = element.FirstChildElement() ; + child_el != NULL ; child_el = child_el->NextSiblingElement()) { + const char * value_st = child_el->Attribute("value"); + if (value_st == NULL) // Check for the new style XML for simple types + value_st = child_el->Attribute("name"); + check_error(value_st != NULL); + switch (type) { + case BOOL: case INT: case FLOAT: case STRING: case SYMBOL: + values.push_back(m_client->createValue(typeName.c_str(), value_st)); + break; + case OBJECT: + values.push_back(m_client->getObject(value_st)->getKey()); + break; + case ANY: + check_error(ALWAYS_FAILS); } + } - // return the domain - if (otherTypeName != NULL) - typeName = otherTypeName; + // return the domain + if (otherTypeName != NULL) + typeName = otherTypeName; - switch (type) { + switch (type) { case BOOL: case INT: case FLOAT: return(new EnumeratedDomain(getCESchema()->getDataType(typeName.c_str()),values)); case STRING: @@ -1554,11 +1553,11 @@ namespace EUROPA { return(new SymbolDomain(values,getCESchema()->getDataType(typeName.c_str()))); case OBJECT: return(new EnumeratedDomain(getCESchema()->getDataType(typeName.c_str()),values)); - default: + case ANY: check_error(ALWAYS_FAILS); return(0); - } } +} edouble DbClientTransactionPlayer::xmlAsValue(const TiXmlElement & value, const char * name) { const char * tag = value.Value(); @@ -1583,10 +1582,10 @@ namespace EUROPA { // Now deallocate domains created for arguments for (std::vector::const_iterator it = arguments.begin(); it != arguments.end(); ++it) { - Domain* tmp = (Domain*)(*it); + Domain* tmp = const_cast(*it); delete tmp; } - return (edouble)object->getKey(); + return static_cast(object->getKey()); } if (strcmp(tag, "value") == 0) { // New style XML for simple types. @@ -1633,20 +1632,20 @@ namespace EUROPA { if (token_path != NULL) { TokenId token = m_client->getTokenByPath(pathAsVector(token_path)); check_error(token.isValid()); - check_error((unsigned)index < token->getVariables().size()); - return token->getVariables()[index]; + check_error(static_cast(index) < token->getVariables().size()); + return token->getVariables()[static_cast(index)]; } const char * object_name = variable.Attribute("object"); if (object_name != NULL) { ObjectId object = m_client->getObject(object_name); check_error(object.isValid()); - check_error((unsigned)index < object->getVariables().size()); - return object->getVariables()[index]; + check_error(static_cast(index) < object->getVariables().size()); + return object->getVariables()[static_cast(index)]; } // rule variables - return m_client->getVariableByIndex(index); + return m_client->getVariableByIndex(static_cast(index)); } ConstrainedVariableId var = xmlAsCreateVariable(NULL, NULL, &variable); diff --git a/src/PLASMA/PlanDatabase/component/Methods.cc b/src/PLASMA/PlanDatabase/component/Methods.cc index 155a027f3..0616ab47b 100644 --- a/src/PLASMA/PlanDatabase/component/Methods.cc +++ b/src/PLASMA/PlanDatabase/component/Methods.cc @@ -15,16 +15,16 @@ namespace EUROPA { // TODO: keep using pdbClient? -const DbClientId& getCtxPDB(EvalContext& context) -{ - // TODO: Add this behavior to EvalContext instead? - DbClient* dbClient = (DbClient*)context.getElement("DbClient"); - if (dbClient != NULL) - return dbClient->getId(); +namespace { +const DbClientId& getCtxPDB(EvalContext& context) { + // TODO: Add this behavior to EvalContext instead? + DbClient* dbClient = reinterpret_cast(context.getElement("DbClient")); + if (dbClient != NULL) + return dbClient->getId(); - PlanDatabase* pdb = (PlanDatabase*)context.getElement("PlanDatabase"); - check_error(pdb != NULL,"Could not find Plan Database in eval context"); - return pdb->getClient(); + PlanDatabase* pdb = reinterpret_cast(context.getElement("PlanDatabase")); + check_error(pdb != NULL,"Could not find Plan Database in eval context"); + return pdb->getClient(); } TokenId varToToken(const ConstrainedVariableId& v) @@ -37,8 +37,9 @@ ObjectId varToObject(const ConstrainedVariableId& v) { return Entity::getTypedEntity(v->derivedDomain().getSingletonValue()); } +} -DataRef PDBClose::eval(EvalContext& context, const std::vector& args) const +DataRef PDBClose::eval(EvalContext& context, const std::vector&) const { getCtxPDB(context)->close(); return DataRef::null; @@ -84,13 +85,13 @@ DataRef SpecifyVariable::eval(EvalContext& context, ConstrainedVariableId& var, return DataRef::null; } -DataRef ResetVariable::eval(EvalContext& context, ConstrainedVariableId& var, const std::vector& args) const +DataRef ResetVariable::eval(EvalContext& context, ConstrainedVariableId& var, const std::vector&) const { getCtxPDB(context)->reset(var); return DataRef::null; } -DataRef CloseVariable::eval(EvalContext& context, ConstrainedVariableId& var, const std::vector& args) const +DataRef CloseVariable::eval(EvalContext& context, ConstrainedVariableId& var, const std::vector&) const { getCtxPDB(context)->close(var); return DataRef::null; @@ -150,7 +151,7 @@ const DataTypeId& TokenMethod::getReturnType() return VoidDT::instance(); } -DataRef ActivateToken::eval(EvalContext& context, TokenId& tok, const std::vector& args) const +DataRef ActivateToken::eval(EvalContext& context, TokenId& tok, const std::vector&) const { if(!tok->isActive()) //Temporary. Pull out when we scrub test input files. DbClientTransactionPlayer is doing the same getCtxPDB(context)->activate(tok); @@ -165,13 +166,13 @@ DataRef MergeToken::eval(EvalContext& context, TokenId& tok, const std::vector& args) const +DataRef RejectToken::eval(EvalContext& context, TokenId& tok, const std::vector&) const { getCtxPDB(context)->reject(tok); return DataRef::null; } -DataRef CancelToken::eval(EvalContext& context, TokenId& tok, const std::vector& args) const +DataRef CancelToken::eval(EvalContext& context, TokenId& tok, const std::vector&) const { getCtxPDB(context)->cancel(tok); return DataRef::null; diff --git a/src/PLASMA/PlanDatabase/component/Timeline.cc b/src/PLASMA/PlanDatabase/component/Timeline.cc index 784a96b34..a555065ae 100644 --- a/src/PLASMA/PlanDatabase/component/Timeline.cc +++ b/src/PLASMA/PlanDatabase/component/Timeline.cc @@ -46,7 +46,7 @@ namespace EUROPA { void Timeline::getOrderingChoices(const TokenId& token, std::vector< std::pair >& results, - unsigned int limit){ + unsigned long limit){ check_error(results.empty()); check_error(token.isValid()); check_error(limit > 0, "Cannot set limit to less than 1."); @@ -408,13 +408,13 @@ namespace EUROPA { // Also ensure x.end <= (x+1).start. if (!cleaningUp && getPlanDatabase()->getConstraintEngine()->constraintConsistent()) { check_error(predecessor.isNoId() || isConstrainedToPrecede(predecessor, token)); - eint earliest_start = (eint) token->start()->lastDomain().getLowerBound(); - eint latest_start = (eint) token->start()->lastDomain().getUpperBound(); + eint earliest_start = static_cast(token->start()->lastDomain().getLowerBound()); + eint latest_start = static_cast(token->start()->lastDomain().getUpperBound()); check_error(earliest_start == MINUS_INFINITY || earliest_start == PLUS_INFINITY || earliest_start > prior_earliest_start); check_error(prior_earliest_end <= earliest_start); check_error(prior_latest_end <= latest_start); - prior_earliest_end = (eint) token->end()->lastDomain().getLowerBound(); - prior_latest_end = (eint) token->end()->lastDomain().getLowerBound(); + prior_earliest_end = static_cast(token->end()->lastDomain().getLowerBound()); + prior_latest_end = static_cast(token->end()->lastDomain().getLowerBound()); prior_earliest_start = earliest_start; } predecessor = token; @@ -512,8 +512,8 @@ namespace EUROPA { return (!token->isDeleted() && m_tokenIndex.find(token->getKey()) == m_tokenIndex.end()); } - void Timeline::notifyMerged(const TokenId& token){} - void Timeline::notifyRejected(const TokenId& token) {} + void Timeline::notifyMerged(const TokenId& ){} + void Timeline::notifyRejected(const TokenId&) {} void Timeline::notifyDeleted(const TokenId& token){ remove(token); } @@ -531,7 +531,7 @@ namespace EUROPA { const PlanDatabaseId& planDb, const LabelStr& objectType, const LabelStr& objectName, - const std::vector& arguments) const + const std::vector&) const { ObjectId instance = (new Timeline(planDb, objectType, objectName,true))->getId(); debugMsg("Interpreter:NativeObjectFactory","Created Native " << m_className.toString() << ":" << objectName.toString() << " type:" << objectType.toString()); diff --git a/src/PLASMA/PlanDatabase/component/Timeline.hh b/src/PLASMA/PlanDatabase/component/Timeline.hh index 5be805c21..1f6391e4e 100644 --- a/src/PLASMA/PlanDatabase/component/Timeline.hh +++ b/src/PLASMA/PlanDatabase/component/Timeline.hh @@ -34,7 +34,7 @@ namespace EUROPA { void getOrderingChoices(const TokenId& token, std::vector< std::pair >& results, - unsigned int limit = std::numeric_limits::max()); + unsigned long limit = std::numeric_limits::max()); void getTokensToOrder(std::vector& results); diff --git a/src/PLASMA/RulesEngine/ModuleRulesEngine.cc b/src/PLASMA/RulesEngine/ModuleRulesEngine.cc index c3c3ff542..398a83dcf 100644 --- a/src/PLASMA/RulesEngine/ModuleRulesEngine.cc +++ b/src/PLASMA/RulesEngine/ModuleRulesEngine.cc @@ -8,6 +8,8 @@ #include "Constraints.hh" #include "Propagators.hh" +#include + namespace EUROPA { ModuleRulesEngine::ModuleRulesEngine() @@ -27,30 +29,29 @@ namespace EUROPA { { } - void ModuleRulesEngine::initialize(EngineId engine) - { - PlanDatabase* pdb = (PlanDatabase*)engine->getComponent("PlanDatabase"); - RuleSchema* rs = new RuleSchema(); - engine->addComponent("RuleSchema",rs); - RulesEngine* re = new RulesEngine(rs->getId(),pdb->getId()); - engine->addComponent("RulesEngine",re); - - // Allocate an instance of Default Propagator to handle rule related constraint propagation. - // Will be cleaned up automatically by the ConstraintEngine - new DefaultPropagator("RulesEngine", pdb->getConstraintEngine(), SYSTEM_PRIORITY); - - CESchema* ces = (CESchema*)engine->getComponent("CESchema"); - REGISTER_SYSTEM_CONSTRAINT(ces,ProxyVariableRelation, "proxyRelation", "Default"); - REGISTER_SYSTEM_CONSTRAINT(ces,RuleVariableListener, RuleVariableListener::CONSTRAINT_NAME(),"Default"); - REGISTER_SYSTEM_CONSTRAINT(ces,LockConstraint, "filterLock", "RulesEngine"); - } - - void ModuleRulesEngine::uninitialize(EngineId engine) - { - RulesEngine* re = (RulesEngine*)engine->removeComponent("RulesEngine"); - delete re; +void ModuleRulesEngine::initialize(EngineId engine) { + PlanDatabase* pdb = + boost::polymorphic_cast(engine->getComponent("PlanDatabase")); + RuleSchema* rs = new RuleSchema(); + engine->addComponent("RuleSchema",rs); + RulesEngine* re = new RulesEngine(rs->getId(),pdb->getId()); + engine->addComponent("RulesEngine",re); + + // Allocate an instance of Default Propagator to handle rule related constraint propagation. + // Will be cleaned up automatically by the ConstraintEngine + new DefaultPropagator("RulesEngine", pdb->getConstraintEngine(), SYSTEM_PRIORITY); + + CESchema* ces = boost::polymorphic_cast(engine->getComponent("CESchema")); + REGISTER_SYSTEM_CONSTRAINT(ces,ProxyVariableRelation, "proxyRelation", "Default"); + REGISTER_SYSTEM_CONSTRAINT(ces,RuleVariableListener, RuleVariableListener::CONSTRAINT_NAME(),"Default"); + REGISTER_SYSTEM_CONSTRAINT(ces,LockConstraint, "filterLock", "RulesEngine"); +} - RuleSchema* rs = (RuleSchema*)engine->removeComponent("RuleSchema"); - delete rs; - } +void ModuleRulesEngine::uninitialize(EngineId engine) { + RulesEngine* re = boost::polymorphic_cast(engine->removeComponent("RulesEngine")); + delete re; + + RuleSchema* rs = boost::polymorphic_cast(engine->removeComponent("RuleSchema")); + delete rs; +} } diff --git a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc index 84b3fad3c..077e81c03 100644 --- a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc +++ b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.cc @@ -70,7 +70,7 @@ namespace EUROPA { bool ProxyVariableRelation::canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType){ // If the object variable is specified to a singleton, and the proxy variable can be specified, then // we will force the proxy to be set to the field value of the given object @@ -123,7 +123,8 @@ namespace EUROPA { */ void ProxyVariableRelation::updatePathFromSource(){ if(m_sourceConstraint.isId() && m_sourceConstraintKey != m_sourceConstraint->getKey()){ - ProxyVariableRelation* proxyConstraint = (ProxyVariableRelation*) m_sourceConstraint; + ProxyVariableRelation* proxyConstraint = + id_cast(m_sourceConstraint); m_path = proxyConstraint->m_path; m_sourceConstraint = ConstraintId::noId(); } diff --git a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.hh b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.hh index 231981c4e..7c23e6b0b 100644 --- a/src/PLASMA/RulesEngine/base/ProxyVariableRelation.hh +++ b/src/PLASMA/RulesEngine/base/ProxyVariableRelation.hh @@ -36,7 +36,7 @@ namespace EUROPA { * @brief Used to only track set and reset events. Will not be subject to propagation */ bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); /** diff --git a/src/PLASMA/RulesEngine/base/Rule.cc b/src/PLASMA/RulesEngine/base/Rule.cc index 80ae3797e..e566d0cc9 100644 --- a/src/PLASMA/RulesEngine/base/Rule.cc +++ b/src/PLASMA/RulesEngine/base/Rule.cc @@ -53,16 +53,9 @@ namespace EUROPA { return m_rulesByName; } - void RuleSchema::purgeAll() - { - std::multimap& rules = m_rulesByName; - for(std::multimap::const_iterator it = rules.begin(); it != rules.end(); ++it){ - RuleId rule = it->second; - delete (Rule*) rule; - } - - rules.clear(); - } +void RuleSchema::purgeAll() { + cleanup(m_rulesByName); +} Rule::Rule(const LabelStr& name) : m_id(this) diff --git a/src/PLASMA/RulesEngine/base/RuleInstance.cc b/src/PLASMA/RulesEngine/base/RuleInstance.cc index bb6506cb7..aead6dfa9 100644 --- a/src/PLASMA/RulesEngine/base/RuleInstance.cc +++ b/src/PLASMA/RulesEngine/base/RuleInstance.cc @@ -378,11 +378,11 @@ void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& do debugMsg("RuleInstance:setGuard", "Added guard: " << m_guardListener->toLongString()); } - TokenId RuleInstance::addSlave(Token* slave){ - m_slaves.push_back(slave->getId()); - slave->addDependent((Entity*) this); - return slave->getId(); - } +TokenId RuleInstance::addSlave(Token* slave){ + m_slaves.push_back(slave->getId()); + slave->addDependent(this); + return slave->getId(); +} ConstrainedVariableId RuleInstance::addVariable( const Domain& baseDomain, bool canBeSpecified, @@ -470,14 +470,14 @@ void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& do addConstraint(constraint); } - void RuleInstance::addConstraint(const ConstraintId& constraint){ - m_constraints.push_back(constraint); - const LabelStr& name = constraint->getName(); - m_constraintsByName.erase(name.getKey()); - m_constraintsByName.insert(std::make_pair(name.getKey(), constraint)); - constraint->addDependent((Entity*) this); +void RuleInstance::addConstraint(const ConstraintId& constraint){ + m_constraints.push_back(constraint); + const LabelStr& name = constraint->getName(); + m_constraintsByName.erase(name.getKey()); + m_constraintsByName.insert(std::make_pair(name.getKey(), constraint)); + constraint->addDependent(this); debugMsg("RuleInstance:addConstraint", "added constraint:" << constraint->toString()); - } +} void RuleInstance::addChildRule(RuleInstance* instance){ m_childRules.push_back(instance->getId()); @@ -549,7 +549,7 @@ void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& do std::vector RuleInstance::getVariables(const std::string& delimitedVars) const{ std::vector scope; LabelStr strScope(delimitedVars); - unsigned int size = strScope.countElements(":"); + unsigned long size = strScope.countElements(":"); for(unsigned int i=0; i < size; i++){ LabelStr strVar = strScope.getElement(i, ":"); ConstrainedVariableId var; @@ -583,87 +583,89 @@ void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& do return retVar; } - ConstrainedVariableId RuleInstance::varFromObject(const ConstrainedVariableId& obj, - const std::string& varString, - const std::string& fullName, - bool canBeSpecified){ - std::vector names; - tokenize(varString, names, std::string(Schema::getDelimiter())); - unsigned int varindex = 0; - - // First we compute the position index, and get the type of the last variable. This will then - // be used to populate the base domain of the proxy variable by iteration over the base domain. - - // Initialize with any object in the domain - ObjectId iObj = Entity::getTypedEntity(obj->lastDomain().getLowerBound()); - std::vector path; /*!< Push indexes as they are found */ - - // Traverse the object structure using the names in each case. Store indexes as we go to build a path - for (; varindex < names.size()-1; ++varindex) { - ConstrainedVariableId iVar = iObj->getVariable(LabelStr(iObj->getName().toString() + "." + names[varindex])); - path.push_back(iVar->getIndex()); - checkError(iVar->lastDomain().isSingleton(), iVar->toString() + ", " + iObj->getName().toString() + "." + names[varindex]); - iObj = Entity::getTypedEntity(iVar->lastDomain().getSingletonValue()); - } +ConstrainedVariableId RuleInstance::varFromObject(const ConstrainedVariableId& obj, + const std::string& varString, + const std::string& fullName, + bool canBeSpecified){ + std::vector names; + tokenize(varString, names, std::string(Schema::getDelimiter())); + unsigned int varindex = 0; - // Finally, handle the terminal point - the field variable itself - std::string field_name = iObj->getName().toString() + "." + names[varindex]; - ConstrainedVariableId fieldVar = iObj->getVariable(LabelStr(field_name)); - checkError(fieldVar.isValid(), "No variable named '" << field_name << "' in " << iObj->getName().toString()); - path.push_back(fieldVar->getIndex()); + // First we compute the position index, and get the type of the last variable. This will then + // be used to populate the base domain of the proxy variable by iteration over the base domain. - // Get the field type for the resulting domain. - const bool isOpen = fieldVar->baseDomain().isOpen(); - const bool isBool = fieldVar->baseDomain().isBool(); + // Initialize with any object in the domain + ObjectId iObj = Entity::getTypedEntity(obj->lastDomain().getLowerBound()); + std::vector path; /*!< Push indexes as they are found */ - // At this point, the index is complete, and we know the type. We can allocate and populate the domain - const ObjectDomain& objectDomain = static_cast(obj->baseDomain()); + // Traverse the object structure using the names in each case. Store indexes as we go to build a path + for (; varindex < names.size()-1; ++varindex) { + ConstrainedVariableId iVar = iObj->getVariable(LabelStr(iObj->getName().toString() + "." + names[varindex])); + path.push_back(static_cast(iVar->getIndex())); + checkError(iVar->lastDomain().isSingleton(), iVar->toString() + ", " + iObj->getName().toString() + "." + names[varindex]); + iObj = Entity::getTypedEntity(iVar->lastDomain().getSingletonValue()); + } - // Iterate over each object. For each, obtain the variable using the path, and store its value - const std::list objects = objectDomain.makeObjectList(); + // Finally, handle the terminal point - the field variable itself + std::string field_name = iObj->getName().toString() + "." + names[varindex]; + ConstrainedVariableId fieldVar = iObj->getVariable(LabelStr(field_name)); + checkError(fieldVar.isValid(), "No variable named '" << field_name << "' in " << iObj->getName().toString()); + path.push_back(static_cast(fieldVar->getIndex())); - EnumeratedDomain proxyBaseDomain(fieldVar->baseDomain().getDataType()); + // Get the field type for the resulting domain. + const bool isOpen = fieldVar->baseDomain().isOpen(); + const bool isBool = fieldVar->baseDomain().isBool(); - std::list values; - for(std::list::const_iterator it = objects.begin(); it != objects.end(); ++it){ - ObjectId object = *it; - ConstrainedVariableId fieldVar = object->getVariable(path); - checkError(fieldVar->lastDomain().isSingleton(), fieldVar->toString() + " : " + fieldVar->lastDomain().toString() + " is not a singleton."); - edouble value = fieldVar->lastDomain().getSingletonValue(); - proxyBaseDomain.insert(value); - debugMsg("RuleInstance:varFromObject", "Adding value from " << fieldVar->toString()); - } + // At this point, the index is complete, and we know the type. We can allocate and populate the domain + const ObjectDomain& objectDomain = static_cast(obj->baseDomain()); - // Allocate the proxy variable - ConstrainedVariableId proxyVariable; + // Iterate over each object. For each, obtain the variable using the path, and store its value + const std::list objects = objectDomain.makeObjectList(); - // If it is a boolean, allocate a bool domain instead of the enumerated domain - if(isBool){ - BoolDomain boolDomain(fieldVar->baseDomain().getDataType()); - edouble lb = proxyBaseDomain.getLowerBound(); - edouble ub = proxyBaseDomain.getUpperBound(); + EnumeratedDomain proxyBaseDomain(fieldVar->baseDomain().getDataType()); - // If a singleton, set as such - if(lb == ub) - boolDomain.set(ub); + std::list values; + for(std::list::const_iterator it = objects.begin(); it != objects.end(); ++it){ + ObjectId object = *it; + ConstrainedVariableId objectFieldVar = object->getVariable(path); + checkError(objectFieldVar->lastDomain().isSingleton(), + objectFieldVar->toString() << " : " << + objectFieldVar->lastDomain().toString() << " is not a singleton."); + edouble value = objectFieldVar->lastDomain().getSingletonValue(); + proxyBaseDomain.insert(value); + debugMsg("RuleInstance:varFromObject", "Adding value from " << objectFieldVar->toString()); + } - proxyVariable = addVariable(boolDomain, canBeSpecified, fullName); - } - else { - // Close if necessary - if(!isOpen) - proxyBaseDomain.close(); + // Allocate the proxy variable + ConstrainedVariableId proxyVariable; - proxyVariable = addVariable(proxyBaseDomain, canBeSpecified, fullName); - } + // If it is a boolean, allocate a bool domain instead of the enumerated domain + if(isBool){ + BoolDomain boolDomain(fieldVar->baseDomain().getDataType()); + edouble lb = proxyBaseDomain.getLowerBound(); + edouble ub = proxyBaseDomain.getUpperBound(); - // Post the new constraint - ConstraintId proxyVariableRelation = (new ProxyVariableRelation(obj, proxyVariable, path))->getId(); - addConstraint(proxyVariableRelation); + // If a singleton, set as such + if(lb == ub) + boolDomain.set(ub); - // Return the new variable - return proxyVariable; + proxyVariable = addVariable(boolDomain, canBeSpecified, fullName); } + else { + // Close if necessary + if(!isOpen) + proxyBaseDomain.close(); + + proxyVariable = addVariable(proxyBaseDomain, canBeSpecified, fullName); + } + + // Post the new constraint + ConstraintId proxyVariableRelation = (new ProxyVariableRelation(obj, proxyVariable, path))->getId(); + addConstraint(proxyVariableRelation); + + // Return the new variable + return proxyVariable; +} ConstrainedVariableId RuleInstance::varfromtok(const TokenId& token, const std::string varstring) { std::string local_name = varstring.substr(0, varstring.find(Schema::getDelimiter())); @@ -769,7 +771,7 @@ void RuleInstance::setGuard(const ConstrainedVariableId& guard, const Domain& do else { ss << "Slaves: " << std::endl; for(std::map::const_iterator it = m_slavesByName.begin(); it != m_slavesByName.end(); ++it){ - LabelStr name = (LabelStr) it->first; + LabelStr name(it->first); TokenId token = it->second; ss << TAB_DELIMITER << name.toString() << "==" << token->toString() << std::endl; } diff --git a/src/PLASMA/RulesEngine/base/RuleInstance.hh b/src/PLASMA/RulesEngine/base/RuleInstance.hh index 3ecb7204f..31d6a1b5d 100644 --- a/src/PLASMA/RulesEngine/base/RuleInstance.hh +++ b/src/PLASMA/RulesEngine/base/RuleInstance.hh @@ -33,7 +33,6 @@ namespace EUROPA{ /** * @brief Constructor to construct a guarded root rule context where the guard is triggered * whenever the guard variable is set to a singleton. - * @param guard The variable which will be evaluated. trigger rule when set to any singleton value. */ RuleInstance(const RuleId& rule, const TokenId& token, const PlanDatabaseId& planDb, const std::vector& guards); @@ -138,7 +137,7 @@ namespace EUROPA{ /** * @brief Tests if the condition, if there is one, is satisfied. - * @param The guard variables to evaluate against + * @param guards The guard variables to evaluate against */ bool test(const std::vector& guards) const; @@ -294,8 +293,8 @@ namespace EUROPA{ bool m_isPositive; /*!< If this is false, the rule's guard is on a negative test. */ std::vector m_constraints; /*!< Constraints introduced through rule execution */ std::vector m_childRules; /*!< Child rules introduced through rule execution */ - std::vector m_variables; /*< Local variables introduced through rule execution */ - std::vector m_slaves; /*< Slaves introduced through rule execution */ + std::vector m_variables; /*!< Local variables introduced through rule execution */ + std::vector m_slaves; /*!< Slaves introduced through rule execution */ std::map m_variablesByName; /*!< Context lookup */ std::map m_slavesByName; /*!< Context lookup */ std::map m_constraintsByName; /*!< Context lookup */ diff --git a/src/PLASMA/RulesEngine/base/RuleVariableListener.cc b/src/PLASMA/RulesEngine/base/RuleVariableListener.cc index 66e15c222..6d2341d7f 100644 --- a/src/PLASMA/RulesEngine/base/RuleVariableListener.cc +++ b/src/PLASMA/RulesEngine/base/RuleVariableListener.cc @@ -44,9 +44,9 @@ namespace EUROPA { * so that rule execution is not subject to the vagaries of propagtion timing * @return true */ - bool RuleVariableListener::canIgnore(const ConstrainedVariableId& variable, - int argIndex, - const DomainListener::ChangeType& changeType){ + bool RuleVariableListener::canIgnore(const ConstrainedVariableId&, + unsigned int, + const DomainListener::ChangeType&){ checkError(getRuleInstance().isValid(), getKey() << " has lost its rule instance:" << getRuleInstance()); if(getRuleInstance().isNoId()) @@ -64,7 +64,7 @@ namespace EUROPA { checkError(m_sourceConstraint.isValid(), "Must be able to get this from a source constraint."); // Now obtain the rule instance from the source - RuleVariableListener* source = (RuleVariableListener*) m_sourceConstraint; + RuleVariableListener* source = id_cast(m_sourceConstraint); m_ruleInstance = source->getRuleInstance(); checkError(m_ruleInstance.isNoId() || m_ruleInstance.isValid(), m_sourceConstraint->toString()); diff --git a/src/PLASMA/RulesEngine/base/RuleVariableListener.hh b/src/PLASMA/RulesEngine/base/RuleVariableListener.hh index f4ebe9f41..4e0b8194c 100644 --- a/src/PLASMA/RulesEngine/base/RuleVariableListener.hh +++ b/src/PLASMA/RulesEngine/base/RuleVariableListener.hh @@ -76,7 +76,7 @@ namespace EUROPA const std::vector& scope); bool canIgnore(const ConstrainedVariableId& variable, - int argIndex, + unsigned int argIndex, const DomainListener::ChangeType& changeType); void handleExecute(); diff --git a/src/PLASMA/RulesEngine/base/RulesEngine.cc b/src/PLASMA/RulesEngine/base/RulesEngine.cc index 104042cd7..6950e8bb3 100644 --- a/src/PLASMA/RulesEngine/base/RulesEngine.cc +++ b/src/PLASMA/RulesEngine/base/RulesEngine.cc @@ -55,25 +55,25 @@ namespace EUROPA{ check_error(m_planDb->getTokens().empty()); } - RulesEngine::~RulesEngine(){ - check_error(m_planDbListener.isValid()); - - // If we are not purging, then events should have propagated removal of all rule instances - check_error(Entity::isPurging() || m_ruleInstancesByToken.empty()); - - m_deleted = true; - // Thus, only if we are in purge mode will we directly remove rule instances - for(std::multimap::const_iterator it=m_ruleInstancesByToken.begin();it!=m_ruleInstancesByToken.end();++it){ - RuleInstanceId ruleInstance = it->second; - check_error(ruleInstance.isValid()); - ruleInstance->discard(); - } - - delete (PlanDatabaseListener*) m_planDbListener; // removes itself from the plan database set of listeners - delete (PostPropagationCallback*) m_callback; - m_id.remove(); +RulesEngine::~RulesEngine(){ + check_error(m_planDbListener.isValid()); + + // If we are not purging, then events should have propagated removal of all rule instances + check_error(Entity::isPurging() || m_ruleInstancesByToken.empty()); + + m_deleted = true; + // Thus, only if we are in purge mode will we directly remove rule instances + for(std::multimap::const_iterator it=m_ruleInstancesByToken.begin();it!=m_ruleInstancesByToken.end();++it){ + RuleInstanceId ruleInstance = it->second; + check_error(ruleInstance.isValid()); + ruleInstance->discard(); } + delete static_cast(m_planDbListener); // removes itself from the plan database set of listeners + delete static_cast(m_callback); + m_id.remove(); +} + const RulesEngineId& RulesEngine::getId() const{return m_id;} const PlanDatabaseId& RulesEngine::getPlanDatabase() const {return m_planDb;} diff --git a/src/PLASMA/RulesEngine/base/RulesEngineListener.cc b/src/PLASMA/RulesEngine/base/RulesEngineListener.cc index bc35e272e..54be085b2 100644 --- a/src/PLASMA/RulesEngine/base/RulesEngineListener.cc +++ b/src/PLASMA/RulesEngine/base/RulesEngineListener.cc @@ -20,4 +20,8 @@ namespace EUROPA { const RulesEngineListenerId &RulesEngineListener::getId() const { return m_id; } + +void RulesEngineListener::notifyExecuted(const RuleInstanceId &){} +void RulesEngineListener::notifyUndone(const RuleInstanceId &){} + } diff --git a/src/PLASMA/RulesEngine/base/RulesEngineListener.hh b/src/PLASMA/RulesEngine/base/RulesEngineListener.hh index 43ea91f4c..11838cc43 100644 --- a/src/PLASMA/RulesEngine/base/RulesEngineListener.hh +++ b/src/PLASMA/RulesEngine/base/RulesEngineListener.hh @@ -7,8 +7,8 @@ namespace EUROPA { class RulesEngineListener { public: virtual ~RulesEngineListener(); - virtual void notifyExecuted(const RuleInstanceId &rule){} - virtual void notifyUndone(const RuleInstanceId &rule){} + virtual void notifyExecuted(const RuleInstanceId &rule); + virtual void notifyUndone(const RuleInstanceId &rule); const RulesEngineListenerId &getId() const; protected: diff --git a/src/PLASMA/Solvers/ModuleSolvers.cc b/src/PLASMA/Solvers/ModuleSolvers.cc index 3a2bd0b85..1ffdcdf30 100644 --- a/src/PLASMA/Solvers/ModuleSolvers.cc +++ b/src/PLASMA/Solvers/ModuleSolvers.cc @@ -15,6 +15,8 @@ #include "RulesEngine.hh" #include "PSSolversImpl.hh" +#include + // TODO: is this necessary? #ifdef near #undef near @@ -42,69 +44,74 @@ namespace EUROPA { { } - void ModuleSolvers::initialize(EngineId engine) - { - ConstraintEngine* ce = (ConstraintEngine*)engine->getComponent("ConstraintEngine"); - PlanDatabase* pdb = (PlanDatabase*)engine->getComponent("PlanDatabase"); - PSSolverManager* sm = new PSSolverManagerImpl(pdb->getId()); - engine->addComponent("PSSolverManager",sm); - - REGISTER_SYSTEM_CONSTRAINT(ce->getCESchema(),SOLVERS::FlawHandler::VariableListener,SOLVERS::FlawHandler::VariableListener::CONSTRAINT_NAME(),SOLVERS::FlawHandler::VariableListener::PROPAGATOR_NAME()); - - EUROPA::SOLVERS::ComponentFactoryMgr* cfm = new EUROPA::SOLVERS::ComponentFactoryMgr(); - engine->addComponent("ComponentFactoryMgr",cfm); - REGISTER_COMPONENT_FACTORY(cfm,SOLVERS::FlawFilter, FlawFilter); - - REGISTER_FLAW_MANAGER(cfm,SOLVERS::UnboundVariableManager, UnboundVariableManager); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, StandardVariableHandler); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, Min); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::MaxValue, Max); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::RandomValue, Random); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::ValueEnum, ValEnum); - - REGISTER_FLAW_MANAGER(cfm,SOLVERS::OpenConditionManager, OpenConditionManager); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::SupportedOCDecisionPoint, StandardOpenConditionHandler); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::OpenConditionDecisionPoint, BasicOpenConditionHandler); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::SupportedOCDecisionPoint, SupportedOpenConditionHandler); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::OpenConditionDecisionPoint, HSTSOpenConditionDecisionPoint); - - REGISTER_FLAW_MANAGER(cfm,SOLVERS::ThreatManager, ThreatManager); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::ThreatDecisionPoint, StandardThreatHandler); - REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::ThreatDecisionPoint, HSTSThreatDecisionPoint); - - REGISTER_FLAW_FILTER(cfm,SOLVERS::GuardFilter, GuardFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::NotGuardFilter, NotGuardFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::ParameterFilter, ParameterFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::LocalVariableFilter, LocalVariableFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::SingletonFilter, Singleton); - REGISTER_FLAW_FILTER(cfm,SOLVERS::InfiniteDynamicFilter, InfiniteDynamicFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::HorizonFilter, HorizonFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::HorizonVariableFilter, HorizonVariableFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::MasterMustBeAssignedFilter, MasterMustBeInsertedFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::TokenMustBeAssignedFilter, TokenMustBeAssignedFilter); - REGISTER_FLAW_FILTER(cfm,SOLVERS::TokenMustBeAssignedFilter, ParentMustBeInsertedFilter); - - REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::EarlyTokenComparator, early); - REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::LateTokenComparator, late); - REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::NearTokenComparator, near); - REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::FarTokenComparator, far); - REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::AscendingKeyTokenComparator, ascendingKey); - - EUROPA::SOLVERS::MatchFinderMgr* mfm = new EUROPA::SOLVERS::MatchFinderMgr(); - engine->addComponent("MatchFinderMgr",mfm); - REGISTER_MATCH_FINDER(mfm,SOLVERS::VariableMatchFinder,ConstrainedVariable::entityTypeName()); - REGISTER_MATCH_FINDER(mfm,SOLVERS::TokenMatchFinder,Token::entityTypeName()); - } +void ModuleSolvers::initialize(EngineId engine) { + ConstraintEngine* ce = + boost::polymorphic_cast(engine->getComponent("ConstraintEngine")); + + PlanDatabase* pdb = + boost::polymorphic_cast(engine->getComponent("PlanDatabase")); + + PSSolverManager* sm = new PSSolverManagerImpl(pdb->getId()); + engine->addComponent("PSSolverManager",sm); + + REGISTER_SYSTEM_CONSTRAINT(ce->getCESchema(),SOLVERS::FlawHandler::VariableListener,SOLVERS::FlawHandler::VariableListener::CONSTRAINT_NAME(),SOLVERS::FlawHandler::VariableListener::PROPAGATOR_NAME()); + + EUROPA::SOLVERS::ComponentFactoryMgr* cfm = new EUROPA::SOLVERS::ComponentFactoryMgr(); + engine->addComponent("ComponentFactoryMgr",cfm); + REGISTER_COMPONENT_FACTORY(cfm,SOLVERS::FlawFilter, FlawFilter); + + REGISTER_FLAW_MANAGER(cfm,SOLVERS::UnboundVariableManager, UnboundVariableManager); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, StandardVariableHandler); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::MinValue, Min); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::MaxValue, Max); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::RandomValue, Random); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::ValueEnum, ValEnum); + + REGISTER_FLAW_MANAGER(cfm,SOLVERS::OpenConditionManager, OpenConditionManager); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::SupportedOCDecisionPoint, StandardOpenConditionHandler); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::OpenConditionDecisionPoint, BasicOpenConditionHandler); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::SupportedOCDecisionPoint, SupportedOpenConditionHandler); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::OpenConditionDecisionPoint, HSTSOpenConditionDecisionPoint); + + REGISTER_FLAW_MANAGER(cfm,SOLVERS::ThreatManager, ThreatManager); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::ThreatDecisionPoint, StandardThreatHandler); + REGISTER_FLAW_HANDLER(cfm,SOLVERS::HSTS::ThreatDecisionPoint, HSTSThreatDecisionPoint); + + REGISTER_FLAW_FILTER(cfm,SOLVERS::GuardFilter, GuardFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::NotGuardFilter, NotGuardFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::ParameterFilter, ParameterFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::LocalVariableFilter, LocalVariableFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::SingletonFilter, Singleton); + REGISTER_FLAW_FILTER(cfm,SOLVERS::InfiniteDynamicFilter, InfiniteDynamicFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::HorizonFilter, HorizonFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::HorizonVariableFilter, HorizonVariableFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::MasterMustBeAssignedFilter, MasterMustBeInsertedFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::TokenMustBeAssignedFilter, TokenMustBeAssignedFilter); + REGISTER_FLAW_FILTER(cfm,SOLVERS::TokenMustBeAssignedFilter, ParentMustBeInsertedFilter); + + REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::EarlyTokenComparator, early); + REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::LateTokenComparator, late); + REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::NearTokenComparator, near); + REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::FarTokenComparator, far); + REGISTER_TOKEN_SORTER(cfm,SOLVERS::HSTS::AscendingKeyTokenComparator, ascendingKey); + + EUROPA::SOLVERS::MatchFinderMgr* mfm = new EUROPA::SOLVERS::MatchFinderMgr(); + engine->addComponent("MatchFinderMgr",mfm); + REGISTER_MATCH_FINDER(mfm,SOLVERS::VariableMatchFinder,ConstrainedVariable::entityTypeName()); + REGISTER_MATCH_FINDER(mfm,SOLVERS::TokenMatchFinder,Token::entityTypeName()); +} - void ModuleSolvers::uninitialize(EngineId engine) - { - EUROPA::SOLVERS::MatchFinderMgr* mfm = (EUROPA::SOLVERS::MatchFinderMgr*)engine->removeComponent("MatchFinderMgr"); - delete mfm; +void ModuleSolvers::uninitialize(EngineId engine) { + EUROPA::SOLVERS::MatchFinderMgr* mfm = + boost::polymorphic_cast(engine->removeComponent("MatchFinderMgr")); + delete mfm; - EUROPA::SOLVERS::ComponentFactoryMgr* cfm = (EUROPA::SOLVERS::ComponentFactoryMgr*)engine->removeComponent("ComponentFactoryMgr"); - delete cfm; + EUROPA::SOLVERS::ComponentFactoryMgr* cfm = + boost::polymorphic_cast(engine->removeComponent("ComponentFactoryMgr")); + delete cfm; - PSSolverManager* sm = (PSSolverManager*)engine->removeComponent("PSSolverManager"); - delete sm; - } + PSSolverManager* sm = + boost::polymorphic_cast(engine->removeComponent("PSSolverManager")); + delete sm; +} } diff --git a/src/PLASMA/Solvers/SolverDefs.hh b/src/PLASMA/Solvers/SolverDefs.hh index 0010e0657..bc2b0f1cc 100644 --- a/src/PLASMA/Solvers/SolverDefs.hh +++ b/src/PLASMA/Solvers/SolverDefs.hh @@ -57,11 +57,11 @@ namespace EUROPA { return sl_bestCasePriority; } - inline const Priority getBestCasePriority() { + inline Priority getBestCasePriority() { return bestCasePriority(); } - inline const Priority getWorstCasePriority() { + inline Priority getWorstCasePriority() { return worstCasePriority(); } diff --git a/src/PLASMA/Solvers/base/ComponentFactory.cc b/src/PLASMA/Solvers/base/ComponentFactory.cc index eb340d59e..dea66c169 100644 --- a/src/PLASMA/Solvers/base/ComponentFactory.cc +++ b/src/PLASMA/Solvers/base/ComponentFactory.cc @@ -39,10 +39,9 @@ namespace EUROPA { m_name = name; } - ComponentId ComponentFactoryMgr::createInstance(const TiXmlElement& configData) - { - LabelStr name = extractData(configData, "component"); - return FactoryMgr::createInstance(name,ComponentArgs(configData)); - } + ComponentId ComponentFactoryMgr::createComponentInstance(const TiXmlElement& configData) { + LabelStr name = extractData(configData, "component"); + return FactoryMgr::createInstance(name,ComponentArgs(configData)); } + } diff --git a/src/PLASMA/Solvers/base/ComponentFactory.hh b/src/PLASMA/Solvers/base/ComponentFactory.hh index 005f1a481..048d83cb8 100644 --- a/src/PLASMA/Solvers/base/ComponentFactory.hh +++ b/src/PLASMA/Solvers/base/ComponentFactory.hh @@ -49,10 +49,10 @@ namespace EUROPA { /** * @brief Defines a base class for factories that take xml configuration data. */ - class ComponentFactoryMgr : public FactoryMgr { - public: - virtual ComponentId createInstance(const TiXmlElement& configData); - }; + class ComponentFactoryMgr : public FactoryMgr { + public: + virtual ComponentId createComponentInstance(const TiXmlElement& configData); + }; /** * @brief Provides concrete allocation using a template. @@ -64,10 +64,10 @@ namespace EUROPA { ComponentFactory(const LabelStr& name) : Factory(name) {} virtual EUROPA::FactoryObjId& createInstance(const EUROPA::FactoryArgs& fa) { - const ComponentArgs& args = (const ComponentArgs&)fa; + const ComponentArgs& args = dynamic_cast(fa); ComponentType* ct = new ComponentType(args.configData); ct->setName(getName()); - return (EUROPA::FactoryObjId&)(ct->getId()); + return static_cast(ct->getId()); } }; diff --git a/src/PLASMA/Solvers/base/FlawHandler.cc b/src/PLASMA/Solvers/base/FlawHandler.cc index 8a1d45df7..fc4ab0e02 100644 --- a/src/PLASMA/Solvers/base/FlawHandler.cc +++ b/src/PLASMA/Solvers/base/FlawHandler.cc @@ -81,7 +81,9 @@ namespace EUROPA { double FlawHandler::getWeight() const {return m_weight;} - unsigned int FlawHandler::getMaxChoices() const {return m_maxChoices;} + unsigned int FlawHandler::getMaxChoices() const {return m_maxChoices;} + + bool FlawHandler::customStaticMatch(const EntityId&) const {return true;} std::string FlawHandler::toString() const{ std::stringstream sstr; diff --git a/src/PLASMA/Solvers/base/FlawHandler.hh b/src/PLASMA/Solvers/base/FlawHandler.hh index d4e35e4e8..108e12f77 100644 --- a/src/PLASMA/Solvers/base/FlawHandler.hh +++ b/src/PLASMA/Solvers/base/FlawHandler.hh @@ -56,7 +56,7 @@ namespace EUROPA { /** * @brief Tests for a match between this factory and the entity */ - virtual bool customStaticMatch(const EntityId& entity) const {return true;} + virtual bool customStaticMatch(const EntityId& entity) const; /** * @brief Tests how many costm static filters should be applied. Factors into comparative weights @@ -96,8 +96,8 @@ namespace EUROPA { const ConstrainedVariableId& guardVar, const edouble& testValue); - static const unsigned int WEIGHT_BASE() {return 100000;} /*!< Used to weight active instances. - Establishes upper limit on priority values.*/ + static unsigned int WEIGHT_BASE() {return 100000;} /*!< Used to weight active instances. + Establishes upper limit on priority values.*/ friend class FlawManager; diff --git a/src/PLASMA/Solvers/base/FlawManager.cc b/src/PLASMA/Solvers/base/FlawManager.cc index 3de0e1145..cdd99d553 100644 --- a/src/PLASMA/Solvers/base/FlawManager.cc +++ b/src/PLASMA/Solvers/base/FlawManager.cc @@ -119,7 +119,8 @@ namespace EUROPA { return IteratorId::noId(); } - void FlawManager::notifyRemoved(const ConstraintId& constraint) { + void FlawManager::notifyAdded(const ConstraintId&) {} + void FlawManager::notifyRemoved(const ConstraintId& constraint) { // Check if it's the correct type (FlawHandler::VariableListener) // then we search through the map and remove any instances of it. if(Id::convertable(constraint)) { @@ -259,6 +260,11 @@ namespace EUROPA { condDebugMsg(!isValid(), "FlawManager:isValid", "Invalid datastructures in flaw manger."); } + void FlawManager::notifyChanged(const ConstrainedVariableId& , + const DomainListener::ChangeType& ){} + + + void FlawManager::notifyAdded(const TokenId&){} void FlawManager::notifyRemoved(const TokenId& token) { debugMsg("FlawManager:notifyRemoved", getId() << " Removing active flaw handlers and guards for " << token->getPredicateName().toString() << "(" << token->getKey() << ")"); diff --git a/src/PLASMA/Solvers/base/FlawManager.hh b/src/PLASMA/Solvers/base/FlawManager.hh index 2b3fbcfdc..ab3cd97fd 100644 --- a/src/PLASMA/Solvers/base/FlawManager.hh +++ b/src/PLASMA/Solvers/base/FlawManager.hh @@ -106,11 +106,12 @@ namespace EUROPA { */ virtual IteratorId createIterator(); - virtual void notifyAdded(const ConstraintId& constraint){} + virtual void notifyAdded(const ConstraintId& constraint); virtual void notifyRemoved(const ConstraintId& constraint); virtual void notifyRemoved(const ConstrainedVariableId& var); - virtual void notifyChanged(const ConstrainedVariableId& variable, const DomainListener::ChangeType& changeType){} - virtual void notifyAdded(const TokenId& token) {} + virtual void notifyChanged(const ConstrainedVariableId& variable, + const DomainListener::ChangeType& changeType); + virtual void notifyAdded(const TokenId& token); virtual void notifyRemoved(const TokenId& token); /** diff --git a/src/PLASMA/Solvers/base/MatchingEngine.hh b/src/PLASMA/Solvers/base/MatchingEngine.hh index 7b8a85eab..c70521895 100644 --- a/src/PLASMA/Solvers/base/MatchingEngine.hh +++ b/src/PLASMA/Solvers/base/MatchingEngine.hh @@ -49,10 +49,7 @@ namespace EUROPA { * written for each type. */ template - void getMatches(const T& entity, std::vector& results) { - checkError(ALWAYS_FAIL, - "Don't know how to match objects of type " << typeid(T).name()); - } + void getMatches(const T& entity, std::vector& results); /** * @brief Adds a rule. Details of how it is indexed are internal @@ -128,6 +125,12 @@ namespace EUROPA { std::map& getEntityMatchers(); }; + template + void MatchingEngine::getMatchesInternal(const T&, std::vector&) { + checkError(ALWAYS_FAIL, + "Don't know how to match objects of type " << typeid(T).name()); + } + template<> void MatchingEngine::getMatches(const EntityId& entity, std::vector& results); diff --git a/src/PLASMA/Solvers/base/Solver.hh b/src/PLASMA/Solvers/base/Solver.hh index 7176bc584..613502197 100644 --- a/src/PLASMA/Solvers/base/Solver.hh +++ b/src/PLASMA/Solvers/base/Solver.hh @@ -267,7 +267,7 @@ namespace EUROPA { unsigned int m_maxSteps; /*!< The maximum number of steps to take. Used only for planner control.*/ unsigned int m_maxDepth; /*!< The maximum depth to search. Used only for planner control.*/ MasterFilter m_masterFlawFilter; /*!< Used to handle shared filter data across contained flaw managers */ - ContextId m_context; /*getId(); } - const ConstraintEngineId& getConstraintEngine() { return ((ConstraintEngine*)getComponent("ConstraintEngine"))->getId(); } - const PlanDatabaseId& getPlanDatabase() { return ((PlanDatabase*)getComponent("PlanDatabase"))->getId(); } - const RulesEngineId& getRulesEngine() { return ((RulesEngine*)getComponent("RulesEngine"))->getId(); } + public: + SolversTestEngine(); + virtual ~SolversTestEngine(); + + const SchemaId& getSchema() { return static_cast(getComponent("Schema"))->getId(); } + const ConstraintEngineId& getConstraintEngine() { return static_cast(getComponent("ConstraintEngine"))->getId(); } + const PlanDatabaseId& getPlanDatabase() { return static_cast(getComponent("PlanDatabase"))->getId(); } + const RulesEngineId& getRulesEngine() { return static_cast(getComponent("RulesEngine"))->getId(); } protected: void createModules(); @@ -205,7 +205,7 @@ class ComponentFactoryTests{ child = child->NextSiblingElement()) { ComponentFactoryMgr* cfm = - (ComponentFactoryMgr*)testEngine.getComponent("ComponentFactoryMgr"); + dynamic_cast(testEngine.getComponent("ComponentFactoryMgr")); TestComponent * testComponent = static_cast(cfm->createInstance(*child)); delete testComponent; diff --git a/src/PLASMA/TemporalNetwork/ModuleTemporalNetwork.cc b/src/PLASMA/TemporalNetwork/ModuleTemporalNetwork.cc index 352b0eeae..6bda4f712 100644 --- a/src/PLASMA/TemporalNetwork/ModuleTemporalNetwork.cc +++ b/src/PLASMA/TemporalNetwork/ModuleTemporalNetwork.cc @@ -7,6 +7,8 @@ #include "TemporalPropagator.hh" #include "STNTemporalAdvisor.hh" +#include + namespace EUROPA { ModuleTemporalNetwork::ModuleTemporalNetwork() @@ -26,31 +28,31 @@ namespace EUROPA { { } - void ModuleTemporalNetwork::initialize(EngineId engine) - { - ConstraintEngine* ce = (ConstraintEngine*)engine->getComponent("ConstraintEngine"); - CESchema* ces = ce->getCESchema(); - - REGISTER_SYSTEM_CONSTRAINT(ces,EqualConstraint, "concurrent", "Temporal"); - REGISTER_SYSTEM_CONSTRAINT(ces,LessThanEqualConstraint, "precedes", "Temporal"); - REGISTER_SYSTEM_CONSTRAINT(ces, LessThanConstraint, "strictlyPrecedes", "Temporal"); - REGISTER_SYSTEM_CONSTRAINT(ces,AddEqualConstraint, "temporalDistance", "Temporal"); - - PlanDatabase* pdb = (PlanDatabase*)engine->getComponent("PlanDatabase"); - - PropagatorId temporalPropagator; - if (engine->getConfig()->getProperty("TemporalNetwork.useTemporalPropagator") != "N") { - temporalPropagator = (new TemporalPropagator(LabelStr("Temporal"), ce->getId()))->getId(); - pdb->setTemporalAdvisor((new STNTemporalAdvisor(temporalPropagator))->getId()); - } - else { - temporalPropagator = (new DefaultPropagator(LabelStr("Temporal"), ce->getId()))->getId(); - pdb->setTemporalAdvisor((new DefaultTemporalAdvisor(ce->getId()))->getId()); - } - } +void ModuleTemporalNetwork::initialize(EngineId engine) { + ConstraintEngine* ce = + boost::polymorphic_cast(engine->getComponent("ConstraintEngine")); + CESchema* ces = ce->getCESchema(); - void ModuleTemporalNetwork::uninitialize(EngineId engine) - { - // TODO: cleanup + REGISTER_SYSTEM_CONSTRAINT(ces,EqualConstraint, "concurrent", "Temporal"); + REGISTER_SYSTEM_CONSTRAINT(ces,LessThanEqualConstraint, "precedes", "Temporal"); + REGISTER_SYSTEM_CONSTRAINT(ces, LessThanConstraint, "strictlyPrecedes", "Temporal"); + REGISTER_SYSTEM_CONSTRAINT(ces,AddEqualConstraint, "temporalDistance", "Temporal"); + + PlanDatabase* pdb = + boost::polymorphic_cast(engine->getComponent("PlanDatabase")); + + PropagatorId temporalPropagator; + if (engine->getConfig()->getProperty("TemporalNetwork.useTemporalPropagator") != "N") { + temporalPropagator = (new TemporalPropagator(LabelStr("Temporal"), ce->getId()))->getId(); + pdb->setTemporalAdvisor((new STNTemporalAdvisor(temporalPropagator))->getId()); + } + else { + temporalPropagator = (new DefaultPropagator(LabelStr("Temporal"), ce->getId()))->getId(); + pdb->setTemporalAdvisor((new DefaultTemporalAdvisor(ce->getId()))->getId()); } } + +void ModuleTemporalNetwork::uninitialize(EngineId) { + // TODO: cleanup +} +} diff --git a/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc b/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc index 5d915be50..a7c46cf12 100644 --- a/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc +++ b/src/PLASMA/TemporalNetwork/base/DispatchGraph.cc @@ -34,6 +34,8 @@ #include "DispatchGraph.hh" #include "Error.hh" +#include + namespace EUROPA { DnodeId DispatchGraph::makeNode() @@ -45,7 +47,8 @@ DnodeId DispatchGraph::makeNode() DispatchNode* DispatchGraph::createNode(Referent name) { - DispatchNode* node = (DispatchNode*)DistanceGraph::createNode(); + //this line can't possibly be right. dispatchgraph appears to be broken + DispatchNode* node = id_cast(DistanceGraph::createNode()); node->name = name; node->isSccMember = false; return node; @@ -74,7 +77,7 @@ void DispatchGraph::filter( void (*keepEdge)(DispatchNode*, DispatchNode*, this->sccLeaders = std::vector(); // Set initial distances to same as potential for (std::vector::const_iterator it=nodes.begin(); it != nodes.end(); ++it) { - DispatchNode* node = (DispatchNode*) *it; + DispatchNode* node = id_cast(*it); node->distance = node->potential; } @@ -106,7 +109,7 @@ void DispatchGraph::findSccs( void (*keepEdge)(DispatchNode*, DispatchNode*, // See P. 488 in "Introduction To Algorithms" // by Cormen, Leiverson, & Rivest. // The SCCs contain all the rigid (no slack) edges in the network. - Int nodeCount = this->nodes.size(); + Int nodeCount = static_cast(this->nodes.size()); DispatchNode** scc = new DispatchNode*[nodeCount]; // Scratch list for SCCs. if (!scc) check_error(!scc, @@ -114,42 +117,41 @@ void DispatchGraph::findSccs( void (*keepEdge)(DispatchNode*, DispatchNode*, TempNetErr::TempNetMemoryError()); buildReversePostorder (this->nodes); Dnode::unmarkAll(); - for (Int i=0; i < nodeCount; i++) { + for (unsigned long i=0; i < static_cast(nodeCount); i++) { DispatchNode* node = this->reversePostorder[i]; if (!node->isMarked()) { size_t sccSize = 0; predGraphTraceScc (node, scc, sccSize, nodeCount); // Builds scc. - qsort ((void*)scc, sccSize, sizeof(DispatchNode*), - (Int (*)(const void*,const void*)) compareNodes); + //std::sort(scc, scc + sccSize, compareNodes); + // qsort (static_cast(scc), sccSize, sizeof(DispatchNode*), + // static_cast(compareNodes)); processScc (scc, sccSize, keepEdge); } } delete[] scc; } -void DispatchGraph::buildReversePostorder (std::vector& argNodes) -{ +void DispatchGraph::buildReversePostorder (std::vector& argNodes) { // Do depth-first searches, collecting nodes into reverse-postorder. Dnode::unmarkAll(); - Int position = argNodes.size(); + Int position = static_cast(argNodes.size()); for (std::vector::const_iterator it=argNodes.begin(); it != argNodes.end(); ++it) { Dnode* node = *it; if (!node->isMarked()) - predGraphDfs ((DispatchNode*)node, position); + predGraphDfs (boost::polymorphic_cast(node), position); } check_error(!(position > 0), "Lost some nodes from reversePostorder list", TempNetErr::TempNetInternalError()); } -void DispatchGraph::predGraphDfs (DispatchNode* node, Int& position) -{ +void DispatchGraph::predGraphDfs (DispatchNode* node, Int& position) { // Depth-first-search through predecessor graph (PG). An edge // is in PG if start_distance + length(edge) == end_distance. node->mark(); for (Int i=0; i < node->outCount; i++) { Dedge* edge = node->outArray[i]; - DispatchNode* next = (DispatchNode*) edge->to; + DispatchNode* next = id_cast(edge->to); if (!next->isMarked() && node->distance + edge->length == next->distance) this->predGraphDfs (next, position); } @@ -161,18 +163,18 @@ void DispatchGraph::predGraphDfs (DispatchNode* node, Int& position) } void DispatchGraph::predGraphTraceScc (DispatchNode* node, DispatchNode* scc[], - size_t& sccSize, Int nodeCount) -{ + size_t& sccSize, Int nodeCount) { node->mark(); node->isSccMember = true; - check_error(!((Int)sccSize >= nodeCount), "Inserting node beyond end of node-array", + check_error(!(static_cast(sccSize) >= nodeCount), + "Inserting node beyond end of node-array", TempNetErr::TempNetInternalError()); scc[sccSize++] = node; for (Int i=0; i< node->inCount; i++) { Dedge* edge = node->inArray[i]; - DispatchNode* parent = (DispatchNode*) edge->from; + DispatchNode* parent = id_cast(edge->from); if (!parent->isMarked() && parent->distance + edge->length == node->distance) predGraphTraceScc (parent, scc, sccSize, nodeCount); @@ -194,7 +196,7 @@ void DispatchGraph::processScc (DispatchNode* scc[], size_t sccSize, // Arrange in a doubly-linked chain. DispatchNode* previous = leader; Time prevdistance = leader->distance; - for (Int i=1; i < (Int)sccSize; i++) { + for (Int i=1; i < static_cast(sccSize); i++) { DispatchNode* node = scc[i]; Time distance = node->distance; Time increment = distance - prevdistance; @@ -242,8 +244,8 @@ void DispatchGraph::sccMoveFluids (DispatchNode* node, DispatchNode* leader) } // Following are defined in DistanceGraph.cc -Void attachEdge (DedgeId*& edgeArray, Int& size, Int& count, DedgeId edge); -Void detachEdge (DedgeId*& edgeArray, Int& count, DedgeId edge); +// Void attachEdge (DedgeId*& edgeArray, Int& size, Int& count, DedgeId edge); +// Void detachEdge (DedgeId*& edgeArray, Int& count, DedgeId edge); /* TBW: Replaced by newer version that does more error checking @@ -314,7 +316,7 @@ void DispatchGraph::sccMoveDirectional (DispatchNode* node, for (Int i=0; i< node->*outCount; i++) { Dedge* edge = (node->*outs)[i]; - DispatchNode* next = (DispatchNode*) (edge->*to); + DispatchNode* next = id_cast(edge->*to); if (next == leader) // Delink from leader detachEdge (leader->*ins, leader->*inCount, edge); if (next->isSccMember == false) { // next is not in the SCC. @@ -326,7 +328,7 @@ void DispatchGraph::sccMoveDirectional (DispatchNode* node, Dedge* leaderEdge = 0; for (Int j=0; j < leader->*outCount; j++) { Dedge* e = (leader->*outs)[j]; - Dnode* eTo = (Dnode*)(e->*to); + Dnode* eTo = id_cast(e->*to); if (eTo == next) leaderEdge = e; } @@ -355,7 +357,7 @@ void DispatchGraph::findKeptEdges (DispatchNode* source, { // This computes what edges to keep among those that are outside // the SCCs. These are the fluid (non-rigid) edges. - Int leaderCount = this->sccLeaders.size(); + Int leaderCount = static_cast(this->sccLeaders.size()); Dnode::unmarkAll(); Int position = leaderCount; // Following collects nodes downward into reverse-postorder @@ -376,7 +378,7 @@ void DispatchGraph::findKeptEdges (DispatchNode* source, if ( node->isMarked() ) { for (Int j=0; j < node->outCount; j++) { Dedge* edge = node->outArray[j]; - DispatchNode* child = (DispatchNode*) edge->to; + DispatchNode* child = id_cast(edge->to); if ( node->distance + edge->length == child->distance ) child->mark(); } @@ -390,7 +392,7 @@ void DispatchGraph::findKeptEdges (DispatchNode* source, Time minDistance = POS_INFINITY; for (Int k=0; k < node->inCount; k++) { Dedge* edge = node->inArray[k]; - DispatchNode* parent = (DispatchNode*) edge->from; + DispatchNode* parent = id_cast(edge->from); if ( parent->distance + edge->length == node->distance // Pred graph && parent->minDistance < minDistance) minDistance = parent->minDistance; diff --git a/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc b/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc index b736acb5f..cb16d1a75 100644 --- a/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc +++ b/src/PLASMA/TemporalNetwork/base/DistanceGraph.cc @@ -35,7 +35,7 @@ void deleteIfEqual(std::vector& elements, ELEMENT element){ } // Global value overridden only for Rax-derived system test. -Bool IsOkToRemoveConstraintTwice = false; +// Bool IsOkToRemoveConstraintTwice = false; DistanceGraph::DistanceGraph () { @@ -69,7 +69,43 @@ DnodeId DistanceGraph::createNode() return node; } -Void detachEdge (DedgeId*& edgeArray, Int& count, DedgeId edge); +Void attachEdge (DedgeId*& edgeArray, Int& size, Int& count, DedgeId edge) { + check_error(!(count > size), "Corrupted edge-array in TemporalNetwork", + TempNetErr::TempNetInternalError()); + + if (count == size) { + // Grow edge-array + if (size < 1) + size = 1; + else + size = 2*size; + DedgeId* newEdgeArray = new DedgeId[size]; + if(!newEdgeArray) + check_error(!newEdgeArray, + "Memory allocation failed for TemporalNetwork edge-array", + TempNetErr::TempNetMemoryError()); + for (Int i=0; i size), "Corrupted edge-array in TemporalNetwork", - TempNetErr::TempNetInternalError()); - - if (count == size) { - // Grow edge-array - if (size < 1) - size = 1; - else - size = 2*size; - DedgeId* newEdgeArray = new DedgeId[size]; - if(!newEdgeArray) - check_error(!newEdgeArray, - "Memory allocation failed for TemporalNetwork edge-array", - TempNetErr::TempNetMemoryError()); - for (Int i=0; ifrom->outArray, edge->from->outCount, edge); @@ -187,7 +187,7 @@ Void DistanceGraph::eraseEdge(DedgeId edge) edge->from = DnodeId::noId(); edge->to = DnodeId::noId(); edge->length = 99; // A clue for debugging purposes - delete (Dedge*) edge; + delete static_cast(edge); } Void DistanceGraph::addEdgeSpec(DnodeId from, DnodeId to, Time length) @@ -250,7 +250,7 @@ Bool DistanceGraph::bellmanFord() // minimizes the amount of wasted superseded propagations. queue->insertInQueue (node, -oldPotential); } - Int BFbound = nodes.size(); + Int BFbound = static_cast(nodes.size()); while (true) { DnodeId node = queue->popMinFromQueue(); if (node.isNoId()) @@ -291,7 +291,7 @@ Bool DistanceGraph::bellmanFord() Bool DistanceGraph::incBellmanFord() { - Int BFbound = nodes.size(); + Int BFbound = static_cast(nodes.size()); //Dqueue* queue = dqueue; BucketQueue* queue = bqueue; @@ -369,7 +369,7 @@ Void DistanceGraph::dijkstra (DnodeId source, DnodeId destination) BucketQueue* queue = initializeBqueue(); queue->insertInQueue (source); #ifndef EUROPA_FAST - Int BFbound = this->nodes.size(); + Int BFbound = static_cast(this->nodes.size()); #endif while (true) { DnodeId node = queue->popMinFromQueue(); @@ -576,8 +576,8 @@ Void DistanceGraph::preventNodeMarkOverflow() // Unlikely to happen, but just in case... if (Dnode::markGlobal == INT_MAX) { // Roll all marks over to zero. - Int nodeCount = this->nodes.size(); - for (Int i=0; i< nodeCount; i++) + unsigned long nodeCount = this->nodes.size(); + for (unsigned long i=0; i< static_cast(nodeCount); i++) nodes[i]->markLocal = 0; Dnode::markGlobal = 0; } @@ -588,8 +588,8 @@ Void DistanceGraph::preventGenerationOverflow() // Unlikely to happen, but just in case... if (this->dijkstraGeneration == INT_MAX) { // Roll all generations over to zero. - Int nodeCount = this->nodes.size(); - for (Int i=0; i< nodeCount; i++) + unsigned long nodeCount = this->nodes.size(); + for (unsigned long i=0; i< nodeCount; i++) this->nodes[i]->generation = 0; this->dijkstraGeneration = 0; } @@ -644,7 +644,7 @@ Void DistanceGraph::boundedDijkstra (const DnodeId& source, BucketQueue* queue = initializeBqueue(); queue->insertInQueue (source); - Int BFbound EUROPA_ATTRIBUTE_UNUSED = this->nodes.size(); + check_error_variable(Int BFbound = static_cast(this->nodes.size())); while (true) { DnodeId node = queue->popMinFromQueue(); if (node.isNoId()) diff --git a/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh b/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh index 98a27e8f1..57e4ffad1 100644 --- a/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh +++ b/src/PLASMA/TemporalNetwork/base/DistanceGraph.hh @@ -121,7 +121,7 @@ public: /** * @brief Add edge to the network * @param from start of the edge - * @param end end of the edge + * @param to end of the edge * @param length length of the edge */ Void addEdgeSpec(DnodeId from, DnodeId to, Time length); @@ -260,7 +260,7 @@ protected: * createEdge directly. (The DispatchGraph uses this feature.) * @param from from node * @param to to node - * @param time duration of edge + * @param length duration of edge */ DedgeId createEdge(DnodeId from, DnodeId to, Time length); @@ -280,7 +280,7 @@ protected: * @brief Allow subclass to take action when a node is updated * @param node node updated */ - virtual void handleNodeUpdate(const DnodeId& node) {} + virtual void handleNodeUpdate(const DnodeId& node); private: Void deleteEdge(DedgeId edge); @@ -406,7 +406,7 @@ public: */ ~Dedge(){m_id.remove();} /** - * @breif get id of edge + * @brief get id of edge * @return id of edge */ const DedgeId& getId() const {return m_id;} @@ -535,6 +535,8 @@ public: Bool isEmpty(); }; +Void attachEdge (DedgeId*& edgeArray, Int& size, Int& count, DedgeId edge); +Void detachEdge (DedgeId*& edgeArray, Int& count, DedgeId edge); } /* namespace Europa */ #endif diff --git a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc index ae9f4a6ea..eb2c4f8a7 100644 --- a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc +++ b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.cc @@ -16,6 +16,8 @@ #include "TemporalNetwork.hh" #include "Debug.hh" +#include + namespace EUROPA { Bool TemporalNetwork::isValidId(const TimepointId& id){ @@ -125,8 +127,9 @@ namespace EUROPA { check_error(this->consistent, "TemporalNetwork: Checking distance in inconsistent network", TempNetErr::TempNetInconsistentError()); - DistanceGraph* graph = (DistanceGraph*) this; - return graph->isDistanceLessThan(from, to, bound); + return DistanceGraph::isDistanceLessThan(from, to, bound); + // DistanceGraph* graph = boost::polymorphic_cast(this); + // return graph->isDistanceLessThan(from, to, bound); } @@ -257,7 +260,7 @@ namespace EUROPA { Void TemporalNetwork::propagateBoundsFrom (const TimepointId& src) { for(std::vector::const_iterator it = nodes.begin(); it != nodes.end(); ++it){ - TimepointId node = (TimepointId) *it; + TimepointId node = *it; node->upperBound = POS_INFINITY; node->lowerBound = NEG_INFINITY; } @@ -371,7 +374,7 @@ namespace EUROPA { void TemporalNetwork::getConstraintScope(const TemporalConstraintId& constraint, TimepointId& source, TimepointId& target) const{ check_error(constraint.isValid()); - Tspec* spec = (Tspec*) constraint; + Tspec* spec = id_cast(constraint); source = spec->head->getId(); target = spec->foot->getId(); } @@ -544,12 +547,12 @@ namespace EUROPA { return origin->getId(); } - TimepointId TemporalNetwork::addTimepoint() - { - TimepointId node = (TimepointId) createNode(); - node->ordinal=++(this->nodeCounter); - return node->getId(); - } +TimepointId TemporalNetwork::addTimepoint() { + //this seems terrible. ~MJI + TimepointId node = createNode(); + node->ordinal=++(this->nodeCounter); + return node->getId(); +} Void TemporalNetwork::deleteTimepoint(const TimepointId& node) { @@ -578,7 +581,7 @@ namespace EUROPA { for (std::list::const_iterator it=edgeNogoodList.begin(); it != edgeNogoodList.end(); ++it) { DedgeId edge = *it; - TimepointId node = (TimepointId) edge->to; + TimepointId node = edge->to; ans.push_back(node->getId()); } return ans; @@ -616,7 +619,7 @@ namespace EUROPA { // and backward directions to update the lower/upper bounds. // Note: these could be done lazily on request for bounds. for(std::vector::const_iterator it = nodes.begin(); it != nodes.end(); ++it){ - TimepointId node = (TimepointId) *it; + TimepointId node = *it; node->upperBound = POS_INFINITY; node->lowerBound = NEG_INFINITY; } @@ -642,7 +645,7 @@ namespace EUROPA { (m_refpoint->inCount == 0) ? POS_INFINITY : NEG_INFINITY; for (unsigned i=0; i < nodes.size(); i++) { - TimepointId node = (TimepointId) nodes[i]; + TimepointId node = nodes[i]; node->reftime = initref; } m_refpoint->reftime = 0; @@ -780,51 +783,47 @@ namespace EUROPA { return DnodeId::noId(); } - Void TemporalNetwork::incDijkstraForward() - { +Void TemporalNetwork::incDijkstraForward() { + BucketQueue* queue = this->bqueue; + check_error_variable(unsigned long BFbound = this->nodes.size()); - BucketQueue* queue = this->bqueue; -#ifndef EUROPA_FAST - int BFbound = this->nodes.size(); -#endif - while (true) { - DnodeId dnode = queue->popMinFromQueue(); - if (dnode.isNoId()) - return; - - TimepointId node(dnode); - - for (int i=0; i< node->outCount; i++) { - DedgeId edge = node->outArray[i]; - TimepointId next = (TimepointId) edge->to; - Time newDistance = node->upperBound + edge->length; - if (newDistance < next->upperBound) { - check_error(!(newDistance > MAX_DISTANCE || newDistance < MIN_DISTANCE), - "Potential over(under)flow during upper bound propagation", - TempNetErr::TimeOutOfBoundsError()); - // Next check is a failsafe to prevent infinite propagation. - check_error(!((next->depth = node->depth + 1) > BFbound), - "Dijkstra propagation in inconsistent network", - TempNetErr::TempNetInternalError()); - next->upperBound = newDistance; - // Appropriate priority key as derived from Johnson's algorithm - queue->insertInQueue (next, newDistance - next->potential); + while (true) { + DnodeId dnode = queue->popMinFromQueue(); + if (dnode.isNoId()) + return; - // Store in set of updated timepoints - handleNodeUpdate(next); - } + TimepointId node(dnode); + + for (int i=0; i< node->outCount; i++) { + DedgeId edge = node->outArray[i]; + TimepointId next = edge->to; + Time newDistance = node->upperBound + edge->length; + if (newDistance < next->upperBound) { + check_error(!(newDistance > MAX_DISTANCE || newDistance < MIN_DISTANCE), + "Potential over(under)flow during upper bound propagation", + TempNetErr::TimeOutOfBoundsError()); + // Next check is a failsafe to prevent infinite propagation. + check_error(!(static_cast(next->depth = node->depth + 1) > BFbound), + "Dijkstra propagation in inconsistent network", + TempNetErr::TempNetInternalError()); + next->upperBound = newDistance; + // Appropriate priority key as derived from Johnson's algorithm + queue->insertInQueue (next, newDistance - next->potential); + + // Store in set of updated timepoints + handleNodeUpdate(next); } } } +} Void TemporalNetwork::incDijkstraBackward() { BucketQueue* queue = this->bqueue; -#ifndef EUROPA_FAST - int BFbound = this->nodes.size(); -#endif + check_error_variable(unsigned long BFbound = this->nodes.size()); + while (true) { DnodeId dnode = queue->popMinFromQueue(); if(dnode.isNoId()) @@ -834,14 +833,15 @@ namespace EUROPA { for (int i=0; i< node->inCount; i++) { DedgeId edge = node->inArray[i]; - TimepointId next = (TimepointId) edge->from; + TimepointId next = edge->from; Time newDistance = -(node->lowerBound) + edge->length; if (newDistance < -(next->lowerBound)) { check_error(!(newDistance > MAX_DISTANCE || newDistance < MIN_DISTANCE), "Potential over(under)flow during lower bound propagation", TempNetErr::TimeOutOfBoundsError()); - // Next check is a failsafe to prevent infinite propagation. - check_error(!((next->depth = node->depth + 1) > BFbound), + // Next check is a failsafe to prevent infinite propagation. + //but a risky one, since it's got a side effect! ~MJI + check_error(!(static_cast(next->depth = node->depth + 1) > BFbound), "Dijkstra propagation in inconsistent network", TempNetErr::TempNetInternalError()); next->lowerBound = -newDistance; @@ -860,9 +860,8 @@ namespace EUROPA { { // PHM New function to support reftime calculations BucketQueue* queue = this->bqueue; -#ifndef EUROPA_FAST - int BFbound = this->nodes.size(); -#endif + check_error_variable(unsigned long BFbound = this->nodes.size()); + while (true) { DnodeId dnode = queue->popMinFromQueue(); if (dnode.isNoId()) @@ -870,14 +869,14 @@ namespace EUROPA { TimepointId node(dnode); for (int i=0; i< node->outCount; i++) { DedgeId edge = node->outArray[i]; - TimepointId next = (TimepointId) edge->to; + TimepointId next = edge->to; Time newDistance = node->reftime + edge->length; if (newDistance < next->reftime) { check_error(!(newDistance > MAX_DISTANCE || newDistance < MIN_DISTANCE), "Potential over(under)flow during upper bound propagation", TempNetErr::TimeOutOfBoundsError()); // Next check is a failsafe to prevent infinite propagation. - check_error(!((next->depth = node->depth + 1) > BFbound), + check_error(!(static_cast(next->depth = node->depth + 1) > BFbound), "Dijkstra propagation in inconsistent network", TempNetErr::TempNetInternalError()); next->reftime = newDistance; @@ -895,9 +894,9 @@ namespace EUROPA { { // PHM New function to support reftime calculations BucketQueue* queue = this->bqueue; -#ifndef EUROPA_FAST - int BFbound = this->nodes.size(); -#endif + + check_error_variable(unsigned long BFbound = this->nodes.size()); + while (true) { DnodeId dnode = queue->popMinFromQueue(); if(dnode.isNoId()) @@ -905,14 +904,14 @@ namespace EUROPA { TimepointId node(dnode); for (int i=0; i< node->inCount; i++) { DedgeId edge = node->inArray[i]; - TimepointId next = (TimepointId) edge->from; + TimepointId next = edge->from; Time newDistance = -(node->reftime) + edge->length; if (newDistance < -(next->reftime)) { check_error(!(newDistance > MAX_DISTANCE || newDistance < MIN_DISTANCE), "Potential over(under)flow during lower bound propagation", TempNetErr::TimeOutOfBoundsError()); // Next check is a failsafe to prevent infinite propagation. - check_error(!((next->depth = node->depth + 1) > BFbound), + check_error(!(static_cast(next->depth = node->depth + 1) > BFbound), "Dijkstra propagation in inconsistent network", TempNetErr::TempNetInternalError()); next->reftime = -newDistance; @@ -959,7 +958,7 @@ namespace EUROPA { "TemporalNetwork:: accessing invalid timepoint.", TempNetErr::TempNetInvalidTimepointError()); Tnode* tpoint = tpId.operator->(); - Tnode* tpt = (Tnode*) tpoint->ringLeader; + Tnode* tpt = id_cast(tpoint->ringLeader); if (tpt == 0) tpt = tpoint; // Trivial TEQ, timepoint is own leader. @@ -969,9 +968,9 @@ namespace EUROPA { std::list ans; int numedges = tpt->outCount; for (int i=0; ioutArray[i]; + Dedge* e = static_cast(tpt->outArray[i]); Time length = e->length; - Tnode* next = (Tnode*) e->to; + Tnode* next = static_cast(e->to); if (length < 0) // Negative predecessors are enabling. ans.push_back (next->getId()); diff --git a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.hh b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.hh index 4eedd05af..fb35bf5b6 100644 --- a/src/PLASMA/TemporalNetwork/base/TemporalNetwork.hh +++ b/src/PLASMA/TemporalNetwork/base/TemporalNetwork.hh @@ -56,7 +56,7 @@ namespace EUROPA { Bool hasDeletions; Int nodeCounter; /** - * @breif Used for specialized cycle detection + * @brief Used for specialized cycle detection */ TimepointId incrementalSource; @@ -125,7 +125,7 @@ namespace EUROPA { * @param id the timepoint for which you require this information. * @return lower bound of timepoint. */ - Time getLowerTimepointBound(const TimepointId&); + Time getLowerTimepointBound(const TimepointId& id); /** * @brief Accessor for the Upper Timepoint bound. The method @@ -133,7 +133,7 @@ namespace EUROPA { * @param id the timepoint for which you require this information. * @return upper bound of timepoint. */ - Time getUpperTimepointBound(const TimepointId&); + Time getUpperTimepointBound(const TimepointId& id); /** * @brief Test if the STN is consistent @@ -189,27 +189,27 @@ namespace EUROPA { * @param id temporal constraint of interest. * @result two time points - the head and foot of the constraint (in that order). */ - std::list getConstraintScope(const TemporalConstraintId&); + std::list getConstraintScope(const TemporalConstraintId& id); /** * @brief Get the upperbound on the time of a temporal constraint. * @param id temporal constraint of interest. * @result Upperbound time on constraint. */ - Time getConstraintUpperBound(const TemporalConstraintId&); + Time getConstraintUpperBound(const TemporalConstraintId& id); /** * @brief Get the lowerbound on the time of a temporal constraint. * @param id temporal constraint of interest. * @result Lowerbound time on constraint. */ - Time getConstraintLowerBound(const TemporalConstraintId&); + Time getConstraintLowerBound(const TemporalConstraintId& id); /** * @brief Identify the timepoints that mark the head and foot of a temporal constraint. * @param constraint temporal constraint of interest. - * @param returns head of temporal constraint - * @param returns foot of temporal constraint + * @param source head of temporal constraint + * @param target foot of temporal constraint */ void getConstraintScope(const TemporalConstraintId& constraint, TimepointId& source, TimepointId& target) const; @@ -317,7 +317,7 @@ namespace EUROPA { /** * @brief Identify if timepoint is connected to the origin of the STN through edges in the network - * @param timepoint + * @param timepoint The timepoint to test * @return true iff timepoint has edge to the origin. False, otherwise. * @todo make const when we constify methods in the DistanceGraph */ @@ -331,29 +331,13 @@ namespace EUROPA { // For Dispatchability Processing - /** - * @brief - * @return - */ std::list addDispatchConstraints(); // Additional exec-oriented functions - /** - * @brief - * @return - */ TimepointId getRingLeader(TimepointId tpId); - /** - * @brief - * @return - */ std::list getRingFollowers (TimepointId tpId); - /** - * @brief - * @return - */ std::list getRingPredecessors (TimepointId tpId); /** @@ -395,7 +379,7 @@ namespace EUROPA { /** * @brief For incremental propagation, determines whether a propagation - * should be tried from head to foot or vice versa. + * should be tried from head to foot or vice versa, and does first propagation * * The supplied * edge must be in the direction of propagation from head to foot. @@ -403,15 +387,10 @@ namespace EUROPA { * supplied) in the other direction. Used with various * distance-like values. Note that an effective prop in one * direction precludes one in the other direction. - * @return node at which incremental propogation should be tried. - */ - /** - * @brief For incremental propagation, determines whether a propagation - * is started from head to foot or vice versa, and does first - * propagation. (PHM: 06/21/2007 Recoded for efficiency.) - * @return node from which to continue - * the propagation (or noId if first prop is ineffective). + * @return node from which to continue the propagation + * (or noId if the first prop is ineffective) */ + //(PHM: 06/21/2007 Recoded for efficiency.) DnodeId startNode (TimepointId head, Time& headDistance, TimepointId foot, Time& footDistance, bool forwards = true); @@ -443,14 +422,8 @@ namespace EUROPA { */ Void propagateBoundsFrom (const TimepointId& src); - /** - * @brief - */ Void maintainTEQ (Time lb, Time ub, TimepointId src, TimepointId targ); - /** - * @brief - */ Void cleanupTEQ(TimepointId tpt); /** @@ -460,7 +433,7 @@ namespace EUROPA { Bool isValidId(const TimepointId& id); /** - * @breif check if constraint is valid + * @brief check if constraint is valid */ Bool isValidId(const TemporalConstraintId& id); diff --git a/src/PLASMA/TemporalNetwork/base/queues.cc b/src/PLASMA/TemporalNetwork/base/queues.cc index 39ce24417..8c252aa51 100644 --- a/src/PLASMA/TemporalNetwork/base/queues.cc +++ b/src/PLASMA/TemporalNetwork/base/queues.cc @@ -73,7 +73,7 @@ Bool Dqueue::isEmpty() /* BucketQueue functions */ -BucketQueue::BucketQueue (int n) +BucketQueue::BucketQueue (int) { buckets = new DnodePriorityQueue(); } diff --git a/src/PLASMA/TemporalNetwork/component/STNTemporalAdvisor.cc b/src/PLASMA/TemporalNetwork/component/STNTemporalAdvisor.cc index 15d226f75..443d01d3a 100644 --- a/src/PLASMA/TemporalNetwork/component/STNTemporalAdvisor.cc +++ b/src/PLASMA/TemporalNetwork/component/STNTemporalAdvisor.cc @@ -55,11 +55,11 @@ namespace EUROPA { || second->getExternalEntity().isNoId() ) { - eint f_lb = (eint) first->getLastDomain().getLowerBound(); - eint f_ub = (eint) first->getLastDomain().getUpperBound(); + eint f_lb = static_cast(first->getLastDomain().getLowerBound()); + eint f_ub = static_cast(first->getLastDomain().getUpperBound()); - eint s_lb = (eint) second->getLastDomain().getLowerBound(); - eint s_ub = (eint) second->getLastDomain().getUpperBound(); + eint s_lb = static_cast(second->getLastDomain().getLowerBound()); + eint s_ub = static_cast(second->getLastDomain().getUpperBound()); eint min_distance = -g_infiniteTime(); @@ -98,9 +98,12 @@ namespace EUROPA { void STNTemporalAdvisor::getTemporalDistanceSigns(const ConstrainedVariableId& first, const std::vector& seconds, - std::vector